Skip to content

Commit

Permalink
Add user model
Browse files Browse the repository at this point in the history
  • Loading branch information
amiiy committed Feb 14, 2020
1 parent a02f379 commit 243ed15
Show file tree
Hide file tree
Showing 4 changed files with 1,358 additions and 4 deletions.
4 changes: 4 additions & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,20 @@
"author": "Amir Imani",
"license": "ISC",
"dependencies": {
"@types/bcrypt-nodejs": "^0.0.31",
"@types/compression": "^1.0.1",
"@types/errorhandler": "^0.0.32",
"@types/mongoose": "^5.7.1",
"@types/morgan": "^1.7.37",
"@types/node": "^13.5.2",
"bcrypt-nodejs": "^0.0.3",
"body-parser": "^1.19.0",
"compression": "^1.7.4",
"errorhandler": "^1.5.1",
"express": "^4.17.1",
"express-session": "^1.17.0",
"global": "^4.4.0",
"mongoose": "^5.9.0",
"morgan": "^1.9.1",
"tslint": "^6.0.0",
"typescript": "^3.7.5"
Expand Down
65 changes: 65 additions & 0 deletions api/src/models/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import mongoose from 'mongoose';
import bcrypt from 'bcrypt-nodejs';

export type UserDocument = mongoose.Document & {
email: string;
passowrd: string;
tokens: AuthToken[];
comparePassword: comparePasswordFunction;
};

export interface AuthToken {
accessToken: string;
kind: string;
}
type comparePasswordFunction = (
candidatePassword: string,
cb: (err: any, isMatch: any) => {}
) => void;

const userSchema = new mongoose.Schema(
{
email: { type: String, unique: true },
passowrd: { type: String },
profile: {
email: String
}
},
{ timestamps: true }
);

userSchema.pre('save', function save(next) {
const user = this as UserDocument;
if (!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.passowrd, salt, undefined, (err: mongoose.Error, hash) => {
if (err) {
return next(err);
}
user.passowrd = hash;
return next();
});
});
});

const comparePassword: comparePasswordFunction = function(
candidatePassword,
cb
) {
bcrypt.compare(
candidatePassword,
this.passowrd,
(err: mongoose.Error, isMatch: Boolean) => {
cb(err, isMatch);
}
);
};

userSchema.methods.comparePassord = comparePassword;

export const User = mongoose.model<UserDocument>('User', userSchema);
Loading

0 comments on commit 243ed15

Please sign in to comment.