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

chore: rework supabase and setup openapi #46

Merged
merged 4 commits into from
Apr 9, 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
5 changes: 3 additions & 2 deletions apps/admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.0.0",
"private": true,
"scripts": {
"clean": "git clean -xdf .turbo node_modules .next",
"dev": "next dev --port 3100",
"build": "next build",
"start": "next start",
Expand All @@ -19,8 +20,8 @@
"devDependencies": {
"@repo/biome-config": "workspace:*",
"@repo/typescript-config": "workspace:*",
"@types/node": "^20.12.5",
"@types/react": "^18.2.74",
"@types/node": "^20.12.6",
"@types/react": "^18.2.75",
"@types/react-dom": "^18.2.24",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.38",
Expand Down
12 changes: 9 additions & 3 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"type": "module",
"private": true,
"scripts": {
"clean": "git clean -xdf .turbo node_modules dist",
"dev": "tsx watch src/index.ts",
"build": "tsc --outDir dist",
"start": "node dist/index.js",
Expand All @@ -12,16 +13,21 @@
"lint:check": "biome check ."
},
"dependencies": {
"@repo/types": "workspace:*",
"@hono/node-server": "^1.9.1",
"@hono/swagger-ui": "^0.2.1",
"@hono/zod-openapi": "^0.10.0",
"@hono/zod-validator": "^0.2.1",
"@supabase/supabase-js": "^2.42.0",
"hono": "^4.2.2",
"zod": "^3.22.4"
"hono": "^4.2.3",
"zod": "^3.22.4",
"zod-validation-error": "^3.1.0"
},
"devDependencies": {
"@repo/biome-config": "workspace:*",
"@repo/typescript-config": "workspace:*",
"@types/node": "^20.12.5",
"@types/node": "^20.12.6",
"@types/swagger-ui-dist": "^3.30.4",
"supabase": "^1.153.4",
"tsx": "^4.7.2",
"typescript": "^5.4.4"
Expand Down
145 changes: 63 additions & 82 deletions apps/api/src/handlers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,99 +1,80 @@
import { zValidator } from '@hono/zod-validator';
import { Hono } from 'hono';
import { OpenAPIHono } from '@hono/zod-openapi';
import { getCookie, setCookie } from 'hono/cookie';
import { HTTPException } from 'hono/http-exception';
import { z } from 'zod';
import { supabase } from '../libs/supabase.js';
import { zodErrorHook } from '../libs/zodError.js';
import { loginUser, refreshTokens, signupUser } from '../routes/auth.js';

const authRoutes = new Hono()
.post(
'/sign-up',
zValidator(
'json',
z.object({
email: z.string(),
password: z.string().min(8),
}),
),
async (c) => {
const { email, password } = c.req.valid('json');
export const auth = new OpenAPIHono({
defaultHook: zodErrorHook,
});

const { data, error } = await supabase.auth.signUp({
email,
password,
});
auth.openapi(signupUser, async (c) => {
const { email, password } = c.req.valid('json');

if (error || !data?.user?.email) {
throw new Error(error?.message || 'Error while signing up', {
cause: error,
});
}
return c.json({ message: 'User created successfully' });
},
)
.post(
'/login',
zValidator(
'json',
z.object({
email: z.string(),
password: z.string().min(8),
}),
),
async (c) => {
const { email, password } = c.req.valid('json');
const { data, error } = await supabase.auth.signUp({
email,
password,
});

const { data, error } = await supabase.auth.signInWithPassword({ email, password });
if (error || !data?.user?.email) {
throw new Error(error?.message || 'Error while signing up', {
cause: error,
});
}
return c.json({ message: 'User created successfully' });
});

if (error) {
console.error('Error while signing in', error);
throw new HTTPException(401, { message: error.message });
}
auth.openapi(loginUser, async (c) => {
const { email, password } = c.req.valid('json');

setCookie(c, 'access_token', data?.session.access_token, {
maxAge: 604800, // 1 week
httpOnly: true,
path: '/',
secure: true,
});
const { data, error } = await supabase.auth.signInWithPassword({ email, password });

setCookie(c, 'refresh_token', data?.session.refresh_token, {
maxAge: 31536000, // 1 year
httpOnly: true,
path: '/',
secure: true,
});
if (error) {
console.error('Error while signing in', error);
throw new HTTPException(401, { message: error.message });
}

return c.json({
access_token: data.session.access_token,
refresh_token: data.session.refresh_token,
});
},
)
.get('/refresh', async (c) => {
const refresh_token = getCookie(c, 'refresh_token');
if (!refresh_token) {
throw new HTTPException(403, { message: 'No refresh token' });
}
setCookie(c, 'access_token', data?.session.access_token, {
maxAge: 31536000, // 1 year
httpOnly: true,
path: '/',
secure: true,
});

const { data, error } = await supabase.auth.refreshSession({
refresh_token,
});
setCookie(c, 'refresh_token', data?.session.refresh_token, {
maxAge: 31536000,
httpOnly: true,
path: '/',
secure: true,
});

if (error) {
console.error('Error while refreshing token', error);
throw new HTTPException(403, { message: error.message });
}
return c.json({ message: 'User logged in' }, 200);
});

if (data?.session) {
setCookie(c, 'refresh_token', data.session.refresh_token, {
httpOnly: true,
path: '/',
secure: true,
});
}
auth.openapi(refreshTokens, async (c) => {
const refresh_token = getCookie(c, 'refresh_token');
if (!refresh_token) {
throw new HTTPException(403, { message: 'No refresh token' });
}

return c.json({ message: 'Token refreshed' });
const { data, error } = await supabase.auth.refreshSession({
refresh_token,
});

export default authRoutes;
if (error) {
console.error('Error while refreshing token', error);
throw new HTTPException(403, { message: error.message });
}

if (data?.session) {
setCookie(c, 'refresh_token', data.session.refresh_token, {
maxAge: 31536000,
httpOnly: true,
path: '/',
secure: true,
});
}

return c.json({ message: 'Token refreshed' });
});
171 changes: 61 additions & 110 deletions apps/api/src/handlers/blog.ts
Original file line number Diff line number Diff line change
@@ -1,121 +1,72 @@
import { zValidator } from '@hono/zod-validator';
import { Hono } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { z } from 'zod';
import { OpenAPIHono } from '@hono/zod-openapi';
import { supabase } from '../libs/supabase.js';
import authMiddleware from '../middlewares/auth.js';
import { zodErrorHook } from '../libs/zodError.js';
import { createPost, deletePost, getAllPosts, getPost, updatePost } from '../routes/blog.js';

export const blog = new Hono();
export const blog = new OpenAPIHono({
defaultHook: zodErrorHook,
});

blog.get('/posts', authMiddleware, async (c) => {
blog.openapi(getAllPosts, async (c) => {
const { data, error } = await supabase.from('POSTS').select('*');

if (error) {
throw new HTTPException(500, { message: error.message });
return c.json({ message: error.message }, 500);
}

return c.json(data, 200);
});

blog.get(
'/posts/:postId',
authMiddleware,
zValidator(
'param',
z.object({
postId: z.coerce.number().min(1),
}),
),
async (c) => {
const { postId } = c.req.valid('param');
const { data, error } = await supabase.from('POSTS').select('*').eq('id', postId).single();

if (error) {
throw new HTTPException(500, { message: error.message });
}
if (!data) {
return c.json({ message: 'Post not found' }, 404);
}

return c.json(data, 200);
},
);

blog.post(
'/posts',
authMiddleware,
zValidator(
'json',
z.object({
title: z.string(),
content: z.string(),
}),
),
async (c) => {
const { title, content } = c.req.valid('json');
const { data, error } = await supabase.from('POSTS').insert({ title, content }).select().single();

if (error) {
throw new HTTPException(500, { message: error.message });
}

return c.json(data, 201);
},
);

blog.delete(
'/posts/:postId',
authMiddleware,
zValidator(
'param',
z.object({
postId: z.coerce.number().min(1),
}),
),

async (c) => {
const { postId } = c.req.valid('param');
const { error, count } = await supabase.from('POSTS').delete({ count: 'exact' }).eq('id', postId);

if (error) {
throw new HTTPException(500, { message: error.message });
}
if (count === 0) {
return c.json({ message: 'Post not found' }, 404);
}

return c.json({ message: 'Post deleted successfully' }, 200);
},
);

blog.patch(
'/posts/:postId',
authMiddleware,
zValidator(
'param',
z.object({
postId: z.coerce.number().min(1),
}),
),
zValidator(
'json',
z.object({
title: z.string(),
content: z.string(),
}),
),
async (c) => {
const { postId } = c.req.valid('param');
const { title, content } = c.req.valid('json');
const { data, error } = await supabase.from('POSTS').update({ title, content }).eq('id', postId).select().single();

if (error) {
throw new HTTPException(500, { message: error.message });
}
if (!data) {
return c.json({ message: 'Post not found' }, 404);
}

return c.json(data, 200);
},
);
blog.openapi(getPost, async (c) => {
const { id } = c.req.valid('param');
const { data, error } = await supabase.from('POSTS').select('*').eq('id', id).single();

if (error) {
return c.json({ message: error.message }, 500);
}
if (!data) {
return c.json({ message: 'Post not found' }, 404);
}

return c.json(data, 200);
});

blog.openapi(createPost, async (c) => {
const { title, content } = c.req.valid('json');
const { data, error } = await supabase.from('POSTS').insert({ title, content }).select().single();

if (error) {
return c.json({ message: error.message }, 500);
}

return c.json(data, 201);
});

blog.openapi(updatePost, async (c) => {
const { id } = c.req.valid('param');
const { title, content } = c.req.valid('json');
const { data, error } = await supabase.from('POSTS').update({ title, content }).eq('id', id).select().single();

if (error) {
return c.json({ message: error.message }, 500);
}
if (!data) {
return c.json({ message: 'Post not found' }, 404);
}

return c.json(data, 200);
});

blog.openapi(deletePost, async (c) => {
const { id } = c.req.valid('param');
const { error, count } = await supabase.from('POSTS').delete({ count: 'exact' }).eq('id', id);

if (error) {
return c.json({ message: error.message }, 500);
}
if (count === 0) {
return c.json({ message: 'Post not found' }, 404);
}

return c.json({ message: 'Post deleted successfully' }, 200);
});
Loading
Loading