Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement totp #1

Merged
merged 2 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions app/[lang]/account/[index]/totp/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import configuration from '#/configuration';
import { ROUTING } from '#/lib/router';
import AuthService from '#/services/backend/auth.service';
import { getCurrentSessions } from '#/services/backend/zitadel.service';
import RegisterTOTP from '#/ui/TOTP/RegisterTOTP';
import { redirect } from 'next/navigation';

export default async ({ params: { index } }: { params: { index: number } }) => {
const sessions = await getCurrentSessions();
const session = sessions[index];
if (!session.factors?.user) redirect(ROUTING.LOGIN);

const userId = session.factors?.user?.id;
const orgId = session.factors?.user?.organizationId;
const loginName = session.factors?.user?.loginName;

const accessToken = await AuthService.getAdminAccessToken();

return (
<RegisterTOTP
orgId={orgId}
userId={userId}
loginName={loginName}
appUrl={configuration.appUrl}
/>
);
};
1 change: 0 additions & 1 deletion app/[lang]/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export default async ({ searchParams }: { searchParams: SearchParams }) => {

return (
<Login
zitadelUrl={configuration.zitadel.url}
appUrl={configuration.appUrl}
authRequest={result.authRequest}
application={result.application}
Expand Down
6 changes: 6 additions & 0 deletions app/[lang]/totp/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import configuration from '#/configuration';
import LoginTOTP from '#/ui/TOTP/LoginTOTP';

export default () => {
return <LoginTOTP appUrl={configuration.appUrl} />;
};
55 changes: 55 additions & 0 deletions app/api/totp/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { defaultHandler, isValidRequest } from '#/lib/api-handler';
import AuthService from '#/services/backend/auth.service';
import CookieService from '#/services/backend/cookie.service';
import type { APILoginPasskey } from '#/types/api';
import type { NextRequest } from 'next/server';
import * as z from 'zod';

const schema = z.object({
username: z.string().trim(),
});

export async function POST(request: NextRequest) {
return defaultHandler<APILoginPasskey>({ request }, async (body) => {
isValidRequest({
data: {
...body,
},
schema,
});

const { username: loginName, webAuthN } = body;

const accessToken = await AuthService.getAdminAccessToken();
const sessionService = AuthService.createSessionService(accessToken);

const newSession = await sessionService.createSession({
checks: {
user: {
loginName,
},
},
webAuthN,
});

const session = await sessionService.getSession({
sessionId: newSession.sessionId,
});

if (!session?.factors?.user) throw new Error('Invalid session');

const userId = session.factors.user.id;

CookieService.addSessionToCookie({
sessionId: newSession.sessionId,
sessionToken: newSession.sessionToken,
userId,
});

const result: APILoginPasskey['result'] = {
userId,
};

return result;
});
}
50 changes: 50 additions & 0 deletions app/api/totp/start/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { defaultHandler, isValidRequest } from '#/lib/api-handler';
import AuthService, { zitadelService } from '#/services/backend/auth.service';
import type { APIStartTOTP } from '#/types/api';
import { RegisterTOTP } from '#/types/zitadel';
import type { NextRequest } from 'next/server';
import * as z from 'zod';

const schema = z.object({
orgId: z.string().trim(),
userId: z.string().trim(),
});

export async function POST(request: NextRequest) {
return defaultHandler<APIStartTOTP>(
{
request,
tracingName: 'startTOTP',
},
async (body) => {
isValidRequest({
data: {
...body,
},
schema,
});

const { orgId, userId } = body;

const accessToken = await AuthService.getAdminAccessToken();

const result = await zitadelService.request<RegisterTOTP>({
url: '/v2beta/users/{userId}/totp',
params: {
userId,
},
method: 'post',
headers: {
Authorization: `Bearer ${accessToken}`,
'x-zitadel-orgid': `${orgId}`,
},
data: {},
});

return {
secret: result.secret,
uri: result.uri,
};
},
);
}
47 changes: 47 additions & 0 deletions app/api/totp/verify/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { defaultHandler, isValidRequest } from '#/lib/api-handler';
import AuthService, { zitadelService } from '#/services/backend/auth.service';
import { APIVerifyTOTP } from '#/types/api';
import type { VerifyTOTPRegistration } from '#/types/zitadel';
import type { NextRequest } from 'next/server';
import * as z from 'zod';

const schema = z.object({
orgId: z.string().trim(),
userId: z.string().trim(),
code: z.string().trim(),
});

export async function POST(request: NextRequest) {
return defaultHandler<APIVerifyTOTP>(
{
request,
tracingName: 'verifyTOTP',
},
async (body) => {
isValidRequest({
data: {
...body,
},
schema,
});

const { orgId, userId, code } = body;
const accessToken = await AuthService.getAdminAccessToken();

await zitadelService.request<VerifyTOTPRegistration>({
url: '/v2beta/users/{userId}/totp/verify',
params: {
userId,
},
method: 'post',
headers: {
Authorization: `Bearer ${accessToken}`,
'x-zitadel-orgid': `${orgId}`,
},
data: {
code,
},
});
},
);
}
2 changes: 1 addition & 1 deletion e2e/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"test": "playwright test"
},
"keywords": [],
"author": "",
"author": "quochuydev",
"license": "ISC",
"devDependencies": {
"@playwright/test": "^1.38.0"
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"next": "14.0.3-canary.7",
"next-translate": "2.6.2",
"next-translate-plugin": "2.6.2",
"qrcode.react": "3.1.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "7.51.4",
Expand Down
2 changes: 1 addition & 1 deletion proto/zitadel/session/v2beta/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export interface UserFactor {
id: string;
loginName: string;
displayName: string;
organisationId: string;
organizationId: string;
}

export interface PasswordFactor {
Expand Down
36 changes: 36 additions & 0 deletions types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,39 @@ export type APIExternalLinkIDP = {
};
};
};

// TOTP
export type APIStartTOTP = {
url: '/api/totp/start';
method: 'post';
data: {
orgId: string;
userId: string;
};
result: {
secret: string;
uri: string;
};
};

export type APIVerifyTOTP = {
url: '/api/totp/verify';
method: 'post';
data: {
orgId: string;
userId: string;
code: string;
};
result: void;
};

export type APILoginTOTP = {
url: '/api/totp/login';
method: 'post';
data: {
username: string;
};
result: {
userId: string;
};
};
48 changes: 48 additions & 0 deletions types/zitadel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,54 @@ export type VerifyPasskeyRegistration = {
result: void;
};

// https://zitadel.com/docs/apis/resources/user_service_v2/user-service-register-totp
export type RegisterTOTP = {
url: '/v2beta/users/{userId}/totp';
method: 'post';
params: {
userId: string;
};
data: {};
result: {
details: {
sequence: string;
changeDate: string;
resourceOwner: string;
};
uri: string;
secret: string;
};
};

// https://zitadel.com/docs/apis/resources/user_service_v2/user-service-verify-totp-registration
export type VerifyTOTPRegistration = {
url: '/v2beta/users/{userId}/totp/verify';
method: 'post';
params: {
userId: string;
};
data: {
code: string;
};
result: {
details: {
sequence: string;
changeDate: string;
resourceOwner: string;
};
};
};

// https://zitadel.com/docs/apis/resources/user_service_v2/user-service-remove-totp
export type RemoveTOTP = {
url: '/v2beta/users/{userId}/totp';
method: 'delete';
params: {
userId: string;
};
result: void;
};

/** @see https://zitadel.com/docs/apis/resources/user_service/user-service-set-password#change-password
*/
export type ChangePassword = {
Expand Down
9 changes: 9 additions & 0 deletions ui/Home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export default (props: {
<div className="flex w-[480px] lg:p-[40px] flex-col items-center justify-center rounded-[8px] border-gray-300 md:border">
<h1 className="text-[42px]">👋 Welcome!</h1>

<pre className="hidden">{JSON.stringify(activeSession, null, 2)}</pre>

<Image
width={100}
height={100}
Expand All @@ -65,6 +67,13 @@ export default (props: {
Register passkeys
</a>

<a
className="text-[12px] font-normal text-[#4F6679] cursor-pointer mt-[20px]"
onClick={() => router.replace(`/account/${index}/totp`)}
>
Add MFA
</a>

<a
className="text-[12px] font-normal text-[#4F6679] cursor-pointer mt-[20px]"
onClick={() => router.replace(`/account/${index}/password`)}
Expand Down
Loading