-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
229 lines (205 loc) · 6.42 KB
/
auth.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
var bcrypt = require('bcrypt'),
db = require('./pghelper'),
// config = require('./config'),
uuid = require('node-uuid'),
Q = require('q'),
validator = require('validator'),
winston = require('winston'),
invalidCredentials = 'Invalid email or password';
/**
* Encrypt password with per-user salt
* @param password
* @param callback
*/
function encryptPassword(password, callback) {
winston.info('encryptPassword');
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return callback(err);
}
bcrypt.hash(password, salt, function (err, hash) {
return callback(err, hash);
});
});
}
/**
* Compare clear with hashed password
* @param password
* @param hash
* @param callback
*/
function comparePassword(password, hash, callback) {
winston.info('comparePassword');
bcrypt.compare(password, hash, function (err, match) {
if (err) {
return callback(err);
}
return callback(null, match);
});
}
/**
* Create an access token
* @param user
* @returns {promise|*|Q.promise}
*/
function createAccessToken(user) {
winston.info('createAccessToken');
var token = uuid.v4(),
deferred = Q.defer();
db.query('INSERT INTO tokens (userId, token) VALUES ($1, $2)', [user.username, token])
.then(function() {
deferred.resolve(token);
})
.catch(function(err) {
deferred.reject(err);
});
return deferred.promise;
}
/**
* Regular login with application credentials
* @param req
* @param res
* @param next
* @returns {*|ServerResponse}
*/
function login(req, res, next) {
winston.info('login');
var creds = req.body;
console.log(req.body);
// Don't allow empty passwords which may allow people to login using the email address of a Facebook user since
// these users don't have passwords
if (!creds.password || !validator.isLength(creds.password, 1)) {
return res.send(401, invalidCredentials);
}
db.query('SELECT firstName, lastName, email, password FROM salesforce.contact WHERE email=$1', [creds.username], true)
.then(function (user) {
if (!user) {
return res.send(401, invalidCredentials);
}
comparePassword(creds.password, user.password, function (err, match) {
if (err) return next(err);
if (match) {
createAccessToken(user)
.then(function(token) {
return res.send({'user':{'username': user.email, 'firstName': user.firstname, 'lastName': user.lastname}, 'token': token});
})
.catch(function(err) {
return next(err);
});
} else {
// Passwords don't match
return res.send(401, invalidCredentials);
}
});
})
.catch(next);
};
/**
* Logout user
* @param req
* @param res
* @param next
*/
function logout(req, res, next) {
winston.info('logout');
var token = req.headers['authorization'];
winston.info('Logout token:' + token);
db.query('DELETE FROM tokens WHERE token = $1', [token])
.then(function () {
winston.info('Logout successful');
res.send('OK');
})
.catch(next);
};
/**
* Signup
* @param req
* @param res
* @param next
* @returns {*|ServerResponse}
*/
function signup(req, res, next) {
winston.info('signup');
var user = req.body;
if (!validator.isEmail(user.username)) {
return res.send(400, "Invalid email address");
}
if (!validator.isLength(user.firstname, 1) || !validator.isAlphanumeric(user.firstname)) {
return res.send(400, "First name must be at least one character");
}
if (!validator.isLength(user.lastname, 1) || !validator.isAlphanumeric(user.lastname)) {
return res.send(400, "Last name must be at least one character");
}
if (!validator.isLength(user.password, 4)) {
return res.send(400, "Password must be at least 4 characters");
}
console.log('line 3');
db.query('SELECT email FROM salesforce.contact WHERE email=$1', [user.email], true)
.then(function (u) {
if(u) {
return next(new Error('Email address already registered'));
}
encryptPassword(user.password, function (err, hash) {
if (err) return next(err);
createUser(user, hash)
.then(function () {
return res.send('OK');
})
.catch(next);
});
})
.catch(next);
};
/**
* Create a user
* @param user
* @param password
* @returns {promise|*|Q.promise}
*/
function createUser(user, password) {
var deferred = Q.defer(),
externalUserId = (+new Date()).toString(36),
createdDate = (+new Date()).toString(36) ; // TODO: more robust UID logic
db.query('INSERT INTO salesforce.contact( email, firstname, lastname, password, accountid) VALUES ($1, $2, $3, $4, $5) RETURNING email, firstName, lastName, password',
[user.username, user.firstname, user.lastname, password,'0016100000PGbTm'], true)
.then(function (insertedUser) {
deferred.resolve(insertedUser);
})
.catch(function(err) {
deferred.reject(err);
});
return deferred.promise;
};
/**
* Validate authorization token
* @param req
* @param res
* @param next
* @returns {*|ServerResponse}
*/
function validateToken (req, res, next) {
var token = req.headers['authorization'];
if (!token) {
token = req.session['token']; // Allow token to be passed in session cookie
}
if (!token) {
winston.info('No token provided');
return res.send(401, 'Invalid token');
}
db.query('SELECT * FROM tokens WHERE token = $1', [token], true, true)
.then(function (item) {
if (!item) {
winston.info('Invalid token');
return res.send(401, 'Invalid token');
}
req.userId = item.userid;
return next();
})
.catch(next);
};
exports.login = login;
exports.logout = logout;
exports.signup = signup;
exports.createUser = createUser;
exports.createAccessToken = createAccessToken;
exports.validateToken = validateToken;