Newer
Older
import UserModel from '../model/User.model.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import ENV from '../config.js'
/** POST: http://localhost:8080/api/register
* @param : {
"username" : "example123",
"password" : "admin123",
"email": "example@gmail.com",
"profile": ""
}
*/
export async function register(req,res){
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
try {
const { username, password, profile, email } = req.body;
// Checking existing Username
const existUsername = new Promise((resolve, reject) => {
UserModel.findOne({ username }, function(err, user){
if(err) reject(new Error(err))
if(user) reject({ error : "Please use unique username"});
resolve();
})
});
// Checking existing Email
const existEmail = new Promise((resolve, reject) => {
UserModel.findOne({ email }, function(err, email){
if(err) reject(new Error(err))
if(email) reject({ error : "Please use unique Email"});
resolve();
})
});
Promise.all([existUsername, existEmail])
.then(() => {
if(password){
bcrypt.hash(password, 10)
.then( hashedPassword => {
const user = new UserModel({
username,
password: hashedPassword,
profile: profile || '',
email
});
// return save result as a response
user.save()
.then(result => res.status(201).send({ msg: "User Registered Successfully"}))
.catch(error => res.status(500).send({error}))
}).catch(error => {
return res.status(500).send({
error : "Enable to hashed password"
})
})
}
}).catch(error => {
return res.status(500).send({ error })
})
} catch (error) {
return res.status(500).send(error);
}
}
/** POST: http://localhost:8080/api/login
* @param: {
"username" : "example123",
"password" : "admin123"
}
*/
export async function login(req,res){
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
const { username, password } = req.body;
try {
UserModel.findOne({ username })
.then(user => {
bcrypt.compare(password, user.password)
.then(passwordCheck => {
if(!passwordCheck) return res.status(400).send({ error: "Don't have Password"});
// create jwt token
const token = jwt.sign({
userId: user._id,
username : user.username
}, ENV.JWT_SECRET , { expiresIn : "24h"});
return res.status(200).send({
msg: "Login Successful...!",
username: user.username,
token
});
})
.catch(error =>{
return res.status(400).send({ error: "Password does not Match"})
})
})
.catch( error => {
return res.status(404).send({ error : "Username not Found"});
})
} catch (error) {
return res.status(500).send({ error});
}