mirror of
https://gitlab.massbug.com/massbug/judge4c.git
synced 2025-07-04 15:41:17 +00:00
feat(auth): add session middleware for user authentication and context management
This commit is contained in:
parent
b4a986f51e
commit
5bb77e4ad4
55
src/lib/session-middleware.ts
Normal file
55
src/lib/session-middleware.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import "server-only";
|
||||
|
||||
import {
|
||||
Client,
|
||||
Account,
|
||||
Databases,
|
||||
Storage,
|
||||
Models,
|
||||
type Account as AccountType,
|
||||
type Databases as DatabasesType,
|
||||
type Storage as StorageType,
|
||||
type Users as UsersType,
|
||||
} from "node-appwrite";
|
||||
import { getCookie } from "hono/cookie";
|
||||
import { createMiddleware } from "hono/factory";
|
||||
import { AUTH_COOKIE } from "@/features/auth/constants";
|
||||
|
||||
type AdditionalContext = {
|
||||
Variables: {
|
||||
account: AccountType;
|
||||
databases: DatabasesType;
|
||||
storage: StorageType;
|
||||
users: UsersType;
|
||||
user: Models.User<Models.Preferences>;
|
||||
};
|
||||
};
|
||||
|
||||
export const sessionMiddleware = createMiddleware<AdditionalContext>(
|
||||
async (c, next) => {
|
||||
const client = new Client()
|
||||
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT!)
|
||||
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT!);
|
||||
|
||||
const session = getCookie(c, AUTH_COOKIE);
|
||||
|
||||
if (!session) {
|
||||
return c.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
client.setSession(session);
|
||||
|
||||
const account = new Account(client);
|
||||
const databases = new Databases(client);
|
||||
const storage = new Storage(client);
|
||||
|
||||
const user = await account.get();
|
||||
|
||||
c.set("account", account);
|
||||
c.set("databases", databases);
|
||||
c.set("storage", storage);
|
||||
c.set("user", user);
|
||||
|
||||
await next();
|
||||
}
|
||||
);
|
Loading…
Reference in New Issue
Block a user