url-minify/backend/models/user.js

73 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-02-13 08:28:33 +00:00
const mongoose = require('mongoose')
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
2022-02-01 20:47:55 +00:00
2022-02-13 08:28:33 +00:00
const { Schema } = mongoose
2022-02-01 20:47:55 +00:00
const UsersSchema = new Schema(
2022-02-13 08:28:33 +00:00
{
email: {
type: String,
unique: true,
},
name: {
type: String,
// required: true,
},
profilepic: {
type: String,
// required: true,
},
apiKey: {
type: String,
default: 'NaN',
},
2022-02-13 08:28:33 +00:00
hash: String,
salt: String,
},
{
timestamps: true,
}
)
2022-02-01 20:47:55 +00:00
UsersSchema.methods.setPassword = function (password) {
2022-02-13 08:28:33 +00:00
this.salt = crypto.randomBytes(16).toString('hex')
this.hash = crypto
.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
.toString('hex')
}
2022-02-01 20:47:55 +00:00
UsersSchema.methods.validatePassword = function (password) {
2022-02-13 08:28:33 +00:00
const hash = crypto
.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
.toString('hex')
return this.hash === hash
}
2022-02-01 20:47:55 +00:00
UsersSchema.methods.generateJWT = function () {
2022-02-13 08:28:33 +00:00
const today = new Date()
const expirationDate = new Date(today)
expirationDate.setDate(today.getDate() + 60)
return jwt.sign(
{
name : this.name,
2022-02-13 08:28:33 +00:00
email: this.email,
hash: this.hash,
id: this._id,
exp: parseInt(String(expirationDate.getTime() / 1000), 10),
},
process.env.AUTH_SECRET
)
}
2022-02-01 20:47:55 +00:00
UsersSchema.methods.toAuthJSON = function () {
2022-02-13 08:28:33 +00:00
return {
id: this._id,
email: this.email,
token: this.generateJWT(),
}
}
module.exports = mongoose.model('users', UsersSchema)