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

feat: user auth #47

Merged
merged 22 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from 12 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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ POSTGRES_PASSWORD=postgres
POSTGRES_DB=medium
POSTGRES_HOST=0.0.0.0
POSTGRES_PORT=5432
JWT_SECRET=supersecretkey
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"editor.tabSize": 2
"editor.tabSize": 2,
"[javascript]": {
"editor.defaultFormatter": "biomejs.biome"
}
}
Binary file modified bun.lockb
Binary file not shown.
22 changes: 11 additions & 11 deletions db/config.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import type { Config } from 'drizzle-kit';
export const dbCredentials = {
host: process.env.POSTGRES_HOST || '0.0.0.0',
port: parseInt(process.env.POSTGRES_PORT || '5432'),
user: process.env.POSTGRES_USER || 'postgres',
password: process.env.POSTGRES_PASSWORD || 'postgres',
database: process.env.POSTGRES_DB || 'medium',
};
host: Bun.env.POSTGRES_HOST || "0.0.0.0",
port: parseInt(Bun.env.POSTGRES_PORT || '5432'),
user: Bun.env.POSTGRES_USER || "postgres",
password: Bun.env.POSTGRES_PASSWORD || "postgres",
database: Bun.env.POSTGRES_DB || "medium"
}

export const dbCredentialsString = `postgres://${dbCredentials.user}:${dbCredentials.password}@${dbCredentials.host}:${dbCredentials.port}/${dbCredentials.database}`;

export default {
out: './src/db/migrations',
schema: '**/*.schema.ts',
breakpoints: false,
driver: 'pg',
dbCredentials,
out: "./migrations",
Hajbo marked this conversation as resolved.
Show resolved Hide resolved
schema: "**/*.schema.ts",
breakpoints: false,
driver: "pg",
dbCredentials
} satisfies Config;
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
CREATE TABLE IF NOT EXISTS "users" (
"id" serial PRIMARY KEY NOT NULL,
"email" text NOT NULL,
"bio" text NOT NULL,
"image" text NOT NULL,
"bio" text,
"image" text,
"password" text NOT NULL,
"username" text NOT NULL,
"created_at" date DEFAULT CURRENT_DATE,
"updated_at" date DEFAULT CURRENT_DATE
"updated_at" date DEFAULT CURRENT_DATE,
CONSTRAINT "users_email_unique" UNIQUE("email")
);
16 changes: 12 additions & 4 deletions db/migrations/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"version": "5",
"dialect": "pg",
"id": "86aed854-dd08-4bcd-8138-412a71492c24",
"id": "8ed456d0-e522-4f1a-a07e-a19b3cd900bc",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"users": {
Expand All @@ -24,13 +24,13 @@
"name": "bio",
"type": "text",
"primaryKey": false,
"notNull": true
"notNull": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": true
"notNull": false
},
"password": {
"name": "password",
Expand Down Expand Up @@ -62,7 +62,15 @@
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
"uniqueConstraints": {
"users_email_unique": {
"name": "users_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
}
}
},
"enums": {},
Expand Down
4 changes: 2 additions & 2 deletions db/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
{
"idx": 0,
"version": "5",
"when": 1695584965813,
"tag": "0000_bored_warstar",
"when": 1695849229878,
"tag": "0000_perpetual_blazing_skull",
"breakpoints": false
}
]
Expand Down
7 changes: 0 additions & 7 deletions db/migrations/migrate.ts
Hajbo marked this conversation as resolved.
Show resolved Hide resolved

This file was deleted.

20 changes: 0 additions & 20 deletions db/seed.ts
Hajbo marked this conversation as resolved.
Show resolved Hide resolved

This file was deleted.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"prepare": "husky install"
},
"dependencies": {
"@elysiajs/jwt": "^0.7.0",
"@elysiajs/swagger": "^0.7.3",
"drizzle-orm": "^0.28.6",
"drizzle-typebox": "^0.1.1",
Expand Down
44 changes: 39 additions & 5 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,53 @@
import { Elysia } from 'elysia';
import { swagger } from '@elysiajs/swagger';
import { usersPlugin } from '@users/users.plugin';
import { title, version, description } from '../package.json';
import { Elysia } from "elysia";
import { swagger } from "@elysiajs/swagger";
import { jwt } from "@elysiajs/jwt";
import { title, version, description } from "../package.json";
import { usersPlugin } from "@/users/users.plugin";
import { AuthenticationError, AuthorizationError } from "@/errors";
import { ALG } from "@/auth";
import { env } from "@/config";

// the file name is in the spirit of NestJS, where app module is the device in charge of putting together all the pieces of the app
// see: https://docs.nestjs.com/modules


/**
* Add all plugins to the app
*/
export const setupApp = () => {
return new Elysia()
.error({
AUTHENTICATION: AuthenticationError,
AUTHORIZATION: AuthorizationError,
})
.onError(({ error, code, set }) => {
// Handle Elysia schema validation errors
switch (code) {
case "VALIDATION":
set.status = 422;
case "NOT_FOUND":
set.status = 404;
case "AUTHENTICATION":
set.status = 401;
case "AUTHORIZATION":
set.status = 403;
}
const errorType = "type" in error ? error.type : "internal";
return { errors: { [errorType]: error.message } };
})
.use(
swagger({
documentation: {
info: { title, version, description },
},
}),
)
.group('/api', (app) => app.use(usersPlugin));
.use(
jwt({
name: "jwt",
secret: env.JWT_SECRET,
alg: ALG,
})
)
.group("/api", (app) => app.use(usersPlugin));
};
54 changes: 54 additions & 0 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import * as jose from 'jose';
import { UserInDb } from '@/users/users.schema';
import { env } from '@/config';
import { AuthenticationError } from '@/errors';

export const ALG = 'HS256';

export async function generateToken(user: UserInDb) {
const encoder = new TextEncoder();
const secret = encoder.encode(env.JWT_SECRET);

return await new jose.SignJWT({
user: { id: user.id, email: user.email, username: user.username },
})
.setProtectedHeader({ alg: ALG })
.setIssuedAt()
.setIssuer('agnyz')
.setAudience(user.email)
.setExpirationTime('24h')
.sign(secret);
}

// TODO: add typing
export const getUserFromHeaders = async ({
jwt,
request: { headers },
}: // biome-ignore lint/suspicious/noExplicitAny: <explanation>
any) => {
const rawHeader = headers.get('Authorization');
if (!rawHeader) throw new AuthenticationError('Missing authorization header');

const tokenParts = rawHeader?.split(' ');
const tokenType = tokenParts?.[0];
if (tokenType !== 'Token')
throw new AuthenticationError(
"Invalid token type. Expected header format: 'Token jwt'",
);

const token = tokenParts?.[1];
const validatedToken = await jwt.verify(token);
if (!validatedToken) throw new AuthenticationError('Invalid token');
return validatedToken;
};

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export const requireLogin = async ({ jwt, request }: any) => {
await getUserFromHeaders({ jwt, request });
};

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export const getUserEmailFromHeader = async ({ jwt, request }: any) => {
const user = await getUserFromHeaders({ jwt, request });
return user.user.email;
};
14 changes: 14 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Type } from "@sinclair/typebox";
yamcodes marked this conversation as resolved.
Show resolved Hide resolved
import { Value } from "@sinclair/typebox/value";

const envSchema = Type.Object({
POSTGRES_DB: Type.String(),
POSTGRES_USER: Type.String(),
POSTGRES_PASSWORD: Type.String(),
POSTGRES_HOST: Type.String(),
POSTGRES_PORT: Type.String(),
JWT_SECRET: Type.String(),
})
// TODO: this is ugly, find a better way to do this
yamcodes marked this conversation as resolved.
Show resolved Hide resolved
if (!Value.Check(envSchema, Bun.env)) throw new Error("Invalid env variables");
export const env = Value.Cast(envSchema, Bun.env);
15 changes: 15 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export class AuthenticationError extends Error {
public status = 401;
public type = "authentication";
constructor(public message: string) {
super(message);
}
}

export class AuthorizationError extends Error {
public status = 403;
public type = "authorization";
constructor(public message: string) {
super(message);
}
}
12 changes: 10 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { setupApp } from '@/app.module';
import { Elysia } from 'elysia';
import { Elysia } from "elysia";
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import { setupApp } from "@/app.module";
import { migrationsClient } from "@/database.providers";


await migrate(drizzle(migrationsClient), {
migrationsFolder: `${import.meta.dir}/../db/migrations`,
});

const app = new Elysia({ prefix: '/api' }).use(setupApp).listen(3000);

Expand Down
61 changes: 48 additions & 13 deletions src/users/users.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,50 @@
import { Elysia } from 'elysia';
import { setupUsers } from '@/users/users.module';
import { Elysia } from "elysia";
import { setupUsers } from "@/users/users.module";
import {
InsertUserSchema,
UserAuthSchema,
UserLoginSchema,
} from "@/users/users.schema";
import { ALG, getUserEmailFromHeader, requireLogin } from "@/auth";
import { jwt } from "@elysiajs/jwt";
import { env } from "@/config";

export const usersPlugin = new Elysia().use(setupUsers).group(
'/users',
{
detail: {
tags: ['Users'],
},
},
(app) =>
export const usersPlugin = new Elysia()
.use(setupUsers)
.group("/users", (app) =>
app
.post('', ({ store }) => store.usersService.findAll())
.post('/login', ({ store }) => store.usersService.findAll()),
);
.post("", ({ body, store }) => store.usersService.createUser(body.user), {
body: InsertUserSchema,
response: UserAuthSchema,
})
.post(
"/login",
({ body, store }) =>
store.usersService.loginUser(body.user.email, body.user.password),
{
body: UserLoginSchema,
response: UserAuthSchema,
}
)
)
.group("/user", (app) =>
app
.use(
jwt({
name: "jwt",
secret: env.JWT_SECRET,
alg: ALG,
})
)
.get(
"",
async ({ jwt, request, store }) =>
store.usersService.findByEmail(
await getUserEmailFromHeader({ jwt, request })
),
{
beforeHandle: requireLogin,
response: UserAuthSchema,
}
)
);
Loading