· 7 years ago · Sep 02, 2018, 09:38 AM
1// users.js for authentication and authorization
2
3const express = require("express");
4const router = express.Router();
5const gravatar = require("gravatar");
6const bcrypt = require("bcryptjs");
7const keys = require("../../config/keys");
8const jwt = require("jsonwebtoken");
9const passport = require("passport");
10
11// Load User Model to check existing email is used for registration or not?
12const User = require("../../models/User");
13
14// @route GET request to api/users/test
15// @description Tests users route
16// @access Public, without login
17router.get("/test", (req, res) => res.json({ msg: "Users Works" }));
18
19// @route GET request to api/users/register
20// @description new registration of user.
21// @access Public, without login first register
22
23router.post("/register", (req, res) => {
24 User.findOne({ email: req.body.email }).then(user => {
25 if (user) {
26 return res.status(400).json({ email: "Email value exists already." });
27 } else {
28 console.log("no user found of this email in DB");
29 const avatar = gravatar.url(req.body.email, {
30 s: "200", //Size of gravatar in pixels
31 r: "pg", //rating,
32 d: "mm" //default value= 'mm'
33 });
34 // create user
35 const newUser = new User({
36 name: req.body.name,
37 email: req.body.email,
38 avatar,
39 password: req.body.password
40 });
41
42 // gensalt(noOfSalts_of_Iterations,(err,salt_result)=>{})
43 bcrypt.genSalt(10, (err, salt) => {
44 // hash(plaintext,salt,callback(err,resultant ciphertext))
45 bcrypt.hash(newUser.password, salt, (err, hash) => {
46 if (err) {
47 console.log("error in bcrypt.hash()");
48 throw err;
49 }
50 //assign salted hash to password
51 newUser.password = hash;
52
53 // Save new password in datebase, overriding plaintext;
54 newUser
55 .save()
56 .then(user => res.json(user)) // if yes,then send it as argument in brackets.
57 .catch(err =>
58 console.log("Error occured in saving hash password in DBn")
59 );
60 });
61 });
62 }
63 });
64});
65
66// @route GET request to api/users/login
67// @description Login/signing-in registered user. return JWT token
68// @access Public
69
70router.post("/login", (req, res) => {
71 const email = req.body.email;
72 const password = req.body.password;
73
74 // find user to match it's password
75 User.findOne({ email: req.body.email }).then(user => {
76 //check if no user
77 if (!user) {
78 return res.status(404).json({ email: "User's email found." });
79 }
80
81 // else if do this..
82
83 // if user's email-id is found then match it's password-hash with local-database
84 bcrypt.compare(password, user.password).then(isMatch => {
85 if (isMatch) {
86 // user pswd matched => then return JWT token back for authentication
87 // res.json({ msg: "Success" });
88 const payload = { it: user.id, name: user.name, avatar: user.avatar };
89
90 // created JWT token
91 // now sign token
92 // jwt.sign(payload, secretKey, expire-time, callback );
93
94 // jwt.sign
95
96 jwt.sign(
97 payload,
98 keys.secretOrKey,
99 { expiresIn: 3600 },
100 (err, token) => {
101 res.json({
102 success: true,
103 token: "bearer " + token
104 });
105 }
106 );
107 } else {
108 // pswd doesn't matched
109 return res.status(400).json({ password: "Password didn't match" });
110 }
111 });
112 });
113});
114
115// @route GET request to api/users/current - current user with token
116// @description Return current user
117// @access Private, can't go without login
118
119router.get(
120 "/current",
121 passport.authenticate("jwt", { session: false }),
122 (req, res) => {
123 res.json({ msg: "Success" });
124 }
125);
126
127module.exports = router;