This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathauthentication.js
95 lines (69 loc) · 2.49 KB
/
authentication.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
'use strict';
// Dependencies
const bcrypt = require('bcryptjs');
// Imports
const User = require('./models/User');
// Custom express middleware function
const authentication = function (req, res, next) {
// Login function
req.login = (user_id) => req.session.user_id = user_id;
// Logout function
req.logout = () => delete req.session.user_id;
// If there is a user id in the session
if (req.session.user_id) {
// Find a user in the database with the id in the session
User.findUserById(req.session.user_id, (err, user) => {
// If a user was found with no error
if (!err && user) {
// Set request properties
req.user_id = req.session.user_id;
req.authenticated = true;
req.user = user;
// Set response local variables
res.locals.user_id = req.session.user_id;
res.locals.authenticated = true;
res.locals.user = user;
// Set session data
req.session.authenticated = true;
req.session.user = user;
// Call next middleware
next();
// If no user was found or there was an error
} else {
// Set request property
req.authenticated = false;
// Set response local variable
res.locals.authenticated = false;
// Set session property
req.session.authenticated = true;
// Call next middleware and send a suitable message
next(err ? 'Database error.' : 'User not found.');
}
});
// If there is no user id in the session
} else {
// Set request property
req.authenticated = false;
// Set response local variable
res.locals.authenticated = false;
// Set session property
req.session.authenticated = true;
// Call next middleware
next();
}
};
// Compare password function
authentication.comparePassword = function (password, hash, callback) {
// Compare password to hash using bcrypt
bcrypt.compare(password, hash, (err, res) => {
// If no error and match found, send true
if (!err, res) {
callback(true);
// If error or no match found, send false
} else {
callback(false);
}
});
};
// Export authentication module
module.exports = authentication;