-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathuser.js
More file actions
75 lines (61 loc) · 1.96 KB
/
user.js
File metadata and controls
75 lines (61 loc) · 1.96 KB
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
'use strict';
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const createError = require('http-errors');
const Promise = require('bluebird');
const debug = require('debug')('cfgram:user');
const Schema = mongoose.Schema;
const userSchema = Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
findHash: { type: String, unique: true }
});
userSchema.methods.generatePasswordHash = function(password) {
debug('generatePasswordHash');
return new Promise((resolve, reject) => {
bcrypt.hash(password, 10, (err, hash) => {
if (err) return reject(err);
this.password = hash;
resolve(this);
});
});
};
userSchema.methods.comparePasswordHash = function(password) {
debug('comparePasswordHash');
return new Promise((resolve, reject) => {
bcrypt.compare(password, this.password, (err, valid) => {
if (err) return reject(err);
if (!valid) return reject(createError(401, 'wrong password'));
resolve(this);
});
});
};
userSchema.methods.generateFindHash = function() {
debug('generateFindHash');
return new Promise((resolve, reject) => {
let tries = 0;
_generateFindHash.call(this);
function _generateFindHash() {
this.findHash = crypto.randomBytes(32).toString('hex');
this.save()
.then(() => resolve(this.findHash))
.catch( err => {
if (tries > 3) return reject(err);
tries++;
_generateFindHash.call(this);
});
};
});
};
userSchema.methods.generateToken = function() {
debug('generateToken');
return new Promise((resolve, reject) => {
this.generateFindHash()
.then(findHash => resolve(jwt.sign({ token: findHash }, process.env.APP_SECRET)))
.catch( err => reject(err));
});
};
module.exports = mongoose.model('user', userSchema);