-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
132 lines (100 loc) · 2.66 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const express=require("express");
const User=require("./model/user");
const authRouter=express.Router();
const bcrypt=require("bcryptjs");
const jwt = require("jsonwebtoken");
var salt=bcrypt.genSalt(10);
const auth=require("./middlewares/authMiddleware");
authRouter.post("/api/signUp",async (req,res)=>{
try {
const {name,email,password,address,phone,image}=req.body;
const existingUser=await User.findOne({
email:email
});
if(existingUser){
return res.status(400).json({
msg:"User with same email already exists"
});
}
const hash=await bcrypt.hash(password,8);
let user= new User({
name:name,
email:email,
password: hash,
address:address,
phone:phone,
image:image
});
user=await user.save();
res.status(200).json(user);
} catch (error) {
res.status(500).json({error:error.message});
}
});
authRouter.post("/api/signIn",async (req,res)=>{
try {
const {email,password}=req.body;
const user=await User.findOne({
email:email
});
if (!user) {
return res
.status(400)
.json({ msg: "User with this email does not exist!" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ msg: "password not correct" });
}
const token=jwt.sign({id:user._id},"adityaMalekith09");
res.status(200).json({token,...user._doc});
} catch (error) {
res.status(500).json({error:error.message});
}
})
authRouter.post("/tokenValid",async(req,res) =>{
try {
const token=req.header('x-auth-token');
if(!token){
return res.json(false);
}
const isVerified=jwt.verify(token,"adityaMalekith09");
if(!isVerified){
return res.json(false);
}
const user=await User.findById(isVerified.id);
if(!user){
return res.json(false);
}
res.json(true);
} catch (error) {
res.status(500).json({error:error.message});
}
})
authRouter.get("/api/users",async(req,res)=>{
try{
const users=await User.find();
res.status(200).json(users);
}
catch(error){
res.status(500).json({error:error.message});
}
})
authRouter.get("/authorized-User", auth, async (req, res) => {
const user = await User.findById(req.user);
res.json({ ...user._doc, token: req.token });
});
authRouter.get("/user/:email",async (req,res)=>{
try {
const {email}=req.params;
const user=await User.findOne({email:email});
if(user){
res.status(200).json(user)
}else{
res.status(400).json({msg:"no user found"})
}
} catch (error) {
res.status(500).json({error:error.message});
}
})
module.exports=authRouter;