Add Optional 2FA Support (#61)
* Add TOTP MFA Support * Add Passkey MFA Support It's not impossible I missed some minor cleanup, but most things make sense and there isn't a lot of obvious duplication anymore. --------- Co-authored-by: Bruno Bernardino <me@brunobernardino.com>
This commit is contained in:
119
routes/api/auth/multi-factor/disable.ts
Normal file
119
routes/api/auth/multi-factor/disable.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PASSWORD_SALT } from '/lib/auth.ts';
|
||||
import { generateHash } from '/lib/utils/misc.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import {
|
||||
getMultiFactorAuthMethodByIdFromUser,
|
||||
getMultiFactorAuthMethodsFromUser,
|
||||
} from '/lib/utils/multi-factor-auth.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
methodId?: string;
|
||||
password: string;
|
||||
disableAll?: boolean;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { methodId, password, disableAll } = body;
|
||||
|
||||
if (!password) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Password is required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const hashedPassword = await generateHash(`${password}:${PASSWORD_SALT}`, 'SHA-256');
|
||||
|
||||
if (user.hashed_password !== hashedPassword) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Invalid password',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
if (disableAll) {
|
||||
user.extra.multi_factor_auth_methods = [];
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
}
|
||||
|
||||
if (!methodId) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Method ID is required when not disabling all methods',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const methods = getMultiFactorAuthMethodsFromUser(user);
|
||||
const method = getMultiFactorAuthMethodByIdFromUser(user, methodId);
|
||||
|
||||
if (!method) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
if (!method.enabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method is not enabled',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
MultiFactorAuthModel.disableMethodFromUser(user, methodId);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
130
routes/api/auth/multi-factor/enable.ts
Normal file
130
routes/api/auth/multi-factor/enable.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
import { TOTPModel } from '/lib/models/multi-factor-auth/totp.ts';
|
||||
import { getMultiFactorAuthMethodByIdFromUser } from '/lib/utils/multi-factor-auth.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
methodId: string;
|
||||
code: string | 'passkey-verified';
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { methodId, code } = body;
|
||||
|
||||
if (!methodId || !code) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Method ID and verification code are required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const method = getMultiFactorAuthMethodByIdFromUser(user, methodId);
|
||||
if (!method) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
if (method.enabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication method is already enabled',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
if (method.type === 'totp') {
|
||||
const hashedSecret = method.metadata.totp?.hashed_secret;
|
||||
if (!hashedSecret) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'TOTP secret not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const secret = await TOTPModel.decryptTOTPSecret(hashedSecret);
|
||||
const isValid = TOTPModel.verifyTOTP(secret, code);
|
||||
if (!isValid) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Invalid verification code',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
} catch {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Failed to decrypt TOTP secret',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 500 });
|
||||
}
|
||||
} else if (method.type === 'passkey') {
|
||||
if (code !== 'passkey-verified') {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey not properly verified',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
if (!method.metadata.passkey?.credential_id || !method.metadata.passkey?.public_key) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey credentials not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
MultiFactorAuthModel.enableMethodForUser(user, methodId);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
87
routes/api/auth/multi-factor/passkey/begin.ts
Normal file
87
routes/api/auth/multi-factor/passkey/begin.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
options?: PublicKeyCredentialCreationOptionsJSON;
|
||||
sessionData?: {
|
||||
challenge: string;
|
||||
methodId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request) {
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passwordless passkey login requires multi-factor authentication to be enabled.',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { email } = body;
|
||||
|
||||
if (!email) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Email is required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const user = await UserModel.getByEmail(email);
|
||||
|
||||
if (!user) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'User not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const allowedCredentials = PasskeyModel.getCredentialsFromUser(user);
|
||||
|
||||
if (allowedCredentials.length === 0) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'No passkeys registered for this user',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const options = await PasskeyModel.generateAuthenticationOptions(
|
||||
config.auth.baseUrl,
|
||||
allowedCredentials,
|
||||
);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
options,
|
||||
sessionData: {
|
||||
challenge: options.challenge,
|
||||
methodId: options.challenge,
|
||||
},
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
67
routes/api/auth/multi-factor/passkey/setup-begin.ts
Normal file
67
routes/api/auth/multi-factor/passkey/setup-begin.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { PublicKeyCredentialCreationOptionsJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
|
||||
export interface RequestBody {}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
options?: PublicKeyCredentialCreationOptionsJSON;
|
||||
sessionData?: {
|
||||
challenge: string;
|
||||
methodId: string;
|
||||
userId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passwordless passkey login requires multi-factor authentication to be enabled.',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const methodId = MultiFactorAuthModel.generateMethodId();
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const existingCredentials = PasskeyModel.getCredentialsFromUser(user);
|
||||
|
||||
const options = await PasskeyModel.generateRegistrationOptions(
|
||||
user.id,
|
||||
user.email,
|
||||
config.auth.baseUrl,
|
||||
existingCredentials,
|
||||
);
|
||||
|
||||
const sessionData: ResponseBody['sessionData'] = {
|
||||
challenge: options.challenge,
|
||||
methodId,
|
||||
userId: user.id,
|
||||
};
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
options,
|
||||
sessionData,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
102
routes/api/auth/multi-factor/passkey/setup-complete.ts
Normal file
102
routes/api/auth/multi-factor/passkey/setup-complete.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { isoBase64URL } from '@simplewebauthn/server/helpers';
|
||||
import { RegistrationResponseJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
methodId: string;
|
||||
challenge: string;
|
||||
registrationResponse: RegistrationResponseJSON;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passwordless passkey login requires multi-factor authentication to be enabled.',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { methodId, challenge, registrationResponse } = body;
|
||||
|
||||
if (!methodId || !challenge || !registrationResponse) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Method ID, challenge, and registration response are required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const expectedOrigin = config.auth.baseUrl;
|
||||
const expectedRPID = new URL(config.auth.baseUrl).hostname;
|
||||
|
||||
const verification = await PasskeyModel.verifyRegistration(
|
||||
registrationResponse,
|
||||
challenge,
|
||||
expectedOrigin,
|
||||
expectedRPID,
|
||||
);
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey registration verification failed',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const { registrationInfo } = verification;
|
||||
const credentialID = registrationInfo.credential.id;
|
||||
const credentialPublicKey = isoBase64URL.fromBuffer(registrationInfo.credential.publicKey);
|
||||
|
||||
const method = PasskeyModel.createMethod(
|
||||
methodId,
|
||||
'Passkey',
|
||||
credentialID,
|
||||
credentialPublicKey,
|
||||
registrationInfo.credential.counter,
|
||||
registrationInfo.credentialDeviceType,
|
||||
registrationInfo.credentialBackedUp,
|
||||
// @ts-expect-error SimpleWebAuthn supports a few more transports, and that's OK
|
||||
registrationResponse.response?.transports || [],
|
||||
);
|
||||
|
||||
if (!user.extra.multi_factor_auth_methods) {
|
||||
user.extra.multi_factor_auth_methods = [];
|
||||
}
|
||||
|
||||
user.extra.multi_factor_auth_methods.push(method);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseBody: ResponseBody = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody));
|
||||
},
|
||||
};
|
||||
99
routes/api/auth/multi-factor/passkey/verify.ts
Normal file
99
routes/api/auth/multi-factor/passkey/verify.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
import { AuthenticationResponseJSON } from '@simplewebauthn/server';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { PasskeyModel } from '/lib/models/multi-factor-auth/passkey.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { createSessionResponse } from '/lib/auth.ts';
|
||||
|
||||
export interface RequestBody {
|
||||
email: string;
|
||||
challenge: string;
|
||||
authenticationResponse: AuthenticationResponseJSON;
|
||||
redirectUrl?: string;
|
||||
}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request) {
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.clone().json() as RequestBody;
|
||||
const { email, challenge, authenticationResponse, redirectUrl } = body;
|
||||
|
||||
if (!email || !challenge || !authenticationResponse) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Email, challenge, and authentication response are required',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const user = await UserModel.getByEmail(email);
|
||||
if (!user) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'User not found',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 404 });
|
||||
}
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const expectedOrigin = config.auth.baseUrl;
|
||||
const expectedRPID = new URL(config.auth.baseUrl).hostname;
|
||||
|
||||
const userCredentials = PasskeyModel.getCredentialsFromUser(user);
|
||||
const credentialID = authenticationResponse.id;
|
||||
|
||||
const credential = userCredentials.find((credential) => credential.credentialID === credentialID);
|
||||
if (!credential) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Credential not found for this user',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
const verification = await PasskeyModel.verifyAuthentication(
|
||||
authenticationResponse,
|
||||
challenge,
|
||||
expectedOrigin,
|
||||
expectedRPID,
|
||||
credential,
|
||||
);
|
||||
|
||||
if (!verification.verified) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Passkey authentication verification failed',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 400 });
|
||||
}
|
||||
|
||||
// Update the counter to protect against replay attacks
|
||||
PasskeyModel.updateCounterForUser(user, credentialID, verification.authenticationInfo.newCounter);
|
||||
await UserModel.update(user);
|
||||
|
||||
return await createSessionResponse(request, user, {
|
||||
urlToRedirectTo: redirectUrl || '/',
|
||||
});
|
||||
},
|
||||
};
|
||||
66
routes/api/auth/multi-factor/totp/setup.ts
Normal file
66
routes/api/auth/multi-factor/totp/setup.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Handlers } from 'fresh/server.ts';
|
||||
|
||||
import { FreshContextState } from '/lib/types.ts';
|
||||
import { UserModel } from '/lib/models/user.ts';
|
||||
import { AppConfig } from '/lib/config.ts';
|
||||
import { MultiFactorAuthModel } from '/lib/models/multi-factor-auth.ts';
|
||||
import { TOTPModel } from '/lib/models/multi-factor-auth/totp.ts';
|
||||
|
||||
export interface RequestBody {}
|
||||
|
||||
export interface ResponseBody {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
data?: {
|
||||
methodId: string;
|
||||
secret?: string;
|
||||
qrCodeUrl?: string;
|
||||
backupCodes?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export const handler: Handlers<unknown, FreshContextState> = {
|
||||
async POST(request, context) {
|
||||
if (!context.state.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
const isMultiFactorAuthEnabled = await AppConfig.isMultiFactorAuthEnabled();
|
||||
|
||||
if (!isMultiFactorAuthEnabled) {
|
||||
const responseBody: ResponseBody = {
|
||||
success: false,
|
||||
error: 'Multi-factor authentication is not enabled on this server',
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseBody), { status: 403 });
|
||||
}
|
||||
|
||||
const { user } = context.state;
|
||||
|
||||
const config = await AppConfig.getConfig();
|
||||
const issuer = new URL(config.auth.baseUrl).hostname;
|
||||
const methodId = MultiFactorAuthModel.generateMethodId();
|
||||
const setup = await TOTPModel.createMethod(methodId, 'Authenticator App', issuer, user.email);
|
||||
|
||||
if (!user.extra.multi_factor_auth_methods) {
|
||||
user.extra.multi_factor_auth_methods = [];
|
||||
}
|
||||
|
||||
user.extra.multi_factor_auth_methods.push(setup.method);
|
||||
|
||||
await UserModel.update(user);
|
||||
|
||||
const responseData: ResponseBody = {
|
||||
success: true,
|
||||
data: {
|
||||
methodId: setup.method.id,
|
||||
secret: setup.plainTextSecret,
|
||||
qrCodeUrl: setup.qrCodeUrl,
|
||||
backupCodes: setup.plainTextBackupCodes,
|
||||
},
|
||||
};
|
||||
|
||||
return new Response(JSON.stringify(responseData));
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user