"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "AuthController", {
    enumerable: true,
    get: function() {
        return AuthController;
    }
});
const _awilixexpress = require("awilix-express");
const _runtimeexceptions = require("../exceptions/runtime.exceptions");
const _serverconstants = require("../server.constants");
const _authcontrollervalidation = require("./validation/auth-controller.validation");
const _authenticate = require("../middleware/authenticate");
const _settingsstore = require("../state/settings.store");
const _loggerfactory = require("../handlers/logger-factory");
const _express = require("express");
const _userserviceinterface = require("../services/interfaces/user-service.interface");
const _authserviceinterface = require("../services/interfaces/auth.service.interface");
const _roleserviceinterface = require("../services/interfaces/role-service.interface");
const _demomiddleware = require("../middleware/demo.middleware");
const _configservice = require("../services/core/config.service");
const _usercontrollervalidation = require("./validation/user-controller.validation");
const _validators = require("../handlers/validators");
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 AuthController {
    authService;
    settingsStore;
    userService;
    roleService;
    configService;
    logger;
    constructor(loggerFactory, authService, settingsStore, userService, roleService, configService){
        this.authService = authService;
        this.settingsStore = settingsStore;
        this.userService = userService;
        this.roleService = roleService;
        this.configService = configService;
        this.logger = loggerFactory(AuthController.name);
    }
    async login(req, res) {
        this.logger.debug(`Login attempt from IP ${req.ip} and user-agent ${req.headers["user-agent"]}`);
        const tokens = await this.authService.loginUser(req.body.username, req.body.password);
        return res.send(tokens);
    }
    async getLoginRequired(req, res) {
        const loginRequired = await this.settingsStore.getLoginRequired();
        const registration = this.settingsStore.isRegistrationEnabled();
        let wizardState = this.settingsStore.getWizardState();
        const isDemoMode = this.configService.isDemoMode();
        wizardState = {
            ...wizardState,
            wizardCompleted: isDemoMode ? true : wizardState.wizardCompleted
        };
        res.send({
            loginRequired,
            registration,
            wizardState,
            isDemoMode
        });
    }
    async verifyLogin(req, res) {
        return res.send({
            success: true
        });
    }
    async needsPasswordChange(req, res) {
        const registration = this.settingsStore.isRegistrationEnabled();
        const isLoginRequired = await this.settingsStore.getLoginRequired();
        if (!isLoginRequired) {
            return res.send({
                loginRequired: isLoginRequired,
                registration,
                needsPasswordChange: false,
                authenticated: true
            });
        }
        if (req.isAuthenticated()) {
            return res.send({
                loginRequired: isLoginRequired,
                registration,
                needsPasswordChange: req.user?.needsPasswordChange,
                authenticated: true
            });
        }
        return res.send({
            loginRequired: isLoginRequired,
            needsPasswordChange: null,
            authenticated: false
        });
    }
    async refreshLogin(req, res) {
        const { refreshToken } = await (0, _validators.validateMiddleware)(req, _authcontrollervalidation.refreshTokenSchema);
        this.logger.debug(`Refresh login attempt from IP ${req.ip} and user-agent ${req.headers["user-agent"]}`);
        const idToken = await this.authService.renewLoginByRefreshToken(refreshToken);
        return res.send({
            token: idToken
        });
    }
    async logout(req, res) {
        const isLoginRequired = await this.settingsStore.getLoginRequired();
        if (!isLoginRequired) {
            return res.end();
        }
        const jwtToken = req.headers.authorization?.replace("Bearer ", "") || undefined;
        const userId = req.user.id;
        await this.authService.logoutUserId(userId, jwtToken);
        res.end();
    }
    async register(req, res) {
        let registrationEnabled = this.settingsStore.isRegistrationEnabled();
        if (!registrationEnabled) {
            throw new _runtimeexceptions.BadRequestException("Registration is disabled. Cant register user");
        }
        const { username, password } = await (0, _validators.validateMiddleware)(req, _usercontrollervalidation.registerUserSchema);
        if (username.toLowerCase().includes("admin") || username.toLowerCase().includes("root") || username.toLowerCase() === "demo") {
            throw new _runtimeexceptions.BadRequestException("Username is not allowed");
        }
        const roles = await this.roleService.getAppDefaultRoleNames();
        const result = await this.userService.register({
            username,
            password,
            roles,
            needsPasswordChange: false,
            isDemoUser: false,
            isRootUser: false,
            isVerified: false
        });
        const userDto = this.userService.toDto(result);
        res.send(userDto);
    }
}
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/login"),
    _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)
], AuthController.prototype, "login", null);
_ts_decorate([
    (0, _awilixexpress.GET)(),
    (0, _awilixexpress.route)("/login-required"),
    _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)
], AuthController.prototype, "getLoginRequired", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/verify"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)()
    ]),
    _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)
], AuthController.prototype, "verifyLogin", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/needs-password-change"),
    _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)
], AuthController.prototype, "needsPasswordChange", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/refresh"),
    _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)
], AuthController.prototype, "refreshLogin", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/logout"),
    (0, _awilixexpress.before)([
        (0, _authenticate.authenticate)()
    ]),
    _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)
], AuthController.prototype, "logout", null);
_ts_decorate([
    (0, _awilixexpress.POST)(),
    (0, _awilixexpress.route)("/register"),
    (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)
], AuthController.prototype, "register", null);
AuthController = _ts_decorate([
    (0, _awilixexpress.route)(_serverconstants.AppConstants.apiRoute + "/auth"),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [
        typeof _loggerfactory.ILoggerFactory === "undefined" ? Object : _loggerfactory.ILoggerFactory,
        typeof _authserviceinterface.IAuthService === "undefined" ? Object : _authserviceinterface.IAuthService,
        typeof _settingsstore.SettingsStore === "undefined" ? Object : _settingsstore.SettingsStore,
        typeof _userserviceinterface.IUserService === "undefined" ? Object : _userserviceinterface.IUserService,
        typeof _roleserviceinterface.IRoleService === "undefined" ? Object : _roleserviceinterface.IRoleService,
        typeof _configservice.IConfigService === "undefined" ? Object : _configservice.IConfigService
    ])
], AuthController);

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