games-express-api/models/User.js

96 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2024-09-12 15:48:27 -04:00
import mongoose from 'mongoose'
const { Schema } = mongoose
import gravatar from 'gravatar'
// import crypt from 'argon2'
import jwt from 'jsonwebtoken'
import crypto from 'crypto'
const UserSchema = new Schema({
name: {
type: String,
trim: true,
required: [true, 'Please add a name'],
},
email: {
type: String,
required: [true, 'Please enter a valid email address'],
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
'Please add a valid email',
],
unique: true,
},
password: {
type: String,
required: [true, 'Please enter a password with a minimum of 6 characters'],
minlength: 6,
select: false
},
avatar: {
type: String,
},
displayName: {
type: String,
required: [true, 'Please add a name to show with your icon'],
unique: true,
},
createDate: {
type: Date,
default: Date.now,
},
updateDate: Date,
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
},
resetPasswordToken: String,
resetPasswordExpire: Date,
})
UserSchema.pre('save', async function (next) {
if(!this.isModified('password')) next()
this.password = await Bun.password.hash(this.password)
})
UserSchema.pre('save', async function(next) {
if(!this.isModified('email')) next()
this.avatar = await gravatar.url(this.email, {
s: '200',
r: 'pg',
d: 'retro',
})
})
// Sign JWT and return
UserSchema.methods.getSignedJwtToken = function () {
return jwt.sign({ id: this._id }, Bun.env.ACCESS_TOKEN_SECRET, {
expiresIn: Bun.env.JWT_EXPIRE,
})
}
// Match user entered password to hashed password in database
UserSchema.methods.matchPassword = async function (enteredPassword) {
return await Bun.password.verify(enteredPassword, this.password)
}
// Generate and hash password token
UserSchema.methods.getResetPasswordToken = async function () {
// Generate token
const resetToken = crypto.randomBytes(20).toString('hex')
// Hash token and set to resetPasswordToken field
this.resetPasswordToken = crypto
.createHash('sha256')
.update(resetToken)
.digest('hex')
// Set expire
this.resetPasswordExpire = Date.now() + 10 * 60 * 1000
return resetToken
}
export default mongoose.model('User', UserSchema)