aboutsummaryrefslogtreecommitdiff
path: root/src/server/authentication/models
diff options
context:
space:
mode:
authormadelinegr <laura_wilson@brown.edu>2019-02-14 00:22:11 -0500
committermadelinegr <laura_wilson@brown.edu>2019-02-14 00:22:11 -0500
commitff25c29c6801b1858ce6cd15a5735dba1fc67e8c (patch)
tree12f31374536e4bb79351341191abff6e8a49082b /src/server/authentication/models
parentbb3ebfa2e3176fdfb648cb7da052e07989fee050 (diff)
initial signup / login implementation
Diffstat (limited to 'src/server/authentication/models')
-rw-r--r--src/server/authentication/models/User.ts76
1 files changed, 76 insertions, 0 deletions
diff --git a/src/server/authentication/models/User.ts b/src/server/authentication/models/User.ts
new file mode 100644
index 000000000..9f58d317d
--- /dev/null
+++ b/src/server/authentication/models/User.ts
@@ -0,0 +1,76 @@
+import * as bcrypt from "bcrypt-nodejs";
+import * as crypto from "crypto";
+import * as mongoose from "mongoose";
+
+export type UserModel = mongoose.Document & {
+ email: string,
+ password: string,
+ passwordResetToken: string,
+ passwordResetExpires: Date,
+ tokens: AuthToken[],
+
+ profile: {
+ name: string,
+ gender: string,
+ location: string,
+ website: string,
+ picture: string
+ },
+
+ comparePassword: comparePasswordFunction,
+ gravatar: (size: number) => string
+};
+
+type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => {}) => void;
+
+export type AuthToken = {
+ accessToken: string,
+ kind: string
+};
+
+const userSchema = new mongoose.Schema({
+ email: { type: String, unique: true },
+ password: String,
+ passwordResetToken: String,
+ passwordResetExpires: Date,
+
+ facebook: String,
+ twitter: String,
+ google: String,
+ tokens: Array,
+
+ 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 UserModel;
+ 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: UserModel, candidatePassword, cb) {
+ bcrypt.compare(candidatePassword, this.password, (err: mongoose.Error, isMatch: boolean) => {
+ cb(err, isMatch);
+ });
+};
+
+userSchema.methods.comparePassword = comparePassword;
+
+const User = mongoose.model("User", userSchema);
+export default User; \ No newline at end of file