p5.js-web-editor/server/models/user.js

156 lines
4.2 KiB
JavaScript
Raw Normal View History

import mongoose from 'mongoose';
const bcrypt = require('bcrypt-nodejs');
Email verification (#369) * Re-introduce Email Verification code Revert "Revert "Email verification"" This reverts commit d154d8bff259350523a0f139e844db96c43d2ee1. * Uses MJML to generate Reset Password email * Sends Password Reset and Email Confirmation emails using MJML template * Sends verified status along with user data * API endpoint for resending email verification confirmation * Displays verification status on Account page and allows resending * Send back error string * Passes email address through to sign/verify helper * Uses enum-style object to set verified state * Sends minimal info when user verifies since it can be done without login * Provides /verify UI and sends confirmation token to API * Better name for JWT secret token env var * Adds mail config variables to Readme * Encrypts email address in JWT The JWT sent as the token in the Confirm Password URL can be unencoded by anyone, although it's signature can only be verified by us. To ensure that no passwords are leaked, we encrypt the email address before creating the token. * Removes unused mail templates * Resets verified flag when email is changed and sends another email * Moves email confirmation functions next to each other * Extracts random token generator to helper * Moves email confirmation actions into Redux - updates the AccountForm label with a message to check inbox - show status when verifying email token * Uses generated token stored in DB for email confirmation * Sets email confirmation status to verified if logging in from Github * Sends email using new method on account creation * Fixes linting errors * Removes replyTo config
2017-06-26 16:48:28 +00:00
const EmailConfirmationStates = {
Verified: 'verified',
Sent: 'sent',
Resent: 'resent',
};
2018-05-05 00:59:43 +00:00
const { Schema } = mongoose;
const apiKeySchema = new Schema({
label: { type: String, default: 'API Key' },
lastUsedAt: { type: Date },
hashedKey: { type: String, required: true },
}, { timestamps: true, _id: true });
apiKeySchema.virtual('id').get(function getApiKeyId() {
return this._id.toHexString();
});
/**
* When serialising an APIKey instance, the `hashedKey` field
* should never be exposed to the client. So we only return
* a safe list of fields when toObject and toJSON are called.
*/
function apiKeyMetadata(doc, ret, options) {
return {
id: doc.id, label: doc.label, lastUsedAt: doc.lastUsedAt, createdAt: doc.createdAt
};
}
2019-05-14 10:26:25 +00:00
apiKeySchema.set('toObject', {
transform: apiKeyMetadata
});
apiKeySchema.set('toJSON', {
virtuals: true,
transform: apiKeyMetadata
});
const userSchema = new Schema({
2016-06-23 22:29:55 +00:00
name: { type: String, default: '' },
2016-06-27 17:09:18 +00:00
username: { type: String, required: true, unique: true },
2016-06-23 22:29:55 +00:00
password: { type: String },
2016-10-12 16:02:46 +00:00
resetPasswordToken: String,
resetPasswordExpires: Date,
Email verification (#369) * Re-introduce Email Verification code Revert "Revert "Email verification"" This reverts commit d154d8bff259350523a0f139e844db96c43d2ee1. * Uses MJML to generate Reset Password email * Sends Password Reset and Email Confirmation emails using MJML template * Sends verified status along with user data * API endpoint for resending email verification confirmation * Displays verification status on Account page and allows resending * Send back error string * Passes email address through to sign/verify helper * Uses enum-style object to set verified state * Sends minimal info when user verifies since it can be done without login * Provides /verify UI and sends confirmation token to API * Better name for JWT secret token env var * Adds mail config variables to Readme * Encrypts email address in JWT The JWT sent as the token in the Confirm Password URL can be unencoded by anyone, although it's signature can only be verified by us. To ensure that no passwords are leaked, we encrypt the email address before creating the token. * Removes unused mail templates * Resets verified flag when email is changed and sends another email * Moves email confirmation functions next to each other * Extracts random token generator to helper * Moves email confirmation actions into Redux - updates the AccountForm label with a message to check inbox - show status when verifying email token * Uses generated token stored in DB for email confirmation * Sets email confirmation status to verified if logging in from Github * Sends email using new method on account creation * Fixes linting errors * Removes replyTo config
2017-06-26 16:48:28 +00:00
verified: { type: String },
verifiedToken: String,
verifiedTokenExpires: Date,
2016-06-23 22:29:55 +00:00
github: { type: String },
email: { type: String, unique: true },
tokens: Array,
apiKeys: { type: [apiKeySchema] },
preferences: {
fontSize: { type: Number, default: 18 },
indentationAmount: { type: Number, default: 2 },
isTabIndent: { type: Boolean, default: false },
2016-08-12 19:50:33 +00:00
autosave: { type: Boolean, default: true },
linewrap: { type: Boolean, default: true },
2016-08-12 19:50:33 +00:00
lintWarning: { type: Boolean, default: false },
textOutput: { type: Boolean, default: false },
gridOutput: { type: Boolean, default: false },
soundOutput: { type: Boolean, default: false },
theme: { type: String, default: 'light' },
autorefresh: { type: Boolean, default: false }
}
2019-05-02 23:10:14 +00:00
}, { timestamps: true, usePushEach: true });
/**
* Password hash middleware.
*/
2016-06-27 17:09:18 +00:00
userSchema.pre('save', function checkPassword(next) { // eslint-disable-line consistent-return
const user = this;
if (!user.isModified('password')) { return next(); }
2016-06-27 17:09:18 +00:00
bcrypt.genSalt(10, (err, salt) => { // eslint-disable-line consistent-return
if (err) { return next(err); }
2016-06-27 17:09:18 +00:00
bcrypt.hash(user.password, salt, null, (innerErr, hash) => {
if (innerErr) { return next(innerErr); }
user.password = hash;
2016-06-27 17:09:18 +00:00
return next();
});
});
});
2018-11-06 12:36:19 +00:00
/**
* API keys hash middleware
*/
2018-11-06 16:28:17 +00:00
userSchema.pre('save', function checkApiKey(next) { // eslint-disable-line consistent-return
2018-11-06 12:36:19 +00:00
const user = this;
if (!user.isModified('apiKeys')) { return next(); }
let hasNew = false;
user.apiKeys.forEach((k) => {
if (k.isNew) {
hasNew = true;
2018-11-06 16:28:17 +00:00
bcrypt.genSalt(10, (err, salt) => { // eslint-disable-line consistent-return
2018-11-06 12:36:19 +00:00
if (err) { return next(err); }
bcrypt.hash(k.hashedKey, salt, null, (innerErr, hash) => {
if (innerErr) { return next(innerErr); }
k.hashedKey = hash;
return next();
});
});
}
});
if (!hasNew) return next();
});
userSchema.virtual('id').get(function idToString() {
return this._id.toHexString();
});
userSchema.set('toJSON', {
virtuals: true
});
/**
* Helper method for validating user's password.
*/
2016-06-27 17:09:18 +00:00
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
2016-06-24 22:18:22 +00:00
// userSchema.methods.comparePassword = (candidatePassword, cb) => {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
2018-11-06 16:28:17 +00:00
/**
* Helper method for validating a user's api key
*/
userSchema.methods.findMatchingKey = function findMatchingKey(candidateKey, cb) {
let foundOne = false;
this.apiKeys.forEach((k) => {
if (bcrypt.compareSync(candidateKey, k.hashedKey)) {
foundOne = true;
cb(null, true, k);
2018-11-06 16:28:17 +00:00
}
});
if (!foundOne) cb('Matching API key not found !', false, null);
};
userSchema.statics.findByMailOrName = function findByMailOrName(email) {
const query = {
$or: [{
email,
}, {
username: email,
}],
};
return this.findOne(query).exec();
};
Email verification (#369) * Re-introduce Email Verification code Revert "Revert "Email verification"" This reverts commit d154d8bff259350523a0f139e844db96c43d2ee1. * Uses MJML to generate Reset Password email * Sends Password Reset and Email Confirmation emails using MJML template * Sends verified status along with user data * API endpoint for resending email verification confirmation * Displays verification status on Account page and allows resending * Send back error string * Passes email address through to sign/verify helper * Uses enum-style object to set verified state * Sends minimal info when user verifies since it can be done without login * Provides /verify UI and sends confirmation token to API * Better name for JWT secret token env var * Adds mail config variables to Readme * Encrypts email address in JWT The JWT sent as the token in the Confirm Password URL can be unencoded by anyone, although it's signature can only be verified by us. To ensure that no passwords are leaked, we encrypt the email address before creating the token. * Removes unused mail templates * Resets verified flag when email is changed and sends another email * Moves email confirmation functions next to each other * Extracts random token generator to helper * Moves email confirmation actions into Redux - updates the AccountForm label with a message to check inbox - show status when verifying email token * Uses generated token stored in DB for email confirmation * Sets email confirmation status to verified if logging in from Github * Sends email using new method on account creation * Fixes linting errors * Removes replyTo config
2017-06-26 16:48:28 +00:00
userSchema.statics.EmailConfirmation = EmailConfirmationStates;
2016-06-24 22:18:22 +00:00
export default mongoose.model('User', userSchema);