-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
executable file
·92 lines (85 loc) · 2 KB
/
user.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
const bcrypt = require("bcrypt");
const settings = require("./settings");
const jwt = require("jsonwebtoken");
const knex = require("knex")({
client: "sqlite3",
connection: {
filename: "./dev.sqlite3"
},
useNullAsDefault: true
});
const hashPassword = password => {
return new Promise((resolve, reject) => {
bcrypt.hash(password, 10, (error, hash) => {
error ? reject(error) : resolve(hash);
});
});
};
const checkPassword = (password, hash) => {
return new Promise((resolve, reject) => {
bcrypt.compare(password, hash, (error, response) => {
if (error) {
reject(error);
} else if (response) {
resolve(response);
} else {
reject("Incorrect password");
}
});
});
};
const createToken = payload => {
const secret = "s3cr3t"; // process.env.secret
const expiresIn = 1000 * 60 * 60 * 24 * 7;
const token = jwt.sign({ payload }, secret, { expiresIn });
return token;
};
function insertUser(name, username, password) {
return hashPassword(password).then(hash => {
return knex("users")
.where({
username
})
.then(response => {
if (response.length > 0) {
throw new Error();
} else {
return knex("users")
.insert({ name, username, password: hash })
.then(id => {
return knex
.select("*")
.from("users")
.where("username", username)
.first();
});
}
});
});
}
function checkUser(username, password) {
let user = null;
return knex("users")
.where({
username
})
.then(response => {
if (response.length > 0) {
user = response[0];
return checkPassword(password, response[0].password);
}
})
.then(response => {
if (response) {
delete user.password;
return user;
} else {
return false;
}
});
}
module.exports = {
insertUser,
checkUser,
createToken
};