Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. *
  3. * Example of authenticating users based on the combination of session cookies and JSON Web Tokens
  4. * Please note that these examples are largely pseudo-code and that you'll need to implement the token validation and
  5. * signing yourself.
  6. *
  7. */
  8.  
  9. /* Assuming the credentials are correct we issue a cookie containing the JWT with the httpOnly flag set to true.
  10. We will respond to the client with just the JWT Payload in plain text. */
  11.  
  12. router.post('/login', async (req, res) => {
  13.   try {
  14.     let { email, password } = req.body;
  15.     let data = await Users.login(email, password);
  16.     res.cookie('token', data.token, { httpOnly: true }).send(data.payload);
  17.   } catch (err) {
  18.     res.status(err.status).send(err);
  19.   }
  20. });
  21.  
  22. /* To validate the request on the protected route we simply verify the token that's included in the session cookie we issued previously. Here is an example of a middleware used on all routes we want to protect. */
  23.  
  24. router.use((req, res, next) => {
  25.   try {
  26.     let token = req.cookies.token;
  27.     Authorization.authorize(token);
  28.     next();
  29.   } catch (err) {
  30.     res.status(err.status).send(err);
  31.   }
  32. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement