/**
 * @file authMiddleware.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

const jwt = require("jsonwebtoken");
const service = require('../services/usersServices');

const authMiddleware = (req, res, next) => {
    let token = req.signedCookies.usertoken;
    if (!token) {
        const authHeader = req.headers["authorization"];
        token = authHeader && authHeader.split(' ')[1];
    }

    if (!token) {
        return res.sendStatus(401);
    }
    jwt.verify(token, process.env.SECRET_TOKEN, async (err, data) => {
        if (err) {
            return res.sendStatus(403);
        }
        const user = await service.getByID(data.id);
        if (!user) {
            return res.sendStatus(403);
        }
        delete user.password;
        req.user = user;
        next();
    });
}

module.exports = authMiddleware;