"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 _runtimeexceptions = require("../exceptions/runtime.exceptions");
const _configservice = require("../services/core/config.service");
const _userserviceinterface = require("../services/interfaces/user-service.interface");
const _demomiddleware = require("../middleware/demo.middleware");
const _roleserviceinterface = require("../services/interfaces/role-service.interface");
const _authserviceinterface = require("../services/interfaces/auth.service.interface");
const _loggerfactory = require("../handlers/logger-factory");
const _errorutils = require("../utils/error.utils");
const _settingsstore = require("../state/settings.store");
const _awilixexpress = require("awilix-express");
const _usercontrollervalidation = require("./validation/user-controller.validation");
const _paramconvertermiddleware = require("../middleware/param-converter.middleware");
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;
    configService;
    roleService;
    authService;
    settingsStore;
    logger;
    constructor(loggerFactory, userService, configService, roleService, authService, settingsStore){
        this.userService = userService;
        this.configService = configService;
        this.roleService = roleService;
        this.authService = authService;
        this.settingsStore = settingsStore;
        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, roles } = await (0, _validators.validateMiddleware)(req, _usercontrollervalidation.registerUserWithRolesSchema);
        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,
            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 user = await this.userService.getUser(req.local.id);
        res.send(this.userService.toDto(user));
    }
    async delete(req, res) {
        const deletedUserId = req.local.id;
        const ownUserId = req.user?.id;
        if (ownUserId == deletedUserId) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to delete own account");
        }
        const isRootUser = await this.userService.isUserRootUser(deletedUserId);
        if (isRootUser) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to delete root user");
        }
        if (this.configService.isDemoMode()) {
            const demoUserId = await this.userService.getDemoUserId();
            if (deletedUserId === demoUserId) {
                this.throwIfDemoMode();
            }
        }
        await this.userService.deleteUser(deletedUserId);
        try {
            await this.authService.logoutUserId(deletedUserId);
        } catch (e) {
            this.logger.error((0, _errorutils.errorSummary)(e));
        }
        res.send();
    }
    async changeUsername(req, res) {
        const changedUserId = req.local.id;
        if (req.user?.id != changedUserId && await this.settingsStore.getLoginRequired()) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change username of other users");
        }
        const { username } = await (0, _validators.validateInput)(req.body, _usercontrollervalidation.usernameSchema);
        await this.userService.updateUsernameById(changedUserId, username);
        res.send();
    }
    async changePassword(req, res) {
        const changedUserId = req.local.id;
        if (req.user?.id != changedUserId && 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, _usercontrollervalidation.changePasswordSchema);
        await this.userService.updatePasswordById(changedUserId, oldPassword, newPassword);
        res.send();
    }
    async setUserRoles(req, res) {
        const changedUserId = req.local.id;
        const ownUserId = req.user?.id;
        if (!ownUserId) {
            throw new _runtimeexceptions.ForbiddenError("Need to be logged in, in order to set user roles");
        }
        const ownUser = await this.userService.getUser(ownUserId);
        const mappedUser = this.userService.toDto(ownUser);
        const ownUserRoles = mappedUser.roles;
        if (ownUserId == changedUserId && !ownUserRoles.includes(_authorizationconstants.ROLES.ADMIN) && !mappedUser.isRootUser) {
            throw new _runtimeexceptions.ForbiddenError("Only an ADMIN or OWNER user is allowed to change its own roles");
        }
        const { roles } = await (0, _validators.validateInput)(req.body, _usercontrollervalidation.setUserRolesSchema);
        if (ownUserId == changedUserId && !roles.includes(_authorizationconstants.ROLES.ADMIN)) {
            if (mappedUser.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.setUserRoles(changedUserId, roles);
        res.send();
    }
    async setVerified(req, res) {
        const changedUserId = req.local.id;
        const ownUserId = req.user?.id;
        if (ownUserId == changedUserId) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change own verified status");
        }
        const isRootUser = await this.userService.isUserRootUser(changedUserId);
        if (isRootUser) {
            throw new _runtimeexceptions.ForbiddenError("Not allowed to change root user to unverified");
        }
        const { isVerified } = await (0, _validators.validateInput)(req.body, _usercontrollervalidation.isVerifiedSchema);
        await this.userService.setVerifiedById(changedUserId, isVerified);
        res.send();
    }
    async setRootUser(req, res) {
        const changedUserId = req.local.id;
        const userId = req.user?.id;
        if (userId) {
            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, _usercontrollervalidation.isRootUserSchema);
        await this.userService.setIsRootUserById(changedUserId, 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
        ]),
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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,
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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,
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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,
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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,
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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,
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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,
        (0, _paramconvertermiddleware.ParamId)("id")
    ]),
    _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", [
        typeof _loggerfactory.ILoggerFactory === "undefined" ? Object : _loggerfactory.ILoggerFactory,
        typeof _userserviceinterface.IUserService === "undefined" ? Object : _userserviceinterface.IUserService,
        typeof _configservice.IConfigService === "undefined" ? Object : _configservice.IConfigService,
        typeof _roleserviceinterface.IRoleService === "undefined" ? Object : _roleserviceinterface.IRoleService,
        typeof _authserviceinterface.IAuthService === "undefined" ? Object : _authserviceinterface.IAuthService,
        typeof _settingsstore.SettingsStore === "undefined" ? Object : _settingsstore.SettingsStore
    ])
], UserController);

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