"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    AuthController: function() {
        return AuthController;
    },
    default: function() {
        return _default;
    }
});
const _awilixexpress = require("awilix-express");
const _runtimeexceptions = require("../exceptions/runtime.exceptions");
const _serverconstants = require("../server.constants");
const _validators = require("../handlers/validators");
const _usercontrollervalidation = require("./validation/user-controller.validation");
const _authcontrollervalidation = require("./validation/auth-controller.validation");
const _authenticate = require("../middleware/authenticate");
const _demomiddleware = require("../middleware/demo.middleware");
class AuthController {
    authService;
    settingsStore;
    userService;
    roleService;
    logger;
    configService;
    constructor({ authService, settingsStore, userService, roleService, loggerFactory, 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.refreshTokenRules);
        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.registerUserRules);
        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.getAppDefaultRoleIds();
        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);
    }
}
const _default = (0, _awilixexpress.createController)(AuthController).prefix(_serverconstants.AppConstants.apiRoute + "/auth").post("/register", "register", _demomiddleware.demoUserNotAllowedInterceptor).post("/login", "login").get("/login-required", "getLoginRequired").post("/needs-password-change", "needsPasswordChange").post("/refresh", "refreshLogin").post("/verify", "verifyLogin", {
    before: [
        (0, _authenticate.authenticate)()
    ]
}).post("/logout", "logout", {
    before: [
        (0, _authenticate.authenticate)()
    ]
});

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