-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
190 lines (156 loc) · 4.03 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
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
const express = require('express')
const path = require('path')
const bcrypt = require('bcrypt')
const mongodb = require('mongodb')
const session = require('express-session')
const connectMongo = require('connect-mongo')
module.exports = connectToDb
const postsRoutes = require('./routes/postsRoutes.js')
const profileRoutes = require('./routes/profileRoutes.js')
const { capitalize } = require('./utils.js')
const {
validateFirstName,
validateLastName,
validateEmail,
validatePassword,
validateConfirmPassword,
} = require('./validations.js')
const app = express()
const MongoStore = connectMongo(session)
const url = 'mongodb://localhost/'
const client = new mongodb.MongoClient(url, { useUnifiedTopology: true })
const dbName = 'social'
async function connectToDb() {
try {
await client.connect()
return client.db(dbName)
} catch (err) {
console.log(err)
}
}
let col
;(async () => {
try {
const db = await connectToDb()
col = db.collection('users')
} catch (err) {
console.log(err)
}
})()
const SESS_NAME = 'sid'
const TEN_YEARS = 1000 * 60 * 60 * 24 * 365 * 10
app.use(express.json())
app.use(
session({
name: SESS_NAME,
secret: 'secret',
store: new MongoStore({ url: url + dbName }),
cookie: {
maxAge: TEN_YEARS,
sameSite: true,
},
resave: false,
saveUninitialized: false,
})
)
app.use(express.static(path.join(__dirname, 'client/build')))
app.get('/auth', (req, res) => {
res.json({ loggedIn: !!req.session.userID })
})
app.post('/signup', async (req, res) => {
const { firstName, lastName, email, password, confirmPassword } = req.body
const [_firstName, _lastName, _email, _password, _confirmPassword] = [
capitalize(firstName.trim()),
capitalize(lastName.trim()),
email.trim(),
password.trim(),
confirmPassword.trim(),
]
const errors = {}
errors.firstNameError = validateFirstName(_firstName)
errors.lastNameError = validateLastName(_lastName)
errors.emailError = await validateEmail(col, _email)
errors.passwordError = validatePassword(_password)
errors.confirmPasswordError = validateConfirmPassword(
_password,
_confirmPassword
)
const hasErrors = Object.values(errors).filter(e => e).length
if (hasErrors) return res.send(errors)
try {
const hashedPassword = await bcrypt.hash(_password, 10)
const document = {
firstName: _firstName,
lastName: _lastName,
email: _email,
password: hashedPassword,
joined: Date.now(),
avatar: '',
}
col.insertOne(document)
res.json({ path: '/login' })
} catch (err) {
console.log(err)
}
})
app.post('/login', async (req, res) => {
const { email, password } = req.body
let emailError
let passwordError
let user
if (!email) {
emailError = 'Enter e-mail'
} else {
user = await col.findOne({ email })
let pwd
if (user)
try {
pwd = await bcrypt.compare(password, user.password)
} catch (err) {
console.log(err)
}
if (!user || !pwd) {
emailError = 'Invalid e-mail or password'
}
}
if (!password) {
passwordError = 'Enter password'
}
if (emailError || passwordError)
return res.json({ emailError, passwordError })
req.session.userID = user._id
req.session.userName = user.firstName + ' ' + user.lastName
res.json({ path: '/home' })
})
app.use('/posts', postsRoutes)
app.use('/getProfile', profileRoutes)
app.get('/getPeople', async (req, res) => {
try {
const users = await col
.aggregate([
{
$project: {
name: { $concat: ['$firstName', ' ', '$lastName'] },
avatar: 1,
},
},
])
.toArray()
res.send(users)
} catch (err) {
console.log(err)
}
})
app.delete('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return console.log(err)
}
res.clearCookie(SESS_NAME)
res.end()
})
})
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/build/index.html'))
})
app.listen(process.env.PORT || 3001)