forked from tjaskula/Coursera
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
79 lines (78 loc) · 2.85 KB
/
auth.js
File metadata and controls
79 lines (78 loc) · 2.85 KB
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 {secret_token} = require("../config/keys")
// //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
// const nodemailer = require('nodemailer')
// const sendgridTransport = require('nodemailer-sendgrid-transport')
// const transporter=nodemailer.createTransport(sendgridTransport({
// auth:{
// api_key:"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"
// }
// }))
router.post('/signup',(req,res)=>{
const {name,email,password,pic} =req.body
if(!email || !name || !password){
console.log("in...")
return res.status(422).json({error:"please enter required fields"})
}
User.findOne({email:email})
.then((saveduser)=>{
console.log("...............")
if(saveduser) {
return res.status(422).json({error:"Email already exists"})
}
bcrypt.hash(password,12)
.then(hashedpassword=>{
const user = new User({
name,
email,
password: hashedpassword,
pic
})
user.save()
.then(user=>{
console.log(user)
// transporter.sendMail({
// to:user.email,
// from:"no-reply@insta.com",
// subject:"signedup successfully",
// html:`<h1>Hi ${user.name},</h1>
// <h2>Welcome to Social Media Website</h2>`
// })
res.status(200).json({message:"saved successfully"})
}).catch(err=>{
console.log("error",err)
})
})
}).catch(err=>{
console.log("err:",err)
})
})
router.post('/signin',(req,res)=>{
const {email,password} =req.body
if(!email || !password){
return res.status(422).json({error:"please add email or password"})
}
User.findOne({email}).then(saveduser=>{
if(!saveduser) {
return res.status(422).json({error:"please enter valid email or password"})
}
bcrypt.compare(password,saveduser.password).then(match=>{
if(match){
const token = jwt.sign({_id:saveduser._id},secret_token)
const {_id,name,email,followers,following,pic} = saveduser
res.send({token,user:{_id,name,email,followers,following,pic}})
}
else{
return res.status(422).json({error:"please enter valid email or password"})
}
}).catch(err=>{
console.log("error:",err)
})
})
})
module.exports = router