-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserControl.js
More file actions
58 lines (44 loc) · 1.56 KB
/
userControl.js
File metadata and controls
58 lines (44 loc) · 1.56 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
const userModel = require("../models/user");
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")
const secretKey = "API"
const signup = async(req, res)=>{
// if the user is existing
const {username, password, email} =req.body;
try {
const UserExists = await userModel.findOne({email:email})
if(UserExists){
return res.status(400).json({message:"User already exists"})
}
const hashPwd = await bcrypt.hash(password,10);
const result = await userModel.create({
email: email,
password: hashPwd,
username: username
});
const token = jwt.sign({email: result.email, id: result._id}, secretKey);
res.status(201).json({user:result, token:token})
} catch (error) {
console.log(error);
res.status(500).json({messgae: "Something went wrong"})
}
}
const signIn = async(req, res)=>{
const {email, password}= req.body;
try {
const UserExists = await userModel.findOne({email:email})
if(!UserExists){
return res.status(404).json({message:"User not found"})
}
const matchPwd = await bcrypt.compare(password, UserExists.password);
if(!matchPwd){
return res.status(400).json({message:"Invalid credentials"});
}
const token = jwt.sign({email: UserExists.email, id: UserExists._id}, secretKey);
res.status(201).json({user:UserExists, token:token})
} catch (error) {
console.log(error);
res.status(500).json({message: "Something went wrong"});
}
}
module.exports = {signup, signIn};