2021-08-08 22:34:44 -07:00
|
|
|
const { BeanModel } = require("redbean-node/dist/bean-model");
|
|
|
|
const passwordHash = require("../password-hash");
|
|
|
|
const { R } = require("redbean-node");
|
2023-10-08 16:01:54 -07:00
|
|
|
const jwt = require("jsonwebtoken");
|
|
|
|
const { shake256, SHAKE256_LENGTH } = require("../util-server");
|
2021-08-08 22:34:44 -07:00
|
|
|
|
|
|
|
class User extends BeanModel {
|
|
|
|
/**
|
2022-04-21 10:30:04 -07:00
|
|
|
* Reset user password
|
2022-04-18 00:21:58 -07:00
|
|
|
* Fix #1510, as in the context reset-password.js, there is no auto model mapping. Call this static function instead.
|
2022-04-21 10:30:04 -07:00
|
|
|
* @param {number} userID ID of user to update
|
2023-08-11 00:46:41 -07:00
|
|
|
* @param {string} newPassword Users new password
|
2021-08-08 22:34:44 -07:00
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
2022-04-18 00:21:58 -07:00
|
|
|
static async resetPassword(userID, newPassword) {
|
2021-08-08 22:34:44 -07:00
|
|
|
await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [
|
|
|
|
passwordHash.generate(newPassword),
|
2022-04-18 00:21:58 -07:00
|
|
|
userID
|
2021-08-08 22:34:44 -07:00
|
|
|
]);
|
2022-04-18 00:21:58 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-04-21 10:30:04 -07:00
|
|
|
* Reset this users password
|
2023-08-11 00:46:41 -07:00
|
|
|
* @param {string} newPassword Users new password
|
2022-04-18 00:21:58 -07:00
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
|
|
|
async resetPassword(newPassword) {
|
2023-12-18 03:52:49 -08:00
|
|
|
const hashedPassword = passwordHash.generate(newPassword);
|
|
|
|
|
|
|
|
await R.exec("UPDATE `user` SET password = ? WHERE id = ? ", [
|
|
|
|
hashedPassword,
|
|
|
|
this.id
|
|
|
|
]);
|
|
|
|
|
|
|
|
this.password = hashedPassword;
|
2021-08-08 22:34:44 -07:00
|
|
|
}
|
2022-04-18 00:21:58 -07:00
|
|
|
|
2023-10-08 16:01:54 -07:00
|
|
|
/**
|
|
|
|
* Create a new JWT for a user
|
2023-10-09 09:39:55 -07:00
|
|
|
* @param {User} user The User to create a JsonWebToken for
|
|
|
|
* @param {string} jwtSecret The key used to sign the JsonWebToken
|
|
|
|
* @returns {string} the JsonWebToken as a string
|
2023-10-08 16:01:54 -07:00
|
|
|
*/
|
|
|
|
static createJWT(user, jwtSecret) {
|
|
|
|
return jwt.sign({
|
|
|
|
username: user.username,
|
|
|
|
h: shake256(user.password, SHAKE256_LENGTH),
|
|
|
|
}, jwtSecret);
|
|
|
|
}
|
|
|
|
|
2021-08-08 22:34:44 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = User;
|