-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
79 lines (70 loc) · 2.2 KB
/
auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const User = mongoose.model("User")
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const{JWT_SECRET } = require('./keys')
router.post('/signup',(req,res)=>{
const {name, email,password} = req.body
if(!email || !password || !name){
return res.json({error: "please add all the fields"})
}
User.findOne({email:email})
.then((savedUser)=>{
if(savedUser){
return res.status(422).json({error:"User already exists with that email"})
}
bcrypt.hash(password,12)
.then(hashedpassword=>{
const newUser = new User({
email,
password:hashedpassword,
name
})
newUser.save()
.then(user=>{
res.json({message:"saved successfully"})
})
.catch(err=>{
console.log(err)
})
})
})
.catch(err=>{
console.log(err)
})
})
router.post('/signin', (req,res)=>{
const {email,password} = req.body
console.log('Received email:', email)
console.log('Received password:', password)
console.log(email,password)
if (!email || !password){
return res.status(422).json({error:"please add email or password"})
}
User.findOne({email:email})
.then(savedUser=>{
console.log('Saved User:', savedUser);
if(!savedUser){
return res.status(422).json({error:"Invalid Email or password"})
}
bcrypt.compare(password,savedUser.password)
.then(doMatch=>{
console.log('Password Match:', doMatch);
if(doMatch){
//res.json({message:"successfully signed in"})
const token = jwt.sign({_id:savedUser._id}, JWT_SECRET)
const {_id,name,email} = savedUser
res.json({token, user:{_id,name,email}})
}
else{
return res.status(422).json({error:"Invalid Email or password"})
}
})
.catch(err=>{
console.log(err)
})
})
})
module.exports = router