Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 44 additions & 25 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')

const contactsRouter = require('./routes/api/contacts')

const app = express()

const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'

app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())

app.use('/api/contacts', contactsRouter)

app.use((req, res) => {
res.status(404).json({ message: 'Not found' })
})

app.use((err, req, res, next) => {
res.status(500).json({ message: err.message })
})

module.exports = app
const express = require('express');
const path = require('path');
const contactsRouter = require('./routes/api/contacts');
const usersRouter = require('./routes/api/users');
const mongoose = require('mongoose');

// Database connection URI
const DB_URI = process.env.DB_URI || 'mongodb+srv://sorintene:1234qwer@test-cluster.jnsni.mongodb.net/db-contacts?retryWrites=true&w=majority';

// Function to establish the database connection
const connectDB = async () => {
try {
await mongoose.connect(DB_URI);
console.log('MongoDB connected successfully');
} catch (err) {
console.error('MongoDB connection error:', err.message);
process.exit(1); // Exit process if the database connection fails
}
};

const app = express();

// Middleware for parsing JSON requests
app.use(express.json());

// Serve static files for avatars
app.use('/avatars', express.static(path.join(__dirname, 'public/avatars')));

// API routes
app.use('/api/contacts', contactsRouter);
app.use('/api/users', usersRouter);

// Middleware for handling 404 errors
app.use((req, res, next) => {
res.status(404).json({ message: 'Not Found' });
});

// Connect to MongoDB when not in test mode
if (process.env.NODE_ENV !== 'test') {
connectDB();
}

// Export the app instance for use in server.js and tests
module.exports = { app, connectDB };
27 changes: 27 additions & 0 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const jwt = require('jsonwebtoken');
const User = require('../models/user');

const auth = async (req, res, next) => {
const { authorization = '' } = req.headers;
const [bearer, token] = authorization.split(' ');

if (bearer !== 'Bearer' || !token) {
return res.status(401).json({ message: 'Not authorized' });
}

try {
const { id } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(id);

if (!user || user.token !== token) {
return res.status(401).json({ message: 'Not authorized' });
}

req.user = user;
next();
} catch {
res.status(401).json({ message: 'Not authorized' });
}
};

module.exports = auth;
29 changes: 13 additions & 16 deletions models/contacts.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
// const fs = require('fs/promises')
const mongoose = require('mongoose');

const listContacts = async () => {}
const contactSchema = new mongoose.Schema({
name: String,
email: String,
phone: String,
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
});

const getContactById = async (contactId) => {}
const Contact = mongoose.model('Contact', contactSchema);

const removeContact = async (contactId) => {}

const addContact = async (body) => {}

const updateContact = async (contactId, body) => {}

module.exports = {
listContacts,
getContactById,
removeContact,
addContact,
updateContact,
}
module.exports = Contact;
62 changes: 0 additions & 62 deletions models/contacts.json

This file was deleted.

18 changes: 18 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
password: { type: String, required: [true, 'Password is required'] },
email: { type: String, required: [true, 'Email is required'], unique: true },
subscription: {
type: String,
enum: ['starter', 'pro', 'business'],
default: 'starter',
},
token: { type: String, default: null },
avatarURL: { type: String }, // Added avatarURL property
});

const User = mongoose.model('user', userSchema);

module.exports = User;
Loading