-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserController.js
More file actions
91 lines (72 loc) · 2.15 KB
/
userController.js
File metadata and controls
91 lines (72 loc) · 2.15 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
80
81
82
83
84
85
86
87
88
89
90
91
const asyncHandler=require("express-async-handler");
const User=require("../models/userModel");
const bcrypt=require("bcrypt");
const jwt=require("jsonwebtoken")
const { json } = require("express");
//@desc Register a user
//@route POST /api/contacts
//@access public
const registerUser = asyncHandler(async(req, res) => {
const {username, email, password}=req.body;
if(!username || !email || !password){
res.status(400);
throw new Error("All fields are mandatory");
}
const userAvailable = await User.findOne({email});
if(userAvailable){
res.status(400);
throw new Error("User Already Registered");
}
//Hash Password
const hashedPassword=await bcrypt.hash(password,10);
console.log("Hashed Password",hashedPassword);
const user= await User.create({
username,
email,
password:hashedPassword
})
console.log(`User created ${user}`);
if(user){
res.status(201).json({_id:user.id,email:user.email});
}else{
res.status(400);
throw new Error(" user data is not valid");
}
res.json({message: "Register the User"});
});
//@desc Login a user
//@route POST /api/contacts
//@access public
const loginUser=asyncHandler(async(req, res) => {
const {email,password}=req.body;
if(!email || !password){
res.status(400);
throw new Error("All fields are mandatory");
}
const user=await User.findOne({email});
//compare password with hashed password
if(user && (await bcrypt.compare(password,user.password))){
const accessToken= jwt.sign({
user:{
username:user.username,
email:user.email,
id:user.id,
},
},
process.env.ACCESS_TOKEN_SECRET,
{expiresIn:"15m"}
);
res.status(200).json({ accessToken});
}else{
res.status(401);
throw new Error("email or password is not valid");
}
res.json ({message: "login user"});
});
//@desc Current user info
//@route POST /api/contacts
//@access private
const currentUser=asyncHandler(async(req, res) => {
res.json(req.user);
});
module.exports={registerUser,loginUser,currentUser}