JKhan
JKhan

Reputation: 1287

How to check user authentication in GET method?

My frontend is Reactjs and backend Nodejs and expressjs with Postgresql database. I have a simple signin page which checks user authentication from database. In my Reactjs app, after signing in, user uploads files and then there is a GET method on my nodejs which send files (res.sendFile) when user wants to get the file from server. It is just a simple

<img alt='none' src=`http://example.com/source/${filename}` />

in my Reactjs app which does request for file.

Problem: if I am not logged in to my app, I can paste the URL in my browser and the file is displayed which is NOT what I want. I want the GET method on nodejs should check for authentication of user either if the user is signed in or not, and then only fulfill the request of sending file.

How can I do it?

Should I use some kind of POST method in my Reactjs app before it makes any GET request to the same location of GET method then parse the information then handle it to app.get etc...

This is my nodejs + expressjs.

server.js

app.post('/signin', (req, res) => { signin.handleSignin(req, res, db, bcrypt)})

app.get('/source/:fileid', (req, res) => {
 const { fileid } = req.params;
 res.sendFile(__dirname + /data/ + fileid);
});

./controllers/signin.js

const handleSignin = (req, res, db, bcrypt) => {
const { email, password } = req.body;
if (!email || !password ) {
    return res.status(400).json('Incorrect form submission');
}
db.select('email', 'hash').from('login')
.where('email', '=', email)
.then(data => {
    const isValid = bcrypt.compareSync(password, data[0].hash);
if (isValid) {
        return db.select('*').from('users')
        .where('email', '=', email)
        .then(user => {
            res.json(user[0])
        })
        .catch(err => res.status(400).json('unable to get user'))
    } else {
        res.status(400).json('wrong credentials' )
    }
})
.catch(err => res.status(400).json('wrong credentials'))
}

module.exports = {
handleSignin: handleSignin
}

Upvotes: 0

Views: 466

Answers (1)

Suresh Prajapati
Suresh Prajapati

Reputation: 4457

You have to implement authentication mechanism via cookie or session. After successful login you will set a cookie in the browser and on each HTTP req you will have access to cookie data.

Create a middleware function which will check for valid cookie data in req object for each API requests.

If a user is not logged in and trying to access the URL you won't receive data in the cookie and you can unauthorized (401) the access to that particular resource.

// On valid credentials, you can set the cookie like this
  res.cookie(cookieName, cookieData, cookieOptions);

and middleware function can go like this

function checkSession(req, res, next) {
  if(!req.cookies || !Object.keys(req.cookies).length){
    res.sendStatus(401)
  }
  else next();
}

You can find more details on how to use cookie-parser here.

Upvotes: 1

Related Questions