123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- const Router = require("express");
- const User = require("../models/User");
- const config = require("config")
- const bcrypt = require("bcryptjs")
- const jwt = require('jsonwebtoken')
- const {check, validationResult} = require('express-validator')
- const routers = new Router();
- const authMiddleware = require('../middleware/auth')
- routers.post(
- '/registration',
- [
- check('email', 'Incorrect email').isEmail(),
- check('password', 'Minimum password length 6 characters').isLength({ min: 6 })
- ],
- async (req,res)=>{
- try{
- const errors = validationResult(req)
- if (!errors.isEmpty()) {
- return res.status(400).json({
- errors: errors.array(),
- message: 'Incorrect registration data'
- })
- }
- const{email,password}= req.body
- const candidate = await User.findOne({email})
- if(candidate){
- return res.status(400).json({message:"this email already exists"})
- }
- const hashPass = await bcrypt.hash(password,5)
- const user = new User({email, password: hashPass})
- await user.save()
- return res.json({message:"User created"})
- }catch(e){
- console.log(e)
- res.send("Server error")
- }
- }
- )
- routers.post(
- '/login',
- async (req,res)=>{
- try{
- const{email,password}=req.body
- const user = await User.findOne({email})
- if(!user){
- return res.status(404).json({message:"Email not found"})
- }
- const validPass= bcrypt.compareSync(password,user.password)
- if(!validPass){
- return res.status(400).json({message:"invalid password"})
- }
- const token = jwt.sign({id: user.id},config.get("jwtKey"),{expiresIn:"1h"})
- return res.json({
- token,
- user:{
- id: user.id,
- email: user.email,
- }
- })
- }catch(e){
- console.log(e)
- res.send("Server error")
- }
- }
- )
- routers.get('/auth', authMiddleware,
- async (req, res) => {
- try {
- const user = await User.findOne({_id: req.user.id})
- const token = jwt.sign({id: user.id}, config.get("jwtKey"), {expiresIn: "1h"})
- return res.json({
- token,
- user: {
- id: user.id,
- email: user.email,
- }
- })
- } catch (e) {
- console.log(e)
- res.send({message: "Server error"})
- }
- })
- module.exports = routers
|