const { getDb } = require('./db');

async function authenticate(req, res, next, asAdmin) {
    const [type, token] = req.get('Authorization').split(' ');

    if (type !== 'Bearer') {
        res.status(403).json({
            status: 'error',
            message: 'incorrect authorization type'
        });
    }
    else if (!token) {
        res.status(403).json({
            status: 'error',
            message: 'problematic authentication token'
        });
    }
    else {
        const db = await getDb(process.env.DB_URL);
        const collection = await db.collection('users');
        const [user] = await collection.find({ accessToken: token }).toArray();

        if (!user || (asAdmin && !user.isAdmin)) {
            res.status(403).json({
                status: 'error',
                message: 'user not authorized'
            });
        }
        else {
            next();
        }
    }
}

module.exports = {
    authenticateAsUser: async (req, res, next) => await authenticate(req, res, next),
    authenticateAsAdmin: async (req, res, next) => await authenticate(req, res, next, true)
};

@@ -80,24 +80,209 @@
  asAdmin) %7B%0A
+    if (!req.get('Authorization')) %7B%0A        res.status(401).json(%7B%0A            status: 'error',%0A            message: 'no authorization header found'%0A        %7D);%0A        return;%0A    %7D%0A%0A
     const %5Bt
@@ -1049,32 +1049,68 @@
 %0A        else %7B%0A
+            res.locals.user = user;%0A
             next

check for no authorization header and put authenticated user on res.locals