-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
63 lines (49 loc) · 1.65 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
require('dotenv').config()
require("./config/database").connect()
const express = require("express")
const User = require("./model/user")
const bcrypt = require("bcryptjs")
var cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.get('/', function (req, res) {
res.send('Hello World')
})
app.post("/register", async (req, res)=>{
try {
//collect all information
const {firstname, lastname, email, password } = req.body
//validate the data, if exists
if (!(email && password && lastname && firstname)) {
res.status(401).send("All fileds are required")
}
//check if email is in correct format
//check if user exists or not
const existingUser = await User.findOne({ email})
if (existingUser) {
res.status(401).send("User already found in database")
}
//encrypt the password
const myEncyPassword = await bcrypt.hash(password, 10)
//create a new entry in database
const user = await User.create({
firstname,
lastname,
email,
password: myEncyPassword,
})
//create a token and send it to user
const token = jwt.sign({
id: user._id, email
}, 'shhhhh', {expiresIn: '2h'})
user.token = token
//don't want to send the password
user.password = undefined
res.status(201).json(user)
} catch (error) {
console.log(error);
console.log("Error is response route");
}
})
module.exports = app