UNPKG

@lomray/microservice-users

Version:

Users microservice based on NodeJS & inverted json.

90 lines (86 loc) 3.22 kB
'use strict'; var tslib = require('tslib'); var microserviceHelpers = require('@lomray/microservice-helpers'); var microserviceNodejsLib = require('@lomray/microservice-nodejs-lib'); var remote = require('../config/remote.js'); /** * Change user password */ class ChangePassword { /** * @constructor */ constructor({ userId, login, confirmBy, repository, isConfirmed, currentToken, clearTokensType, }) { this.userId = userId; this.login = login; this.confirmBy = confirmBy; this.isConfirmed = isConfirmed; this.repository = repository; this.currentToken = currentToken; this.clearTokensType = clearTokensType; } /** * Init service */ static init(params) { return new ChangePassword(params); } /** * Change password */ change(newPassword, oldPassword) { return tslib.__awaiter(this, void 0, void 0, function* () { const user = yield this.repository.findOne(Object.assign({}, (this.userId ? { id: this.userId } : { [this.confirmBy]: this.login })), { select: microserviceHelpers.EntityColumns(this.repository) }); if (!user) { throw new microserviceNodejsLib.BaseException({ status: 404, message: 'User not found.', }); } if (!oldPassword && !this.isConfirmed) { throw new microserviceNodejsLib.BaseException({ status: 422, message: 'Either of confirm methods should be provided.', }); } if (oldPassword && !this.repository.isValidPassword(user, oldPassword)) { throw new microserviceNodejsLib.BaseException({ status: 422, message: 'Invalid old password.', }); } if (this.isConfirmed && (yield this.isConfirmed(user)) === false) { throw new microserviceNodejsLib.BaseException({ status: 422, message: 'Invalid confirmation code.', }); } user.password = newPassword; yield Promise.all([this.repository.encryptPassword(user), this.handleClearUserTokens(user.id)]); return this.repository.save(user); }); } /** * Handle clear user tokens */ handleClearUserTokens(userId) { return tslib.__awaiter(this, void 0, void 0, function* () { // Check default clear tokens type const { changePasswordClearTokensType } = yield remote(); const type = this.clearTokensType || changePasswordClearTokensType; if (!type || type === 'none') { return; } if (type === 'all') { yield this.repository.clearUserTokens(userId); return; } // Clear tokens type - REST. Keep only current if (!this.currentToken) { return; } yield this.repository.clearUserTokens(userId, this.currentToken); }); } } module.exports = ChangePassword;