0

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.

1 Answer 1

1

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. 
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.