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
34 changes: 17 additions & 17 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
const express = require('express')
const logger = require('morgan')
const cors = require('cors')
const express = require('express');
const logger = require('morgan');
const cors = require('cors');
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');

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

const app = express()
app.use(logger('dev'));
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

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('/auth', authRoutes);
app.use('/users', userRoutes);

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

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

module.exports = app
module.exports = app;
31 changes: 31 additions & 0 deletions controllers/auth/login.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const jwt = require('jsonwebtoken');
const User = require('../../models/user');
const { SECRET_KEY } = process.env;

const login = async (req, res, next) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });

if (!user || !user.comparePassword(password)) {
return res.status(401).json({ message: 'Email or password is wrong' });
}

const payload = { id: user._id };
const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });

await User.findByIdAndUpdate(user._id, { token });

res.status(200).json({
token,
user: {
email: user.email,
subscription: user.subscription,
},
});
} catch (error) {
next(error);
}
};

module.exports = login;
Empty file added controllers/auth/register.js
Empty file.
33 changes: 33 additions & 0 deletions controllers/users/updateAvatar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const fs = require('fs/promises');
const path = require('path');
const jimp = require('jimp');
const User = require('../../models/user');

const avatarsDir = path.join(__dirname, '../../public/avatars');

const updateAvatar = async (req, res, next) => {
try {
const { path: tempPath, originalname } = req.file;
const { _id } = req.user;

const extension = originalname.split('.').pop();
const fileName = `${_id}.${extension}`;
const finalPath = path.join(avatarsDir, fileName);

// Redimensionare avatar
const image = await jimp.read(tempPath);
await image.resize(250, 250).writeAsync(tempPath);

// Mutare în folderul public
await fs.rename(tempPath, finalPath);

const avatarURL = `/avatars/${fileName}`;
await User.findByIdAndUpdate(_id, { avatarURL });

res.status(200).json({ avatarURL });
} catch (error) {
next(error);
}
};

module.exports = updateAvatar;
28 changes: 28 additions & 0 deletions middlewares/authenticate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const { SECRET_KEY } = process.env;

const authenticate = 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, SECRET_KEY);
const user = await User.findById(id);

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

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

module.exports = authenticate;
17 changes: 17 additions & 0 deletions middlewares/upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const multer = require('multer');
const path = require('path');

const tmpDir = path.join(__dirname, '../tmp');

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, tmpDir);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});

const upload = multer({ storage });

module.exports = upload;
19 changes: 0 additions & 19 deletions models/contacts.js

This file was deleted.

62 changes: 0 additions & 62 deletions models/contacts.json

This file was deleted.

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

const userSchema = new Schema({
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
subscription: {
type: String,
default: 'starter',
},
avatarURL: {
type: String,
},
token: {
type: String,
default: null,
},
});

userSchema.methods.comparePassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

const User = model('User', userSchema);

module.exports = User;
Loading