diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..d03b723c37bfd4aa65acfa2b3c7331443b24dfac --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +NODE_ENV=development + +# db config +DB_HOST=localhost +DB_USER=postgres +DB_PASSWORD=postgres +DB_NAME=templatedb +DB_PORT=5432 +DB_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME} + +# secret +APP_SECRET=0crebI8PUWwj9E+GRzIGpBt64MwY9ufkBzBkYSH2v+Y= \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3f072776400aff96e7036fa6a16e4eb10a68445c --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +# deps +node_modules/ + +.env diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000000000000000000000000000000000000..de89498e23e4cfa49fabeb9ba25a8135be791598 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,12 @@ +{ + "trailingComma": "es5", + "tabWidth": 2, + "semi": false, + "singleQuote": true, + "jsxSingleQuote": true, + "printWidth": 70, + "arrowParens": "always", + "bracketSpacing": true, + "bracketSameLine": false, + "useTabs": false +} \ No newline at end of file diff --git a/README.md b/README.md index 0084f70e9a9e5cb5aed564afd2ba586617971e8c..d311cb99f7697676e4c2aa68107908932267517b 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,33 @@ -# Backend-MECRED +## Running for dev -New backend for MECRED -## Getting started +1. install docker + https://docs.docker.com/engine/install/ubuntu/ -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +2. Install bun + https://bun.sh/docs/installation -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +3. To install dependencies: + ```sh + bun install + ``` -## Add your files +4. Get the container up and running: + ```sh + docker compose up + cp .env.example .env + ``` -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +5. set dev db + ``` + bun db:migrate + bun db:seed + ``` -``` -cd existing_repo -git remote add origin https://gitlab.c3sl.ufpr.br/mecred/backend-mecred.git -git branch -M main -git push -uf origin main -``` -## Integrate with your tools +6. Run dev server: + ```sh + bun run dev + ``` -- [ ] [Set up project integrations](https://gitlab.c3sl.ufpr.br/mecred/backend-mecred/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +7. open http://localhost:3000 diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..541186b4a229c7a1084630a8380ec367adcb78ba Binary files /dev/null and b/bun.lockb differ diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ae81d8a621167f7deaf6166f039ca188855ee0f --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,2 @@ +preload = ["./src/preload.ts"] +loglevel = "debug" \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1183cb1d1002c0e241c0d345595323c0d9e0f2d9 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,20 @@ +services: + db: + image: postgres + restart: always + environment: + POSTGRES_DB: templatedb + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - "5432:5432" + networks: + - tag_network + volumes: + - postgres_data:/var/lib/postgresql/data + +volumes: + postgres_data: + +networks: + tag_network: diff --git a/drizzle.config.ts b/drizzle.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..011b679218ed0c6ca8f9b491aab03b24b7e92549 --- /dev/null +++ b/drizzle.config.ts @@ -0,0 +1,13 @@ +import { defineConfig, type Config } from 'drizzle-kit' +import env from '@/env' + +export default defineConfig({ + schema: './src/db/schema/index.ts', + out: './src/db/migrations', + dialect: 'postgresql', + dbCredentials: { + url: env.DB_URL, + }, + verbose: true, + strict: true, +}) satisfies Config diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a0baed1738ddc60ced73e1e28b9df2054c6ee715 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,12 @@ +import globals from 'globals' +import pluginJs from '@eslint/js' +import tseslint from 'typescript-eslint' +import prettierEslint from 'eslint-config-prettier' + +export default [ + { files: ['**/*.{js,mjs,cjs,ts}'] }, + { languageOptions: { globals: globals.browser } }, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, + prettierEslint, +] diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b6947c8c135e0e3868233334e060991dfff08a94 --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "hono-backend", + "scripts": { + "dev": "bun run --watch src/index.ts", + "db:generate": "drizzle-kit generate", + "db:migrate": "cross-env DB_MIGRATING=true bun run src/db/migrate.ts", + "db:seed": "cross-env DB_SEEDING=true bun run src/db/seed.ts", + "db:studio": "drizzle-kit studio" + }, + "dependencies": { + "@hono/zod-validator": "^0.2.2", + "dotenv": "^16.4.5", + "dotenv-expand": "^11.0.6", + "drizzle-orm": "^0.31.2", + "drizzle-zod": "^0.5.1", + "hono": "^4.4.8", + "postgres": "^3.4.4", + "reflect-metadata": "^0.2.2", + "typedi": "^0.10.0", + "zod": "^3.23.8" + }, + "devDependencies": { + "@eslint/js": "^9.5.0", + "@types/bun": "latest", + "cross-env": "^7.0.3", + "drizzle-kit": "^0.22.7", + "eslint": "9.x", + "eslint-config-prettier": "^9.1.0", + "globals": "^15.6.0", + "prettier": "^3.3.2", + "typescript-eslint": "^7.14.1" + } +} \ No newline at end of file diff --git a/src/db/index.ts b/src/db/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..67c0ca07d3793f0ea5a9f136a40912c206e1a44c --- /dev/null +++ b/src/db/index.ts @@ -0,0 +1,18 @@ +import { drizzle } from 'drizzle-orm/postgres-js' +import postgres from 'postgres' +import * as schema from '@/db/schema' +import env from '@/env' + +export const connection = postgres(env.DB_URL, { + max: env.DB_MIGRATING || env.DB_SEEDING ? 1 : undefined, + onnotice: env.DB_SEEDING ? () => {} : undefined, +}) + +export const db = drizzle(connection, { + schema, + logger: true, +}) + +export type db = typeof db + +export default db diff --git a/src/db/migrate.ts b/src/db/migrate.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a527461d83ac9fc612fe4cb48bdf1377788660a --- /dev/null +++ b/src/db/migrate.ts @@ -0,0 +1,14 @@ +import { migrate } from 'drizzle-orm/postgres-js/migrator' +import config from '$/drizzle.config' +import { db, connection } from '@/db' +import env from '@/env' + +if (!env.DB_MIGRATING) { + throw new Error( + 'You must set DB_MIGRATING to "true" when migrating' + ) +} + +await migrate(db, { migrationsFolder: config.out! }) + +await connection.end() diff --git a/src/db/migrations/0000_aspiring_frightful_four.sql b/src/db/migrations/0000_aspiring_frightful_four.sql new file mode 100644 index 0000000000000000000000000000000000000000..0bcca0dc640c615ef323ada5ab224bac0c08fe91 --- /dev/null +++ b/src/db/migrations/0000_aspiring_frightful_four.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS "user" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "username" varchar NOT NULL, + "password" varchar NOT NULL, + "name" varchar NOT NULL, + CONSTRAINT "user_username_unique" UNIQUE("username") +); diff --git a/src/db/migrations/meta/0000_snapshot.json b/src/db/migrations/meta/0000_snapshot.json new file mode 100644 index 0000000000000000000000000000000000000000..bdec6301246a56d76c45e20f38a42b4f674b1da6 --- /dev/null +++ b/src/db/migrations/meta/0000_snapshot.json @@ -0,0 +1,58 @@ +{ + "id": "4cf89ad7-1672-440b-b964-dad35de18ec8", + "prevId": "00000000-0000-0000-0000-000000000000", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "username": { + "name": "username", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "password": { + "name": "password", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_username_unique": { + "name": "user_username_unique", + "nullsNotDistinct": false, + "columns": [ + "username" + ] + } + } + } + }, + "enums": {}, + "schemas": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/src/db/migrations/meta/_journal.json b/src/db/migrations/meta/_journal.json new file mode 100644 index 0000000000000000000000000000000000000000..600010d731beb84a0e2a0996864e2923a20e4a8e --- /dev/null +++ b/src/db/migrations/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "postgresql", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1719362169477, + "tag": "0000_aspiring_frightful_four", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/src/db/repo/auth.repo.ts b/src/db/repo/auth.repo.ts new file mode 100644 index 0000000000000000000000000000000000000000..306d4bed3c9aac19129233e5d018b51517f64874 --- /dev/null +++ b/src/db/repo/auth.repo.ts @@ -0,0 +1,31 @@ +import type { z } from 'zod' +import { userSchemas, type UserModel } from '../schema/user.model' + +export function hashPassword(pass: UserModel['password']) { + return Bun.password.hashSync(pass, { + memoryCost: 4, + timeCost: 3, + algorithm: 'argon2id', + }) +} + +export function verifyPassword( + pass: UserModel['password'], + hash: UserModel['password'] +) { + return Bun.password.verifySync(pass, hash) +} + +export const authSchema = userSchemas.userModelSchema.pick({ + username: true, + password: true, +}) + +export const authPayload = userSchemas.userModelSchema.pick({ + id: true, + username: true, +}) + +export type AuthPayload = z.infer<typeof authPayload> + +export type AuthInput = z.infer<typeof authSchema> diff --git a/src/db/repo/user.repo.ts b/src/db/repo/user.repo.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fd0c6d18c5c4863b9758cefa0013013cbc38eb6 --- /dev/null +++ b/src/db/repo/user.repo.ts @@ -0,0 +1,62 @@ +import { Service } from 'typedi' +import db from '@/db' +import userTable, { + userSchemas, + type UserInput, + type UserModel, +} from '../schema/user.model' +import { z } from 'zod' +import { eq } from 'drizzle-orm' + +@Service() +export class UserRepo { + async findMany(): Promise<UserModel[]> { + return z.array(userSchemas.userModelSchema).parse( + await db.query.userTable.findMany({ + limit: 100, + }) + ) + } + + async findByUsername( + username: UserModel['username'] + ): Promise<UserModel | null> { + const user = await db.query.userTable.findFirst({ + where: eq(userTable.username, username), + }) + + if (!user) return null + + return userSchemas.userModelSchema.parse(user) + } + + async create(user: UserInput, tx?: db): Promise<UserModel> { + const repo = tx ?? db + + const [ret] = await repo + .insert(userTable) + .values(user) + .returning() + + return userSchemas.userModelSchema.parse(ret) + } + + async createMany( + users: UserInput[], + tx?: db + ): Promise<UserModel[]> { + const repo = tx ?? db + + return z + .array(userSchemas.userModelSchema) + .parse(await repo.insert(userTable).values(users).returning()) + } + + async uploadUsers(users: UserInput[]): Promise<UserModel[]> { + return await db.transaction(async (tx) => { + return z + .array(userSchemas.userModelSchema) + .parse(await tx.insert(userTable).values(users).returning()) + }) + } +} diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a9894ef8f94573ccdda030a6a4c12cea2cf41ae --- /dev/null +++ b/src/db/schema/index.ts @@ -0,0 +1,5 @@ +import userTable from './user.model' + +export { userTable } + +export const tables = [userTable] diff --git a/src/db/schema/user.model.ts b/src/db/schema/user.model.ts new file mode 100644 index 0000000000000000000000000000000000000000..c161ebc0bf68ca87961cc7d89121ad0c9418a6f6 --- /dev/null +++ b/src/db/schema/user.model.ts @@ -0,0 +1,28 @@ +import { pgTable, uuid, varchar } from 'drizzle-orm/pg-core' +import { createInsertSchema, createSelectSchema } from 'drizzle-zod' +import { z } from 'zod' + +const userTable = pgTable('user', { + id: uuid('id').primaryKey().defaultRandom(), + username: varchar('username').unique().notNull(), + password: varchar('password').notNull(), + name: varchar('name').notNull(), +}) + +const userInputSchema = createInsertSchema(userTable) +const userModelSchema = createSelectSchema(userTable) +const userDtoSchema = createSelectSchema(userTable).omit({ + password: true, +}) + +export type UserInput = z.infer<typeof userInputSchema> +export type UserModel = z.infer<typeof userModelSchema> +export type UserDto = z.infer<typeof userDtoSchema> + +export const userSchemas = { + userInputSchema, + userModelSchema, + userDtoSchema, +} + +export default userTable diff --git a/src/db/seed.ts b/src/db/seed.ts new file mode 100644 index 0000000000000000000000000000000000000000..de1307e96f2b126ab6ccb0beee2ad2263a08603f --- /dev/null +++ b/src/db/seed.ts @@ -0,0 +1,25 @@ +import env from '@/env' +import { connection, db } from '@/db' +import { Table, getTableName, sql } from 'drizzle-orm' +import * as schema from '@/db/schema' +import * as seeds from '@/db/seeds' + +if (!env.DB_SEEDING) { + throw new Error('You must sed DB_SEEDING to "true" when seeding') +} + +async function resetTable(db: db, table: Table) { + return db.execute( + sql.raw( + `TRUNCATE TABLE "${getTableName(table)}" RESTART IDENTITY CASCADE` + ) + ) +} + +for (const table of schema.tables) { + await resetTable(db, table) +} + +await seeds.userSeed(db) + +await connection.end() diff --git a/src/db/seeds/index.ts b/src/db/seeds/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f9fb7bc3e6114822c37691514e30d4610f13237 --- /dev/null +++ b/src/db/seeds/index.ts @@ -0,0 +1 @@ +export { default as userSeed } from './user.seed' diff --git a/src/db/seeds/user.seed.ts b/src/db/seeds/user.seed.ts new file mode 100644 index 0000000000000000000000000000000000000000..3a18be579440ca764606ac40cf7bf3a0cb9d40a3 --- /dev/null +++ b/src/db/seeds/user.seed.ts @@ -0,0 +1,20 @@ +import type db from '@/db' +import userTable, { type UserInput } from '../schema/user.model' +import { hashPassword } from '../repo/auth.repo' + +export default async function seed(db: db) { + await db.insert(userTable).values(usersData) +} + +const usersData: UserInput[] = [ + { + username: 'admin', + password: hashPassword('1234mudar'), + name: 'Admin name', + }, + { + username: 'client user', + password: hashPassword('1234mudar'), + name: 'Client name', + }, +] diff --git a/src/env.ts b/src/env.ts new file mode 100644 index 0000000000000000000000000000000000000000..01b957df7eb5c42214ce4be3fcc51924cb578dec --- /dev/null +++ b/src/env.ts @@ -0,0 +1,47 @@ +import { config } from 'dotenv' +import { expand } from 'dotenv-expand' + +import { ZodError, z } from 'zod' + +const stringBoolean = z.coerce + .string() + .transform((val) => { + return val === 'true' + }) + .default('false') + +const EnvSchema = z.object({ + NODE_ENV: z.string().default('development'), + DB_HOST: z.string(), + DB_USER: z.string(), + DB_PASSWORD: z.string(), + DB_NAME: z.string(), + DB_PORT: z.string(), + DB_URL: z.string(), + DB_MIGRATING: stringBoolean, + DB_SEEDING: stringBoolean, + APP_SECRET: z.string(), +}) + +export type EnvSchema = z.infer<typeof EnvSchema> + +expand(config()) + +try { + EnvSchema.parse(process.env) +} catch (error) { + if (error instanceof ZodError) { + let message = 'Missing required values in .env:\n' + error.issues.forEach((issue) => { + message += issue.path[0] + '\n' + }) + + const e = new Error(message) + e.stack = '' + throw e + } else { + console.log(error) + } +} + +export default EnvSchema.parse(process.env) diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..0225f616dffaf88af0b060da935c1d2bbf881177 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,52 @@ +import { Hono } from 'hono' +import { logger } from 'hono/logger' + +import { userRouter } from './routes/user.routes' +import { authRouter } from './routes/auth.route' +import { jwt } from 'hono/jwt' +import env from './env' +import type { AuthPayload } from './db/repo/auth.repo' +import { uploaderRouter } from './routes/uploader.route' +import { prettyJSON } from 'hono/pretty-json' +import { cors } from 'hono/cors' +import { bodyLimit } from 'hono/body-limit' + +const app = new Hono() + +app.use('*', logger()) +app.use('*', prettyJSON()) +app.use('/api/*', cors()) +app.use( + '/api/*', + jwt({ + secret: env.APP_SECRET, + }) +) +app.use( + '/api/upload', + bodyLimit({ + maxSize: 50 * 1024 * 1024, // 50mb + onError(c) { + return c.json('overflow', 413) + }, + }) +) + +app.get('/', (c) => c.json({ message: 'sv running on /api' })) + +app.route('auth', authRouter) + +const api = app.basePath('/api') +api.route('/user', userRouter) +api.route('/upload', uploaderRouter) + +export default app +export type AppType = typeof app + +export function honoWithJwt() { + return new Hono<{ + Variables: { + jwtPayload: AuthPayload + } + }>() +} diff --git a/src/preload.ts b/src/preload.ts new file mode 100644 index 0000000000000000000000000000000000000000..dff47f1426e506d3ad75eb6808c7600365f5d5d7 --- /dev/null +++ b/src/preload.ts @@ -0,0 +1,3 @@ +import 'reflect-metadata' + +console.log('preloaded') diff --git a/src/routes/auth.route.ts b/src/routes/auth.route.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3cf6db945668cb2c9bcfd169c4f3b58936776d4 --- /dev/null +++ b/src/routes/auth.route.ts @@ -0,0 +1,24 @@ +import { authSchema } from '@/db/repo/auth.repo' +import { AuhtService } from '@/services/auth.service' +import { zValidator } from '@hono/zod-validator' +import { Hono } from 'hono' +import Container from 'typedi' + +const service = Container.get(AuhtService) + +export const authRouter = new Hono().post( + '/', + zValidator('json', authSchema), + async (c) => { + try { + const input = await c.req.valid('json') + + const token = await service.login(input) + + return c.json({ token }) + } catch (e) { + console.log(e) + return c.notFound() + } + } +) diff --git a/src/routes/uploader.route.ts b/src/routes/uploader.route.ts new file mode 100644 index 0000000000000000000000000000000000000000..30d3dde7fc7cd6d9256e1605473db1347c7f40a8 --- /dev/null +++ b/src/routes/uploader.route.ts @@ -0,0 +1,46 @@ +import { UploaderService } from '@/services/uploader.service' +import Container from 'typedi' +import { z } from 'zod' +import { userSchemas, type UserInput } from '@/db/schema/user.model' +import { honoWithJwt } from '..' + +const service = Container.get(UploaderService) + +export const uploaderRouter = honoWithJwt().post( + '/users', + async (c) => { + const body = await c.req.parseBody() + const file = body['file'] + + console.log(body) + console.log(file) + + if (!(file instanceof File) || file.type !== 'text/csv') + return c.text('Wrong format', 422) + + try { + const data = (await file.text()).split('\n') + const users: UserInput[] = [] + + for (const line of data) { + const split = line.split(',') + const input: UserInput = { + username: split[1], + name: split[2], + password: '1234mudar', + } + + users.push(input) + } + + await service.uploadUsers( + z.array(userSchemas.userInputSchema).parse(users) + ) + + return c.json({ message: 'uploaded' }) + } catch (e) { + console.log(e) + return c.text('Failed to upload', 422) + } + } +) diff --git a/src/routes/user.routes.ts b/src/routes/user.routes.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcf8edc355e0e09d9f7e5ef1959396d25b06ceae --- /dev/null +++ b/src/routes/user.routes.ts @@ -0,0 +1,51 @@ +import { userSchemas } from '@/db/schema/user.model' +import { UserService } from '@/services/user.service' +import { Container } from 'typedi' +import { z } from 'zod' +import { zValidator } from '@hono/zod-validator' +import { honoWithJwt } from '..' + +const service = Container.get(UserService) + +export const userRouter = honoWithJwt() + .get('/:username', async (c) => { + try { + const username = c.req.param('username') + const user = await service.findByUsername(username) + const ret = userSchemas.userDtoSchema.parse(user) + + return c.json({ user: ret }) + } catch { + return c.notFound() + } + }) + .get('/users', async (c) => { + const p = c.get('jwtPayload') + + console.log({ p }) + + const users = await service.findMany() + + const ret = z.array(userSchemas.userDtoSchema).parse(users) + + return c.json({ users: ret }) + }) + .post( + '/create', + zValidator('json', userSchemas.userInputSchema), + async (c) => { + try { + const input = userSchemas.userInputSchema.parse( + await c.req.valid('json') + ) + + const user = userSchemas.userDtoSchema.parse( + await service.create(input) + ) + + return c.json({ user }) + } catch (e) { + return c.text('could not create') + } + } + ) diff --git a/src/services/auth.service.ts b/src/services/auth.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f7bcaa9c4f15a75fe4e2be032a0a79257fa42c4 --- /dev/null +++ b/src/services/auth.service.ts @@ -0,0 +1,34 @@ +import { Inject, Service } from 'typedi' +import { UserService } from './user.service' +import { sign } from 'hono/jwt' +import env from '@/env' +import { + authPayload, + verifyPassword, + type AuthInput, + type AuthPayload, +} from '@/db/repo/auth.repo' + +@Service() +export class AuhtService { + @Inject() + private readonly userService: UserService + + async login(input: AuthInput): Promise<string> { + const user = await this.userService.findByUsername(input.username) + + if (!user) throw new Error('User not found') + + if (!verifyPassword(input.password, user.password)) + throw new Error('Wrong password') + + const payload: AuthPayload = authPayload.parse({ + id: user.id, + username: user.username, + }) + + const token = await sign(payload, env.APP_SECRET) + + return token + } +} diff --git a/src/services/uploader.service.ts b/src/services/uploader.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..bec0b27ce04173b85924955e335b56cc0ed9feb4 --- /dev/null +++ b/src/services/uploader.service.ts @@ -0,0 +1,13 @@ +import { Inject, Service } from 'typedi' +import { UserService } from './user.service' +import type { UserInput, UserModel } from '@/db/schema/user.model' + +@Service() +export class UploaderService { + @Inject() + private readonly userService: UserService + + async uploadUsers(users: UserInput[]): Promise<UserModel[]> { + return await this.userService.uploadUsers(users) + } +} diff --git a/src/services/user.service.ts b/src/services/user.service.ts new file mode 100644 index 0000000000000000000000000000000000000000..71e8eda421dc230bcba9697085379af718788f46 --- /dev/null +++ b/src/services/user.service.ts @@ -0,0 +1,54 @@ +import type db from '@/db' +import { hashPassword } from '@/db/repo/auth.repo' +import { UserRepo } from '@/db/repo/user.repo' +import { + userSchemas, + type UserInput, + type UserModel, +} from '@/db/schema/user.model' +import { Inject, Service } from 'typedi' +import { z } from 'zod' + +@Service() +export class UserService { + @Inject() + private readonly repo: UserRepo + + async findMany(): Promise<UserModel[]> { + return await this.repo.findMany() + } + + async findByUsername( + username: UserModel['username'] + ): Promise<UserModel | null> { + return await this.repo.findByUsername(username) + } + + async create(user: UserInput, tx?: db): Promise<UserModel> { + user.password = hashPassword(user.password) + + return this.repo.create(user, tx) + } + + async createMany( + users: UserInput[], + tx?: db + ): Promise<UserModel[]> { + for (const user of users) { + user.password = hashPassword(user.password) + } + + return this.repo.createMany( + z.array(userSchemas.userInputSchema).parse(users), + tx + ) + } + + async uploadUsers(users: UserInput[]): Promise<UserModel[]> { + for (const user of users) { + user.password = hashPassword(user.password) + } + + return this.repo.uploadUsers(users) + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..31bc674e60c4b3688a84f7c6fb8bc7b0363bba1a --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + // Enable latest features + "lib": ["ESNext"], + "target": "ESNext", + "module": "ESNext", + "moduleDetection": "force", + "jsx": "react-jsx", + "allowJs": true, + + // Bundler mode + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + + // Best practices + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + + // Some stricter flags + "noUnusedLocals": true, + "noUnusedParameters": true, + "noPropertyAccessFromIndexSignature": true, + "strictNullChecks": true, + + "outDir": "./dist", + "paths": { + "@/*": ["./src/*"], + "$/*": ["./*"] + }, + + // typedi + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "strictPropertyInitialization": false + }, + "exclude": [ + "node_modules" + ], + "include": [ + "src/**/*.ts", + "*.ts" + ] +} \ No newline at end of file