ardyhim

Untitled

Dec 7th, 2016
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express');
  2. var router = express.Router();
  3. var jwt = require('jsonwebtoken');
  4. var mongoose = require('mongoose');
  5. var db = require('../mongodb/mongo');
  6.  
  7. /* GET users listing. */
  8. // #routes:10 function untuk mengecek token
  9. function isAuthenticated(req, res, next){
  10.   var token = req.body.token || req.query.token || req.headers.authorization; // mengambil token di antara request
  11.   if(token){ //jika ada token
  12.     jwt.verify(token, 'jwtsecret', function(err, decoded){ //jwt melakukan verify
  13.       if (err) { // apa bila ada error
  14.         res.json({message: 'Failed to authenticate token'}); // jwt melakukan respon
  15.       }else { // apa bila tidak error
  16.         req.decoded = decoded; // menyimpan decoded ke req.decoded
  17.         next(); //melajutkan proses
  18.       }
  19.     });
  20.   }else { // apa bila tidak ada token
  21.     return res.status(403).send({message: 'No token provided.'}); // melkukan respon kalau token tidak ada
  22.   }
  23. }
  24.  
  25. // #routes:0 membuat router ke url "http://localhost:3000/users/login"
  26. router.post('/login', function(req, res, next) {
  27.  
  28.   db.users.findOne({username:req.body.username}, function(err,data){ //mencari data
  29.     if (data) { // apabila menemukan
  30.       if (data.password === req.body.password) { //apabila data password sama dengan user password
  31.  
  32.         var token = jwt.sign(data, 'jwtsecret', { // melakukan generate token di jwt
  33.           algorithm: 'HS256'
  34.         });
  35.  
  36.         res.json({message:'succes login', token: token, succes: true});
  37.  
  38.       }else { //apabila salah password
  39.         res.json({message:'wrong password', succes: false});
  40.       }
  41.     }else { //apabila username tidak di temukan
  42.       res.json({message:'username not found', succes: false});
  43.     }
  44.   });
  45.  
  46. });
  47.  
  48. // #routes:20 router kusus buat yang sudah login atau sudah punya token
  49. router.get('/private', isAuthenticated, function(req, res, next){
  50.   res.json({message:'succes access with token'});
  51. });
  52. // #routes:30 router yang bersifat public atau bisa di akses semua orang
  53. router.get('/public', function(req, res, next){
  54.   res.json({message:'succes acces without token'});
  55. });
  56.  
  57. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment