Skip to content

Commit

Permalink
手元のsupabaseでも動くように諸々変更
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-20 committed Dec 25, 2023
1 parent 04597ee commit 7e77e81
Show file tree
Hide file tree
Showing 8 changed files with 334 additions and 304 deletions.
11 changes: 6 additions & 5 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,18 @@
"dev": "bun run --hot src/main.ts"
},
"dependencies": {
"@hono/zod-openapi": "^0.9.0",
"@hono/zod-openapi": "^0.9.5",
"@read-stack/database": "workspace:*",
"@read-stack/lib": "workspace:*",
"@read-stack/openapi": "workspace:*",
"@read-stack/tsconfig": "workspace:*",
"@supabase/supabase-js": "^2.39.0",
"hono": "^3.10.3",
"@supabase/ssr": "^0.0.10",
"hono": "^3.11.8",
"zod": "^3.22.4"
},
"devDependencies": {
"bun-types": "^1.0.14",
"@read-stack/eslint-config": "workspace:*"
"@read-stack/eslint-config": "workspace:*",
"@supabase/supabase-js": "^2.39.1",
"bun-types": "^1.0.17"
}
}
40 changes: 8 additions & 32 deletions apps/server/src/handlers/helpers/getUser.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,13 @@
import type { Context } from 'hono';
import { getCookie } from 'hono/cookie';
import { z } from 'zod';

import { SUPABASE_ID } from '@/utils/env';
import { supabase } from '@/gateways/supabase';
import type { SupabaseMiddlewareVariable } from '@/middleware/supabase';

const authCookieSchema = z.tuple([
z.string(),
z.string(),
z.string().nullable(),
z.string().nullable(),
z.unknown(),
]);
export const getUser = async (
c: Context<{ Variables: SupabaseMiddlewareVariable }>,
) => {
const {
data: { user },
} = await c.var.supabase.auth.getUser();

export const getUser = async (c: Context) => {
const authCookie = getCookie(c, `sb-${SUPABASE_ID}-auth-token`);

if (authCookie === undefined) return null;

try {
const authCookieParts = authCookieSchema.parse(JSON.parse(authCookie));
const [accessToken, refreshToken, _providerToken, _providerRefreshToken] =
authCookieParts;

const result = await supabase.auth.setSession({
access_token: accessToken,
refresh_token: refreshToken,
});

if (result.error !== null) return null;

return result.data.user;
} catch (err) {
return null;
}
return user;
};
5 changes: 4 additions & 1 deletion apps/server/src/handlers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ import {

import { getUser } from '@/handlers/helpers/getUser';
import { parseBody } from '@/handlers/helpers/parseBody';
import type { SupabaseMiddlewareVariable } from '@/middleware/supabase';

export const registerUsersHandlers = (app: OpenAPIHono) => {
export const registerUsersHandlers = (
app: OpenAPIHono<{ Variables: SupabaseMiddlewareVariable }>,
) => {
app.openapi(getMeRoute, async (c) => {
const user = await getUser(c);
if (user === null) return c.json({ user: null }, 401);
Expand Down
9 changes: 8 additions & 1 deletion apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { handle } from 'hono/vercel';
import { registerArticlesHandlers } from '@/handlers/articles';
import { registerDocsHandler } from '@/handlers/docs';
import { registerUsersHandlers } from '@/handlers/users';
import type { SupabaseMiddlewareVariable } from '@/middleware/supabase';
import { supabaseMiddleware } from '@/middleware/supabase';

export const app = new OpenAPIHono().basePath('/api');

Expand All @@ -18,7 +20,12 @@ app.use('*', async (c, next) => {

const v1 = app.basePath('/v1');

registerUsersHandlers(v1);
v1.use('*', supabaseMiddleware);

registerUsersHandlers(
// うまくEnvに型を付けたい
v1 as unknown as OpenAPIHono<{ Variables: SupabaseMiddlewareVariable }>,
);
registerArticlesHandlers(v1);
registerDocsHandler(v1);

Expand Down
37 changes: 37 additions & 0 deletions apps/server/src/middleware/supabase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { createServerClient } from '@supabase/ssr';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { Context, MiddlewareHandler } from 'hono';
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';

import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@/utils/env';

export interface SupabaseMiddlewareVariable {
supabase: SupabaseClient;
[key: string]: unknown;
}

export const supabaseMiddleware: MiddlewareHandler<{
Variables: SupabaseMiddlewareVariable;
}> = async (c, next) => {
const client = createServerClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
cookies: {
get: (key) => {
return getCookie(c as Context, key);
},
set: (key, value, options) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- 知らんけど
setCookie(c, key, value, options);
},
remove: (key, options) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- 知らんけど
deleteCookie(c, key, options);
},
},
cookieOptions: {
httpOnly: true,
secure: true,
},
});
c.set('supabase', client);
await next();
};
6 changes: 0 additions & 6 deletions apps/server/src/utils/env.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
if (!process.env.SUPABASE_ID) {
throw new Error('Missing SUPABASE_ID');
}

export const SUPABASE_ID = process.env.SUPABASE_ID;

if (!process.env.SUPABASE_URL) {
throw new Error('Missing SUPABASE_URL');
}
Expand Down
15 changes: 8 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
"openapi": "pnpm -F \"@read-stack/openapi\"",
"database": "pnpm -F \"@read-stack/database\"",
"lib": "pnpm -F \"@read-stack/lib\"",
"dev": "turbo dev",
"build": "turbo build",
"start": "turbo start",
"deploy": "turbo deploy",
"test": "turbo test",
"lint": "turbo lint",
"format": "turbo format",
"dev": "dotenv -- turbo dev",
"build": "dotenv -- turbo build",
"start": "dotenv -- turbo start",
"deploy": "dotenv -- turbo deploy",
"test": "dotenv -- turbo test",
"lint": "dotenv -- turbo lint",
"format": "dotenv -- turbo format",
"preinstall": "npx only-allow pnpm",
"prepare": "husky install"
},
Expand All @@ -26,6 +26,7 @@
},
"devDependencies": {
"@biomejs/biome": "1.4.1",
"dotenv-cli": "^7.3.0",
"eslint": "^8.56.0",
"husky": "^8.0.3",
"lint-staged": "^15.2.0",
Expand Down
Loading

0 comments on commit 7e77e81

Please sign in to comment.