authorization.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const Router = require("express");
  2. const User = require("../models/User");
  3. const config = require("config")
  4. const bcrypt = require("bcryptjs")
  5. const jwt = require('jsonwebtoken')
  6. const {check, validationResult} = require('express-validator')
  7. const routers = new Router();
  8. const authMiddleware = require('../middleware/auth')
  9. routers.post(
  10. '/registration',
  11. [
  12. check('email', 'Некорректный email').isEmail(),
  13. check('password', 'Минимальная длина пароля 6 символов').isLength({ min: 6 })
  14. ],
  15. async (req,res)=>{
  16. try{
  17. const errors = validationResult(req)
  18. if (!errors.isEmpty()) {
  19. return res.status(400).json({
  20. errors: errors.array(),
  21. message: 'Некорректный данные при регистрации'
  22. })
  23. }
  24. const{email,password}= req.body
  25. const candidate = await User.findOne({email})
  26. if(candidate){
  27. return res.status(400).json({message:"this email already exists"})
  28. }
  29. const hashPass = await bcrypt.hash(password,5)
  30. const user = new User({email, password: hashPass})
  31. await user.save()
  32. return res.json({message:"User created"})
  33. }catch(e){
  34. console.log(e)
  35. res.send("error blyad")
  36. }
  37. }
  38. )
  39. routers.post(
  40. '/login',
  41. async (req,res)=>{
  42. try{
  43. const{email,password}=req.body
  44. const user = await User.findOne({email})
  45. if(!user){
  46. return res.status(404).json({message:"Email not found"})
  47. }
  48. const validPass= bcrypt.compareSync(password,user.password)
  49. if(!validPass){
  50. return res.status(400).json({message:"invalid password"})
  51. }
  52. const token = jwt.sign({id: user.id},config.get("jwtKey"),{expiresIn:"1h"})
  53. return res.json({
  54. token,
  55. user:{
  56. id: user.id,
  57. email: user.email,
  58. }
  59. })
  60. }catch(e){
  61. console.log(e)
  62. res.send("error blyad")
  63. }
  64. }
  65. )
  66. routers.get('/auth', authMiddleware,
  67. async (req, res) => {
  68. try {
  69. const user = await User.findOne({_id: req.user.id})
  70. const token = jwt.sign({id: user.id}, config.get("jwtKey"), {expiresIn: "1h"})
  71. return res.json({
  72. token,
  73. user: {
  74. id: user.id,
  75. email: user.email,
  76. }
  77. })
  78. } catch (e) {
  79. console.log(e)
  80. res.send({message: "Server error"})
  81. }
  82. })
  83. module.exports = routers