-
Notifications
You must be signed in to change notification settings - Fork 8
/
auth.js
106 lines (91 loc) · 3.37 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
var _ = require('underscore'),
everyauth = require ('everyauth'),
bcrypt = require('bcrypt'),
mbc = require('mbc-common'),
Auth = require("mbc-common/models/Auth"),
collections = mbc.config.Common.Collections,
logger = mbc.logger().addLogger('caspa_auth');
var auth = module.exports = exports = function (backends) {
var self = this;
this.everyauth = everyauth;
this.collection = new Auth.UserList();
backends.register_sync (this.collection, 'user');
this.collection.fetch();
everyauth.debug = true;
everyauth.everymodule.userPkey('_id');
everyauth.everymodule
.findUserById( function (id, callback) {
var user = self.collection.get (id);
if (user) {
return callback(null, user.toJSON());
}
var err = "TypeError in reverse user mapping";
logger.error ('error in auth: ' + err, id);
return callback(err, null);
});
everyauth
.password
.loginWith('login')
.getLoginPath('/login')
.postLoginPath('/login')
.loginView('login.jade')
.loginLocals( function (req, res, done) {
setTimeout( function () {
done(null, {
title: 'Async login',
name: 'Login',
});
}, 200);
})
.authenticate( function (login, password) {
var promise
, errors = [];
if (!login) errors.push('Missing login.');
if (!password) errors.push('Missing password.');
if (errors.length) return errors;
var user = self.collection.findWhere ({login: login});
if (!user) {
errors.push('User with login ' + login + ' does not exist.');
return errors;
}
promise = this.Promise();
bcrypt.compare(password, user.get('hash'), function (err, didSucceed) {
if (err) {
return promise.fail(err);
errors.push('Wrong password.');
return promise.fulfill(errors);
}
if (didSucceed) {
return promise.fulfill(user.toJSON());
}
errors.push('Wrong password.');
return promise.fulfill(errors);
});
return promise;
})
.getRegisterPath('/register')
.postRegisterPath('/register')
.registerView('login.jade')
.registerLocals({
title: 'Register',
name: 'Register',
})
.validateRegistration( function (attrs, errors) {
var login = attrs.login;
var user = self.collection.findWhere ({login: login});
if (user) errors.push('Login already taken');
return errors;
})
.registerUser( function (attrs) {
var password = attrs.password;
delete attrs['password']; // Don't store password
var salt = bcrypt.genSaltSync(10);
attrs.hash = bcrypt.hashSync(password, salt);
var user = self.collection.create (attrs, {wait: true});
if (!user)
return user;
return user.toJSON();
})
.loginSuccessRedirect('/')
.registerSuccessRedirect('/');
};