ardyhim

Untitled

Dec 7th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. function isAuthenticated(req, res, next){
  2. var token = req.body.token || req.query.token || req.headers.authorization; // mengambil token di antara request
  3. if(token){ //jika ada token
  4. jwt.verify(token, 'jwtsecret', function(err, decoded){ //jwt melakukan verify
  5. if (err) { // apa bila ada error
  6. res.json({message: 'Failed to authenticate token'}); // jwt melakukan respon
  7. }else { // apa bila tidak error
  8. req.decoded = decoded; // menyimpan decoded ke req.decoded
  9. next(); //melajutkan proses
  10. }
  11. });
  12. }else { // apa bila tidak ada token
  13. return res.status(403).send({message: 'No token provided.'}); // melkukan respon kalau token tidak ada
  14. }
  15. }
  16.  
  17. router.get('/test',isAuthenticated, function(req, res, next){
  18. res.json({succes:true});
  19. });
  20.  
  21. router.post('/test2', function(req, res, next){
  22. if (req.body.userId === "cantik") {
  23. if (req.body.userPassword === 'cewek') {
  24. var token = jwt.sign(req.body, 'jwtsecret', { // melakukan generate token di jwt
  25. algorithm: 'HS256'
  26. });
  27. res.json({succes: true, token: token});
  28. }else {
  29. res.json({succes: true, message: 'password salah'});
  30. }
  31. }else {
  32. res.json({succes: false, message: 'username salah'});
  33. }
  34. });
Advertisement
Add Comment
Please, Sign In to add comment