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

fix/auth jwt #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
51 changes: 25 additions & 26 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import { opentelemetry } from "@elysiajs/opentelemetry";
import { config } from "@/config/config";
import { handleUserCreation } from "@/services/userService";
import { logger } from "@/infrastructure/logger";
//import { zitadelAuthMiddleware } from "@/infrastructure/introspect";
import { authGuard } from "./infrastructure/authGuard";
import jwt from "@elysiajs/jwt";
import { createRemoteJWKSet, JWTPayload, jwtVerify } from "jose";

Expand Down Expand Up @@ -75,31 +73,32 @@ const app = new Elysia()
logger.error(error);
return undefined;
}
}},)).post(
"/users",
async ({ jwt, body }) => {
if (!jwt) { throw new Error("Jwt error"); };
try {
const user = await handleUserCreation(body);
return { status: "success", data: user };
} catch (error) {
return {
status: "error",
message:
error instanceof Error ? error.message : "Unknown error occurred",
};
}
},
{
body: 'createUser',
zitadelAuth: true,
detail: {
tags: ["Users"],
description: "Create a new user in Zitadel",
},
}
},)).post(
"/users",
async ({ jwt, body }) => {
if (!jwt) { throw new Error("Jwt error"); };
try {
const user = await handleUserCreation(body);
return { status: "success", data: user };
} catch (error) {
return {
status: "error",
message:
error instanceof Error ? error.message : "Unknown error occurred",
};
}
},
{
body: 'createUser',
zitadelAuth: true,
detail: {
tags: ["Users"],

description: "Create a new user in Zitadel",
},
)
},
)
.onStart(() => {
logger.info("Server starting", { port: config.PORT });
})
Expand Down
1 change: 1 addition & 0 deletions src/infrastructure/authGuard.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// zitadelAuthPlugin.ts
// not used but let's keep it for now
import { Elysia, t } from 'elysia';
import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose';

Expand Down
60 changes: 30 additions & 30 deletions src/infrastructure/createUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,38 @@ import type { CreateUserRequest, ZitadelError } from "@/domain/models";
import { formatZitadelError } from "@/domain/errors";

export async function createZitadelUser(userData: CreateUserRequest) {
logger.info("Creating new user in Zitadel", {
username: userData.username,
email: userData.email.email,
});
logger.info("Creating new user in Zitadel", {
username: userData.username,
email: userData.email.email,
});

try {
const response = await fetch(`${config.ZITADEL_DOMAIN}/v2/users/human`, {
method: "POST",
headers: {
Authorization: `Bearer ${config.ZITADEL_PAT}`,
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
try {
const response = await fetch(`${config.ZITADEL_DOMAIN}/v2/users/human`, {
method: "POST",
headers: {
Authorization: `Bearer ${config.ZITADEL_PAT}`,
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});

const responseData = await response.json();
const responseData = await response.json();

if (!response.ok) {
const zitadelError = responseData as ZitadelError;
logger.error("Failed to create user in Zitadel", zitadelError, {
statusCode: response.status,
});
throw new Error(formatZitadelError(zitadelError));
}
if (!response.ok) {
const zitadelError = responseData as ZitadelError;
logger.error("Failed to create user in Zitadel", zitadelError, {
statusCode: response.status,
});
throw new Error(formatZitadelError(zitadelError));
}

logger.info("Successfully created user in Zitadel", {
userId: responseData.id,
});
return responseData;
} catch (error) {
logger.error("Error creating user", error, { username: userData.username });
throw error;
}
logger.info("Successfully created user in Zitadel", {
userId: responseData.id,
});
return responseData;
} catch (error) {
logger.error("Error creating user", error, { username: userData.username });
throw error;
}
}
62 changes: 32 additions & 30 deletions src/infrastructure/introspect.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,47 @@
// Not used any more

import { config } from "@/config/config";
import { logger } from "@/infrastructure/logger";
import {
createRemoteJWKSet,
type JWTPayload,
jwtVerify,
type JWTVerifyResult,
createRemoteJWKSet,
type JWTPayload,
jwtVerify,
type JWTVerifyResult,
} from "jose";

const JWKS = createRemoteJWKSet(new URL(config.ZITADEL_JWKS_ENDPOINT ?? ""));

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export async function zitadelAuthMiddleware({
authHeader,
store,
authHeader,
store,
}: { authHeader: any; store: any }) {
if (!authHeader) {
logger.error(`Unauthorized: Invalid Authorization header ${authHeader}`);
}
if (!authHeader) {
logger.error(`Unauthorized: Invalid Authorization header ${authHeader}`);
}

const token = authHeader;
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: config.ZITADEL_DOMAIN,
audience: config.ZITADEL_CLIENT_ID,
});
const token = authHeader;
try {
const { payload } = await jwtVerify(token, JWKS, {
issuer: config.ZITADEL_DOMAIN,
audience: config.ZITADEL_CLIENT_ID,
});

const requiredScopes = ["read:data"];
const tokenScopes = (payload.scope as string).split(" ") || [];
const hasRequiredScopes = requiredScopes.every((scope) =>
tokenScopes.includes(scope),
);
const requiredScopes = ["read:data"];
const tokenScopes = (payload.scope as string).split(" ") || [];
const hasRequiredScopes = requiredScopes.every((scope) =>
tokenScopes.includes(scope),
);

if (!hasRequiredScopes) {
return logger.error("Forbidden: Insufficient scope");
}
if (!hasRequiredScopes) {
return logger.error("Forbidden: Insufficient scope");
}

store.user = payload;
} catch (error: unknown) {
if (error instanceof Error) {
return logger.error(error.message);
}
return logger.error("Forbidden: Invalid JWT");
}
store.user = payload;
} catch (error: unknown) {
if (error instanceof Error) {
return logger.error(error.message);
}
return logger.error("Forbidden: Invalid JWT");
}
}
48 changes: 24 additions & 24 deletions src/infrastructure/logger.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
export const logger = {
info: (message: string, metadata?: object) => {
const logEntry = {
level: "info",
timestamp: new Date().toISOString(),
message,
...metadata,
};
console.log(JSON.stringify(logEntry));
},
error: (message: string, errorObject?: unknown, metadata?: object) => {
const error =
errorObject instanceof Error
? { message: errorObject.message, stack: errorObject.stack }
: errorObject;
info: (message: string, metadata?: object) => {
const logEntry = {
level: "info",
timestamp: new Date().toISOString(),
message,
...metadata,
};
console.log(JSON.stringify(logEntry));
},
error: (message: string, errorObject?: unknown, metadata?: object) => {
const error =
errorObject instanceof Error
? { message: errorObject.message, stack: errorObject.stack }
: errorObject;

console.error(
JSON.stringify({
level: "error",
timestamp: new Date().toISOString(),
message,
error,
...metadata,
}),
);
},
console.error(
JSON.stringify({
level: "error",
timestamp: new Date().toISOString(),
message,
error,
...metadata,
}),
);
},
};