UNPKG

@andreabiagini5/applicazioni-e-servizi-web-project

Version:
84 lines 2.94 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.AccountFactory = void 0; const bcrypt_1 = __importDefault(require("bcrypt")); const Rating_1 = require("./Rating"); /** * Factory for creating accounts. */ class AccountFactory { } exports.AccountFactory = AccountFactory; _a = AccountFactory; /** * Account factory. Creates a new account with the given username and password. The password will be hashed. * @param username the username of the user * @param email the email of the user * @param password the password of the user * @param rating the rating of the user * @returns {Account} the account object */ AccountFactory.createWithHashing = async (username, email, password, rating) => { const salt = await bcrypt_1.default.genSalt(); const hashedPassword = await bcrypt_1.default.hash(password, salt); return new AccountImpl(username, email, hashedPassword, rating); }; /** * Account factory. Creates a new account with the given username and hashed password. * @param username the username of the user * @param email the email of the user * @param hashedPassword the hashed password of the user * @param rating the rating of the user * @returns {Account} the account object */ AccountFactory.create = (username, email, hashedPassword, rating) => new AccountImpl(username, email, hashedPassword, rating); class AccountImpl { get username() { return this._username; } get email() { return this._email; } get hashedPassword() { return this._hashedPassword; } get rating() { return this._rating; } constructor(username, email, password, rating) { if (!this.isValidEmail(email)) throw new Error('Invalid email'); if (!this.isValidUsername(username)) throw new Error('Invalid username'); this._username = username; this._email = email; this._hashedPassword = password; this._rating = rating !== null && rating !== void 0 ? rating : Rating_1.RatingFactory.create(); } async checkPassword(password) { return await bcrypt_1.default.compare(password, this._hashedPassword); } changeEmail(newEmail) { if (!this.isValidEmail(newEmail)) return false; this._email = newEmail; return true; } changeRating(newRating) { this._rating = newRating; return true; } isValidEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@(([^<>()\[\]\\.,;:\s@"]+\.)+[^<>()\[\]\\.,;:\s@"]{2,})$/; return re.test(email); } isValidUsername(username) { const re = /^[a-zA-Z0-9_]{3,20}$/; return re.test(username); } } //# sourceMappingURL=Account.js.map