Advertisement
EntropyStarRover

auth

Jun 21st, 2021
80
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const jwt=require('jsonwebtoken');
  2. const bcrypt=require('bcrypt');
  3. const {TOKEN_SECRET, COOKIE_NAME}= require('../config')
  4.  
  5. const userService=require('../services/userService');
  6.  
  7. module.exports=()=> function(req, res, next){
  8. if (parseToken(req,res)){
  9.  
  10. req.auth={
  11. async register(username,password){
  12. const token= await register(username, password);
  13. res.cookie(COOKIE_NAME, token)
  14. },
  15. async login(username, password){
  16. const token=await login(username, password);
  17. res.cookie(COOKIE_NAME,token);
  18. },
  19. logout(){
  20. res.clearCookie(COOKIE_NAME);
  21. }
  22. };
  23.  
  24.  
  25. next();
  26. }
  27. };
  28.  
  29.  
  30. async function register(username, password){
  31. //adapt params and validate
  32. const existing=await userService.getUserByUsername(username);
  33. if (existing){
  34. throw new Error ('Username is taken!');
  35. }
  36.  
  37. const hashedPassword=await bcrypt.hash(password, 10);
  38. const user=await userService.createUser(username, hashedPassword);
  39.  
  40. //logi user
  41. return generateToken(user);
  42. }
  43.  
  44. async function login(username,password){
  45. const user=await userService.getUserByUsername(username);
  46. console.log(user)
  47. if (!user){
  48. throw new Error ('No such user');
  49. }
  50.  
  51. const hasMatch=await bcrypt.compare(password, user.hashedPassword);
  52. console.log(password, user.hashedPassword)
  53. if (!hasMatch){
  54. throw new Error ('Incorrect password!')
  55. }
  56.  
  57. return generateToken(user);
  58.  
  59. }
  60.  
  61. function generateToken(userData){
  62. return jwt.sign({
  63. _id:userData._id,
  64. username:userData.username
  65. }, TOKEN_SECRET);
  66.  
  67. }
  68.  
  69. function parseToken(req,res){
  70. const token=req.cookies[COOKIE_NAME];
  71. if (token){
  72. try {
  73. const userData=jwt.verify(token, TOKEN_SECRET);
  74. req.user=userData;
  75. } catch (err) {
  76. res.clearCookie(COOKIE_NAME);
  77. res.redirect('/auth/login');
  78.  
  79. return false;
  80. }
  81. }
  82. return true;
  83. }
Advertisement
RAW Paste Data Copied
Advertisement