shumana chowdhury
shumana chowdhury

Reputation: 1882

NodeJS user authentication middleware

I want to create a user authentication middleware for an application. I will not use any data from database for this authentication. Suppose,

var user = "me";
function authme(){
 //condition}

I will use "authme" in my router as a middleware.

app.post('/api', authme, function(res, req){
})

I want to write authme function in a way so that when user=me, it routes this api. I know this is very basic, but I could not make this happen. Thank you in advance.

Upvotes: 0

Views: 382

Answers (1)

Samay Jain
Samay Jain

Reputation: 265

I am assuming that you will receive the login credentials from the user in the request body.

Your function "authme" should look something like this...

/*
   Sample request body which you will receive from the client
   {
       "userId":"me",
       "password":"password"
   }
*/    
function authme(req,res,next){
    if(req.body.userId=="me" && req.body.password=="random_password"){
        console.log("User authenticated");
        next(); 
    }
    else{
        console.log("Wrong authentication");
        res.sendStatus(401);
    }
}

app.post('/api', authme, function(req,res){
     //the user has been authenticated. 
})

Upvotes: 1

Related Questions