"use strict";
var __decorate = (this && this.__decorate) || function (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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const user_entity_1 = require("../../user/entities/user.entity");
const auth_constants_1 = require("../../auth.constants");
const mfa_service_1 = require("./mfa.service");
const jwt_service_1 = require("../../core/services/jwt.service");
const event_emitter_1 = require("@nestjs/event-emitter");
const session_manager_service_1 = require("../../session/services/session-manager.service");
const request_context_1 = require("../../request-context/request-context");
const user_registered_event_1 = require("../events/user-registered.event");
const user_logged_in_event_1 = require("../events/user-logged-in.event");
const user_2fa_verified_event_1 = require("../events/user-2fa-verified.event");
const user_refresh_token_event_1 = require("../events/user-refresh-token.event");
const logged_out_event_1 = require("../events/logged-out.event");
const logged_out_all_event_1 = require("../events/logged-out-all.event");
const auth_provider_registry_service_1 = require("../../core/services/auth-provider-registry.service");
const tenant_service_1 = require("../../tenant/services/tenant.service");
const debug_logger_service_1 = require("../../core/services/debug-logger.service");
const auth_config_service_1 = require("../../core/services/auth-config.service");
const cookie_helper_1 = require("../../utils/cookie.helper");
const user_service_1 = require("../../user/services/user.service");
let AuthService = class AuthService {
    userRepository;
    authProviderRegistry;
    mfaService;
    sessionManager;
    jwtService;
    eventEmitter;
    tenantService;
    debugLogger;
    authConfigService;
    userService;
    constructor(userRepository, authProviderRegistry, mfaService, sessionManager, jwtService, eventEmitter, tenantService, debugLogger, authConfigService, userService) {
        this.userRepository = userRepository;
        this.authProviderRegistry = authProviderRegistry;
        this.mfaService = mfaService;
        this.sessionManager = sessionManager;
        this.jwtService = jwtService;
        this.eventEmitter = eventEmitter;
        this.tenantService = tenantService;
        this.debugLogger = debugLogger;
        this.authConfigService = authConfigService;
        this.userService = userService;
    }
    getUserWithRolesAndPermissions(userId, relations = []) {
        return this.userRepository.findOne({
            where: { id: userId },
            relations: [
                'roles',
                ...relations
            ],
        });
    }
    async getUser() {
        const user = request_context_1.RequestContext.currentUser();
        if (!user) {
            return null;
        }
        const fullUser = await this.getUserWithRolesAndPermissions(user.id);
        const config = this.authConfigService.getConfig();
        if (config.user?.serialize) {
            return await config.user.serialize(fullUser);
        }
        return fullUser;
    }
    async signup(input) {
        this.debugLogger.logFunctionEntry('signup', 'AuthService', { email: input.email, phone: input.phone, hasPassword: !!input.password });
        try {
            const config = this.authConfigService.getConfig();
            if (config.registration?.enabled === false) {
                throw new common_1.ForbiddenException({
                    message: 'Registration is disabled',
                    code: auth_constants_1.ERROR_CODES.REGISTRATION_DISABLED,
                });
            }
            const { email, phone, password } = input;
            let { tenantId = null } = input;
            if (config.registrationHooks?.beforeSignup) {
                const req = request_context_1.RequestContext.currentRequest();
                await config.registrationHooks.beforeSignup(input, { request: req });
            }
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            this.debugLogger.logAuthOperation('signup', 'email|phone', undefined, { email, phone, resolvedTenantId: tenantId });
            if (!email && !phone) {
                this.debugLogger.error('Signup failed: Neither email nor phone provided', 'AuthService');
                throw new common_1.BadRequestException({
                    message: 'Either email or phone must be provided',
                    code: auth_constants_1.ERROR_CODES.EMAIL_OR_PHONE_REQUIRED,
                });
            }
            const providersToLink = [];
            if (email && config.emailAuth?.enabled !== false) {
                const provider = this.authProviderRegistry.getProvider(auth_constants_1.EMAIL_AUTH_PROVIDER);
                if (provider) {
                    providersToLink.push({ provider, userId: email, type: 'email' });
                }
            }
            if (phone && config.phoneAuth?.enabled === true) {
                const provider = this.authProviderRegistry.getProvider(auth_constants_1.PHONE_AUTH_PROVIDER);
                if (provider) {
                    providersToLink.push({ provider, userId: phone, type: 'phone' });
                }
            }
            if (providersToLink.length === 0) {
                this.debugLogger.error('Provider not found for signup', 'AuthService', { email: !!email, phone: !!phone });
                throw new common_1.InternalServerErrorException({
                    message: 'Phone or email authentication is not enabled',
                    code: auth_constants_1.ERROR_CODES.PROVIDER_NOT_FOUND,
                });
            }
            for (const item of providersToLink) {
                this.debugLogger.debug('Checking for existing identity', 'AuthService', { providerUserId: item.userId, type: item.type });
                const identity = await item.provider.findIdentity(item.userId);
                if (identity) {
                    this.debugLogger.warn('Identity already exists', 'AuthService', { email: !!email, phone: !!phone, tenantId });
                    if (item.type === 'email') {
                        throw new common_1.BadRequestException({
                            message: 'Email already exists in this tenant',
                            code: auth_constants_1.ERROR_CODES.EMAIL_ALREADY_EXISTS,
                        });
                    }
                    if (item.type === 'phone') {
                        throw new common_1.BadRequestException({
                            message: 'Phone number already exists in this tenant',
                            code: auth_constants_1.ERROR_CODES.PHONE_ALREADY_EXISTS,
                        });
                    }
                }
            }
            this.debugLogger.debug('Creating new user via UserService', 'AuthService', { email: !!email, phone: !!phone, tenantId });
            let user = await this.userService.createUser({
                email,
                phone,
                tenantId,
                isVerified: false,
                password
            }, input);
            this.debugLogger.info('User created successfully', 'AuthService', { userId: user.id, tenantId });
            for (const item of providersToLink) {
                this.debugLogger.debug('Linking user to provider', 'AuthService', { userId: user.id, providerName: item.provider.providerName });
                await item.provider.linkToUser(user.id, item.userId);
            }
            if (config.registrationHooks?.onSignup) {
                this.debugLogger.debug('Applying registrationHooks.onSignup hook', 'AuthService', { userId: user.id });
                const request = request_context_1.RequestContext.currentRequest();
                const modifiedUser = await config.registrationHooks.onSignup(user, input, { request });
                if (modifiedUser) {
                    user = modifiedUser;
                }
            }
            user = await this.getUserWithRolesAndPermissions(user.id);
            if (input?.guard && user.roles) {
                const isExistsGuard = user.roles.some(r => r.guard === input.guard);
                if (!isExistsGuard) {
                    await this.userService.deleteUser(user.id);
                    throw new common_1.UnauthorizedException({
                        message: 'Not allowed to signup with this guard',
                        code: auth_constants_1.ERROR_CODES.FORBIDDEN,
                    });
                }
            }
            this.debugLogger.debug('Creating session for new user', 'AuthService', { userId: user.id });
            const session = await this.sessionManager.createSessionFromUser(user);
            const tokens = await this.generateTokensFromSession(session);
            const isRequiresMfa = await this.mfaService.isRequiresMfa(user.id);
            this.debugLogger.debug('Signup tokens generated', 'AuthService', { userId: user.id, isRequiresMfa });
            this.debugLogger.debug('Emitting user registration event', 'AuthService', { userId: user.id });
            const provider = providersToLink[0]?.provider;
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.REGISTERED, new user_registered_event_1.UserRegisteredEvent({
                user,
                tenantId: user.tenantId,
                input,
                provider,
                session,
                tokens,
                isRequiresMfa
            }));
            this.debugLogger.logFunctionExit('signup', 'AuthService', { userId: user.id, isRequiresMfa });
            const autoLoginAfterSignup = config.registration?.autoLoginAfterSignup !== false;
            if (!autoLoginAfterSignup) {
                return {
                    message: 'Account created successfully. Please login.',
                    accessToken: '',
                    refreshToken: '',
                    isRequiresMfa: false,
                };
            }
            return this.generateAuthResponse(user, session, tokens, isRequiresMfa);
        }
        catch (error) {
            this.debugLogger.logError(error, 'signup', { email: input.email, phone: input.phone });
            this.handleError(error, 'signup');
            throw error;
        }
    }
    async login(input) {
        let { credentials, providerName, createUserIfNotExists = false, guard } = input;
        this.debugLogger.logFunctionEntry('login', 'AuthService', { providerName, createUserIfNotExists, guard });
        let { tenantId = null } = input;
        try {
            const config = this.authConfigService.getConfig();
            tenantId = await this.tenantService.resolveTenantId(tenantId);
            this.debugLogger.logAuthOperation('login', providerName, undefined, { resolvedTenantId: tenantId, createUserIfNotExists });
            const provider = this.authProviderRegistry.getProvider(providerName);
            if (!provider) {
                throw new common_1.UnauthorizedException({
                    message: 'Invalid authentication providerName or provider is not enabled',
                    code: auth_constants_1.ERROR_CODES.INVALID_PROVIDER,
                });
            }
            const requiredFields = provider.getRequiredFields();
            if (!requiredFields.every(field => credentials[field])) {
                throw new common_1.BadRequestException({
                    message: `Missing ${requiredFields.join(', ')} required fields`,
                    code: auth_constants_1.ERROR_CODES.MISSING_REQUIRED_FIELDS,
                });
            }
            const authProviderUser = await provider.validate(credentials);
            const identity = await provider.findIdentity(authProviderUser.userId);
            let user = identity?.user || null;
            if (!user) {
                if (!createUserIfNotExists) {
                    throw new common_1.UnauthorizedException({
                        message: 'Invalid credentials',
                        code: auth_constants_1.ERROR_CODES.INVALID_CREDENTIALS,
                    });
                }
                user = await this.handleSocialLogin(provider, authProviderUser, tenantId);
            }
            if (user.isActive === false) {
                throw new common_1.UnauthorizedException({
                    message: 'Your account is suspended, please contact support',
                    code: auth_constants_1.ERROR_CODES.ACCOUNT_INACTIVE,
                });
            }
            if (config.loginHooks?.onLogin) {
                this.debugLogger.debug('Applying loginHooks.onLogin hook', 'AuthService', { userId: user.id });
                const request = request_context_1.RequestContext.currentRequest();
                const modifiedUser = await config.loginHooks.onLogin(user, input, { request, provider });
                if (modifiedUser) {
                    user = modifiedUser;
                }
            }
            user = await this.getUserWithRolesAndPermissions(user.id);
            let isRequiresMfa = false;
            let isTrusted = false;
            if (!provider.skipMfa) {
                isRequiresMfa = await this.mfaService.isRequiresMfa(user.id);
            }
            user.isMfaEnabled = isRequiresMfa;
            if (guard && user.roles) {
                const isExistsGuard = user.roles.some(r => r.guard === guard);
                if (!isExistsGuard) {
                    throw new common_1.UnauthorizedException({
                        message: 'Invalid credentials',
                        code: auth_constants_1.ERROR_CODES.INVALID_CREDENTIALS,
                    });
                }
            }
            let session = await this.sessionManager.createSessionFromUser(user);
            if (isRequiresMfa) {
                isTrusted = await this.checkTrustedDevice(user);
                if (isTrusted) {
                    isRequiresMfa = false;
                }
                session = await this.sessionManager.updateSession(session.id, {
                    data: { ...session.data, isMfaEnabled: true, isMfaVerified: isTrusted }
                });
            }
            const tokens = await this.generateTokensFromSession(session);
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.LOGGED_IN, new user_logged_in_event_1.UserLoggedInEvent({
                user,
                tenantId: user.tenantId,
                input,
                provider,
                session,
                tokens,
                isRequiresMfa
            }));
            return this.generateAuthResponse(user, session, tokens, isRequiresMfa);
        }
        catch (error) {
            this.debugLogger.logError(error, 'login', { providerName, createUserIfNotExists });
            this.handleError(error, 'login');
            throw error;
        }
    }
    async verify2fa(input) {
        this.debugLogger.logFunctionEntry('verify2fa', 'AuthService', { method: input.method });
        try {
            const session = request_context_1.RequestContext.currentSession();
            if (!session) {
                this.debugLogger.error('Session not found for 2FA verification', 'AuthService');
                throw new common_1.UnauthorizedException({
                    message: 'Session not found',
                    code: auth_constants_1.ERROR_CODES.SESSION_NOT_FOUND,
                });
            }
            this.debugLogger.debug('Verifying MFA code', 'AuthService', { userId: session.userId, method: input.method });
            const isValid = await this.mfaService.verifyMfa(session.userId, input.otp, input.method);
            if (!isValid) {
                this.debugLogger.warn('Invalid MFA code provided', 'AuthService', { userId: session.userId, method: input.method });
                throw new common_1.UnauthorizedException({
                    message: 'Invalid MFA code',
                    code: auth_constants_1.ERROR_CODES.MFA_CODE_INVALID,
                });
            }
            this.debugLogger.debug('Updating session with MFA verification', 'AuthService', { sessionId: session.id });
            const payload = await this.sessionManager.updateSession(session.id, {
                data: {
                    ...session.data,
                    isMfaVerified: true,
                }
            });
            const tokens = await this.generateTokensFromSession(payload);
            let trustToken;
            if (input.rememberDevice) {
                const req = request_context_1.RequestContext.currentRequest();
                if (req) {
                    const userAgent = (req.headers['user-agent'] || '');
                    const ip = (req.ip || req.socket.remoteAddress || '');
                    trustToken = await this.mfaService.createTrustedDevice(session.userId, userAgent, ip);
                }
            }
            const user = await this.getUser();
            this.debugLogger.debug('Emitting 2FA verified event', 'AuthService', { userId: user.id });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.TWO_FACTOR_VERIFIED, new user_2fa_verified_event_1.User2faVerifiedEvent({
                user: user,
                tenantId: user?.tenantId,
                input,
                session,
                tokens
            }));
            this.debugLogger.logFunctionExit('verify2fa', 'AuthService', { userId: user.id });
            return {
                accessToken: tokens.accessToken,
                refreshToken: tokens.refreshToken,
                trustToken,
            };
        }
        catch (error) {
            this.debugLogger.logError(error, 'verify2fa', { method: input.method });
            this.handleError(error, 'mfa');
            throw error;
        }
    }
    async send2faCode(userId, method) {
        const user = await this.userRepository.findOne({ where: { id: userId } });
        if (!user) {
            throw new common_1.UnauthorizedException({
                message: 'User not found',
                code: auth_constants_1.ERROR_CODES.USER_NOT_FOUND,
            });
        }
        await this.mfaService.sendMfaCode(user.id, method);
        return true;
    }
    async handleSocialLogin(provider, providerUser, tenantId) {
        let identity = await provider.findIdentity(providerUser.userId);
        if (identity) {
            return identity.user;
        }
        const linkUserWith = provider.linkUserWith();
        const linkUserValue = providerUser?.[linkUserWith] || providerUser.userId;
        let user = await this.userRepository.findOne({ where: { [linkUserWith]: linkUserValue } });
        if (!user) {
            try {
                user = await this.userService.createUser({
                    [linkUserWith]: linkUserValue,
                    isVerified: true,
                    metadata: providerUser.metadata || {},
                    tenantId: tenantId,
                }, {
                    [linkUserWith]: linkUserValue,
                    ...providerUser,
                    firstName: providerUser.metadata?.name?.split(' ')[0],
                    lastName: providerUser.metadata?.name?.split(' ').slice(1).join(' '),
                    provider: provider.providerName,
                    description: 'Social login auto-creation'
                });
            }
            catch (error) {
                if (error instanceof common_1.ConflictException || error.status === 409) {
                    user = await this.userRepository.findOne({ where: { [linkUserWith]: linkUserValue } });
                    if (!user) {
                        throw error;
                    }
                }
                else {
                    throw error;
                }
            }
        }
        await provider.linkToUser(user.id, providerUser.userId, providerUser.metadata || {});
        return user;
    }
    async refreshToken(refreshToken) {
        this.debugLogger.logFunctionEntry('refreshToken', 'AuthService', { hasRefreshToken: !!refreshToken });
        try {
            if (!refreshToken) {
                this.debugLogger.error('No refresh token provided', 'AuthService');
                throw new common_1.UnauthorizedException({
                    message: 'No refresh token provided',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_INVALID,
                });
            }
            this.debugLogger.debug('Verifying refresh token', 'AuthService');
            let payload;
            try {
                payload = await this.jwtService.verifyToken(refreshToken);
            }
            catch (error) {
                this.debugLogger.warn('Invalid or expired refresh token', 'AuthService');
                throw new common_1.UnauthorizedException({
                    message: 'Invalid or expired refresh token',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_EXPIRED,
                });
            }
            if (!payload.sessionId) {
                throw new common_1.UnauthorizedException({
                    message: 'Invalid refresh token payload',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_INVALID,
                });
            }
            const session = await this.sessionManager.getSession(payload.sessionId);
            if (!session) {
                throw new common_1.UnauthorizedException({
                    message: 'Invalid refresh token',
                    code: auth_constants_1.ERROR_CODES.REFRESH_TOKEN_INVALID,
                });
            }
            const newSession = await this.sessionManager.refreshSession(session);
            this.debugLogger.debug('Generating new tokens from refreshed session', 'AuthService', { sessionId: newSession.id });
            const tokens = await this.generateTokensFromSession(newSession);
            this.debugLogger.debug('Emitting refresh token event', 'AuthService', { sessionId: newSession.id });
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.REFRESH_TOKEN, new user_refresh_token_event_1.UserRefreshTokenEvent({
                oldRefreshToken: refreshToken,
                session: newSession,
                tokens,
            }));
            this.debugLogger.logFunctionExit('refreshToken', 'AuthService', { sessionId: newSession.id });
            return tokens;
        }
        catch (error) {
            this.debugLogger.logError(error, 'refreshToken', { hasRefreshToken: !!refreshToken });
            this.handleError(error, 'refresh');
            throw error;
        }
    }
    async logout(logoutType = 'user', reason) {
        const session = request_context_1.RequestContext.currentSession();
        const user = await this.getUser();
        if (session) {
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.LOGGED_OUT, new logged_out_event_1.LoggedOutEvent({
                user: user,
                tenantId: user?.tenantId,
                session,
                logoutType,
                reason,
            }));
            await this.sessionManager.revokeSession(session.id);
        }
        return true;
    }
    async logoutAll(userId, logoutType = 'user', reason) {
        const sessions = await this.sessionManager.getUserSessions(userId);
        await this.sessionManager.revokeAllUserSessions(userId);
        const user = await this.userRepository.findOne({ where: { id: userId } });
        if (user) {
            await this.eventEmitter.emitAsync(auth_constants_1.NestAuthEvents.LOGGED_OUT_ALL, new logged_out_all_event_1.LoggedOutAllEvent({
                user,
                tenantId: user.tenantId,
                logoutType,
                reason,
                sessions,
            }));
        }
        return true;
    }
    async generateTokensPayload(session, otherPayload = {}) {
        let payload = {
            id: session.userId,
            sub: session.userId,
            sessionId: session.id,
            email: session.data?.user?.email,
            phone: session.data?.user?.phone,
            isVerified: session.data?.user?.isVerified,
            roles: session.data?.roles?.map((r) => {
                delete r?.permissions;
                return { ...r };
            }),
            tenantId: session.data?.user?.tenantId,
            isMfaEnabled: session.data?.user?.isMfaEnabled,
            isMfaVerified: session.data?.isMfaVerified,
            ...otherPayload,
        };
        const config = this.authConfigService.getConfig();
        if (config.session?.customizeTokenPayload) {
            payload = await config.session.customizeTokenPayload(payload, session);
        }
        return payload;
    }
    handleError(error, context) {
        const config = this.authConfigService.getConfig();
        if (config.errorHandler) {
            const result = config.errorHandler(error, context);
            if (result) {
                throw result;
            }
        }
    }
    async generateTokensFromSession(session) {
        const payload = await this.generateTokensPayload(session);
        const tokens = await this.jwtService.generateTokens(payload);
        return tokens;
    }
    async generateAuthResponse(user, session, tokens, isRequiresMfa) {
        const config = this.authConfigService.getConfig();
        let serializedUser = user;
        if (config.user?.serialize) {
            serializedUser = await config.user.serialize(user);
        }
        const roleNames = user.roles?.map(r => r.name) || [];
        const permissions = this.extractPermissions(user);
        let response = {
            accessToken: tokens.accessToken,
            refreshToken: tokens.refreshToken,
            isRequiresMfa: isRequiresMfa,
            user: {
                id: serializedUser.id,
                email: serializedUser.email,
                phone: serializedUser.phone,
                isVerified: serializedUser.isVerified,
                isMfaEnabled: serializedUser.isMfaEnabled,
                roles: roleNames,
                permissions,
                metadata: serializedUser.metadata,
                tenantId: serializedUser.tenantId,
            },
        };
        if (isRequiresMfa) {
            const enabledMethods = await this.mfaService.getEnabledMethods(user.id);
            response.mfaMethods = enabledMethods;
            response.defaultMfaMethod = this.mfaService.mfaConfig?.defaultMethod || enabledMethods[0];
        }
        if (config.auth?.transformResponse) {
            response = await config.auth.transformResponse(response, user, session);
        }
        return response;
    }
    extractPermissions(user) {
        const permissions = new Set();
        if (user.roles) {
            for (const role of user.roles) {
                if (role.permissions) {
                    for (const perm of role.permissions) {
                        permissions.add(perm);
                    }
                }
            }
        }
        return Array.from(permissions);
    }
    async checkTrustedDevice(user) {
        const trustCookieName = auth_config_service_1.AuthConfigService.getOptions().mfa?.trustDeviceStorageName || auth_constants_1.NEST_AUTH_TRUST_DEVICE_KEY;
        const req = request_context_1.RequestContext.currentRequest();
        if (req) {
            let trustToken = cookie_helper_1.CookieHelper.get(req, trustCookieName);
            if (!trustToken) {
                trustToken = req.headers[trustCookieName];
            }
            if (trustToken) {
                return await this.mfaService.validateTrustedDevice(user.id, trustToken);
            }
        }
        return false;
    }
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(user_entity_1.NestAuthUser)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        auth_provider_registry_service_1.AuthProviderRegistryService,
        mfa_service_1.MfaService,
        session_manager_service_1.SessionManagerService,
        jwt_service_1.JwtService,
        event_emitter_1.EventEmitter2,
        tenant_service_1.TenantService,
        debug_logger_service_1.DebugLoggerService,
        auth_config_service_1.AuthConfigService,
        user_service_1.UserService])
], AuthService);
//# sourceMappingURL=auth.service.js.map