-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
261 lines (214 loc) · 7.61 KB
/
server.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
const express = require('express')
const Joi = require('joi')
const app = express()
require('dotenv').config()
const jwt = require('jsonwebtoken')
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
// Basic configuration
app.use(express.json())
app.use(express.urlencoded({extended: true}))
// Database connection
async function dbConnect() {
try{
await mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true})
console.log('$$ DB Connection Successful $$')
} catch (error) {
console.log('!! DB Connection Failed !!')
console.log(error)
}
}
dbConnect()
// Database schema and model setup
const userSchema = mongoose.Schema({
username: {type: String, required: true},
email: {type: String, required: true},
password: {type: String, required: true},
joinDate: {type: Date, default: Date.now}
})
const User = mongoose.model('User', userSchema)
// User input validation schema for account creation
const JoiRegSchema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required(),
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
.required(),
password: Joi.string()
.min(6)
.max(30)
.required()
})
const JoiLogSchema = Joi.object({
email: Joi.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
.required(),
password: Joi.string()
.min(6)
.max(30)
.required()
})
const JoiPutSchema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30),
password: Joi.string()
.min(6)
.max(30)
})
// JWT Authentication
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (!token) {
return res.status(401).send('!! ACCESS DENIED !!')
} else {
jwt.verify(token, process.env.SECRET, (err, decoded) => {
if (err) return res.send('!! ACCESS DENIED !!')
req.decoded = decoded
next()
})
}
}
// The root GET
app.get('/', (req, res) => {
res.sendFile(process.cwd()+'/index.html')
})
// Registering a new user
app.post('/api/register', (req, res) => {
let data = JoiRegSchema.validate(req.body)
if ('error' in data) {
return res.json(data.error.details[0].message)
} else {
User.findOne({email: req.body.email}, (err, cb) => {
if (err) return console.log(err), res.status(500).send('server error, try again')
if (cb === null) {
let hash = bcrypt.hashSync(req.body.password, 8)
let userData = {...req.body}
userData.password = hash
User.create(userData, (err, data) => {
if (err) return console.error(err), res.status(500).send('server error, try again')
const cleaned = {
username: data.username,
email: data.email,
password: data.password,
joinDate: data.joinDate
}
return res.json(cleaned)
})
} else {
res.json({'error': 'User with the email already exist. Try another email.'})
}
})
}
})
// User log-in and authentication
app.post('/api/login', (req, res) => {
let data = JoiLogSchema.validate(req.body)
if ('error' in data) {
return res.json(data.error.details[0].message)
} else {
User.findOne({email: req.body.email}, (err, cb) => {
if (err) return console.error(err), res.status(500).send('server error, try again')
if (cb === null) return res.json({error: "wrong email or password"})
let result = bcrypt.compareSync(req.body.password, cb.password)
if (result === true) {
let token = jwt.sign({email: cb.email}, process.env.SECRET)
res.send(`Welcome ${cb.username}, here's your token: BEARER ${token}`)
} else {
return res.json({error: "wrong email or password"})
}
})
}
})
// Get single user details
app.get('/api/users/:id', authenticateToken, (req, res) => {
let ad_mail = req.decoded.email
if (ad_mail === '[email protected]') {
User.findOne({email: req.params.id}, (err, doc) => {
if (err) return console.error(err), res.status(500).send('server error, try again')
if (doc === null) {
res.status(404).send('No such user found')
} else {
res.status(200).send(doc)
}
})
} else {
res.status(401).send('!! ACCESS DENIED. ADMIN ACCESS ONLY !!')
}
})
// GET the users with the token
app.get('/api/users', authenticateToken, (req, res) => {
let mail = req.decoded.email
if (mail === '[email protected]') {
User.find({}, (err, data) => {
if (err) return console.error(err)
let data_arr = []
data.forEach(function (item) {
let temp = {}
temp.username = item.username
temp.email = item.email
temp.joinDate = item.joinDate
data_arr.push(temp)
})
res.send(data_arr)
})
} else {
res.status(401).send('!! ACCESS DENIED. ADMIN ACCESS ONLY !!')
}
})
// Updating user details
app.put('/api/update', authenticateToken, (req, res) => {
let mail = req.decoded.email
let data = JoiPutSchema.validate(req.body)
if ('error' in data) {
return res.json(data.error.details[0].message)
} else if (Object.keys(req.body).length === 0) {
res.json({error: "no data to update"})
} else if ('username' in req.body && 'password' in req.body) {
let hash = bcrypt.hashSync(req.body.password, 8)
User.findOneAndUpdate({email: mail}, {username: req.body.username, password: hash}, (err, doc) => {
if (err) return console.error(err), res.status(500).send('server error, try again')
res.status(200).send('name and password changed successfully')
})
} else if ('username' in req.body) {
User.findOneAndUpdate({email: mail}, {username: req.body.username}, (err, doc) => {
if (err) return console.error(err), res.status(500).send('server error, try again')
res.status(200).send('username changed successfully')
})
} else {
let hash = bcrypt.hashSync(req.body.password, 8)
User.findOneAndUpdate({email: mail}, {password: hash}, (err, doc) => {
if (err) return console.error(err), res.status(500).send('server error, try again')
res.status(500).send('password changed successfully')
})
}
})
// Deleting users
app.delete('/api/users/:id', authenticateToken, (req, res) => {
let ad_mail = req.decoded.email
let tr_mail = req.params.id
if (tr_mail === ad_mail) {
res.status(403).send('!! FORBIDDEN. CANNOT DELETE ADMIN !!')
} else {
if (ad_mail === '[email protected]') {
User.deleteOne({email :tr_mail}, (err, doc) => {
if (err) console.error(err)
if (doc.deletedCount === 0) {
res.status(404).send('No such user found')
} else {
res.status(200).send(`User with email ${req.params.id} successfully deleted.`)
}
})
} else {
res.status(401).send('!! ACCESS DENIED, ADMIN ACCESS ONLY !!')
}
}
})
app.listen(process.env.PORT || 3000, () => {
console.log('Server up and running.....')
})