user121548789
user121548789

Reputation: 189

How to keep a user logged in after page refresh

I have a simple web application that a user can create an account and login ... whenever a user log in i am generating a json-web-token for him and storing it on his database object ... im using that token to authenticate the user when he visits certain routes ( Bearer token on the header ) but the problem is that when the user refreshes the page i lose that token and he have to provide the email and password again to generate another token ... i was thinking about using localStorage or cookies but maybe there is a better / commonly used way for this ... any advises would be helpful thanks .

router.post('/user/login' ,async (req,res)=>{
    try {
        const user = await User.findByCredentials(req.body.email,req.body.password)
        const token = await user.generateToken()
        res.send({ user, token })
    } catch(e) {
        res.status(404).send(e)
    }
})
axios({
  method: "post",
  url: "/api/user/login",
  data: {
    email: email,
    password: password
  }
})

Upvotes: 3

Views: 9413

Answers (2)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

The traditional way to use Persistent session(remember me feature) is to use cookies.

You can make set the max age lets say 30 days when logging in.

router.post('/user/login', function(req, res) {
    ....
    req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000; // Cookie expires after 30 days
    ....
});

The logical flow should be:

  1. When the user successfully logs, a login cookie is issued.
  2. It should contain some kind of token which you then need to HASH(hash(cookie)) and store it in DB.
  3. When a non-logged-in user visits the site and presents a login cookie, the series identifier is looked up in the database.
  4. If it finds the cookie it gets authenticated, otherwise asks to login.

Upvotes: 7

user11940943
user11940943

Reputation:

Start the session on the first line of your page, and store the login credentials in it. You can do the same for all other pages to be accessed after login.

Upvotes: 0

Related Questions