-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth-check.js
90 lines (72 loc) · 2.34 KB
/
auth-check.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
import User from './models/user';
import socketioJwt from 'socketio-jwt';
let exp = {};
// helper function to extract only necessary
// user data for returning callbacks
function getUserInfo(userModel) {
return {
id: userModel._id,
username: userModel.username,
friends: userModel.friends
};
}
exp.loginAuth = (data, callback) => {
let email = data.email.trim();
let password = data.password.trim();
User.findByEmail(email, (err, user) => {
if (err) { return callback(err); }
if (!user) {
let error = new Error('User with that email does not exist.');
return callback(error);
}
user.verifyPassword(password, (err, valid) => {
if (err) { return callback(err); }
if (!valid) {
let error = new Error('Incorrect password.');
return callback(error);
}
return callback(null, getUserInfo(user));
});
});
};
exp.signupAuth = (data, callback) => {
let userData = {
email : data.email.trim(),
username : data.username.trim(),
password : data.password.trim()
};
User.findByEmail(userData.email, (err, user) => {
if (err) { return callback(err); }
if (user) {
let error = new Error('Email is already in use.');
return callback(error);
}
User.findByUsername(userData.username, (err, user) => {
if (err) { return callback(err); }
if (user) {
let error = new Error('Username is already in use.');
return callback(error);
}
let newUser = new User(userData);
User.createUser(newUser, (err) => {
if (err) { return callback(err); }
return callback(null, getUserInfo(newUser));
});
});
});
};
exp.socketTokenAuth = socketioJwt.authorize({
secret: 'aips2017jajacmasamitic',
timeout: 1000 * 60 * 60
});
// exp.socketUserAuth = (userId, callback) => {
// User.findById(userId, (err, user) => {
// if (err || !user) {
// return callback(new Error("User not found."));
// } else {
// // attach user info to socket
// return callback(null, getUserInfo(user));
// }
// });
// };
module.exports = exp;