aboutsummaryrefslogtreecommitdiff
path: root/src/server/authentication/models/user_model.ts
blob: 45fbf23b1f4223d2119d8a82e7fed5b2c328be0e (plain)
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
//@ts-ignore
import * as bcrypt from "bcrypt-nodejs";
//@ts-ignore
import * as mongoose from "mongoose";
var url = 'mongodb://localhost:27017/Dash';

mongoose.connect(url, { useNewUrlParser: true });

mongoose.connection.on('connected', function () {
    console.log('Stablished connection on ' + url);
});
mongoose.connection.on('error', function (error) {
    console.log('Something wrong happened: ' + error);
});
mongoose.connection.on('disconnected', function () {
    console.log('connection closed');
});
export type DashUserModel = mongoose.Document & {
    email: String,
    password: string,
    passwordResetToken?: string,
    passwordResetExpires?: Date,

    userDocumentId: string;

    profile: {
        name: string,
        gender: string,
        location: string,
        website: string,
        picture: string
    },

    comparePassword: comparePasswordFunction,
};

type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => {}) => void;

export type AuthToken = {
    accessToken: string,
    kind: string
};

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    passwordResetToken: String,
    passwordResetExpires: Date,

    userDocumentId: String,

    facebook: String,
    twitter: String,
    google: String,

    profile: {
        name: String,
        gender: String,
        location: String,
        website: String,
        picture: String
    }
}, { timestamps: true });

/**
 * Password hash middleware.
 */
userSchema.pre("save", function save(next) {
    const user = this as DashUserModel;
    if (!user.isModified("password")) {
        return next();
    }
    bcrypt.genSalt(10, (err, salt) => {
        if (err) {
            return next(err);
        }
        bcrypt.hash(user.password, salt, () => void {}, (err: mongoose.Error, hash) => {
            if (err) {
                return next(err);
            }
            user.password = hash;
            next();
        });
    });
});

const comparePassword: comparePasswordFunction = function (this: DashUserModel, candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, cb);
};

userSchema.methods.comparePassword = comparePassword;

const User = mongoose.model("User", userSchema);
export default User;