-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
129 lines (80 loc) · 2.46 KB
/
app.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
require('dotenv').config();
require('./config/database').connect();
const express = require('express');
const User = require('./model/user');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs/dist/bcrypt');
const auth = require('./middleware/auth');
const app = express();
app.use(express.json());
app.post("/register" , async (req , res) =>{
//register logic
try{
//get user input
const{ first_name ,last_name, email, pasword }= req.body;
//validate user input
if(!(email && pasword && first_name && last_name)){
res.status(400).send('All input is required');
}
//check if user already exist
const oldUser = await User.findOne({email});
if(oldUser){
return res.status(409).send('User already exist.Please login');
}
//encypt user password
encrytedPassword = await bcrypt.hash(pasword, 10 );
//create user in our database
const user = await User.create({
first_name,
last_name,
email:email.toLowerCase(),
password: encrytedPassword
});
const token = jwt.sign(
{user_id: user._id, email},
process.env.TOKEN_KEY,
{
expiresIn:'2h'
}
)
//save user token
user.token = token;
//return new user
res.status(201).json(user);
}catch(err){
console.log(err);
}
});
app.post("/login" , async (req , res) =>{
//login logic
try{
//get user input
const {email, password} = req.body;
//validate
if(!(email && password)){
res.status(400).send('All in put is required');
}
//validate if user exist in our database
const user = await User.findOne({email});
if(user &&(await bcrypt.compare(password,user.password))){
//create token
const token = jwt.sign(
{user_id:user._id,email },
process.env.TOKEN_KEY,
{
expiresIn:'2hr'
}
)
//save token
user.token = token;
res.status(200).json(user);
}
res.status(400).send("Invalid")
}catch(err){
console.log(err)
}
});
app.post('/Wellcome', auth, (req, res) =>{
res.status(200).send('Wellcome')
})
module.exports = app;