A
A
Alex Ozerov2021-07-03 13:27:34
Node.js
Alex Ozerov, 2021-07-03 13:27:34

How to conditionally execute middleware?

I have authorization using email and using google auth. The question arose: when a user uploads a file to the chat and sends it to the server, I need the middleware to check if the user is logged in. Well, the question itself: How to check how a user is logged in, and how to call a certain middle in this case?

Auth Middleware

class AuthMiddleware {
    static auth (req,res,next) {
        if(req.method === 'OPTIONS'){
            next()
        }
        try{
            const token = req.headers.authorization.split(' ')[1];
            if(token === 'null'){
                return res.status(403).json({message: 'You are not logged in!'})
            }
            const decoded = jwt.verify(token, process.env.SECRET_KEY)
            req.user = decoded;
            next();
        }
        catch(err){
            console.log(err)
        }
    }
    static async authWithGoogle(req,res,next){
        try{
            const token = req.headers.authorization.split(' ')[1];
            const decode = await admin.auth().verifyIdToken(token)
            if(!decode){
                return res.status(403).json({message: 'You are not logged in! !'})
            }
            next()
        }
        catch(err){
            console.log(err)
        }
    }
}



router

router.post('/upload',  'Тут должен быть мидлвейр', fileController.upload)



PS Everything is written in Express.js

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question