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:
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));
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user