"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "UserController", {
    enumerable: true,
    get: function() {
        return UserController;
    }
});
const _express = require("express");
const _serverconstants = require("../server.constants");
const _authenticate = require("../middleware/authenticate");
const _authorizationconstants = require("../constants/authorization.constants");
const _validators = require("../handlers/validators");
const _genericvalidation = require("./validation/generic.validation");
const _runtimeexceptions = require("../exceptions/runtime.exceptions");
const _demomiddleware = require("../middleware/demo.middleware");
const _errorutils = require("../utils/error.utils");
const _awilixexpress = require("awilix-express");
const _usercontrollervalidation = require("./validation/user-controller.validation");
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
}
class UserController {
    userService;
    roleService;
    configService;
    authService;
    settingsStore;
    logger;
    isTypeormMode;
    constructor({ userService, configService, roleService, settingsStore, authService, loggerFactory, isTypeormMode }){
        this.userService = userService;
        this.configService = configService;
        this.roleService = roleService;
        this.authService = authService;
        this.settingsStore = settingsStore;
        this.isTypeormMode = isTypeormMode;
        this.logger = loggerFactory(UserController.name);
    }
    async list(req, res) {
        const users = await this.userService.listUsers();
        res.send(users.map((u)=>this.userService.toDto(u)));
    }
    async create(req, res) {
        const { username, password, roleIds } = await (0, _validators.validateMiddleware)(req, (0, _usercontrollervalidation.registerUserWithRolesRules)(this.isTypeormMode));
        if (username.toLowerCase().includes("admin") || username.toLowerCase().includes("root") || username.toLowerCase() === "demo") {
            throw new _runtimeexceptions.BadRequestException("Username is not allowed");
        }
        await this.userService.register({
            username,
            password,
            roles: roleIds,
            needsPasswordChange: false,
            isDemoUser: false,
            isRootUser: false,
            isVerified: true
        });
        res.send();
    }
    async listRoles(req, res) {
        const roleDtos = this.roleService.roles.map((r)=>this.roleService.toDto(r));
        res.send(roleDtos);
    }
    async profile(req, res) {
        if (!req.user?.id) {
            res.send({});
            return;
        }
        const user = await this.userService.getUser(req.user?.id);
        res.send(this.userService.toDto(user));
    }
    async get(req, res) {
        const { id } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        const user = await this.userService.getUser(id);
        res.send(this.userService.toDto(user));
    }
    async delete(req, res) {
        const { id } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        const ownUserId = req.user?.id;
        if (ownUserId == id) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to delete own account");
        }
        const isRootUser = await this.userService.isUserRootUser(id);
        if (isRootUser) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to delete root user");
        }
        if (this.configService.isDemoMode()) {
            const demoUserId = await this.userService.getDemoUserId();
            if (id === demoUserId) {
                this.throwIfDemoMode();
            }
        }
        await this.userService.deleteUser(id);
        try {
            await this.authService.logoutUserId(id);
        } catch (e) {
            this.logger.error((0, _errorutils.errorSummary)(e));
        }
        res.send();
    }
    async changeUsername(req, res) {
        const { id } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        if (req.user?.id != id && await this.settingsStore.getLoginRequired()) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change username of other users");
        }
        const { username } = await (0, _validators.validateInput)(req.body, {
            username: "required|string"
        });
        await this.userService.updateUsernameById(id, username);
        res.send();
    }
    async changePassword(req, res) {
        const { id } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        if (req.user?.id != id && await this.settingsStore.getLoginRequired()) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change password of other users");
        }
        const { oldPassword, newPassword } = await (0, _validators.validateInput)(req.body, {
            oldPassword: "required|string",
            newPassword: "required|string"
        });
        await this.userService.updatePasswordById(id, oldPassword, newPassword);
        res.send();
    }
    async setUserRoles(req, res) {
        const { id: currentUserId } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        const ownUserId = req.user?.id;
        const ownUser = await this.userService.getUser(ownUserId);
        const ownUserRoles = ownUser.roles;
        const adminRole = await this.roleService.getSynchronizedRoleByName(_authorizationconstants.ROLES.ADMIN);
        if (ownUserId == currentUserId && !ownUserRoles.includes(adminRole.id) && !ownUser.isRootUser) {
            throw new _runtimeexceptions.ForbiddenError("Only an ADMIN or OWNER user is allowed to change its own roles");
        }
        const { roleIds } = await (0, _validators.validateInput)(req.body, {
            roleIds: "array",
            "roleIds.*": "alphaNumeric"
        });
        if (ownUserId == currentUserId && !roleIds.includes(adminRole.id)) {
            if (ownUser.isRootUser) {
                throw new _runtimeexceptions.BadRequestException("It does not make sense to remove ADMIN role from an OWNER user.");
            } else {
                throw new _runtimeexceptions.BadRequestException("An ADMIN user cannot remove its ADMIN role.");
            }
        }
        await this.userService.setUserRoleIds(currentUserId, roleIds);
        res.send();
    }
    async setVerified(req, res) {
        const { id } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        const ownUserId = req.user?.id;
        if (ownUserId == id) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change own verified status");
        }
        const isRootUser = await this.userService.isUserRootUser(id);
        if (isRootUser) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change root user to unverified");
        }
        const { isVerified } = await (0, _validators.validateInput)(req.body, {
            isVerified: "required|boolean"
        });
        await this.userService.setVerifiedById(id, isVerified);
        res.send();
    }
    async setRootUser(req, res) {
        const { id } = await (0, _validators.validateInput)(req.params, (0, _genericvalidation.idRulesV2)(this.isTypeormMode));
        const userId = req.user?.id;
        if (req.user?.id) {
            const isRootUser = await this.userService.isUserRootUser(userId);
            if (!isRootUser) {
                throw new _runtimeexceptions.ForbiddenError("Not allowed to change owner without being owner yourself");
            }
        }
        const { isRootUser } = await (0, _validators.validateInput)(req.body, {
            isRootUser: "required|boolean"
        });
        await this.userService.setIsRootUserById(id, isRootUser);
        res.send();
    }
    throwIfDemoMode() {
        const isDemoMode = this.configService.isDemoMode();
        if (isDemoMode) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed in demo mode");
        }
    }
}
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ])
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "list", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ])
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "create", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/roles"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "listRoles", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/profile"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "profile", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/:id"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ])
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "get", null);
_ts_decorate([
    (0, _awilixexpress.DELETE)(),
    (0, _awilixexpress.route)("/:id"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ]),
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "delete", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/change-username"),
    (0, _awilixexpress.before)([
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "changeUsername", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/change-password"),
    (0, _awilixexpress.before)([
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "changePassword", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/set-user-roles"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ]),
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "setUserRoles", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/set-verified"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authorizeRoles)([
            _authorizationconstants.ROLES.ADMIN
        ]),
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "setVerified", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/:id/set-root-user"),
    (0, _awilixexpress.before)([
        _demomiddleware.demoUserNotAllowed
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _express.Request === "undefined" ? Object : _express.Request,
        typeof _express.Response === "undefined" ? Object : _express.Response
    ]),
    _ts_metadata("design:returntype", Promise)
], UserController.prototype, "setRootUser", null);
UserController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/user"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)()
    ]),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        Object
    ])
], UserController);

//# sourceMappingURL=user.controller.js.map