Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

2.5 KB
Raw Blame
import { ActivepiecesError, ErrorCode, isNil, UserId } from '@activepieces/core-utils'
import { ApplicationEvent, ApplicationEventName, OtpType, ResetPasswordRequestBody, UserIdentity, VerifyEmailRequestBody } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { otpService } from '../../../authentication/otp/otp-service'
import { userIdentityService } from '../../../authentication/user-identity/user-identity-service'
import { applicationEvents } from '../../../helper/application-events'
import { userService } from '../../../user/user-service'

export const enterpriseLocalAuthnService = (log: FastifyBaseLogger) => ({
    async verifyEmail({ identityId, otp }: VerifyEmailRequestBody): Promise<UserIdentity> {
        const isOtpValid = await otpService(log).confirm({
            identityId,
            type: OtpType.EMAIL_VERIFICATION,
            value: otp,
        })

        if (!isOtpValid) {
            throw new ActivepiecesError({
                code: ErrorCode.INVALID_OTP,
                params: {},
            })
        }

        await sendAuditLogForIdentity(identityId, {
            action: ApplicationEventName.USER_EMAIL_VERIFIED,
            data: {},
        }, log)

        return userIdentityService(log).verify(identityId)
    },

    async resetPassword({
        identityId,
        otp,
        newPassword,
    }: ResetPasswordRequestBody): Promise<void> {
        const isOtpValid = await otpService(log).confirm({
            identityId,
            type: OtpType.PASSWORD_RESET,
            value: otp,
        })

        if (!isOtpValid) {
            throw new ActivepiecesError({
                code: ErrorCode.INVALID_OTP,
                params: {},
            })
        }

        await sendAuditLogForIdentity(identityId, {
            action: ApplicationEventName.USER_PASSWORD_RESET,
            data: {},
        }, log)

        await userIdentityService(log).updatePassword({
            id: identityId,
            newPassword,
        })
    },
})

const sendAuditLogForIdentity = async (
    identityId: UserId,
    event: Pick<ApplicationEvent, 'action' | 'data'>,
    log: FastifyBaseLogger,
): Promise<void> => {
    const users = await userService(log).getUsersByIdentityId({ identityId })
    for (const { id, platformId } of users) {
        if (isNil(platformId)) {
            continue
        }
        applicationEvents(log).sendUserEvent(
            {
                platformId,
                userId: id,
            },
            event as ApplicationEvent,
        )
    }
}