import jwt from 'jsonwebtoken' import expressJwt from 'express-jwt' import User from '../user/user.model.js' import config from '../config/config.js' const signin = async (req, res) => { try { let user = await User.findOne({ 'email': req.body.email }) if (!user) { return res.status(401).json({ error: 'User not found' }) } if (!user.authenticate(req.body.password)) { return res.status(401).json({ error: "Email and password don't match" }) } const token = jwt.sign({ _id: user._id }, config.jwtSecret) return res.json({ token, user: { _id: user._id, name: user.name, email: user.email, } }) } catch (error) { return res.status(400).json({ error: 'Could not sign in' }) } } const signout = (req, res) => { return res.json({ message: 'Signed out' }) } const requireSignin = expressJwt({ secret: config.jwtSecret, requestProperty: 'auth', algorithms: ['HS256'] }) const hasAuthorization = (req, res, next) => { // console.log('profile:', req.profile, 'auth:', req.auth); // console.log('id is equal?:', req.profile._id === req.auth._id); const authorized = req.profile && req.auth && req.profile._id == req.auth._id if (!authorized) { // console.log('authorized?', authorized); return res.status(403).json({ error: 'User is not authorized' }) } next() } export default { signin, signout, requireSignin, hasAuthorization, }