This repository has been archived by the owner on Feb 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
auth.js
58 lines (52 loc) · 1.59 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
var r = require("rethinkdb");
var jwt = require("jsonwebtoken");
var bluebird = require("bluebird");
var bcrypt = bluebird.promisifyAll(require("bcrypt"));
var config = require("./config");
function userFind(username) {
return r.connect(config.database).then(function(conn) {
return r.table("users").getAll(username, {index: "username"})(0)
.default(null).run(conn)
.finally(function() { conn.close(); });
});
}
function userMake(username, hash) {
var user = {
username: username, password: hash,
admin: config.admins.indexOf(username) >= 0
};
return r.connect(config.database).then(function(conn) {
return r.table("users").insert(user, {returnChanges: true})
("changes")(0)("new_val").run(conn)
.finally(function() { conn.close(); });
});
}
module.exports = {
create: function(username, password) {
return userFind(username).then(function(user) {
if (user) throw "User already exists";
})
.then(function() {
return bcrypt.hashAsync(password, 10);
})
.then(function(hash) {
return userMake(username, hash);
})
.then(function(user) {
return {user: user, token: jwt.sign(user, config.jwt.secret)};
});
},
login: function(username, password) {
var user;
return userFind(username).then(function(u) {
if (!(user = u)) throw "User doesn't exist";
return bcrypt.compareAsync(password, u.password);
})
.then(function(auth) {
if (!auth) throw "Authentication failed";
})
.then(function() {
return {user: user, token: jwt.sign(user, config.jwt.secret)};
});
}
};