-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
82 lines (69 loc) · 2.55 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
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const dbURL = 'mongodb+srv://<username>:<password>@cluster0.hy7dn.mongodb.net/<dbname>?retryWrites=true&w=majority'
const userModel = require('./Model/users')
const key = 'password'
const algo = 'aes256'
const jwtKey = 'jwt'
mongoose.connect(dbURL, {useUnifiedTopology: true, useNewUrlParser: true})
.then(() => console.log('connected'))
app.get('/', (request, response) => {
response.end('hello')
})
app.post('/register', jsonParser, (request, response) => {
const cipher = crypto.createCipher(algo, key)
const encryptedPassword = cipher.update(request.body.password, 'utf8', 'hex') + cipher.final('hex')
const data = new userModel({
_id: new mongoose.Types.ObjectId,
name: request.body.name,
email: request.body.email,
password: encryptedPassword
})
data.save()
.then((result) => {
jwt.sign({result}, jwtKey, {expiresIn: '300s'}, (err, token) => {
response.status(201).json({token})
})
})
.catch((err) => {
console.log(err)
})
})
app.post('/login', jsonParser, (request, response) => {
userModel.findOne({email: request.body.email})
.then(result => {
const deCipher = crypto.createDecipher(algo, key)
const deCryptedPassword = deCipher.update(result.password, 'hex', 'utf8') + deCipher.final('utf8')
if (deCryptedPassword === request.body.password) {
jwt.sign({result}, jwtKey, {expiresIn: '300s'}, (err, token) => {
response.status(200).json({token})
})
} else {
response.end('Something went wrong. Please check your password and email')
}
})
})
app.get('/users', userValidityCheck, (request, response) => {
userModel.find()
.then(data => {
response.status(200).json(data)
})
})
function userValidityCheck(request, response, next) {
const bearerHeader = request.headers['authorization']
if (typeof bearerHeader !== 'undefined') {
request.token = bearerHeader.split(' ')[1]
jwt.verify(request.token, jwtKey, (err, authData) => {
if (err) response.json({result: err})
else next()
})
} else {
response.send({'result': 'Token not provided'})
}
}
app.listen(5050)