Template
1
0

refactor: identity -> iam

This commit is contained in:
2025-10-03 16:07:10 +02:00
parent fe50394ec0
commit 7504361d88
46 changed files with 16 additions and 10 deletions

View File

@@ -0,0 +1,29 @@
import { logger } from "@platform/logger";
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { emailOTP } from "better-auth/plugins";
import { db } from "./database.ts";
export const auth = betterAuth({
database: mongodbAdapter(db.db),
session: {
cookieCache: {
enabled: true,
maxAge: 5 * 60, // Cache duration in seconds
},
},
plugins: [
emailOTP({
async sendVerificationOTP({ email, otp, type }) {
if (type === "sign-in") {
logger.info({ email, otp, type });
} else if (type === "email-verification") {
// Send the OTP for email verification
} else {
// Send the OTP for password reset
}
},
}),
],
});

View File

@@ -0,0 +1,61 @@
import { getDatabaseAccessor } from "@platform/database/accessor.ts";
import {
PRINCIPAL_TYPE_NAMES,
type Principal,
PrincipalSchema,
PrincipalTypeId,
parsePrincipal,
} from "../models/principal.ts";
export const db = getDatabaseAccessor<{
principal: Principal;
}>("auth");
/*
|--------------------------------------------------------------------------------
| Methods
|--------------------------------------------------------------------------------
*/
export async function getPrincipalById(id: string): Promise<Principal | undefined> {
return db
.collection("principal")
.findOne({ id })
.then((value) => parsePrincipal(value));
}
export async function setPrincipalRolesById(id: string, roles: string[]): Promise<void> {
await db.collection("principal").updateOne({ id }, { $set: { roles } });
}
export async function setPrincipalAttributesById(id: string, attr: Record<string, any>): Promise<void> {
await db.collection("principal").updateOne({ id }, { $set: { attr } });
}
/**
* Retrieve a principal for a better-auth user.
*
* @param userId - User id from better-auth user list.
*/
export async function getPrincipalByUserId(userId: string): Promise<Principal> {
const principal = await db.collection("principal").findOneAndUpdate(
{ id: userId },
{
$setOnInsert: {
id: userId,
type: {
id: PrincipalTypeId.User,
name: PRINCIPAL_TYPE_NAMES[PrincipalTypeId.User],
},
roles: ["user"],
attr: {},
},
},
{ upsert: true, returnDocument: "after" },
);
if (principal === null) {
throw new Error("Failed to resolve Principal");
}
return PrincipalSchema.parse(principal);
}

View File

@@ -0,0 +1,3 @@
import { logger as platformLogger } from "@platform/logger";
export const logger = platformLogger.prefix("Modules/Identity");

View File

@@ -0,0 +1,34 @@
import cookie from "cookie";
import { config } from "../config.ts";
import { auth } from "./auth.ts";
/**
* Get session headers which can be applied on a Response object to apply
* an authenticated session to the respondent.
*
* @param accessToken - Token to apply to the cookie.
* @param maxAge - Max age of the token.
*/
export async function getSessionHeaders(accessToken: string, maxAge: number): Promise<Headers> {
return new Headers({
"set-cookie": cookie.serialize(
"better-auth.session_token",
encodeURIComponent(accessToken), // URL-encode the token
config.cookie(maxAge),
),
});
}
/**
* Get session container from request headers.
*
* @param headers - Request headers to extract session from.
*/
export async function getSessionByRequestHeader(headers: Headers) {
const response = await auth.api.getSession({ headers });
if (response === null) {
return undefined;
}
return response.session;
}