Compare commits

..
Author SHA1 Message Date
asepharyana 7a5c560347 docs: materi + AI agent RAG (finding #6) 2026-08-05 17:26:48 +07:00
asepharyana 164c1860da feat(dimentorin): AI agent RAG (embedding materi -> Qdrant + chat via 9router)
- ENV: AI_LLM_BASE_URL/API_KEY/MODEL, AI_EMBEDDING_MODEL (gemini-embedding-001), QDRANT_URL
- ai_agent module: chunking materi, embed_text + chat_completion (9router, SSE parse), Qdrant repo (dimentorin_materi collection, 3072d cosine)
- routes: POST /ai/chat (RAG answer + sources), POST /ai/materials/{id}/index, POST /ai/reindex
- e2e verified: reindex 3 chunks; chat 'ownership' -> materi Rust paling relevan 0.88; chat 'endpoint axum' -> materi Axum 0.82; jawaban gronding konteks
2026-08-05 17:15:11 +07:00
asepharyana ac8177d87e feat(dimentorin): materials module (CRUD konten mentoring, public+protected routes)
- app_materials table: mentor_id, title, slug, category, description, content
- domain/application/infrastructure pola articles: repo postgres, service, DTO ZodValidate
- routes: GET /materials (public, published only), GET /materials/{id|slug|categories}, POST/PUT/DELETE (auth, author-only)
- verified e2e: create 3 materi sebagai mentor, list, slug, categories
2026-08-05 17:01:59 +07:00
asepharyana b4a9972ad7 docs: payment lifecycle complete (auto-paid refresh + dashboards) 2026-08-05 15:58:47 +07:00
asepharyana 9af1c2d163 feat(dimentorin): session mentor can confirm their payments (not just admins)
- mentor can confirm payments of sessions they own (see transfer arrive)
- admin/Admin Pembayaran still allowed; others forbidden
- e2e verified: mentor confirm QRIS payment -> paid + session confirmed
2026-08-05 15:56:35 +07:00
asepharyana 495e043088 feat(dimentorin): GET /payments/session/{id} for mentee/mentor dashboard 2026-08-05 15:24:41 +07:00
asepharyana 390f46b0e7 feat(dimentorin): payment status refresh via Midtrans + auto-paid auto-confirm
- store provider_order_id (Midtrans order id) on payment create
- POST /payments/{id}/refresh: query Midtrans v2/{order}/status (settlement/capture → paid + confirm session)
- fix: status URL must end with /status; force Accept-Encoding: identity (istio gzip mangling)
- e2e verified: simulated VA payment in sandbox → refresh → paid + session confirmed
2026-08-05 15:15:43 +07:00
asepharyana aa0b659b48 docs: SMTP fixed + Midtrans provider status in audit findings 2026-08-05 13:38:02 +07:00
asepharyana 9214b32139 feat(dimentorin): Midtrans payment provider (sandbox VA + QRIS)
- Env: MIDTRANS_MERCHANT_ID / CLIENT_KEY / SERVER_KEY (masked in Debug)
- midtrans_provider: Core API v2/charge for bank_transfer (VA BCA) and qris (gopay)
- PaymentServiceImpl: when MIDTRANS_MERCHANT_ID set -> provider=midtrans, external_ref = real VA number / QR string; falls back to manual refs otherwise
- SMTP: Google app password working (send-otp 200, OTP stored)
- E2E verified (sandbox): VA externalRef=47329093597744219189188, QRIS qr_string EMVCo, confirm->paid
- Credentials stored in BWS (dimentorin_midtrans_*, dimentorin_smtp_*)
2026-08-05 13:34:59 +07:00
asepharyana 2ea6cd3d17 docs: payment flow status in audit findings 2026-08-05 09:32:37 +07:00
asepharyana 6d5af29de8 feat(dimentorin): confirm payment auto-confirms linked session
- confirm_payment now transitions linked session pending->confirmed
- e2e verified: book -> create payment -> admin confirm -> session confirmed + payment paid
2026-08-05 09:32:04 +07:00
asepharyana 444c98074f feat(dimentorin): payment module - gateway-agnostic VA/QRIS with admin confirm
- app_payments table + PaymentEntity (amount from mentor mentoring_rate + service fee 2000)
- PaymentRepository (postgres) + PaymentServiceImpl (create/get/confirm/list)
- Routes: POST /payments/sessions/{id}/create, GET /payments/me, GET /payments/{id}, POST /payments/{id}/confirm
- confirm guarded by Admin/Admin Pembayaran role; ownership guard mentee-only view
- provider=manual default (swap midtrans/xendit later), e2e verified: VA+QRIS create, confirm 200, re-confirm 409, non-admin 403, foreign payment 403
2026-08-05 09:10:39 +07:00
asepharyana c6ed5c5c19 fix(dimentorin): verify-email validates OTP before activating user
- new app_otp_cache table + OtpCache entity (ResourceEnum::OtpCache)
- PostgresOtpRepository upsert/find/delete keyed by email
- register/resend persist otp_hash+expiry after email sent (no orphan OTP)
- verify_email validates via OtpManager::validate_otp_hash, single-use delete
- 8 unit tests pass, e2e verified: wrong OTP 400, correct OTP 200
2026-08-04 23:35:34 +07:00
asepharyana 3692b81324 feat(dimentorin): mentor stats endpoint public - total sessions, unique mentees, avg rating
- GET /mentors/{id}/stats (public, no auth)
- resolve mentor profile id -> user id in get_mentor_sessions (FK uses app_users.id)
2026-08-04 23:09:08 +07:00
asepharyana 9b5efeff87 fix(dimentorin): register mentor flow - zod regex attr, uuid id override in user & mentor repos
- Remove broken zod_rs regex() attribute (always fails, blocks password validation)
- user repo create: honor entity.id instead of silently generating new v4 (broke FK mentor.user_id)
- mentor repo create: set id explicitly (was NULL not-null violation)
2026-08-04 20:03:08 +07:00
asepharyana 1d34d29b0b feat(dimentorin): complete articles module - HTTP layer, routes, categories fix, seed 2026-08-04 19:16:45 +07:00
asepharyana 7d1078f52a fix(dimentorin): resolve mentor profile id to user id before booking session 2026-08-04 18:34:13 +07:00
asepharyana 67d3f2fced feat(dimentorin): add public mentor list & detail endpoints (verified only)
Nix Build & Deploy / build (push) Canceled after 0s
Nix Build & Deploy / deploy (push) Canceled after 0s
2026-08-04 17:55:59 +07:00
maulanasdqnandClaude Opus 4.6 b68e362a02 fix: extract user_id (UUID) from JWT instead of email in session handlers
Nix Build & Deploy / build (push) Canceled after 0s
Nix Build & Deploy / deploy (push) Canceled after 0s
All session handlers were passing the user's email to service methods
that expected a UUID, causing "Invalid user ID" errors. Now extracts
user_id from JWT claims instead.

Fixed: get_my_sessions, post_book_session, put_update_session_status,
post_submit_feedback

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 21:00:32 +07:00
maulanasdqnandClaude Opus 4.6 db44c5a51f feat: add roadmap CRUD module to CMS
New endpoints under /v1/landing/cms:
- GET /roadmap — public, paginated list
- GET /roadmap/detail/{id} — public, detail
- POST /roadmap/vote/{id} — public, increment votes
- POST /roadmap/create — protected (Administrator)
- PATCH /roadmap/update/{id} — protected (Administrator)
- DELETE /roadmap/delete/{id} — protected (Administrator)

Table: roadmap_items (id, title, description, status, votes, is_deleted, created_at, updated_at)
Status values: upcoming, in_progress, completed

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 21:42:15 +07:00
maulanasdqnandClaude Opus 4.6 6570bbf752 fix: add all frontend origins to default CORS allowed list
Added backoffice, hackathon, qr, and infra subdomains to the default
CORS_ALLOWED_ORIGINS. Previously only gacha, imphnen.dev, and
dimentorin were allowed, causing Network Error on other apps.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 16:04:48 +07:00
maulanasdqnandClaude Opus 4.6 5667a0d608 feat: add include query param and sessions to unified /me endpoint
GET /v1/iam/users/me now supports ?include=hackathon,qr,mentor,sessions
to control which module profiles are returned. Omitting the param
returns all modules. Also added dimentorin sessions data.

Examples:
  /v1/iam/users/me                        → all modules
  /v1/iam/users/me?include=hackathon      → only hackathon profile
  /v1/iam/users/me?include=mentor,sessions → mentor + sessions only

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 12:28:55 +07:00
maulanasdqnandClaude Opus 4.6 a4bbc73c7e feat: unify /me endpoint to aggregate all module profiles
GET /v1/iam/users/me now returns hackathon, QR, and mentor profiles
alongside the core IAM user data. Module-specific profiles are
included as optional fields when the user exists in those modules.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 09:47:27 +07:00
maulanasdqnandClaude Opus 4.6 729335014f fix: use correct Swagger security scheme name across all modules
Changed "bearer_auth" to "Bearer" in utoipa security annotations
for QR and Hackathon handlers to match the registered SecurityAddon
scheme name. Fixes Swagger UI not sending Authorization header.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-10 00:11:01 +07:00
maulanasdqnandClaude Opus 4.6 852e9652ee fix: correct middleware layer ordering in QR routes
Same issue as hackathon routes - qr_auth_middleware needs Arc<PgPool>
from Extension but was outermost layer. Swapped order so pool is
available when middleware runs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 23:32:39 +07:00
maulanasdqnandClaude Opus 4.6 f225ee8969 fix: correct middleware layer ordering in hackathon routes
The hackathon_auth_middleware requires Arc<PgPool> from Extension,
but was applied as the outermost layer (running before Extension(pool)
was injected). Swapped layer order so pool Extension is outermost,
making it available when the auth middleware runs.

Fixes 500 errors on all /v1/hackathon/* authenticated endpoints.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 22:21:30 +07:00
maulanasdqnandClaude Opus 4.6 4ee00f1fe5 fix: resolve permission UUIDs to names in role DTO
The build_role_dto function was using permission UUIDs as both id and
name fields. Now resolves UUIDs to human-readable names via
PermissionsEnum::iter() lookup.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 21:52:50 +07:00
maulanasdqnandClaude Sonnet 4.6 d014a94ea4 feat: add response examples to all hackathon and QR swagger endpoints
Each endpoint now shows a realistic JSON example (data wrapper + version)
so developers can see the exact response shape without calling the API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 02:37:06 +07:00
maulanasdqnandClaude Sonnet 4.6 e1bc336baa feat: add utoipa path annotations to hackathon and QR handlers, register in swagger
All hackathon endpoints (/v1/hackathon/*) and QR endpoints (/v1/qr/*)
are now visible in the Swagger UI at /docs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 01:22:38 +07:00
maulanasdqnandClaude Sonnet 4.6 8144ab40e9 fix: update remaining /v1/users path to /v1/iam/users in swagger
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 00:46:56 +07:00
maulanasdqnandClaude Sonnet 4.6 76201d8d3e feat: add module prefixes to all routes and load all modules in swagger
Route structure:
  /v1/iam/auth/*         (was /v1/auth/*)
  /v1/iam/users/*        (was /v1/users/*)
  /v1/iam/roles/*        (was /v1/roles/*)
  /v1/iam/permissions/*  (was /v1/permissions/*)
  /v1/landing/cms/events/*        (was /v1/cms/landing/events/*)
  /v1/landing/cms/testimonials/*  (was /v1/cms/landing/testimonials/*)
  /v1/dimentorin/mentors/*   (was /v1/mentors/*)
  /v1/dimentorin/sessions/*  (was /v1/sessions/*)
  /v1/gacha/*            (unchanged)
  /v1/hackathon/*        (unchanged)
  /v1/qr/*               (unchanged)

Swagger: add gacha_credits endpoints which were missing from OpenAPI spec.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 00:26:29 +07:00
maulanasdqnandClaude Sonnet 4.6 c38b718eb4 fix: migrate all route path params from :param to {param} syntax
Axum 0.8+ requires {param} capture group syntax.
:param style was causing runtime panic on startup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 23:56:59 +07:00
maulanasdqnandClaude Sonnet 4.6 222495472a ci: allow deploy on workflow_dispatch trigger
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 23:26:38 +07:00
maulanasdqnandClaude Sonnet 4.6 12db8cc6b4 ci: fix SSH pipe drop on long nixos-rebuild, add workflow_dispatch
- Add ServerAliveInterval=30/ServerAliveCountMax=40 to prevent broken
  pipe during nixos-rebuild switch (up to 20min keepalive)
- Remove continue-on-error so deploy failures are visible
- Add workflow_dispatch trigger for manual reruns

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 22:44:10 +07:00
maulanasdqnandClaude Sonnet 4.6 331a4a4e88 feat: v0.3.0 — standardize codebase, centralize infra, merge QR into CMS
- Enforce axum best practices across all 13 workspace crates
  (max 200 LOC/file, no comments, no unwrap, clean architecture)
- Fix domain→infrastructure dependency inversions in imphnen-iam and imphnen-dimentorin
- Extract imphnen-storage (MinIO) and imphnen-email (Lettre) as standalone crates
- Centralize all config in ENV struct: CDN_URL, CORS_ALLOWED_ORIGINS
- Centralize SMTP through imphnen-email; remove dead HackathonConfig
- Centralize database: QR crate now shares main DB pool (single DATABASE_URL)
- Rename QR users table to qr_users to avoid collision with main users table
- Merge imphnen-qr into imphnen-cms/src/qr (13 crates, down from 14)
- Restructure imphnen-hackathon flat modules into clean architecture
- Remove all stale env vars from .env.example (SurrealDB, QR_JWT, Hackathon infra)
- Fix Dockerfile to include all current workspace crates
- Bump all crate versions 0.2.0 → 0.3.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 22:29:08 +07:00
maulanasdqnandClaude Sonnet 4.6 2ae43b3bcc refactor: centralize auth system across all modules
All modules now use the main IAM JWT (ACCESS_TOKEN_SECRET) for authentication,
removing three separate auth systems (hackathon Supabase, hackathon JWT, QR JWT).

Changes:
- hackathon: replace HackathonJwtService with decode_access_token() from imphnen-libs
  - remove entire src/auth/ (Supabase signup/login/GitHub/forgot-reset)
  - remove common/hackathon_jwt.rs, common/supabase_client.rs
  - remove Supabase from HackathonConfig (JWT, GitHub OAuth, Supabase anon/service keys)
  - replace Supabase Storage with MinioService from imphnen-libs
  - all route jwt params removed; hackathon_router takes MinioService instead
- qr: replace QrJwtService with decode_access_token() from imphnen-libs
  - remove entire src/auth/ (register/login/Google OAuth/refresh)
  - remove common/qr_jwt.rs, src/config.rs
  - qr_auth_middleware now lazy-upserts users into QR DB on first access
  - qr_router(pool) — no config needed
- gateway: create MinioService once and pass to hackathon_router; qr_router simplified

Users now register/login via /v1/auth/* and use the same JWT for all endpoints.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:33:02 +07:00
maulanasdqnandClaude Sonnet 4.6 4bba182ea3 feat: migrate imphnen-backend-qr into workspace as imphnen-qr crate
Ports the Go QR campaign overlay service to a self-contained Rust crate
nested at /v1/qr/... in the gateway.

Features:
- Auth: register, login, Google OAuth, JWT refresh (bcrypt compat with Go DB)
- Users: profile management + admin CRUD (list/role/delete)
- Campaigns: create (auto-generates QR PNG via qrcode crate), list,
  activate, delete; process-image endpoint overlays active campaign QR
  onto uploaded images (bottom-right corner, image crate)
- QR pool connects to imphnen_qr database via QR_DATABASE_URL

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 16:03:39 +07:00
maulanasdqnandClaude Sonnet 4.6 5715e75593 fix: remove unused imports in imphnen-hackathon
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 15:47:23 +07:00
maulanasdqnandClaude Sonnet 4.6 11442c6285 feat: migrate imphnen-backend-hackathon into workspace as imphnen-hackathon crate
Consolidates the standalone hackathon backend (16 crates) into a single
imphnen-hackathon crate following the existing clean architecture patterns.
All endpoints are exposed under /v1/hackathon/ via the gateway.

Features migrated:
- Auth: Supabase-based signup/login/GitHub OAuth/password reset (own JWT)
- Users: profile management with team listing
- Teams: CRUD with city validation, deadline enforcement, invite system
- Invitations: team member invitations with accept/reject flow
- Join Requests: team join request workflow
- Chat: team messaging with author/leader delete permissions
- Submissions: project submission lifecycle (draft→pending→submitted)
- Storage: Supabase Storage file upload endpoints
- Certificates: public user certificate data endpoint
- Winners: public winners listing
- Admin: admin-only CRUD for all entities

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 15:15:00 +07:00
maulanasdqn 05a5b39195 fix: pre-fetch swagger-ui assets for Nix sandbox build 2026-04-02 14:09:26 +07:00
maulanasdqn 052fee4b78 chore: update nixpkgs to 2026-04-01 (Rust 1.85+ for edition2024) 2026-04-02 14:04:50 +07:00
maulanasdqn c825a78c6f ci: trigger nix build & deploy pipeline 2026-04-02 14:01:02 +07:00
maulanasdqnandClaude Sonnet 4.6 c4280e9953 ci: replace legacy workflows with nix-build.yml
Switch from cargo-based build + SCP deploy to Nix build + Cachix +
infra flake.lock update pattern, matching imphnen-frontend-service.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 13:49:57 +07:00
maulanasdqnandClaude Sonnet 4.6 30128a8fe2 nix: expose overlay and NixOS module for infrastructure deployment
- Fix default.nix to build from workspace (imphnen-backend/Cargo.toml)
- Add overlays.default adding pkgs.imphnen-backend
- Add nixosModules.backend via nixos-module.nix
- NixOS module defines systemd service on port 8081 with environmentFile

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 13:44:23 +07:00
maulanasdqnandClaude Sonnet 4.6 e432a1a743 refactor: migrate to clean architecture with trait-based DI (v0.2.0)
Complete architectural overhaul across all 12 crates:

- Replace validator crate with zod-rs for all DTO validation
- Replace manual pagination with paginator-rs/paginator-sea-orm
- Migrate all modules (iam, cms, gacha, dimentorin) to clean architecture:
  domain → application → infrastructure layers
- Introduce trait-based DI (Arc<dyn Trait>) at every layer for repositories and services
- Delete all v1/ legacy SurrealDB-era code across every crate
- Replace opaque response helpers with typed IntoResponse structs (ApiSuccess, ApiCreated, ApiPaginated, ApiMessage)
- Remove dual_mode_repository, migration_validation_errors, validator.rs dead code
- Zero cargo clippy warnings; release build clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 13:39:52 +07:00
Maulana SodiqinandGitHub 1b3366d735 Merge pull request #47 from IMPHNEN/feat/postgress
postgress
2026-01-15 14:20:18 +07:00
MythEclipse b429b3a9c7 postgress 2025-12-01 00:20:42 +07:00
Maulana SodiqinandGitHub 6fe495eed1 Merge pull request #46 from IMPHNEN/submissions
Submissions
2025-10-29 17:13:16 +07:00
MythEclipse 97c2fce7be Refactor API endpoints for consistency and clarity
- Updated route paths for hackathon submissions, notifications, registrations, and teams to include more descriptive actions (e.g., "update", "create", "delete").
- Removed deprecated routes and adjusted corresponding test cases to reflect new endpoint structures.
- Enhanced test scripts to ensure compatibility with updated API routes and improved error handling for OTP resend functionality.
- Adjusted server startup script for better Windows compatibility and streamlined process management.
2025-10-29 14:27:07 +07:00
MythEclipse 98c46611fb refactor: Update deployment script for Rust binaries with improved comments and error handling 2025-10-28 21:58:49 +07:00
MythEclipse fbfe3dcd51 refactor: Remove unused imports and clean up status update logic in hackathon service and controller 2025-10-28 19:57:43 +07:00
MythEclipse 5cc5a3dfe1 feat: Implement hackathon status change functionality with audit logging
- Added HackathonStatusChangeRequestDto for status change requests.
- Implemented update_hackathon_status method in HackathonRepository to handle status updates.
- Enhanced HackathonService to validate and process status changes, including audit logging.
- Introduced HackathonAuditLogSchema to track changes and actions related to hackathons.
- Created HackathonAuditRepository for managing audit logs.
- Added validation functions for hackathon operations, including dates, organizers, and prizes.
- Implemented atomic service for creating hackathons with timelines and events, ensuring all-or-nothing behavior.
- Updated mod.rs to include new modules for audit logging and validation.
2025-10-28 19:55:38 +07:00
MythEclipse 95ae55c9df refactor: Simplify string conversion for hackathon and timeline attributes in seed test submission 2025-10-28 18:47:52 +07:00
MythEclipse f7ca67d720 feat: Add contact fields to hackathon and submission data; update registration service to handle string ID 2025-10-28 17:34:03 +07:00
MythEclipse 02421e9bc2 fix: Remove unused HeaderMap import from payment middleware 2025-10-28 14:59:26 +07:00
MythEclipse 5e2b0d3caf feat: Add session counting methods for mentors and users; enhance registration queries with related data 2025-10-28 14:57:20 +07:00
MythEclipse b9a51ce6cc feat: Enhance validation and permissions handling across controllers
- Added `ValidatedJson` extractor for automatic JSON validation in `events_controller.rs`, `testimonials_controller.rs`, `mentors_controller.rs`, `gacha_items_controller.rs`, and `hackathon_controller.rs`.
- Replaced manual permission checks with `require_permissions!` and `require_auth!` macros in relevant controllers to streamline permission handling.
- Introduced `sanitization` utilities in `sanitization.rs` for improved input sanitization.
- Added `permission_macros.rs` to encapsulate permission checking logic and reduce boilerplate.
- Updated dependencies in `Cargo.toml` to include `serde_json` and `validator`.
- Implemented error handling improvements in `notification_service.rs` for better response management.
2025-10-28 14:04:41 +07:00
MythEclipse d4a6c4c9ea Add new test suites for registrations and notifications; update existing tests for improved error handling and security checks
- Updated `run-tests.sh` to include new test suites for registrations and notifications.
- Modified `test-cms.sh` to skip SQL injection tests due to query timeout issues and adjusted expected status codes for XSS tests.
- Adjusted expected status codes in `test-auth.sh` for SQL injection and XSS tests; updated missing password test to return 422.
- Updated `test-roles-permissions.sh` to expect 409 for duplicate role creation.
- Changed expected status for duplicate user creation in `test-users.sh` to 409.
- Added comprehensive tests for notification endpoints in `test-notifications.sh`, including edge cases and pagination.
- Created `test-registrations.sh` to cover hackathon registration endpoints, including registration, approval, and check-in processes.
2025-10-28 10:27:19 +07:00
MythEclipse ece6499e2b feat: Implement hackathon registration module with controller, DTOs, repository, schema, and service
- Added registration_controller.rs to handle registration-related routes and logic.
- Created registration_dto.rs for data transfer objects related to registrations.
- Implemented registration_repository.rs for database interactions concerning registrations.
- Defined registration_schema.rs to represent the registration data structure.
- Developed registration_service.rs to encapsulate business logic for registrations.
- Established routes for registering, listing, updating, and checking in participants for hackathons.
- Added validation for registration requests and status updates.
- Included statistics retrieval for hackathon registrations.
2025-10-27 19:53:05 +07:00
MythEclipse 1caaa8404b a 2025-10-27 19:23:29 +07:00
MythEclipse cb6eef2054 feat: Add endpoint to retrieve the current user's team and corresponding service logic 2025-10-27 17:44:13 +07:00
MythEclipse e77797d7bb feat: Update hackathon event and submission routes to require admin permissions and adjust response descriptions 2025-10-27 17:26:53 +07:00
MythEclipse d5ccf4cf75 Add comprehensive security tests for authentication, roles, and user management
- Enhance `test-auth.sh` with SQL injection, XSS, and credential validation tests.
- Extend `test-roles-permissions.sh` to include unauthorized access and duplicate role creation tests.
- Improve `test-users.sh` with checks for invalid emails, duplicate users, and unauthorized actions.
- Introduce `test-security.sh` for thorough security assessments including CSRF, SQL injection, XSS, rate limiting, and session management.
- Add `.serena.gitignore` and `.serena/project.yml` for project configuration and file management.
2025-10-27 16:33:08 +07:00
MythEclipse 1a36698962 feat: Improve validation logic in HackathonService by adding a helper function and using parameterized queries 2025-10-24 18:14:09 +07:00
MythEclipse 15a2ee1950 feat: Enhance hackathon submission process with additional fields and validation checks 2025-10-24 18:06:47 +07:00
MythEclipse bef8482402 feat: Add response validation functions and examples for API tests 2025-10-24 15:42:06 +07:00
MythEclipse 768e583f81 a 2025-10-24 15:34:04 +07:00
MythEclipse 1ca6d8f47c Add comprehensive tests for CMS, Gacha, Hackathon, IAM, and User Management endpoints
- Implemented tests for Events and Testimonials endpoints in `test-cms.sh`
- Added common functions and variables for API testing in `test-common.sh`
- Created tests for Mentor endpoints in `test-mentors.sh`
- Developed tests for Gacha endpoints in `test-gacha.sh`
- Established tests for Hackathon endpoints in `test-hackathon.sh`
- Implemented tests for Authentication endpoints in `test-auth.sh`
- Added tests for Roles and Permissions endpoints in `test-roles-permissions.sh`
- Created tests for Teams endpoints in `test-teams.sh`
- Developed tests for User Management endpoints in `test-users.sh`
2025-10-24 10:38:21 +07:00
MythEclipse 3fcfb3709e refactor: Clean up unused imports and improve error handling in middleware and DTOs 2025-10-23 22:44:32 +07:00
MythEclipse 6915a97d79 feat: Enhance Hackathon Timeline Management and Admin Features
- Updated HackathonTimelineCreateRequestDto to accept optional title and name fields.
- Added custom validators for HackathonPhase and date checks in hackathon_dto.rs.
- Implemented admin-sensitive data management DTOs for handling user scores and personal info.
- Introduced new admin routes for managing users, roles, and permissions in IAM module.
- Added timeline enforcement middleware to restrict access based on hackathon phases.
- Created tests for timeline enforcement and admin permissions to ensure proper access control.
- Implemented payment middleware as a placeholder for future payment processing logic.
- Enhanced audit logging middleware for improved error handling and logging.
2025-10-13 10:57:53 +07:00
MythEclipse 6f596efadd feat: Implement audit logging and rate limiting middleware with SurrealDB integration
- Added audit logging middleware to track admin actions and save logs to SurrealDB.
- Introduced rate limiting middleware for public endpoints and authentication endpoints.
- Enhanced security headers middleware with nonce generation for CSP in development.
- Created utility functions for extracting real client IP addresses from headers.
- Updated Cargo.toml and Cargo.lock to include new dependencies.
- Added new schemas for audit logs and rate limiting in the entities module.
- Refactored permissions middleware to support new permission checks.
2025-10-12 01:54:34 +07:00
MythEclipse b6b5f48055 Implement rate limiting middleware for authentication endpoints, adding security headers middleware, and comprehensive error handling. Enhance validation tests for various DTOs and ensure proper functionality of gacha credits and rolls. Add unit tests for rate limiting and security headers middleware to validate behavior under different conditions. 2025-10-11 23:23:51 +07:00
Your Name 789b20c278 tests(hackathon): align tests with schema changes and fix clippy warnings 2025-10-11 15:33:52 +07:00
MythEclipse 884b679ba8 fix: Update string formatting in hackathon service and repository tests for consistency 2025-10-11 15:28:27 +07:00
MythEclipse 6ef624c169 feat: Enhance hackathon submission and participant management
- Updated HackathonSubmissionsSchema to use Option types for team_id, project_name, description, technologies, submission_status, and submitted_at.
- Modified seed_hackathons and seed_test_submission scripts to accommodate new optional fields.
- Added routes for participant registration and listing in hackathon_controller.
- Implemented register_participant and list_participants functions in hackathon_controller.
- Introduced HackathonParticipantSchema and corresponding DTOs for participant management.
- Enhanced HackathonRepository with CRUD operations for hackathon participants.
- Updated HackathonService to include methods for participant registration and listing.
- Refactored TeamsService to allow admin-level updates and invitations, bypassing leader-only restrictions.
- Added validation for member emails in TeamsCreateRequestDto and TeamInviteRequestDto.
2025-10-11 15:06:12 +07:00
MythEclipse c10443f881 Add minimal test for basic hackathon operations and enhance test utilities
- Introduced a new test module for hackathon-related functionality.
- Implemented a basic test for creating a hackathon using a mock repository.
- Enhanced the test utilities in `lib.rs` for better request handling and response extraction.
- Added a `ServiceClient` struct to facilitate HTTP requests in tests.
- Created a `RequestBuilder` to streamline building and sending requests with headers and JSON bodies.
2025-10-11 10:58:51 +07:00
MythEclipse 466ba3391a feat: Add seed_test_data script to populate initial test data for events, testimonials, hackathons, and mentors 2025-10-08 23:03:00 +07:00
MythEclipse 8c2527d61e Add access level descriptions to API responses across multiple controllers
- Updated event controller to specify public and admin access levels in response descriptions.
- Modified testimonials controller to indicate public access for list and detail responses.
- Enhanced mentors controller with admin access labels for various responses.
- Adjusted gacha claims and items controllers to reflect admin access in response descriptions.
- Updated hackathon controller to clarify public and admin access levels in response messages.
- Revised authentication controller to specify public access for login and registration responses.
- Enhanced admin teams controller with admin access labels for team-related responses.
- Updated users controller to clarify admin and user access levels in response descriptions.
2025-10-07 17:45:47 +07:00
MythEclipse 018124f7b3 feat: Implement permissions checks for hackathon and testimonial routes, enhancing security with header validation 2025-10-07 13:08:23 +07:00
MythEclipse 7749f6fdec feat: Add public routes for hackathons and enhance permissions checks to support both names and IDs 2025-10-05 20:23:34 +07:00
MythEclipse b27e4a4404 refactor: Enhance permission checks to accept both name and ID for Administrator role 2025-10-05 19:39:15 +07:00
MythEclipse 3dde67a4ac Enhance test coverage for IAM module by validating all required fields in response DTOs
- Added assertions to check for non-empty fields in TokenDto, UsersSchema, PermissionsSchema, and RolesDetailItemDto.
- Ensured that all necessary fields are validated in team-related DTOs, including TeamsCreateResponseDto and TeamsDetailResponseDto.
- Improved checks for user details in UsersDetailItemDto and UsersListItemDto to ensure data integrity.
- Verified that sensitive fields are present in admin team responses and member details.
- Updated tests to ensure that created and updated timestamps are present and valid across various entities.
2025-10-05 18:16:34 +07:00
MythEclipse 49abcf28c3 Refactor tests to enhance response validation and error handling
- Updated gacha claims service tests to parse and verify error JSON content for various scenarios.
- Improved gacha credits controller tests by adding checks for success messages in JSON responses.
- Enhanced gacha items service tests to validate response data structure and content.
- Modified IAM auth controller and service tests to ensure token data integrity and presence of required fields.
- Refined permissions controller and service tests to assert response data correctness.
- Improved roles controller and service tests to validate response data and ensure non-empty fields.
- Enhanced teams controller tests to verify sensitive data exposure and required fields in responses.
- Updated users controller and service tests to ensure response data integrity and presence of required fields.
2025-10-05 17:05:06 +07:00
MythEclipse 9cecc8fa05 Refactor tests to improve response parsing and validation
- Introduced a new common module with response helper functions to streamline response parsing across tests.
- Updated role controller tests to assert success messages in responses for create, update, and delete operations.
- Enhanced role service tests to validate response structures and ensure proper error handling.
- Modified team controller and service tests to check for success messages and validate response data formats.
- Improved user controller and service tests to include success message assertions and error handling for invalid inputs.
- Ensured all tests utilize the new response parsing functions for consistency and maintainability.
2025-10-05 16:00:46 +07:00
MythEclipse a32f54873b feat: Add previous winners field to hackathon schema and update related tests 2025-09-27 22:30:42 +07:00
MythEclipse af41a98111 feat: Add previous winners field to hackathon DTOs and schema 2025-09-27 21:05:34 +07:00
MythEclipse 4c435708c0 feat: Add endpoint to retrieve hackathon submissions and implement seeding for test submissions 2025-09-27 19:24:45 +07:00
MythEclipse ac462ea771 Refactor IAM tests: Remove unused repository tests, streamline service tests, and enhance validation checks for team and user services 2025-09-27 17:58:15 +07:00
MythEclipse 3e52223730 refactor: Update route parameters in hackathon controller for consistency 2025-09-27 13:40:02 +07:00
MythEclipse 01e479350b test: Add not found scenarios for hackathon, event, timeline, and submission repository operations 2025-09-27 13:16:13 +07:00
MythEclipse b0cf9817d7 feat: Implement submission retrieval and timeline validation in hackathon service 2025-09-27 13:06:55 +07:00
MythEclipse e530eba60d Add comprehensive tests for hackathon service functionality
- Implemented tests for creating, retrieving, updating, and deleting hackathons.
- Added validation tests for hackathon creation and updates.
- Included tests for hackathon events and timelines, ensuring proper handling of edge cases.
- Created tests for hackathon submissions, including validation and submission status updates.
- Organized tests into a dedicated module for better structure and maintainability.
2025-09-27 13:01:08 +07:00
MythEclipse ef1d63e893 refactor: Update OTP handling in auth repository tests and clean up unused variables in team and user repository tests 2025-09-26 23:30:13 +07:00
MythEclipse 5859af5294 Refactor environment module: Rename enviroment to environment and consolidate environment configuration management
- Updated all references from `enviroment` to `environment` across the codebase.
- Removed the old `enviroment` module and replaced it with a new `environment` module that includes centralized configuration management.
- Enhanced OTP generation to include secure hashing and expiration handling.
- Improved CSRF token generation and validation with better error handling.
- Cleaned up logging statements in various modules for clarity and consistency.
- Updated response formatting to include versioning from Cargo.toml.
- Removed unused mock test module from utils.
2025-09-26 23:15:33 +07:00
MythEclipse c12da948aa refactor: Clean up Argon2 password hashing implementation and remove unused configuration constants 2025-09-26 22:24:23 +07:00
MythEclipse 3cde18360c refactor: Simplify gateway service initialization and enhance seeding process for gacha rolls 2025-09-26 17:50:31 +07:00
MythEclipse 14b22328de Refactor and enhance SurrealDB integration and resource management
- Updated `lib.rs` to selectively expose specific entities and services for better clarity.
- Improved SurrealDB client initialization with detailed logging in `surrealdb/mod.rs`.
- Enhanced resource definitions in `resource.rs` with additional utility methods for better resource management.
- Refactored user data retrieval logic in `auth_middleware/mod.rs` for improved readability and efficiency.
- Cleaned up middleware exports in `lib.rs` for clearer API surface.
- Added detailed comments and documentation throughout the SurrealDB module for better maintainability.
- Updated tests to ensure compatibility with new changes and improved structure.
- Introduced new permissions module structure in `imphnen-utils` for future enhancements.
2025-09-26 17:35:30 +07:00
MythEclipse 96debc210a Refactor permissions and user DTOs to use imphnen_entities module
- Updated permissions_repository.rs to import PermissionsItemDto from imphnen_entities.
- Modified permissions_schema.rs to import PermissionsItemDto and PermissionsQueryDto from imphnen_entities.
- Changed roles_dto.rs to import PermissionsItemDto and PermissionsQueryDto from imphnen_entities.
- Updated users_dto.rs to import ExperienceDto, EducationDto, UsersDetailQueryDto, RolesDetailQueryDto, and RolesDetailItemDto from imphnen_entities, and removed redundant struct definitions.
- Refactored users_repository.rs to import UsersDetailQueryDto from imphnen_entities.
- Updated users_schema.rs to import UsersDetailQueryDto, ExperienceDto, and EducationDto from imphnen_entities.
- Modified users_service.rs to use UsersDetailQueryDto from imphnen_entities and added UserLookupService implementation.
- Updated Cargo.toml in imphnen-libs to include async-trait as a workspace dependency.
- Refactored axum module to remove redundant imports and streamline code.
- Updated lib.rs to include AppState struct with user_lookup_service and auth_repository fields.
- Refactored surrealdb module to define SurrealWsClient and SurrealMemClient types.
- Removed imphnen-iam dependency from middleware's Cargo.toml.
- Updated auth_middleware to use UsersDetailQueryDto from imphnen_entities and refactored user retrieval logic.
- Refactored permissions_middleware to use PermissionsEnum from imphnen_entities and updated user retrieval logic.
- Updated mock_test.rs to create AppState with user_lookup_service and auth_repository.
- Added permissions.rs and users.rs to imphnen_entities with necessary DTOs and enums.
- Created services.rs in imphnen-libs to define UserLookupService and AuthRepositoryTrait traits.
2025-09-26 15:05:45 +07:00
MythEclipse b80662188f feat: Update admin teams endpoint to return 403 Forbidden for unauthorized access 2025-09-26 13:04:48 +07:00
MythEclipse 7b9ce6cda1 feat: Add seeding process for teams and ensure permissions are seeded even when other seeds are skipped 2025-09-26 02:23:55 +07:00
MythEclipse 1bb2d6a419 feat: Add Administrator permission to seeding process and ensure permissions are seeded even when other seeds are skipped 2025-09-26 01:35:06 +07:00
MythEclipse 14690a378f feat: Allow access for users with Administrator permission in permissions guard 2025-09-26 01:30:00 +07:00
MythEclipse 17cc4ccdba refactor: Update permissions handling to filter out None values and ensure safe access 2025-09-26 01:08:18 +07:00
MythEclipse 1b7368a4b7 feat: Add Administrator permission and update permissions handling for roles and users 2025-09-26 00:45:57 +07:00
MythEclipse ff2e14d5f9 feat: Introduce Administrator permission and update permissions checks for access control 2025-09-25 23:47:29 +07:00
MythEclipse 012aff60ef refactor: Update admin team routes to remove versioning and avoid conflicts 2025-09-25 23:28:37 +07:00
MythEclipse f3d88e2ac9 Add comprehensive tests for Gacha Credits, Auth, and User services
- Implement tests for GachaCreditsService including creation, retrieval, updating, and deletion of gacha credits.
- Add tests for AuthController covering user login, registration, email verification, and error handling for invalid credentials.
- Enhance AuthService tests to include login, registration, email verification, OTP resend, password reset, and token refresh functionalities.
- Create tests for UsersService to validate user creation, retrieval, updating, deletion, and fetching by email.
- Ensure all tests utilize a consistent setup and teardown process for database interactions.
2025-09-25 22:53:26 +07:00
MythEclipse 0e48b6755f refactor: Remove unused execute_safe_count_query import from teams_repository 2025-09-25 22:07:38 +07:00
MythEclipse 7056f8c8a6 Add comprehensive tests for IAM permissions, roles, teams, and users
- Implemented unit tests for PermissionsController and PermissionsService, covering create, read, update, and delete operations.
- Added tests for RolesController and RolesService, including handling of duplicates and retrieval by ID.
- Developed tests for TeamsController, including creation, retrieval, updating, deletion, and search functionality.
- Created tests for UsersController, ensuring user creation and validation of attributes.
- Each test includes setup, execution, and cleanup to maintain database integrity.
2025-09-25 22:06:21 +07:00
MythEclipse 4ecdcd12d2 feat: Add administrator permissions to PermissionsEnum and update related team management functionality 2025-09-25 20:57:31 +07:00
MythEclipse dd4a73e360 feat: Add comprehensive admin team management functionality with new permissions and endpoints 2025-09-25 20:28:08 +07:00
MythEclipse 49e0a89ad1 feat: Enhance team management and permissions structure with detailed DTOs and service methods 2025-09-25 20:18:16 +07:00
MythEclipse 82b85abe8f a 2025-09-25 17:29:17 +07:00
MythEclipse df11aa5eb8 a 2025-09-25 17:26:39 +07:00
MythEclipse ac44867ec1 feat: Add member team management functionality with detailed DTOs and service methods 2025-09-22 17:38:54 +07:00
MythEclipse 7205afe43b feat: Implement admin team management endpoints with permissions and DTOs 2025-09-22 17:25:02 +07:00
MythEclipse b1c678c72b feat: Add public team listing and detail endpoints with DTOs for public access 2025-09-22 17:07:14 +07:00
MythEclipse fa3687c6be feat: Add team-related DTOs and update routes for team management 2025-09-22 16:55:03 +07:00
MythEclipse ba46a19a5a refactor: Replace surrealdb_helpers with integrated query builder methods for improved clarity and functionality 2025-09-22 16:38:07 +07:00
MythEclipse 8cdbca24ba feat: Enhance query builder with new condition methods and safe query execution 2025-09-22 16:09:22 +07:00
MythEclipse 8f981572cd feat: Introduce surrealdb_helpers for query building and execution utilities 2025-09-22 15:06:37 +07:00
MythEclipse 39b75f410f Add unit tests for TeamsRepository and TeamsService
- Implement tests for team creation, retrieval, updating, and deletion in TeamsRepository.
- Add tests for team member management including adding and removing members.
- Create tests for team invitations and searching teams.
- Ensure proper cleanup of test data after each test case.
- Validate unauthorized operations for team management.
2025-09-22 14:59:38 +07:00
MythEclipse 6da1b2a7e7 refactor: Replace make_thing with make_thing_from_enum for consistency and clarity across multiple modules 2025-09-22 09:10:20 +07:00
MythEclipse acccae9f7c fix: Correct typo in FAILED_TESTS_SUMMARY variable and enhance HTTP status code handling in API tests 2025-09-22 08:21:21 +07:00
MythEclipse e7c17784cc feat: Simplify token generation by removing unnecessary permissions parameter from access and refresh token functions 2025-09-22 07:52:00 +07:00
Maulana SodiqinandGitHub 042e0b4eff Merge pull request #45 from IMPHNEN/feat/auth-google
Feat/auth google
2025-08-17 18:26:24 +07:00
MythEclipse 0b51a56dee feat: Enhance CORS middleware to dynamically include development port and allow OPTIONS method 2025-08-17 16:06:21 +07:00
MythEclipse cb98440b65 feat: Refactor update_user_avatar method to be static and enhance avatar deletion logic 2025-08-17 15:22:15 +07:00
MythEclipse 3c19d262f3 feat: Increase CSRF token maximum age to 30 minutes and enhance logging for token generation 2025-08-17 15:08:58 +07:00
MythEclipse bdffe85544 Update dependencies and refactor OAuth service
- Updated various dependencies in Cargo.toml to their latest versions for improved performance and security.
- Refactored the Google OAuth service to streamline the creation of the OAuth client and improve code readability.
- Changed the way WebSocket messages are sent in clear_db_test.rs to use `into()` for better type handling.
- Enhanced error handling and logging in the Google OAuth callback method.
2025-08-16 19:10:27 +07:00
MythEclipse 9ed619e3fd feat: Optimize password verification by using blocking tasks for improved performance 2025-08-16 13:47:29 +07:00
MythEclipse 00fd7e1907 feat: Refactor password hashing and JWT encoding to use static keys for improved performance and security 2025-08-16 13:43:18 +07:00
MythEclipse b70126734e feat: Refactor password reset flow to use async processing and improve token validation 2025-08-16 13:38:35 +07:00
MythEclipse 6af9461079 a 2025-08-16 13:22:39 +07:00
MythEclipse 57b3662951 feat: Refactor auth service and middleware for improved user data handling and caching 2025-08-16 13:18:55 +07:00
MythEclipse c0c08f2821 Enhance Users Service and DTOs
- Added Default trait to UsersDetailItemDto for easier instantiation.
- Refactored UsersServiceTrait to use Pin<Box<dyn Future<...>> for async functions, improving compatibility with async/await.
- Updated all service methods to return futures instead of using async_trait.
- Improved error handling and logging in upload_file method, ensuring proper handling of multipart data.
- Masked sensitive information in Env struct's Debug implementation for better security in logs.
- Cleaned up Cargo.toml by removing unnecessary async-trait workspace dependency.
2025-08-16 12:48:24 +07:00
MythEclipse 8402415649 feat: Enhance user permissions and update event handling with improved response structures 2025-08-15 00:32:15 +07:00
MythEclipse 01e20baa45 feat: Add axum-extra dependency and refactor auth middleware for improved token handling 2025-08-14 23:16:41 +07:00
MythEclipse 10dc869eaf feat: Enhance permissions and roles management with improved indexing and state handling 2025-08-14 23:11:44 +07:00
MythEclipse 199d0c885e feat: Add axum-extra dependency and implement typed headers
feat: Define unique index on users table for email and fix minor syntax error

refactor: Update permissions_guard to use claims from JWT and improve user retrieval

refactor: Modify user-related service methods to accept user details directly

fix: Update token generation functions to include user ID and permissions

test: Update Google OAuth flow tests to reflect changes in token generation
2025-08-14 22:46:42 +07:00
MythEclipse 89ef48a57e feat: Update permissions for user and gacha claim access 2025-08-14 21:38:47 +07:00
MythEclipse da1826ebba feat: Add file upload with deduplication to MinIO service 2025-08-14 17:03:23 +07:00
MythEclipse 874986f1d6 feat: Implement file upload functionality with MinIO integration
- Added new dependencies for HMAC, hex, and urlencoding in Cargo.toml.
- Introduced FileUploadSchema for handling multipart file uploads.
- Enhanced UsersService with upload_file method to handle file uploads to MinIO.
- Implemented MinioService for managing MinIO interactions, including file uploads and presigned URL generation.
- Updated environment configuration to include MinIO region and secure settings.
- Added validation for file types and sizes during upload.
- Improved error handling and logging for file upload processes.
- Created utility functions for base64 decoding and content type extraction.
2025-08-14 16:53:14 +07:00
MythEclipse bbff555a06 feat(docs): add upload_file endpoint to OpenAPI documentation 2025-08-14 14:16:07 +07:00
Asep Haryana Saputra d3eb687a58 Merge branch 'feat/auth-google' of https://github.com/IMPHNEN/imphnen-backend-service into feat/auth-google 2025-08-14 06:55:26 +00:00
Asep Haryana Saputra c5516d4006 a 2025-08-14 06:54:56 +00:00
MythEclipse 5f51dd281d feat: update dependencies and add MinIO integration
- Updated `async-channel` to version 2.5.0 and added new dependencies in `Cargo.lock`.
- Introduced `minio` crate for file upload functionality.
- Added `career_status` field to user-related DTOs and schemas.
- Implemented file upload endpoint in `users_controller.rs` with multipart support.
- Created `MinioService` for handling file uploads to MinIO.
- Updated user seeding and test cases to accommodate new `career_status` field.
- Refactored permissions guard to return user details.
2025-08-14 13:16:39 +07:00
MythEclipse f6232832af feat(users): Enhance user schema and DTOs with additional fields for website, social links, location, skills, experience, and education 2025-08-13 20:40:02 +07:00
MythEclipse 277cf0770d feat(auth): Add GOOGLE_REDIRECT_URL to .env.example for Google OAuth callback 2025-08-13 01:29:41 +07:00
MythEclipse 650728a385 feat(auth): Update Google OAuth service to support custom redirect URIs 2025-08-12 23:21:34 +07:00
MythEclipse 3cc3e2a7d8 feat(auth): Update Google OAuth flow to support custom redirect URIs 2025-08-12 22:06:26 +07:00
MythEclipse 39fc2f86ad feat(users): Include avatar field in user creation from DTO 2025-08-12 19:50:52 +07:00
Asep Haryana Saputra 7bd0ef2274 a 2025-08-12 12:41:16 +00:00
MythEclipse b40a430c49 feat(auth): Enhance Google OAuth flow with async email extraction and caching 2025-08-12 19:25:10 +07:00
MythEclipse 44b1e09551 fix(users): Change meta parameter extraction from Json to Query in get_user_list function 2025-08-12 18:53:11 +07:00
MythEclipse 1b9251b2dd Refactor mentor and user schemas to centralize personal data management
- Updated `seed_mentor_user.rs` to include additional fields in the `app_users` creation and removed redundant fields from `app_mentors`.
- Modified `seed_users.rs` to initialize new user fields including legal name, domicile, and professional links.
- Adjusted `mentors_dto.rs` to remove personal data fields from `MentorDetailWithUserDto` and `MentorDetailResponseDto`, now sourced from `UsersSchema`.
- Updated `mentors_repository.rs` to search for user data through `user_id` instead of mentor fields.
- Refined `mentors_schema.rs` to remove personal data fields, now managed in `UsersSchema`.
- Enhanced `mentors_service.rs` to populate mentor responses with user data from `UsersSchema`.
- Removed identity document URL and related fields from various DTOs and schemas across the codebase.
- Updated tests to reflect the removal of identity document URL and ensure compatibility with the new schema structure.
2025-08-12 18:43:30 +07:00
MythEclipse 34b6cdabfb feat(users): Add optional fields to user schemas and update user avatar functionality 2025-08-12 17:31:12 +07:00
MythEclipse a25e896fa2 feat(auth): Enhance Google OAuth integration with PKCE support and CSRF validation improvements 2025-08-12 16:11:15 +07:00
Asep Haryana Saputra adf3ef8e28 a 2025-08-12 08:14:05 +00:00
MythEclipse ad46687f07 refactor(tests): Remove unused imports in CSRF token tests 2025-08-12 01:51:10 +07:00
MythEclipse 0ba04abee9 feat(auth): Enhance Google OAuth service with CSRF protection and validation logic
feat(auth): Add error handling for authentication and validation errors
feat(auth): Implement default role assignment for new users in Google OAuth flow
feat(utils): Introduce CSRF token generation and validation utilities
fix(dependencies): Update Cargo.toml to include base64 and sha2 dependencies
2025-08-12 00:32:59 +07:00
MythEclipse 1e25a5b496 feat(auth): Update Google OAuth integration to enhance response structure and improve callback handling 2025-08-11 23:47:15 +07:00
MythEclipse d7178c792d a 2025-08-11 23:06:45 +07:00
MythEclipse d2754de9ef feat(auth): Refactor Google OAuth service and controller to utilize environment variables and enhance response structure 2025-08-11 22:54:10 +07:00
MythEclipse cda950ed7e feat(auth): Implement Google OAuth 2.0 integration with user creation and JWT generation
- Added Google OAuth controller and service to handle authentication via Google.
- Introduced DTOs for Google user and token responses.
- Updated AuthService and UsersService traits to support new Google OAuth functionality.
- Implemented logic to create a new user if they do not exist in the system after Google authentication.
- Enhanced existing user retrieval and JWT generation upon successful login.
- Added tests for Google OAuth flow, including login redirection and callback handling for both new and existing users.
- Updated environment configuration to include Google OAuth credentials.
2025-08-11 22:31:51 +07:00
MythEclipse c6a95c1231 fix: update default surrealdb password to 'root' for consistency 2025-07-31 20:34:36 +07:00
MythEclipse 86116b8157 feat: add logging for SurrealDB queries across multiple repositories 2025-07-31 16:51:08 +07:00
MythEclipse ac06224ed1 feat: enhance logging and dependency management with dotenvy and tracing-subscriber 2025-07-31 15:42:15 +07:00
MythEclipse 83e765f358 feat: add logger module with initialization function using tracing and dotenvy 2025-07-31 15:15:55 +07:00
MythEclipse 558e0ce568 refactor: simplify environment variable loading with helper function and remove unused mail configuration 2025-07-31 15:12:01 +07:00
MythEclipse 148cf3a5cd refactor: streamline environment variable loading and improve logging 2025-07-31 15:07:18 +07:00
Maulana SodiqinandGitHub ee9d23e01b Merge pull request #44 from IMPHNEN/feat/mentor
Add comprehensive tests for mentor repository and authentication
2025-07-21 22:18:14 +07:00
MythEclipse 1a2e0c58b6 Add comprehensive tests for mentor repository and authentication
- Implemented tests for creating, retrieving, updating, and deleting mentors in `mentor_repository_test.rs`.
- Added tests for user authentication, including successful login, invalid email formats, and inactive users in `auth_login_tests.rs`.
- Created a mock test environment setup in `mock_test.rs` to facilitate database operations during tests.
- Updated module structure to include new test files for mentors and authentication.
- Ensured cleanup of the database after tests to maintain isolation and prevent side effects.
2025-07-21 21:29:04 +07:00
Maulana SodiqinandGitHub e66f1f1634 chore: remove deprecated deployment 2025-06-30 09:28:11 +07:00
Maulana SodiqinandGitHub 6f45cf80c8 Merge pull request #38 from IMPHNEN/feat/client-dynamic-wss-or-ws
refactor: update surrealdb client usage to support 'any' engine type
2025-06-30 09:27:16 +07:00
MythEclipse 02be09506a refactor: update surrealdb client usage to support 'any' engine type 2025-06-29 23:23:18 +07:00
Maulana SodiqinandGitHub b88ecd1361 Merge pull request #37 from bakunya/develop
crud testi: acc banh
2025-06-29 00:34:44 +07:00
0x6d696b7566616e fa435994f2 crud testi 2025-06-29 00:01:00 +07:00
Maulana SodiqinandGitHub 16c613d699 Merge pull request #36 from IMPHNEN/feat/dotenv-dynamic-engine-seeder
feat: add dotenvy for environment variable management
2025-06-28 20:50:20 +07:00
MythEclipse f598dedb3b feat: add dotenvy for environment variable management and improve error handling in Env struct 2025-06-28 20:21:20 +07:00
Maulana SodiqinandGitHub cfa251337f Create deploy-to-ancikri.yml 2025-05-30 15:40:41 +07:00
Maulana Sodiqin cca9aa6318 chore: optimize dockerfile 2025-05-26 23:41:00 +07:00
Maulana Sodiqin f1e4e02697 fix: landing 2025-05-26 23:09:01 +07:00
Maulana SodiqinandGitHub a3c2715a85 Merge pull request #25 from bakunya/develop
feat: cms event
2025-05-26 15:28:05 +07:00
0x6d696b7566616e 89cc631fb0 feat: cms event 2025-05-26 14:11:17 +07:00
Maulana Sodiqin 36c12110c2 fixing dockerfile 2025-05-22 22:29:28 +07:00
Maulana Sodiqin 070060365a docs: update readme 2025-05-22 16:18:15 +07:00
Maulana Sodiqin 68e816f956 fix: schema default value 2025-05-22 15:25:24 +07:00
Maulana Sodiqin 48db5f07ef fix: register roles missmatch 2025-05-22 15:13:58 +07:00
Maulana Sodiqin a4b5d91906 chore: setup folder structure 2025-05-22 00:40:40 +07:00
Maulana Sodiqin 9878279660 feat: add gacha credits 2025-05-22 00:31:36 +07:00
Maulana Sodiqin 465cbee2c3 feat: finishing gacha feature 2025-05-21 19:37:30 +07:00
Maulana Sodiqin 33a2ae86c6 fix: unit tests 2025-05-21 11:35:35 +07:00
Maulana Sodiqin d906fc4747 chore: update query list 2025-05-20 16:57:45 +07:00
Maulana Sodiqin 055ef6ac8e feat: adjust readme and add new seeder script 2025-05-20 11:54:15 +07:00
Maulana Sodiqin e63658c082 feat: add gacha and init cms 2025-05-20 10:45:01 +07:00
Maulana SodiqinandGitHub f4b0ed0a4a Merge pull request #24 from IMPHNEN/chore/normalize-code
chore: normalize code
2025-05-20 01:50:58 +07:00
Maulana Sodiqin 1e5ed26f76 chore: cleaning code 2025-05-20 01:49:50 +07:00
Maulana Sodiqin d97095a38d chore: cleaning code 2025-05-20 00:26:24 +07:00
Maulana Sodiqin e48507901e chore: normalize code #2 2025-05-18 03:12:20 +07:00
Maulana Sodiqin a43ef8ec04 chore: normalize code 2025-05-17 02:08:59 +07:00
Maulana SodiqinandGitHub 874f25aa80 Merge pull request #23 from bakunya/develop
transform id(thing) to id(string) on get role, permission, users
2025-05-04 17:24:13 +07:00
Bakunya 12a730a394 transform id(thing) to id(string) on get role, permission, users 2025-05-04 17:07:20 +07:00
Bakunya bdcd41f54d transform id(thing) to id(string) on get role, permission, users 2025-05-04 16:37:11 +07:00
Maulana SodiqinandGitHub 96fb8eb7d3 Merge pull request #22 from IMPHNEN/feat/split-middleware
feat: split middleware
2025-04-07 20:43:59 +07:00
Maulana Sodiqin d2c333dbd6 feat: split middleware 2025-04-07 20:41:14 +07:00
Maulana Sodiqin 054f0f63ff chore: adjust README.md 2025-04-07 20:08:26 +07:00
Maulana Sodiqin eb05ea5994 feat: add gacha service 2025-04-07 00:50:57 +07:00
Maulana Sodiqin 4f870ec4c9 fix: unit test 2025-04-06 23:35:02 +07:00
Maulana Sodiqin 31f9b6cfea feat: microservice ready 2025-04-06 22:13:46 +07:00
Maulana SodiqinandGitHub 07a93ff0b7 Merge pull request #21 from bakunya/develop
fix otp and password validation
2025-04-06 20:09:17 +07:00
Bakunya d2b098ed92 fix otp and password validation 2025-04-06 19:15:01 +07:00
Maulana Sodiqin 09a7f4371a chore: remove uneeded cargo package 2025-04-06 13:28:15 +07:00
Maulana Sodiqin b4bf78f0d6 chore: re-map project structure to using multi workspace paradigm 2025-04-06 13:25:44 +07:00
Maulana Sodiqin de9c5a6dc1 feat: implement guard 2025-04-02 09:35:37 +07:00
Maulana Sodiqin 8a661df059 feat: add image url to gacha DTO 2025-04-01 20:05:07 +07:00
Maulana Sodiqin c7c16d4197 feat: add image url 2025-04-01 20:04:28 +07:00
Maulana Sodiqin 3aec0346a9 fix: wrong id 2025-04-01 20:01:40 +07:00
Maulana Sodiqin 8d2f720de1 feat: add gacha 2025-04-01 20:00:00 +07:00
Maulana Sodiqin 4b8da68df4 feat: gacha 2025-03-30 18:58:17 +07:00
Maulana Sodiqin 6460979bab feat: complete backend service 2025-03-30 16:08:58 +07:00
Maulana Sodiqin 3ae9dbd717 feat: success test 2025-03-30 14:13:45 +07:00
Maulana Sodiqin 0816566d03 feat: update logic 2025-03-30 02:46:16 +07:00
Maulana Sodiqin a97044edfc fix: seeder roles permissions 2025-03-28 17:18:07 +07:00
Maulana Sodiqin 9d92a9a136 feat: pagination 2025-03-26 13:06:34 +07:00
Maulana Sodiqin 8e12c79ea6 feat: permissions controller 2025-03-25 20:50:42 +07:00
Maulana Sodiqin 5777268441 feat: fixing role and auth test 2025-03-25 19:30:02 +07:00
Maulana Sodiqin 34eaa418d5 feat: roles router 2025-03-25 10:48:34 +07:00
Maulana Sodiqin 77f12610dd fix: test user 2025-03-24 13:12:54 +07:00
Maulana Sodiqin 5be737ad70 chore: add test coverage 2025-03-23 20:42:38 +07:00
Maulana Sodiqin 0ae1e26ba8 chore: complete unit test of user and authentication system 2025-03-23 12:32:00 +07:00
Maulana Sodiqin 79721b7af6 chore: implement unit test 2025-03-23 07:56:43 +07:00
Maulana Sodiqin 093e290221 feat: complete auth system 2025-03-23 01:19:17 +07:00
Maulana Sodiqin 1e6957720e feat: user management 2025-03-21 17:00:19 +07:00
Maulana Sodiqin a0f263bb4f feat: update query 2025-03-21 13:25:22 +07:00
Maulana Sodiqin 413a28c089 feat: setup data 2025-03-21 05:36:00 +07:00
Maulana Sodiqin a90e8662e1 feat: initial commit 2025-03-20 22:41:20 +07:00
Maulana Sodiqin 955d384f96 fix: docker 2025-03-20 17:36:43 +07:00
Maulana Sodiqin ea5ece9ab2 feat: initial commit 2025-03-20 17:33:57 +07:00
Maulana Sodiqin 8ff532bb67 fix: cors 2025-03-20 17:07:38 +07:00
Maulana Sodiqin eb6cfd51ae feat: auth functionality 2025-03-19 23:17:50 +07:00
Maulana Sodiqin 11d6249007 feat: docs 2025-03-19 20:55:29 +07:00
Maulana Sodiqin 497c250e6d fix: change deployed branch 2025-03-19 19:34:57 +07:00
Maulana Sodiqin 2872c1827a feat: deploy 2025-03-19 19:33:56 +07:00
Maulana Sodiqin f9c49d44b5 feat: gacha roll 2025-03-19 05:34:39 +07:00
Maulana Sodiqin 12043f027c feat: gacha roll, user auth 2025-03-18 14:13:53 +07:00
Maulana Sodiqin 0c28d34d57 feat: apply env 2025-03-17 09:27:19 +07:00
Maulana Sodiqin 271b00c2c4 feat: create gacha item 2025-03-15 02:23:27 +07:00
Maulana Sodiqin b096f4129a feat: add middleware 2025-03-15 01:53:20 +07:00
Maulana Sodiqin 7ab036f5f7 feat: user relation 2025-03-14 17:50:37 +07:00
Maulana Sodiqin 9ffe808797 feat: basic auth 2025-03-14 09:53:20 +07:00
Maulana Sodiqin acfb8259bc feat: auth 2025-03-13 23:40:16 +07:00
Maulana Sodiqin 298144bd36 chore: fix nix 2025-02-26 15:55:48 +07:00
Maulana Sodiqin ff9d8cba69 feat: add cargo 2025-02-26 15:45:39 +07:00
Maulana Sodiqin 8b2769706e feat: add cargo 2025-02-26 15:45:05 +07:00
Maulana Sodiqin b8606ef0bb chore: remove seaorm 2025-02-25 02:02:01 +07:00
Maulana Sodiqin 44de53a49d feat: implement surrealdb and redis 2025-02-25 02:00:19 +07:00
Maulana Sodiqin 9abab01b9c chore: re-format file 2025-02-16 01:09:55 +07:00
Maulana Sodiqin 53414687ff chore: initial commit 2025-02-16 01:02:51 +07:00
Maulana SodiqinandGitHub d2ec21c7b1 chore: add readme 2025-02-08 01:16:14 +07:00
Maulana SodiqinandGitHub 4deee3a9cb chore: configure action 2025-02-08 01:10:48 +07:00
Maulana SodiqinandGitHub b50ce2b060 Merge pull request #1 from IMPHNEN/feat/auth-login
feat: auth login
2025-02-08 01:09:57 +07:00
615 changed files with 36333 additions and 1146 deletions
+2
View File
@@ -0,0 +1,2 @@
[target.x86_64-pc-windows-msvc]
linker = "rust-lld.exe"
+5 -5
View File
@@ -1,5 +1,5 @@
target target
.dockerignore .dockerignore
Dockerfile Dockerfile
.git .git
.gitignore .gitignore
+33 -4
View File
@@ -1,4 +1,33 @@
PORT= RUST_ENV=development
DATABASE_URL= RUST_LOG=debug
ACCESS_TOKEN_SECRET= PORT=4099
REFRESH_TOKEN_SECRET= ACCESS_TOKEN_SECRET=your-access-token-secret-key-here
REFRESH_TOKEN_SECRET=your-refresh-token-secret-key-here
SMTP_EMAIL=your-email@example.com
SMTP_PASSWORD=your-smtp-password
SMTP_NAME="Your App Name"
SMTP_HOST=smtp.gmail.com
REDISDB_URL=localhost
FE_URL=http://localhost
MINIO_ENDPOINT=http://localhost:9000
MINIO_BUCKET_NAME=default_bucket
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin
MINIO_SECURE=false
GOOGLE_CLIENT_ID="your_google_client_id"
GOOGLE_CLIENT_SECRET="your_google_client_secret"
POOL_SIZE=10
CONNECT_TIMEOUT=30
IDLE_TIMEOUT=60
MAX_LIFETIME=1800
STATEMENT_TIMEOUT=30000
IDLE_IN_TRANSACTION_SESSION_TIMEOUT=60000
SSLMODE=require
RETRY_ATTEMPTS=3
RETRY_DELAY=1
GOOGLE_REDIRECT_URL=http://localhost:8000/api/v1/auth/google/callback
CDN_URL=https://cdn.asepharyana.tech
CORS_ALLOWED_ORIGINS=http://localhost:3000,https://gacha.imphnen.dev,https://imphnen.dev,https://dimentorin.imphnen.dev
+1 -1
View File
@@ -1 +1 @@
use flake --impure use flake --impure
+78
View File
@@ -0,0 +1,78 @@
name: Nix Build & Deploy
on:
push:
branches: ['develop']
pull_request:
branches: ['develop']
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@main
- name: Setup Cachix
uses: cachix/cachix-action@v15
with:
name: msdqn
authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
- name: Build
run: nix build .#default -o result
- name: Push to Cachix
if: github.event_name == 'push' && github.ref == 'refs/heads/develop'
run: cachix push msdqn result
deploy:
needs: build
if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
steps:
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@main
- name: Setup SSH
env:
INFRA_DEPLOY_KEY: ${{ secrets.INFRA_DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh
echo "${INFRA_DEPLOY_KEY}" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan github.com >> ~/.ssh/known_hosts 2>/dev/null
ssh-keyscan 167.235.70.37 >> ~/.ssh/known_hosts 2>/dev/null
- name: Update infra flake.lock
run: |
export GIT_SSH_COMMAND="ssh -i ~/.ssh/deploy_key -o IdentitiesOnly=yes"
git clone git@github.com:IMPHNEN/imphnen-infrastructure.git /tmp/infra
cd /tmp/infra
nix flake update imphnen-backend
if git diff --quiet flake.lock; then
echo "flake.lock unchanged, skipping"
else
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add flake.lock
git commit -m "chore: update imphnen-backend-service to ${GITHUB_SHA::7}"
git push
fi
- name: Deploy to server
run: |
ssh -i ~/.ssh/deploy_key \
-o ConnectTimeout=30 \
-o StrictHostKeyChecking=accept-new \
-o ServerAliveInterval=30 \
-o ServerAliveCountMax=40 \
root@167.235.70.37 \
'nixos-rebuild switch --flake github:IMPHNEN/imphnen-infrastructure#hetzner --refresh 2>&1 | tail -50'
- name: Cleanup
if: always()
run: rm -f ~/.ssh/deploy_key
+16 -14
View File
@@ -1,14 +1,16 @@
# Build # Build
/target /target
/resutl /resutl
# Nix # Nix
/.direnv /.direnv
/Cargo.nix
# Environment
.envrc # Environment
.env .envrc
.env.local .env
.env.development .env.local
.env.staging .env.development
.env.production .env.staging
.env.production
**/**.log
+1
View File
@@ -0,0 +1 @@
/cache
+71
View File
@@ -0,0 +1,71 @@
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
# * For C, use cpp
# * For JavaScript, use typescript
# Special requirements:
# * csharp: Requires the presence of a .sln file in the project folder.
language: rust
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# whether to use the project's gitignore file to ignore files
# Added on 2025-04-07
ignore_all_files_in_gitignore: true
# list of additional paths to ignore
# same syntax as gitignore, so you can use * and **
# Was previously called `ignored_dirs`, please update your config if you are using that.
# Added (renamed) on 2025-04-07
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_lines`: Deletes a range of lines within a file.
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
# * `execute_shell_command`: Executes a shell command.
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Gets the initial instructions for the current project.
# Should only be used in settings where the system prompt cannot be set,
# e.g. in clients you have no control over, like Claude Desktop.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_at_line`: Inserts content at a given line in a file.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: Lists memories in Serena's project-specific memory store.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
# * `remove_project`: Removes a project from the Serena configuration.
# * `replace_lines`: Replaces a range of lines within a file with new content.
# * `replace_symbol_body`: Replaces the full definition of a symbol.
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
# * `switch_modes`: Activates modes by providing a list of their names
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
excluded_tools: []
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
project_name: "imphnen-backend-service"
Generated
+2844 -592
View File
File diff suppressed because it is too large Load Diff
+96 -15
View File
@@ -1,24 +1,105 @@
[package] [workspace]
name = "imphnen-cms-be" resolver = "2"
version = "0.1.0" members = [
edition = "2021" "imphnen-entities",
"imphnen-macros",
"imphnen-libs",
"imphnen-storage",
"imphnen-email",
"imphnen-utils",
"imphnen-middleware",
"imphnen-iam",
"imphnen-cms",
"imphnen-gacha",
"imphnen-dimentorin",
"imphnen-hackathon",
"imphnen-gateway",
"imphnen-backend",
]
[dependencies]
axum = { version = "0.8.1", features = ["multipart"] } [workspace.dependencies]
log = "0.4.25" async-trait = "0.1.83"
sea-orm = { version = "1.1.4", features = ["sqlx-postgres", "macros", "with-json", "with-uuid", "runtime-tokio", "runtime-tokio-native-tls"] } oauth2 = "5.0.0"
serde = { version = "1.0.217", features = ["derive"] } reqwest = { version = "0.12.23", features = ["json"] }
serde_json = "1.0.138" serde_json = "1.0.142"
tokio = { version = "1.43.0", features = ["full"] } axum = { version = "0.8.4", features = ["multipart", "macros"] }
log = "0.4.27"
serde = { version = "1.0.219", features = ["derive"] }
tokio = { version = "1.47.1", features = ["full"] }
argon2 = { version = "0.5.3", features = ["password-hash"] } argon2 = { version = "0.5.3", features = ["password-hash"] }
jsonwebtoken = "9.3.1" jsonwebtoken = "9.3.1"
chrono = "0.4.39" chrono = "0.4.41"
utoipa = { version = "5.3.1", features = ["axum_extras"] } utoipa = { version = "5.4.0", features = ["axum_extras", "uuid", "chrono"] }
utoipa-swagger-ui = { version = "9.0.0", features = ["axum"] } utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
redis = "0.28.2" lettre = { version = "0.11.18", features = ["tokio1-native-tls"] }
thiserror = "2.0.14"
anyhow = "1.0.99"
rand = { version = "0.9.2", features = ["std", "alloc"] }
rand_distr = "0.5.1"
tower-http = { version = "0.6.6", features = ["cors", "trace"] }
http-body-util = "0.1.3"
zod-rs = { version = "0.4", features = ["macros"] }
zod-rs-util = "0.4"
paginator-rs = "0.2"
paginator-utils = "0.2"
paginator-sea-orm = { version = "0.2", features = ["sqlx-postgres", "runtime-tokio"] }
paginator-axum = "0.2"
lazy_static = "1.5.0"
regex = "1.11.1"
axum-test = "17.3.0"
axum-extra = { version = "0.10.1", features = ["typed-header"] }
fancy-regex = "0.16.1"
futures = "0.3.31"
tower = "0.5.2"
env_logger = "0.11.8"
tracing = "0.1.41"
uuid = { version = "1.18.0", features = ["v4", "fast-rng", "serde"] }
strum = { version = "0.27.2", features = ["derive"] }
strum_macros = "0.27.2"
base64 = "0.22.1"
sha2 = "0.10.9"
hmac = "0.12"
hex = "0.4"
urlencoding = "2.1"
hyper = "1.6.0"
hyper-util = "0.1.16"
minio = "0.3.0"
sea-orm = { version = "1.1", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros", "with-chrono", "uuid"] }
sqlx = { version = "0.8", features = ["postgres", "runtime-tokio-native-tls", "uuid", "chrono", "json", "macros"] }
num_cpus = "1.16.0"
tokio-test = "0.4.4"
mockall = "0.13.1"
once_cell = "1.21.3"
dotenvy = "0.15.7"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
tokio-tungstenite = "0.27"
url = "2.5"
futures-util = "0.3"
http = "1.3"
imphnen-iam = { path = "./imphnen-iam" }
imphnen-cms = { path = "./imphnen-cms" }
imphnen-libs = { path = "./imphnen-libs" }
imphnen-utils = { path = "./imphnen-utils" }
imphnen-gacha = { path = "./imphnen-gacha" }
imphnen-gateway = { path = "./imphnen-gateway" }
imphnen-backend = { path = "./imphnen-backend" }
imphnen-entities = { path = "./imphnen-entities" }
imphnen-dimentorin = { path = "./imphnen-dimentorin" }
imphnen-middleware = { path = "./imphnen-middleware" }
imphnen-macros = { path = "./imphnen-macros" }
imphnen-hackathon = { path = "./imphnen-hackathon" }
imphnen-storage = { path = "./imphnen-storage" }
imphnen-email = { path = "./imphnen-email" }
bcrypt = "0.15"
image = { version = "0.25", features = ["png", "jpeg"] }
qrcode = { version = "0.14", default-features = false, features = ["image"] }
[profile.release] [profile.release]
lto = "fat" lto = "fat"
codegen-units = 1 codegen-units = 1
panic = "abort" panic = "abort"
opt-level = "z" opt-level = "z"
+46 -13
View File
@@ -1,22 +1,55 @@
FROM rust:1.83-slim-bullseye AS builder FROM rust:1.86-alpine AS builder
RUN apt-get update && apt-get install -y \ RUN apk add --no-cache \
build-essential \ curl \
libssl-dev \ musl-dev \
pkg-config \ openssl-dev \
&& rm -rf /var/lib/apt/lists/* openssl-libs-static \
pkgconfig
WORKDIR /app WORKDIR /app
COPY Cargo.toml Cargo.lock ./ COPY Cargo.toml Cargo.lock ./
COPY ./src ./src
RUN cargo build --release && strip /app/target/release/imphnen-cms-api RUN mkdir -p \
imphnen-backend/src \
imphnen-cms/src \
imphnen-dimentorin/src \
imphnen-email/src \
imphnen-entities/src \
imphnen-gacha/src \
imphnen-gateway/src \
imphnen-hackathon/src \
imphnen-iam/src \
imphnen-libs/src \
imphnen-macros/src \
imphnen-middleware/src \
imphnen-storage/src \
imphnen-utils/src && \
echo "fn main() {}" > imphnen-backend/src/main.rs && \
find . -name "src" -type d -exec sh -c 'touch "$1/lib.rs"' _ {} \;
FROM gcr.io/distroless/cc AS runner COPY imphnen-backend ./imphnen-backend
COPY imphnen-cms ./imphnen-cms
COPY imphnen-dimentorin ./imphnen-dimentorin
COPY imphnen-email ./imphnen-email
COPY imphnen-entities ./imphnen-entities
COPY imphnen-gacha ./imphnen-gacha
COPY imphnen-gateway ./imphnen-gateway
COPY imphnen-hackathon ./imphnen-hackathon
COPY imphnen-iam ./imphnen-iam
COPY imphnen-libs ./imphnen-libs
COPY imphnen-macros ./imphnen-macros
COPY imphnen-middleware ./imphnen-middleware
COPY imphnen-storage ./imphnen-storage
COPY imphnen-utils ./imphnen-utils
WORKDIR /app RUN RUSTFLAGS="-C target-cpu=generic -C opt-level=s -C panic=abort -C codegen-units=1 -C strip=symbols" \
cargo build -p imphnen-backend --release && \
strip target/release/api && \
upx --best --lzma target/release/api 2>/dev/null || true
COPY --from=builder /app/target/release/imphnen-cms-api . FROM scratch AS runner
COPY --from=builder /app/target/release/api /api
CMD ["/app/imphnen-cms-api"] COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
ENTRYPOINT ["/api"]
+130
View File
@@ -0,0 +1,130 @@
# IMPHNEN Backend Service
<p align="center">
<img src="docs/logo.svg" alt="IMPHNEN">
</p>
This repository serves as the **monorepo** for all backend services of IMPHNEN. It encompasses several main services:
1. **IMPHNEN-Backend** - Provides fundamental functionalities and shared resources for other services.
2. **IMPHNEN-IAM** - Handles identity and access management across IMPHNEN applications.
3. **IMPHNEN-CMS** - Supports the cms services by IMPHNEN [Landing Page website](https://imphnen.dev/).
4. **IMPHNEN-Gacha** - Supports the gacha services by IMPHNEN [Gacha website](https://gacha.imphnen.dev/).
5. **IMPHNEN-Dimentorin** - Supports the mentoring services by IMPHNEN [Dimentorin website](https://dimentorin.imphnen.dev/).
6. **IMPHNEN-Gateway** - Acts as the API gateway, routing requests to appropriate services.
7. **IMPHNEN-Middleware** - Acts as the middleware for the API Gateway, providing authentication and authorization.
## How to Install
1. **Clone the repository**:
```sh
git clone https://github.com/IMPHNEN/imphnen-backend-service.git
cd imphnen-backend-service
```
2. **Set up the environment**:
- Copy the example environment files:
```sh
cp .env.example .env
```
if you use windows based system
```sh
./apply-env.ps1
```
if you use unix based system
```sh
source ./apply-env.sh
```
- Modify the `.env` files with your specific configuration settings.
3. **Install dependencies**:
Ensure you have [Rust](https://www.rust-lang.org/) installed. Then, run:
```sh
cargo fetch
```
4. **Run the seeders**:
to run the seeders, run:
```sh
cargo run --bin seeder
```
## How to Run
### Development
To run the services in development mode:
1. **Start the database and other dependencies** using Docker Compose:
```sh
docker-compose up -d
```
2. **Run using cargo run**. For example, to run the Core Service:
```sh
cargo run --bin api
```
3. **Run using cargo watch**. For example, to run the Core Service:
```sh
cargo watch -x "run --bin api"
```
### Production
For production deployment:
1. **Build the Docker image**:
```sh
docker build -t imphnen-backend .
```
2. **Run the Docker container**:
```sh
docker run --name imphnen-backend -d --env-file .env -p 3000:3000 imphnen-backend
```
Adjust the port and environment variables as needed.
## How to Run the Tests
1. **Run the tests**:
```sh
cargo test -p tests
```
## How to Contribute
1. **Fork the repository** and clone it locally.
2. **Create a new branch** for your feature or fix:
```sh
git checkout -b feat/your-feature-name
```
3. **Make your changes**, commit them, and push to your forked repository.
4. **Create a pull request** to the `develop` branch of this repository.
If you encounter any issues or have questions, feel free to create a new issue in the repository.
---
_Note: For detailed API documentation, please refer to our [API Docs](https://api.imphnen.dev/docs)._
+24 -14
View File
@@ -1,15 +1,25 @@
{pkgs ? import <nixpkgs> {}}: let { pkgs ? import <nixpkgs> { } }:
manifest = (pkgs.lib.importTOML ./Cargo.toml).package; let
rustDeps = pkgs.callPackage ./Cargo.nix {}; swaggerUi = pkgs.fetchurl {
packageEntry = rustDeps.workspaceMembers.${manifest.name}; url = "https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.17.14.zip";
deps = packageEntry.build.cargoDeps or null; hash = "sha256-SBJE0IEgl7Efuu73n3HZQrFxYX+cn5UU5jrL4T5xzNw=";
};
in in
pkgs.rustPlatform.buildRustPackage { pkgs.rustPlatform.buildRustPackage {
pname = manifest.name; pname = "imphnen-backend";
version = manifest.version; version = (pkgs.lib.importTOML ./imphnen-backend/Cargo.toml).package.version;
cargoDeps = deps; src = pkgs.lib.cleanSource ./.;
src = pkgs.lib.cleanSource ./.; cargoLock.lockFile = ./Cargo.lock;
cargoLock.lockFile = ./Cargo.lock; cargoBuildFlags = [
nativeBuildInputs = [pkgs.openssl pkgs.pkg-config]; "--package"
buildInputs = [pkgs.openssl]; "imphnen-backend"
} "--bin"
"api"
];
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [ pkgs.openssl ];
preBuild = ''
export SWAGGER_UI_DOWNLOAD_URL="file://${swaggerUi}"
'';
doCheck = false;
}
+46 -8
View File
@@ -1,8 +1,46 @@
services: services:
api: api:
build: build:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
ports: ports:
- "${PORT}:${PORT}" - "${PORT}:${PORT}"
env_file: ".env" env_file: ".env"
depends_on:
- postgres
postgres:
image: postgres:15-alpine
container_name: imphnen_postgres
environment:
POSTGRES_DB: ${POSTGRES_DB:-imphnen}
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
ports:
- "${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-imphnen}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
minio:
image: minio/minio:latest
container_name: minio
ports:
- "9000:9000"
- "9001:9001"
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
command: server /data --console-address ":9001"
volumes:
- minio_data:/data
volumes:
postgres_data:
minio_data:
+43 -42
View File
@@ -1,42 +1,43 @@
{pkgs, ...}: let { pkgs, ... }:
baseImage = pkgs.ociTools.pullImage { let
imageName = "ubuntu"; baseImage = pkgs.ociTools.pullImage {
tag = "latest"; imageName = "ubuntu";
}; tag = "latest";
in };
pkgs.dockerTools.buildImage { in
name = "imphnen-cms-api"; pkgs.dockerTools.buildImage {
name = "imphnen-backend-service";
fromImage = baseImage;
fromImage = baseImage;
copyToRoot = pkgs.buildEnv {
name = "imphnen-cms-api"; copyToRoot = pkgs.buildEnv {
paths = [ name = "imphnen-backend-service";
(pkgs.stdenv.mkDerivation { paths = [
name = "imphnen-cms-api"; (pkgs.stdenv.mkDerivation {
src = ./src; name = "imphnen-backend-service";
src = ./src;
buildInputs = [
pkgs.rustc buildInputs = [
pkgs.cargo pkgs.rustc
pkgs.openssl pkgs.cargo
pkgs.pkg-config pkgs.openssl
]; pkgs.pkg-config
];
buildPhase = ''
cargo build --release buildPhase = ''
''; cargo build --release
'';
installPhase = ''
mkdir -p $out/bin installPhase = ''
cp target/release/najm-course-api $out/bin/ mkdir -p $out/bin
''; cp target/release/imphnen-backend-service $out/bin/
}) '';
]; })
}; ];
};
config = {
Cmd = ["/bin/imphnen-cms-api"]; config = {
WorkingDir = "/bin"; Cmd = [ "/bin/imphnen-backend-service" ];
}; WorkingDir = "/bin";
} };
}
+74
View File
@@ -0,0 +1,74 @@
# Dimentorin — Catatan Temuan Infra (Dev Audit, 2026-08-04)
Dokumen ini mencatat temuan yang membutuhkan perhatian tim sebelum produksi.
Semua diuji lokal (Postgres `dimentorin`, backend :4099).
## 1. SMTP email verification broken (blocker aktivasi user baru) — ✅ FIXED (2026-08-05, Google App Password)
- Endpoint `POST /v1/iam/auth/send-otp` gagal: `SMTP transport error (535): Username and Password not accepted` — kredensial `.env` (`SMTP_EMAIL=dev@example.com`, `SMTP_PASSWORD=dev`) ditolak Google SMTP.
- `POST /v1/iam/auth/verify-email` tetap butuh OTP untuk memanggil, tapi lihat poin 2.
- **Dampak**: mentee/mentor baru tak bisa menerima OTP lewat email → tak bisa aktivasi → tak bisa login, kecuali via verify-email langsung.
- **Diperlukan**: SMTP credential institution yang valid (Gmail App Password atau SMTP relay), sebaiknya dari BWS secret management, bukan hardcode.
## 2. ✅ FIXED — verify-email TIDAK memverifikasi OTP (security issue)
**Status: FIXED di branch feat/dimentorin-postgres (2026-08-04).**
`imphnen-iam/src/auth/application/mod.rs``verify_email()`:
- OTP sekarang dipersist ke tabel **`app_otp_cache`** (entity baru `imphnen-entities/src/seaorm/common/otp_cache.rs`, resource `app_otp_cache` sudah direncanakan di `ResourceEnum::OtpCache`).
- `register()` & `resend_otp()` menyimpan `otp_hash` + `expires_at` setelah email terkirim (kalau email gagal, tidak ada OTP yatim / OTP lama tidak di-overwrite).
- `verify_email()` memanggil `OtpManager::validate_otp_hash(stored_hash, expires_at, payload.otp)` sebelum set `is_active`. `validate_otp_hash` ditambahkan ke `OtpManager` (pure hash+expiry tanpa perlu plaintext code).
- OTP **single-use**: di-delete setelah verifikasi sukses. Reuse / OTP tanpa cache / OTP expired semua ditolak (400).
- Uji lokal (Postgres, :4099): OTP salah → 400 "Invalid or expired OTP", user tetap inactive; OTP benar → 200 "Email verified successfully", user aktif, OTP dihapus; verify ulang → 400 "User already active"; email tanpa OTP → 400 "No OTP issued".
- Tabel dibuat via SQL manual (`create_schema.rs` ditambah `otp_cache` untuk bootstrap penuh).
## 3. (OK, sudah benar) Register mentor + booking
- `POST /v1/dimentorin/mentors/create` → 200, user + mentor profile dibuat, status `pending`, user tak tampil di list public sampai verified.
- `POST /v1/dimentorin/mentors/{id}/sessions/create` → 200, session pending.
- Kedua endpoint fungsional setelah fix UUID (commit 9b5efef).
## Rekomendasi
Tangani #1 dan #2 sebelum go-live. #2 adalah kelas bug "OTP di-generate tapi tak dipakai" — sisi verifikasi email saat ini tidak lebih dari form "set is_active=true tanpa autentikasi".
## 4. ✅ DONE — Payment flow (alur bisnis menjual)
**Status: DONE di feat/dimentorin-postgres (2026-08-05).**
- Tabel `app_payments`: amount (dari `mentoring_rate` mentor) + service_fee 2000 + total; method `va`/`qris`/`manual`; provider `manual` default (swap Midtrans/Xendit nanti — cukup ganti nilai `provider` dan implementasi `generate_external_ref`/notifikasi webhook).
- Routes protected: `POST /payments/sessions/{id}/create`, `GET /payments/me`, `GET /payments/{id}`, `POST /payments/{id}/confirm`.
- Guard: mentee hanya bisa akses payment miliknya (403 kalau bukan); confirm hanya Admin / Admin Pembayaran.
- `confirm_payment` otomatis mengubah session terkait `pending` -> `confirmed` (loop bisnis lengkap: book -> bayar -> sesi terkonfirmasi -> feedback).
- FE: PaymentStep pilih VA/QRIS, rate real dari `mentoring_rate`; modal appointment: book -> create payment -> tampil VA/QR dengan `external_ref` + total + expiry -> success. Service lib: `postCreatePayment/getMyPayments/getPaymentById/postConfirmPayment`.
- E2E verified (lokal :4099): create VA dan QRIS, confirm 200, re-confirm 409, non-admin 403, akses payment orang lain 403, session auto-confirmed.
- TODO produksi: isi kredensial payment gateway (Midtrans/Xendit) + webhook callback; SMTP masih blocker (#1).
## 5. Payment lifecycle complete: auto-paid refresh + dashboards (2026-08-05)
- POST /payments/{id}/refresh: polls Midtrans v2/{order_id}/status; settlement/capture -> payment paid + session confirmed automatically (e2e verified via sandbox simulator: VA paid -> refresh -> paid + confirmed)
- GET /payments/session/{id}: payments for one session, accessible by that session's mentee or mentor (powers both dashboards)
- Session mentor may confirm their own payments (previously admins only) — verified e2e
- FE: /mentoring/my-sessions (mentee) + /mentoring/mentor-dashboard (mentor), both with live payment status and refresh/confirm actions; QRIS step renders real QR from qr_string
## 6. Materi + AI Agent RAG (2026-08-05, commit 164c186 BE / 7294040 FE)
Fitur yang "harusnya ada" menurut user (Figma hanya berisi Design System, halaman Materi/AI Agent tidak ada di file) — dibangun dari pemahaman alur bisnis mentoring.
**Backend — modul materials** (`imphnen-dimentorin/src/materials/`):
- `app_materials` table: mentor_id, title, slug, category, description, content, cover_url, is_published
- Pola articles: domain/repository/service + postgres repo + DTO ZodValidate
- Routes: GET /materials (public, published), /materials/{id|slug|categories}, POST/PUT/DELETE (auth, author-only)
- ENV baru: AI_LLM_BASE_URL/API_KEY/MODEL, AI_EMBEDDING_MODEL, QDRANT_URL
**Backend — AI agent RAG** (`imphnen-dimentorin/src/ai_agent/`):
- Chunking materi (700 chars, overlap 80) -> embed via 9router `gemini/gemini-embedding-001` (3072 dim!)
- Qdrant collection `dimentorin_materi` (3072d cosine, point id = u64 dari uuid xor index — Qdrant TOLAK string non-UUID)
- Chat: embed question -> search top-4 -> LLM (`text` -> gemini-3.1-flash-lite) jawab dengan konteks + sources
- Routes: POST /ai/chat, POST /ai/materials/{id}/index, POST /ai/reindex
- 9router chat SELALU SSE-streaming walau tanpa stream:true — parser harus agregate `data:` lines
**Verified e2e**: reindex 3 chunks; chat 'ownership' -> source materi Rust 0.88; chat 'endpoint axum' -> Axum 0.82; browser: list materi, detail, chatbox jawab + sources 84/64/61%.
**Pitfall**: embedding Gemini = 3072 dim (bukan 768); Qdrant point id harus u64/UUID; model embedding yang berfungsi di 9router = `gemini/gemini-embedding-001` (llama-nemotron -> 'No credentials for provider: openai').
+9
View File
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 351 KiB

Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1775036866,
"narHash": "sha256-ZojAnPuCdy657PbTq5V0Y+AHKhZAIwSIT2cb8UgAz/U=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "6201e203d09599479a3b3450ed24fa81537ebc4e",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+42 -19
View File
@@ -1,24 +1,47 @@
{ {
description = "IMPHNEN CMS API Nix Flake"; description = "IMPHNEN Backend Service Nix Flake";
inputs = { inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
}; };
outputs = {
self, outputs =
nixpkgs, {
}: let self,
supportedSystems = ["x86_64-linux" "x86_64-darwin" "aarch64-darwin" "aarch64-linux"]; nixpkgs,
forAllSystems = nixpkgs.lib.genAttrs supportedSystems; }:
pkgsFor = nixpkgs.legacyPackages; let
in { supportedSystems = [
packages = forAllSystems (system: { "x86_64-linux"
default = pkgsFor.${system}.callPackage ./default.nix {}; "x86_64-darwin"
}); "aarch64-darwin"
devShells = forAllSystems (system: { "aarch64-linux"
default = pkgsFor.${system}.callPackage ./shell.nix {}; ];
}); pkgsFor =
dockerImages = forAllSystems (system: { system:
tryOutApi = pkgsFor.${system}.callPackage ./docker.nix {}; import nixpkgs {
}); inherit system;
}; config.allowUnfree = true;
};
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
in
{
packages = forAllSystems (system: {
default = (pkgsFor system).callPackage ./default.nix { };
});
overlays.default = final: _prev: {
imphnen-backend = final.callPackage ./default.nix { };
};
nixosModules.backend = ./nixos-module.nix;
devShells = forAllSystems (system: {
default = (pkgsFor system).callPackage ./shell.nix { };
});
dockerImages = forAllSystems (system: {
tryOutApi = (pkgsFor system).callPackage ./docker.nix { };
});
};
} }
+76
View File
@@ -0,0 +1,76 @@
[package]
name = "imphnen-backend"
version = "0.3.0"
edition = "2021"
[[bin]]
name = "api"
path = "src/main.rs"
[[bin]]
name = "create_schema"
path = "src/bin/create_schema.rs"
[[bin]]
name = "seeder"
path = "src/bin/seeder.rs"
[[bin]]
name = "seed_events"
path = "src/bin/seed_events.rs"
[[bin]]
name = "seed_gacha_rolls"
path = "src/bin/seed_gacha_rolls.rs"
[[bin]]
name = "seed_mentor_user"
path = "src/bin/seed_mentor_user.rs"
[[bin]]
name = "seed_permissions"
path = "src/bin/seed_permissions.rs"
[[bin]]
name = "seed_roles"
path = "src/bin/seed_roles.rs"
[[bin]]
name = "seed_roles_permissions"
path = "src/bin/seed_roles_permissions.rs"
[[bin]]
name = "seed_test_data"
path = "src/bin/seed_test_data.rs"
[[bin]]
name = "test_postgres"
path = "src/bin/test_postgres.rs"
[dependencies]
sea-orm.workspace = true
imphnen-libs.workspace = true
imphnen-utils.workspace = true
imphnen-gateway.workspace = true
imphnen-entities.workspace = true
imphnen-iam.workspace = true
imphnen-cms.workspace = true
imphnen-gacha.workspace = true
imphnen-dimentorin.workspace = true
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
axum-test.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
env_logger.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace=true
+10
View File
@@ -0,0 +1,10 @@
use imphnen_gateway::gateway_service;
use imphnen_libs::axum_init;
#[tokio::main]
async fn main() {
axum_init(|postgres_db| async {
gateway_service(postgres_db).await
})
.await;
}
+91
View File
@@ -0,0 +1,91 @@
#![allow(clippy::all)]
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::{ConnectionTrait, Statement};
use std::env;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = env::args().collect();
let dry_run = args
.iter()
.any(|s| s == "--dry-run" || s == "--no-exec" || s == "--dry");
let force = args.iter().any(|s| s == "--force" || s == "-f");
println!("🔎 Clear DB script - WARNING: This will remove data from tables\n");
println!("Note: script now runs by default (no --yes required). To preview without executing, use --dry-run.\n");
let tables = vec![
"gacha_claims",
"gacha_rolls",
"gacha_items",
"gacha_credits",
"audit_logs",
"rate_limits",
"testimonials",
"events",
"app_mentors",
"app_sessions",
"app_roles_permissions",
"app_permissions",
"app_roles",
"app_users",
];
let postgres_config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(postgres_config).await?;
let db = &pg_conn.conn;
let mut existing_tables: Vec<&str> = vec![];
for t in tables.iter() {
let check_sql = format!(
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '{}') as exists;",
t
);
let stmt = Statement::from_string(db.get_database_backend(), check_sql);
if let Ok(Some(row)) = pg_conn.query_one(stmt).await {
let exists_val: Option<bool> = row.try_get("", "exists").ok();
if exists_val.unwrap_or(false) {
existing_tables.push(t);
}
}
}
if existing_tables.is_empty() {
println!("No configured tables found to clear - nothing to do.");
return Ok(());
}
let truncate_sql = format!(
"TRUNCATE TABLE {} RESTART IDENTITY CASCADE;",
existing_tables.join(", ")
);
println!("The script will run the following SQL (on the DB configured by env vars):\n\n{}", truncate_sql);
let env_name = imphnen_libs::ENV.rust_env.clone();
if env_name == "production" && !force {
println!("Security: RUST_ENV=production; the script will NOT run without --force. Use --force to override.");
return Ok(());
}
if dry_run {
println!("Dry run enabled. No changes applied. To execute, re-run without --dry-run or use --force (in production).");
return Ok(());
}
println!("Executing truncate...\n");
let postgres_config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(postgres_config).await?;
let db = &pg_conn.conn;
let stmt = Statement::from_string(db.get_database_backend(), truncate_sql);
match pg_conn.execute(stmt).await {
Ok(_) => println!("✅ Successfully cleared DB tables"),
Err(e) => println!("❌ Failed to clear DB tables: {}", e),
}
Ok(())
}
+81
View File
@@ -0,0 +1,81 @@
#![allow(clippy::all)]
use imphnen_entities::seaorm::{auth, common, gacha};
use imphnen_libs::postgres::PostgresConfig;
use sea_orm::sea_query::Table;
use sea_orm::{ConnectionTrait, Database, DbBackend, EntityTrait, Schema};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🛠️ Creating database schema...");
let config = PostgresConfig::from_env()?;
let db = Database::connect(&config.database_url).await?;
let builder = db.get_database_backend();
println!(" Database connected. Creating/updating tables...");
drop_and_create_table(&db, builder, "app_roles", auth::roles::Entity).await?;
drop_and_create_table(&db, builder, "app_permissions", auth::permissions::Entity)
.await?;
drop_and_create_table(&db, builder, "app_users", auth::users::Entity).await?;
drop_and_create_table(
&db,
builder,
"app_roles_permissions",
auth::roles_permissions::Entity,
)
.await?;
drop_and_create_table(&db, builder, "app_mentors", auth::mentors::Entity).await?;
drop_and_create_table(&db, builder, "app_sessions", auth::sessions::Entity)
.await?;
drop_and_create_table(&db, builder, "app_articles", common::articles::Entity)
.await?;
drop_and_create_table(&db, builder, "events", common::events::Entity).await?;
drop_and_create_table(&db, builder, "testimonials", common::testimonials::Entity)
.await?;
drop_and_create_table(&db, builder, "audit_logs", common::audit_log::Entity)
.await?;
drop_and_create_table(&db, builder, "rate_limits", common::rate_limit::Entity)
.await?;
drop_and_create_table(&db, builder, "otp_cache", common::otp_cache::Entity).await?;
drop_and_create_table(&db, builder, "payments", common::payments::Entity)
.await?;
drop_and_create_table(&db, builder, "gacha_credits", gacha::gacha_credits::Entity)
.await?;
drop_and_create_table(&db, builder, "gacha_items", gacha::gacha_items::Entity)
.await?;
drop_and_create_table(&db, builder, "gacha_rolls", gacha::gacha_rolls::Entity)
.await?;
drop_and_create_table(&db, builder, "gacha_claims", gacha::gacha_claims::Entity)
.await?;
println!("✅ Schema creation completed.");
Ok(())
}
async fn drop_and_create_table<E>(
db: &sea_orm::DatabaseConnection,
builder: DbBackend,
name: &str,
entity: E,
) -> Result<(), Box<dyn std::error::Error>>
where
E: EntityTrait,
{
let schema = Schema::new(builder);
let drop_stmt = Table::drop().table(entity).if_exists().cascade().to_owned();
db.execute(builder.build(&drop_stmt)).await?;
println!(" Dropped table if exists: {}", name);
let mut create_stmt = schema.create_table_from_entity(entity);
create_stmt.if_not_exists();
db.execute(builder.build(&create_stmt)).await?;
println!(" ✅ Created table: {}", name);
Ok(())
}
+20
View File
@@ -0,0 +1,20 @@
#![allow(clippy::all)]
use imphnen_libs::jsonwebtoken::encode_access_token;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: mk_token <email_or_sub>");
std::process::exit(1);
}
let sub = args[1].clone();
match encode_access_token(sub.clone(), sub.clone()) {
Ok(token) => println!("{}", token),
Err(e) => {
eprintln!("Failed to generate token: {:?}", e);
std::process::exit(2);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
#![allow(clippy::all)]
use chrono::Utc;
use imphnen_entities::seaorm::common::articles::{
ActiveModel as ArticleActiveModel, Entity as ArticlesEntity,
};
use imphnen_libs::postgres::PostgresConfig;
use sea_orm::{ActiveModelTrait, ActiveValue, Database};
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = PostgresConfig::from_env()?;
let db = Database::connect(&config.database_url).await?;
let articles = vec![
("Cara Memulai Karier di UI/UX Design", "cara-memulai-karier-ui-ux-design", "UI/UX & Design", "Panduan lengkap untuk masuk ke dunia UI/UX design, dari skill yang dibutuhkan hingga portofolio.", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. UI/UX design adalah bidang yang menjanjikan. Artikel ini membahas langkah awal memulai karier sebagai UI/UX designer, tools yang wajib dikuasai seperti Figma, serta cara membangun portofolio yang menarik bagi perekrut."),
("Belajar Rust: Panduan Pemula 2026", "belajar-rust-panduan-pemula-2026", "Software/Web Dev", "Bahasa pemrograman Rust sedang naik daun. Pelajari konsep ownership dan borrow checker.", "Rust adalah bahasa pemrograman yang fokus pada performa dan keamanan memori. Dalam artikel ini kita membahas ownership, borrowing, dan cara setup environment Rust di Linux dan Windows, serta contoh project sederhana."),
("Mengenal Machine Learning untuk Data Analyst", "mengenal-machine-learning-data-analyst", "Data & AI", "Peran Data Analyst berevolusi dengan hadirnya machine learning. Simak panduannya.", "Machine learning membuka peluang besar bagi data analyst. Artikel ini menjelaskan perbedaan data analysis dan machine learning, serta roadmap belajar dari Python, pandas, sampai scikit-learn."),
];
for (title, slug, category, excerpt, content) in articles {
let am = ArticleActiveModel {
id: ActiveValue::Set(Uuid::new_v4()),
title: ActiveValue::Set(title.to_string()),
slug: ActiveValue::Set(slug.to_string()),
category: ActiveValue::Set(category.to_string()),
excerpt: ActiveValue::Set(excerpt.to_string()),
content: ActiveValue::Set(content.to_string()),
cover_url: ActiveValue::Set(None),
author_name: ActiveValue::Set(Some("IMPHNEN Editorial".to_string())),
is_published: ActiveValue::Set(true),
created_at: ActiveValue::Set(Utc::now()),
updated_at: ActiveValue::Set(Utc::now()),
};
am.insert(&db).await?;
println!("✅ Inserted article: {}", slug);
}
println!("🟢 All articles seeded");
Ok(())
}
+205
View File
@@ -0,0 +1,205 @@
#![allow(clippy::all)]
use chrono::Utc;
use imphnen_entities::seaorm::common::events::{
ActiveModel as EventsActiveModel, Entity as EventEntity,
};
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::{
ActiveModelTrait, ActiveValue::Set, ColumnTrait, EntityTrait, QueryFilter,
};
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let postgres_config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(postgres_config).await?;
let db = &pg_conn.conn;
let events = vec![
(
"Tech Conference 2025",
"Annual technology conference featuring the latest innovations in software development, AI, and cloud computing.",
"https://techconf2025.example.com",
150.0,
Some("Jakarta Convention Center".to_string()),
false,
"2025-06-15T09:00:00Z",
"2025-06-17T18:00:00Z",
),
(
"Online Web Development Workshop",
"Comprehensive workshop covering modern web development frameworks including React, Vue, and Angular.",
"https://webdev-workshop.example.com",
75.0,
None,
true,
"2025-07-10T14:00:00Z",
"2025-07-10T17:00:00Z",
),
(
"Startup Pitch Competition",
"Exciting competition where emerging startups present their innovative ideas to a panel of expert judges and investors.",
"https://startup-pitch.example.com",
25.0,
Some("Innovation Hub Surabaya".to_string()),
false,
"2025-08-05T10:00:00Z",
"2025-08-05T16:00:00Z",
),
(
"Digital Marketing Masterclass",
"Learn advanced digital marketing strategies, social media optimization, and data-driven marketing techniques.",
"https://digital-marketing.example.com",
100.0,
None,
true,
"2025-09-20T13:00:00Z",
"2025-09-22T15:00:00Z",
),
(
"Rust Programming Bootcamp",
"Intensive 3-day bootcamp to master Rust fundamentals and advanced concepts.",
"https://rust-bootcamp.example.com",
200.0,
Some("Bandung Digital Valley".to_string()),
false,
"2025-10-01T09:00:00Z",
"2025-10-03T17:00:00Z",
),
(
"AI & Machine Learning Summit",
"Global summit discussing the future of AI and its impact on industries.",
"https://ai-summit.example.com",
300.0,
Some("Bali Nusa Dua Convention Center".to_string()),
false,
"2025-11-15T08:00:00Z",
"2025-11-17T18:00:00Z",
),
(
"Cybersecurity Awareness Webinar",
"Free webinar on best practices for personal and corporate cybersecurity.",
"https://cybersecurity-webinar.example.com",
0.0,
None,
true,
"2025-12-05T14:00:00Z",
"2025-12-05T16:00:00Z",
),
(
"Cloud Computing Workshop",
"Hands-on workshop on deploying scalable applications using AWS and Azure.",
"https://cloud-workshop.example.com",
120.0,
None,
true,
"2026-01-20T10:00:00Z",
"2026-01-22T15:00:00Z",
),
(
"Blockchain for Finance",
"Exploring the applications of blockchain technology in the financial sector.",
"https://blockchain-finance.example.com",
180.0,
Some("Jakarta Ritz-Carlton".to_string()),
false,
"2026-02-10T09:00:00Z",
"2026-02-11T17:00:00Z",
),
(
"Game Development Jam",
"48-hour game development marathon for indie developers.",
"https://game-jam.example.com",
50.0,
Some("Yogyakarta Creative Hub".to_string()),
false,
"2026-03-15T18:00:00Z",
"2026-03-17T18:00:00Z",
),
(
"UX/UI Design Principles",
"Masterclass on creating intuitive and user-friendly interfaces.",
"https://uxui-design.example.com",
90.0,
None,
true,
"2026-04-05T13:00:00Z",
"2026-04-07T16:00:00Z",
),
(
"Data Science Fundamentals",
"Introduction to data analysis, visualization, and statistical modeling.",
"https://data-science.example.com",
110.0,
None,
true,
"2026-05-12T10:00:00Z",
"2026-05-14T15:00:00Z",
),
(
"IoT Innovation Expo",
"Showcase of the latest Internet of Things devices and solutions.",
"https://iot-expo.example.com",
50.0,
Some("Surabaya Expo Center".to_string()),
false,
"2026-06-20T09:00:00Z",
"2026-06-22T18:00:00Z",
),
];
for (
name,
description,
detail_link,
price,
location,
is_online,
start_date_str,
end_date_str,
) in events
{
let existing = EventEntity::find()
.filter(<EventEntity as EntityTrait>::Column::Name.eq(name))
.one(db)
.await?;
if existing.is_some() {
println!("️ Skipping (already exists): {name}");
continue;
}
let uuid = Uuid::new_v4();
let mut event_model: EventsActiveModel = Default::default();
event_model.id = Set(uuid);
event_model.name = Set(name.to_string());
event_model.description = Set(description.to_string());
event_model.detail_link = Set(detail_link.to_string());
event_model.price = Set(price);
event_model.is_online = Set(is_online);
event_model.location = Set(location.clone());
event_model.start_date = Set(
chrono::DateTime::parse_from_rfc3339(start_date_str)?
.with_timezone(&chrono::Utc),
);
event_model.end_date = Set(
chrono::DateTime::parse_from_rfc3339(end_date_str)?
.with_timezone(&chrono::Utc),
);
event_model.is_deleted = Set(false);
event_model.created_at = Set(Utc::now());
event_model.updated_at = Set(Utc::now());
event_model.insert(db).await?;
println!(
"✅ Inserted event: {} ({})",
name,
if is_online { "Online" } else { "In-person" }
);
}
println!("✅ All Events seeded");
Ok(())
}
@@ -0,0 +1,84 @@
#![allow(clippy::all)]
use imphnen_entities::seaorm::gacha::gacha_items::ActiveModel as GachaItemActiveModel;
use imphnen_entities::seaorm::gacha::gacha_rolls::ActiveModel as GachaRollActiveModel;
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::ActiveModelTrait;
use sea_orm::ActiveValue::Set;
use sea_orm::ConnectionTrait;
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(config).await?;
let db = &pg_conn.conn;
let check_item_sql =
"SELECT id FROM app_gacha_items WHERE item_code = 'ITEM_TEST_1' LIMIT 1";
let item_result = pg_conn
.query_one(sea_orm::Statement::from_string(
db.get_database_backend(),
check_item_sql,
))
.await?;
let gacha_item_uuid = if let Some(ref row) = item_result {
row.try_get("", "id")?
} else {
let _ = pg_conn
.execute(sea_orm::Statement::from_string(
db.get_database_backend(),
"DELETE FROM app_gacha_items WHERE item_code = 'ITEM_TEST_1'".to_string(),
))
.await
.ok();
let new_uuid = Uuid::new_v4();
let mut item_model: GachaItemActiveModel = Default::default();
item_model.id = Set(new_uuid);
item_model.item_code = Set("ITEM_TEST_1".to_string());
item_model.name = Set("Test Gacha Item".to_string());
item_model.description = Set("Test item for gacha".to_string());
item_model.rarity = Set("common".to_string());
item_model.type_ = Set("item".to_string());
item_model.category = Set("test".to_string());
item_model.value = Set(1);
item_model.weight = Set(1.0);
item_model.stock = Set(10);
item_model.is_limited = Set(false);
item_model.created_at = Set(chrono::Utc::now());
item_model.updated_at = Set(chrono::Utc::now());
item_model.insert(db).await?;
println!("Gacha Item seeded successfully!");
new_uuid
};
let gacha_roll_id = Uuid::new_v4();
let mut roll_model: GachaRollActiveModel = Default::default();
roll_model.id = Set(gacha_roll_id);
roll_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
roll_model.gacha_id = Set(Uuid::new_v4().to_string());
roll_model.item_id = Set(gacha_item_uuid);
roll_model.weight = Set(1.0);
roll_model.quantity = Set(10);
roll_model.is_deleted = Set(false);
roll_model.created_at = Set(Some(chrono::Utc::now().naive_utc()));
roll_model.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
roll_model.insert(db).await?;
println!("Gacha Roll seeded successfully!");
let gacha_roll_id = Uuid::new_v4();
let mut roll_model: GachaRollActiveModel = Default::default();
roll_model.id = Set(gacha_roll_id);
roll_model.user_id = Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
roll_model.gacha_id = Set(Uuid::new_v4().to_string());
roll_model.item_id = Set(gacha_item_uuid);
roll_model.weight = Set(1.0);
roll_model.quantity = Set(10);
roll_model.is_deleted = Set(false);
roll_model.created_at = Set(Some(chrono::Utc::now().naive_utc()));
roll_model.updated_at = Set(Some(chrono::Utc::now().naive_utc()));
roll_model.insert(db).await?;
println!("✅ Gacha items and rolls seeded.");
Ok(())
}
@@ -0,0 +1,90 @@
#![allow(clippy::all)]
use imphnen_entities::seaorm::auth::mentors::ActiveModel as MentorsActiveModel;
use imphnen_entities::seaorm::auth::roles::{
Column as RoleColumn, Entity as RoleEntity,
};
use imphnen_entities::seaorm::auth::users::ActiveModel as UsersActiveModel;
use imphnen_libs::hash_password;
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::{
ActiveModelTrait, ActiveValue::Set, ColumnTrait, ConnectionTrait, EntityTrait,
QueryFilter,
};
use serde_json::json;
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(config).await?;
let db = &pg_conn.conn;
let _ = pg_conn
.execute(sea_orm::Statement::from_string(
db.get_database_backend(),
"DELETE FROM app_mentors WHERE id = 'e6f78d23-83bf-5c2b-bcd4-001345678901'"
.to_string(),
))
.await
.ok();
let _ = pg_conn
.execute(sea_orm::Statement::from_string(
db.get_database_backend(),
"DELETE FROM app_users WHERE email = 'mentor@example.com'".to_string(),
))
.await
.ok();
let role = RoleEntity::find()
.filter(RoleColumn::Name.eq("Mentor"))
.one(db)
.await?
.ok_or("Role 'Mentor' not found")?;
let user_id = Uuid::new_v4();
let mut user_model: UsersActiveModel = Default::default();
user_model.id = Set(user_id);
user_model.email = Set("mentor@example.com".to_string());
user_model.password_hash = Set(hash_password("password").unwrap());
user_model.username = Set("mentor@example.com".to_string());
user_model.first_name = Set(Some("Mentor".to_string()));
user_model.last_name = Set(Some("User".to_string()));
user_model.avatar_url = Set(Some("https://example.com/avatar.jpg".to_string()));
user_model.is_active = Set(true);
user_model.is_verified = Set(true);
user_model.role_id = Set(Some(role.id));
user_model.created_at = Set(chrono::Utc::now());
user_model.updated_at = Set(chrono::Utc::now());
user_model.insert(db).await?;
let mentor_id = Uuid::new_v4();
let mut mentor_model: MentorsActiveModel = Default::default();
mentor_model.id = Set(mentor_id);
mentor_model.user_id = Set(user_id);
mentor_model.industries = Set(Some(json!(["Software", "Education"])));
mentor_model.expertise = Set(Some(json!(["Rust", "Microservices"])));
mentor_model.languages = Set(Some(json!(["Indonesian", "English"])));
mentor_model.current_company = Set(Some("PT Contoh".to_string()));
mentor_model.current_role = Set(Some("Senior Backend Engineer".to_string()));
mentor_model.years_of_experience = Set(Some(5));
mentor_model.topics_of_interest =
Set(Some(json!(["Rust Programming", "Backend Development"])));
mentor_model.preferred_mentee_level = Set(Some("beginner".to_string()));
mentor_model.preferred_mentoring_formats = Set(Some(json!(["online", "offline"])));
mentor_model.availability_commitment = Set(Some(
"2 jam per minggu untuk mentoring online dan offline".to_string(),
));
mentor_model.mentoring_rate = Set(Some(100000.0));
mentor_model.status = Set(Some("verified".to_string()));
mentor_model.is_deleted = Set(false);
mentor_model.created_at = Set(chrono::Utc::now());
mentor_model.updated_at = Set(chrono::Utc::now());
mentor_model.insert(db).await?;
println!("Mentor created successfully!");
println!("✅ Inserted mentor user: mentor@example.com");
println!("✅ Mentor user seeded");
Ok(())
}
@@ -0,0 +1,79 @@
#![allow(clippy::all)]
use chrono::Utc;
use imphnen_entities::seaorm::auth::permissions::ActiveModel as PermissionActiveModel;
use imphnen_entities::seaorm::auth::permissions::Entity as PermissionEntity;
use imphnen_iam::PermissionsEnum;
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::ActiveModelTrait;
use sea_orm::ActiveValue::Set;
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(config).await?;
let db = &pg_conn.conn;
for permission in [
PermissionsEnum::ReadListUsers,
PermissionsEnum::ReadDetailUsers,
PermissionsEnum::CreateUsers,
PermissionsEnum::DeleteUsers,
PermissionsEnum::UpdateUsers,
PermissionsEnum::ActivateUsers,
PermissionsEnum::ReadListRoles,
PermissionsEnum::ReadDetailRoles,
PermissionsEnum::CreateRoles,
PermissionsEnum::DeleteRoles,
PermissionsEnum::UpdateRoles,
PermissionsEnum::ReadListPermissions,
PermissionsEnum::ReadDetailPermissions,
PermissionsEnum::CreatePermissions,
PermissionsEnum::DeletePermissions,
PermissionsEnum::UpdatePermissions,
PermissionsEnum::CreateGachaClaims,
PermissionsEnum::ReadDetailGachaClaims,
PermissionsEnum::ReadListGachaItems,
PermissionsEnum::ReadDetailGachaItems,
PermissionsEnum::CreateGachaItems,
PermissionsEnum::DeleteGachaItems,
PermissionsEnum::UpdateGachaItems,
PermissionsEnum::ReadDetailGachaRolls,
PermissionsEnum::CreateGachaRolls,
PermissionsEnum::ExecuteGachaRolls,
PermissionsEnum::ReadListMentors,
PermissionsEnum::ReadDetailMentors,
PermissionsEnum::RegisterMentors,
PermissionsEnum::ReadOwnMentorProfile,
PermissionsEnum::UpdateOwnMentorProfile,
PermissionsEnum::ReadOwnMentorStatus,
PermissionsEnum::UpdateMentors,
PermissionsEnum::VerifyMentors,
PermissionsEnum::DeleteMentors,
PermissionsEnum::Administrator,
] {
let parsed_id =
Uuid::parse_str(&permission.id()).unwrap_or_else(|_| Uuid::new_v4());
let existing = PermissionEntity::find_by_id(parsed_id).one(db).await?;
if existing.is_some() {
println!("️ Skipping (already exists): {permission}");
continue;
}
let mut perm_model: PermissionActiveModel = Default::default();
perm_model.id = Set(parsed_id);
perm_model.name = Set(permission.to_string());
perm_model.is_deleted = Set(false);
perm_model.created_at = Set(Utc::now());
perm_model.updated_at = Set(Utc::now());
perm_model.insert(db).await?;
println!("✅ Inserted: {permission}");
}
println!("✅ All Permissions seeded");
Ok(())
}
+79
View File
@@ -0,0 +1,79 @@
use chrono::Utc;
use imphnen_entities::seaorm::auth::roles::{Entity as RoleEntity, RoleBuilder};
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait};
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(config).await?;
let db = &pg_conn.conn;
let roles = vec![
(
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
"Staf",
Some("2025-02-24T16:52:27.630453+00"),
Some("2025-02-24T16:52:27.630461+00"),
),
(
"5713cb37-dc02-4e87-8048-d7a41d352059",
"User",
Some("2025-02-28T14:53:58.576688+00"),
Some("2025-02-28T14:53:58.576688+00"),
),
(
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
"Staff Aktivasi User",
Some("2025-02-20T02:47:09.660640+00"),
Some("2025-02-20T02:48:30.083283+00"),
),
(
"6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0",
"Admin Pembayaran",
Some("2025-01-29T05:39:28.562667+00"),
Some("2025-03-12T22:56:29.597416+00"),
),
(
"f6b03f25-e416-4893-ac88-caaa690afb07",
"Admin",
Some("2025-02-22T15:38:39.868306+00"),
Some("2025-02-22T15:38:39.868306+00"),
),
(
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
"Mentor",
Some("2025-07-06T10:00:00.000000+00"),
Some("2025-07-06T10:00:00.000000+00"),
),
];
for (id, name, _created_at_str, _updated_at_str) in roles {
let uuid = Uuid::parse_str(id).unwrap_or_else(|_| Uuid::new_v4());
let existing = RoleEntity::find_by_id(uuid).one(db).await?;
if existing.is_some() {
println!("️ Skipping (already exists): {name}");
continue;
}
let role_model = RoleBuilder::new()
.name(name.to_string())
.description("System generated role".to_string())
.permissions(vec![])
.is_default(false)
.build()?;
let mut role_model = role_model;
role_model.id = Set(uuid);
role_model.is_system_role = Set(true);
role_model.created_at = Set(Utc::now());
role_model.updated_at = Set(Utc::now());
role_model.insert(db).await?;
println!("✅ Inserted role: {name}");
}
println!("✅ All Roles seeded");
Ok(())
}
@@ -0,0 +1,109 @@
use imphnen_entities::seaorm::auth::roles::ActiveModel as RoleActiveModel;
use imphnen_entities::seaorm::auth::roles::Entity as RolesEntity;
use imphnen_iam::PermissionsEnum;
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::ActiveModelTrait;
use sea_orm::ActiveValue::Set;
use sea_orm::EntityTrait;
use serde_json::Value as JsonValue;
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(config).await?;
let db = &pg_conn.conn;
println!(
"✅ Index 'user_email_index' defined on table 'users' for column 'email'."
);
let roles_permissions = vec![
(
"f6b03f25-e416-4893-ac88-caaa690afb07",
vec![PermissionsEnum::Administrator],
),
(
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
vec![
PermissionsEnum::ReadListUsers,
PermissionsEnum::ReadOwnMentorProfile,
PermissionsEnum::UpdateOwnMentorProfile,
PermissionsEnum::ReadOwnMentorStatus,
PermissionsEnum::ReadListMentors,
PermissionsEnum::ReadDetailMentors,
PermissionsEnum::ReadListGachaItems,
PermissionsEnum::ReadDetailGachaItems,
PermissionsEnum::ReadDetailGachaRolls,
PermissionsEnum::CreateGachaRolls,
PermissionsEnum::ExecuteGachaRolls,
],
),
(
"5713cb37-dc02-4e87-8048-d7a41d352059",
vec![
PermissionsEnum::ReadListGachaItems,
PermissionsEnum::ReadDetailGachaItems,
PermissionsEnum::ReadListUsers,
PermissionsEnum::ReadDetailUsers,
PermissionsEnum::CreateGachaClaims,
PermissionsEnum::ReadDetailGachaClaims,
PermissionsEnum::ReadDetailGachaRolls,
PermissionsEnum::CreateGachaRolls,
PermissionsEnum::ExecuteGachaRolls,
PermissionsEnum::RegisterMentors,
PermissionsEnum::ReadListMentors,
PermissionsEnum::ReadDetailMentors,
PermissionsEnum::ReadOwnMentorProfile,
PermissionsEnum::ReadOwnMentorStatus,
],
),
(
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
vec![
PermissionsEnum::ReadListRoles,
PermissionsEnum::ReadListPermissions,
PermissionsEnum::ReadListUsers,
PermissionsEnum::ReadListMentors,
PermissionsEnum::ReadDetailUsers,
PermissionsEnum::ActivateUsers,
PermissionsEnum::ReadDetailRoles,
PermissionsEnum::ReadDetailPermissions,
PermissionsEnum::ReadListGachaItems,
PermissionsEnum::ReadDetailGachaItems,
PermissionsEnum::ReadListMentors,
PermissionsEnum::ReadDetailMentors,
PermissionsEnum::ReadDetailGachaRolls,
PermissionsEnum::CreateGachaRolls,
PermissionsEnum::ExecuteGachaRolls,
],
),
(
"60f1aeb7-dad2-4e06-bcb5-be1ba510c906",
vec![PermissionsEnum::ActivateUsers],
),
("6d4fea5d-4a08-4b8a-9782-f2ab2183dcf0", vec![]),
];
for (role_id, permissions) in roles_permissions {
let role_uuid = Uuid::parse_str(role_id).unwrap_or_else(|_| Uuid::new_v4());
let json_permissions = JsonValue::Array(
permissions
.iter()
.map(|p| JsonValue::String(p.id()))
.collect(),
);
if let Some(role_model) = RolesEntity::find_by_id(role_uuid).one(db).await? {
let mut am: RoleActiveModel = role_model.into();
am.permissions = Set(Some(json_permissions));
am.update(db).await?;
println!("✅ Permissions updated for role: {role_id}");
} else {
println!("⚠️ Role with id {role_id} not found, skipping permissions update");
}
}
println!("✅ All roles permissions updated!");
Ok(())
}
+79
View File
@@ -0,0 +1,79 @@
#![allow(clippy::all)]
use chrono::Utc;
use imphnen_entities::seaorm::auth::mentors::ActiveModel as MentorsActiveModel;
use imphnen_entities::seaorm::common::events::ActiveModel as EventsActiveModel;
use imphnen_entities::seaorm::common::testimonials::ActiveModel as TestimonialsActiveModel;
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use sea_orm::ActiveModelTrait;
use sea_orm::ActiveValue::Set;
use serde_json::json;
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(config).await?;
let db = &pg_conn.conn;
let uuid = Uuid::new_v4().to_string();
let mut event_model: EventsActiveModel = Default::default();
event_model.id = Set(Uuid::parse_str(&uuid)?);
event_model.name = Set("Test Event".to_string());
event_model.description = Set("Test event description".to_string());
event_model.detail_link = Set("https://example.com/event".to_string());
event_model.price = Set(50.0);
event_model.is_online = Set(true);
event_model.start_date = Set(Utc::now());
event_model.end_date = Set(Utc::now() + chrono::Duration::days(1));
event_model.location = Set(None);
event_model.is_deleted = Set(false);
match event_model.insert(db).await {
Ok(_) => println!("✅ Inserted test event"),
Err(_) => {
println!("⚠️ Test event already exists or could not be inserted, skipping")
}
};
let mut testimonial_model: TestimonialsActiveModel = Default::default();
testimonial_model.id =
Set(Uuid::parse_str("00000000-0000-0000-0000-000000000001")?);
testimonial_model.user_id =
Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
testimonial_model.role = Set("Student".to_string());
testimonial_model.content = Set("This is a great platform!".to_string());
testimonial_model.is_deleted = Set(false);
match testimonial_model.insert(db).await {
Ok(_) => println!("✅ Inserted test testimonial"),
Err(_) => println!(
"⚠️ Test testimonial already exists or could not be inserted, skipping"
),
};
let mentor_id = Uuid::new_v4();
let mut mentor_model: MentorsActiveModel = Default::default();
mentor_model.id = Set(mentor_id);
mentor_model.user_id =
Set(Uuid::parse_str("c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2")?);
mentor_model.industries = Set(Some(json!(["Technology", "Education"])));
mentor_model.expertise = Set(Some(json!(["Software Development"])));
mentor_model.languages = Set(Some(json!(["English", "Indonesian"])));
mentor_model.current_company = Set(Some("Tech Corp".to_string()));
mentor_model.current_role = Set(Some("Senior Engineer".to_string()));
mentor_model.years_of_experience = Set(Some(5));
mentor_model.topics_of_interest = Set(Some(json!(["Rust", "Web Development"])));
mentor_model.preferred_mentee_level = Set(Some("Beginner".to_string()));
mentor_model.preferred_mentoring_formats = Set(Some(json!(["1:1", "Group"])));
mentor_model.availability_commitment = Set(Some("Weekly".to_string()));
mentor_model.mentoring_rate = Set(Some(100.0));
mentor_model.status = Set(Some("active".to_string()));
mentor_model.is_deleted = Set(false);
mentor_model.created_at = Set(chrono::Utc::now());
mentor_model.updated_at = Set(chrono::Utc::now());
mentor_model.insert(db).await?;
println!("✅ Inserted test mentor via SeaORM");
println!("✅ All test data seeded successfully");
Ok(())
}
+164
View File
@@ -0,0 +1,164 @@
#![allow(clippy::all)]
use imphnen_entities::seaorm::auth::users::ActiveModel as UsersActiveModel;
use imphnen_entities::seaorm::auth::users::Entity as UserEntity;
use imphnen_libs::hash_password;
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection};
use chrono::Utc;
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait, IntoActiveModel};
use std::error::Error;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let postgres_config = PostgresConfig::from_env()?;
let pg_conn = PostgresConnection::new(postgres_config).await?;
let db = &pg_conn.conn;
let users = vec![
(
"c3b1d6a8-8d4f-4b36-b789-2e532ec7a7b2",
"admin@example.com",
"Admin",
"f6b03f25-e416-4893-ac88-caaa690afb07",
),
(
"a4d23fb5-9e31-423c-9842-fbd6e75a5298",
"staff@example.com",
"Staff",
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
),
(
"d5e89c12-72af-4b1a-abc3-ff1234567890",
"user@example.com",
"User",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"665a3cfc-ea5f-4bcd-8769-4a6d8d1451d4",
"testuser1@example.com",
"Test User 1",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"3972c139-a450-416c-93b0-c42539dc780f",
"testuser2@example.com",
"Test User 2",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"b426c0a9-0efb-4e26-b078-4f18767255f3",
"testuser3@example.com",
"Test User 3",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"11111111-1111-1111-1111-111111111111",
"user4@example.com",
"User Four",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"22222222-2222-2222-2222-222222222222",
"user5@example.com",
"User Five",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"33333333-3333-3333-3333-333333333333",
"mentor2@example.com",
"Mentor Two",
"3b9f8c4e-6a2d-4f8a-9a12-2d6f8b3c4e5a",
),
(
"44444444-4444-4444-4444-444444444444",
"staff2@example.com",
"Staff Two",
"50133429-f4b1-4249-9f97-7b86e6ee9d86",
),
(
"55555555-5555-5555-5555-555555555555",
"user6@example.com",
"User Six",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"66666666-6666-6666-6666-666666666666",
"user7@example.com",
"User Seven",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"77777777-7777-7777-7777-777777777777",
"user8@example.com",
"User Eight",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"88888888-8888-8888-8888-888888888888",
"user9@example.com",
"User Nine",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
(
"99999999-9999-9999-9999-999999999999",
"user10@example.com",
"User Ten",
"5713cb37-dc02-4e87-8048-d7a41d352059",
),
];
for (id, email, fullname, role_id_str) in users {
let role_uuid = Some(
Uuid::parse_str(role_id_str)
.map_err(|e| format!("Invalid UUID for role: {role_id_str} - {e}"))?,
);
let uid = Uuid::parse_str(id)?;
let names: Vec<&str> = fullname.split_whitespace().collect();
let first_name = names.first().map(|s| s.to_string());
let last_name = if names.len() > 1 {
Some(names[1..].join(" "))
} else {
None
};
let password = "password";
let hashed = hash_password(password).unwrap();
let existing_user = UserEntity::find_by_id(uid).one(db).await?;
let is_update = existing_user.is_some();
let mut user_model: UsersActiveModel = if let Some(existing) = existing_user {
println!("🔄 Updating user: {fullname} ({email})");
existing.into_active_model()
} else {
println!("✅ Inserting user: {fullname} ({email})");
let mut active: UsersActiveModel = Default::default();
active.id = Set(uid);
active.created_at = Set(Utc::now());
active
};
user_model.email = Set(email.to_string());
user_model.password_hash = Set(hashed);
user_model.username = Set(email.to_string());
user_model.first_name = Set(first_name);
user_model.last_name = Set(last_name);
user_model.avatar_url = Set(Some("https://example.com/avatar.jpg".to_string()));
user_model.is_verified = Set(true);
user_model.is_active = Set(true);
user_model.role_id = Set(role_uuid);
user_model.updated_at = Set(Utc::now());
if is_update {
user_model.update(db).await?;
} else {
user_model.insert(db).await?;
}
}
println!("✅ All Users seeded");
Ok(())
}
+33
View File
@@ -0,0 +1,33 @@
#![allow(clippy::all)]
use std::error::Error;
use std::process::Command;
fn run_seed(bin: &str) -> Result<(), Box<dyn Error>> {
println!("🔧 Seeding: {bin}");
#[cfg(target_os = "windows")]
let status = Command::new(format!("./target/release/{}.exe", bin)).status()?;
#[cfg(not(target_os = "windows"))]
let status = Command::new(format!("./target/release/{}", bin)).status()?;
if !status.success() {
Err(format!("❌ Failed to run seed: {bin}").into())
} else {
Ok(())
}
}
fn main() -> Result<(), Box<dyn Error>> {
println!("🚀 Running all seeders...\n");
run_seed("seed_permissions")?;
run_seed("seed_roles")?;
run_seed("seed_roles_permissions")?;
run_seed("seed_users")?;
run_seed("seed_events")?;
run_seed("seed_gacha_rolls")?;
run_seed("seed_mentor_user")?;
run_seed("seed_test_data")?;
println!("\n✅ All seeding completed successfully.");
Ok(())
}
+395
View File
@@ -0,0 +1,395 @@
use chrono::Utc;
use imphnen_entities::seaorm::auth::roles::{
Entity as RolesEntity, Model as RoleModel,
};
use imphnen_entities::seaorm::auth::users::{
Entity as UsersEntity, Model as UserModel,
};
use imphnen_libs::postgres::{PostgresConfig, PostgresConnection, PostgresError};
use sea_orm::{
ActiveModelTrait, DbErr, EntityTrait, PaginatorTrait, Set, TransactionTrait,
};
use std::sync::Arc;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🚀 Starting PostgreSQL Connection Test");
println!("=====================================");
let config = PostgresConfig::from_env()?;
println!("✅ Configuration loaded successfully");
println!(
" Database URL: {}",
config
.database_url
.replace("postgres://", "postgres://****:****@")
);
println!(" Pool size: {}", config.pool_size);
println!(" Connect timeout: {}s", config.connect_timeout);
println!(" Retry attempts: {}", config.retry_attempts);
println!("\n🔌 Testing PostgreSQL connection...");
match test_connection(config).await {
Ok(()) => {
println!("✅ All PostgreSQL tests passed successfully!");
Ok(())
}
Err(e) => {
println!("❌ PostgreSQL test failed: {}", e);
Err(e.into())
}
}
}
async fn test_connection(config: PostgresConfig) -> Result<(), PostgresError> {
println!(" Creating PostgreSQL connection...");
let postgres_conn = PostgresConnection::new(config).await?;
let connection = Arc::new(postgres_conn);
println!(" ✅ Connection established successfully");
println!(" Testing basic connectivity...");
test_basic_connectivity(&connection).await?;
println!(" ✅ Basic connectivity test passed");
println!(" Testing table existence...");
test_table_existence(&connection).await?;
println!(" ✅ Table existence test passed");
println!(" Testing CRUD operations...");
test_crud_operations(&connection).await?;
println!(" ✅ CRUD operations test passed");
println!(" Testing transaction support...");
test_transactions(&connection).await?;
println!(" ✅ Transaction support test passed");
println!(" Testing error handling...");
test_error_handling(&connection).await?;
println!(" ✅ Error handling test passed");
Ok(())
}
async fn test_basic_connectivity(
connection: &Arc<PostgresConnection>,
) -> Result<(), PostgresError> {
let statement = sea_orm::Statement::from_string(
connection.get_database_backend(),
"SELECT 1 as test_value, current_timestamp as current_time".to_string(),
);
let result = connection.query_one(statement).await?.ok_or_else(|| {
PostgresError::ConnectionError(sea_orm::DbErr::Custom(
"No results returned".to_string(),
))
})?;
let test_value: Option<i32> = result.try_get("", "test_value").ok();
let current_time: Option<String> = result.try_get("", "current_time").ok();
if test_value != Some(1) {
return Err(PostgresError::ConnectionError(sea_orm::DbErr::Custom(
format!("Expected test_value=1, got {:?}", test_value),
)));
}
if current_time.is_none() {
return Err(PostgresError::ConnectionError(sea_orm::DbErr::Custom(
"Expected current_time to be set".to_string(),
)));
}
println!(
" 📝 Query result: test_value={:?}, current_time={:?}",
test_value, current_time
);
Ok(())
}
async fn test_table_existence(
connection: &Arc<PostgresConnection>,
) -> Result<(), PostgresError> {
use sea_orm::EntityTrait;
println!(" 📋 Checking users table...");
let user_count = UsersEntity::find()
.count(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?;
println!(
" 📊 Users table accessible, current count: {}",
user_count
);
println!(" 📋 Checking roles table...");
let role_count = RolesEntity::find()
.count(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?;
println!(
" 📊 Roles table accessible, current count: {}",
role_count
);
Ok(())
}
async fn test_crud_operations(
connection: &Arc<PostgresConnection>,
) -> Result<(), PostgresError> {
use sea_orm::{ActiveModelTrait, Set};
println!(" Creating test user...");
let test_user_id = Uuid::new_v4();
let now = Utc::now();
let user_model = imphnen_entities::seaorm::auth::users::ActiveModel {
id: Set(test_user_id),
email: Set(format!("test_user_{}@example.com", test_user_id)),
password_hash: Set("test_password_hash".to_string()),
username: Set(format!("testuser_{}", test_user_id)),
first_name: Set(Some("Test".to_string())),
last_name: Set(Some("User".to_string())),
avatar_url: Set(None),
is_verified: Set(false),
is_active: Set(true),
metadata: Set(None),
role_id: Set(None),
created_at: Set(now),
updated_at: Set(now),
deleted_at: Set(None),
};
let created_user = user_model
.insert(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?;
println!(" ✅ Created user with ID: {}", created_user.id);
println!(" 🔍 Reading test user...");
let found_user = UsersEntity::find_by_id(test_user_id)
.one(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?
.ok_or_else(|| {
PostgresError::ConnectionError(sea_orm::DbErr::Custom(
"User not found after creation".to_string(),
))
})?;
println!(
" ✅ Found user: {} ({})",
found_user.username, found_user.email
);
println!(" ✏️ Updating test user...");
let mut update_model: imphnen_entities::seaorm::auth::users::ActiveModel =
found_user.into();
update_model.first_name = Set(Some("Updated".to_string()));
update_model.updated_at = Set(Utc::now());
let updated_user = update_model
.update(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?;
println!(
" ✅ Updated user first name to: {:?}",
updated_user.first_name
);
println!(" 🗑️ Deleting test user...");
UsersEntity::delete_by_id(updated_user.id)
.exec(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?;
println!(" ✅ Test user deleted successfully");
Ok(())
}
async fn test_transactions(
connection: &Arc<PostgresConnection>,
) -> Result<(), PostgresError> {
println!(" 💰 Testing transaction support...");
let transaction_result = connection
.conn
.transaction(|txn| {
Box::pin(async move {
let test_user_id = Uuid::new_v4();
let now = Utc::now();
let user_model = imphnen_entities::seaorm::auth::users::ActiveModel {
id: Set(test_user_id),
email: Set(format!("transaction_test_{}@example.com", test_user_id)),
password_hash: Set("transaction_password_hash".to_string()),
username: Set(format!("transaction_user_{}", test_user_id)),
first_name: Set(Some("Transaction".to_string())),
last_name: Set(Some("Test".to_string())),
avatar_url: Set(None),
is_verified: Set(false),
is_active: Set(true),
metadata: Set(None),
role_id: Set(None),
created_at: Set(now),
updated_at: Set(now),
deleted_at: Set(None),
};
let _created_user = user_model.insert(txn).await?;
Err::<(), DbErr>(DbErr::Custom("Simulated transaction failure".to_string()))
})
})
.await;
match transaction_result {
Err(e) => {
let e_text = format!("{:?}", e);
if e_text.contains("Simulated transaction failure") {
println!(" ✅ Transaction failed as expected, rollback successful");
} else {
return Err(PostgresError::OperationFailed(format!(
"Unexpected transaction result: {}",
e_text
)));
}
}
Ok(_) => {
return Err(PostgresError::OperationFailed(
"Unexpected transaction result: transaction unexpectedly succeeded"
.to_string(),
));
}
}
let user_exists = UsersEntity::find_by_id(Uuid::nil())
.one(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?
.is_some();
if user_exists {
println!(" ⚠️ User found despite rollback - this might indicate an issue");
} else {
println!(" ✅ Transaction rollback verified - user not found");
}
Ok(())
}
async fn test_error_handling(
connection: &Arc<PostgresConnection>,
) -> Result<(), PostgresError> {
println!(" ⚠️ Testing error handling...");
println!(" 🔍 Testing invalid UUID handling...");
let invalid_uuid = Uuid::nil();
match UsersEntity::find_by_id(invalid_uuid)
.one(&connection.conn)
.await
.map_err(PostgresError::ConnectionError)?
{
Some(_) => {
println!(" ✅ Found user with nil UUID (expected in some cases)")
}
None => println!(" ✅ No user found with nil UUID (expected)"),
}
println!(" 🔍 Testing invalid query handling...");
let invalid_statement = sea_orm::Statement::from_string(
connection.get_database_backend(),
"SELECT * FROM non_existent_table".to_string(),
);
match connection.execute(invalid_statement).await {
Err(_) => println!(" ✅ Invalid query properly handled with error"),
Ok(_) => println!(" ⚠️ Invalid query unexpectedly succeeded"),
}
Ok(())
}
pub mod test_utils {
use super::*;
pub fn create_test_config() -> PostgresConfig {
PostgresConfig {
database_url: "postgres://postgres:postgres@localhost:5432/imphnen_test"
.to_string(),
pool_size: 5,
connect_timeout: 10,
idle_timeout: 30,
max_lifetime: Some(600),
retry_attempts: 2,
retry_delay: 1,
}
}
pub fn create_test_user_model() -> UserModel {
UserModel {
id: Uuid::new_v4(),
email: format!("test_{}@example.com", Uuid::new_v4()),
password_hash: "test_password_hash".to_string(),
username: format!("testuser_{}", Uuid::new_v4()),
first_name: Some("Test".to_string()),
last_name: Some("User".to_string()),
avatar_url: None,
is_verified: false,
is_active: true,
metadata: None,
role_id: None,
created_at: Utc::now(),
updated_at: Utc::now(),
deleted_at: None,
}
}
pub fn create_test_role_model() -> RoleModel {
RoleModel {
id: Uuid::new_v4(),
name: format!("test_role_{}", Uuid::new_v4()),
description: "Test role description".to_string(),
permissions: Some(serde_json::json!(["test.permission"])),
is_system_role: false,
is_default: false,
created_at: Utc::now(),
updated_at: Utc::now(),
deleted_at: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_test_config() {
let config = test_utils::create_test_config();
assert_eq!(config.pool_size, 5);
assert_eq!(config.connect_timeout, 10);
assert!(config.database_url.contains("imphnen_test"));
}
#[test]
fn test_create_test_user_model() {
let user = test_utils::create_test_user_model();
assert!(!user.email.is_empty());
assert!(!user.username.is_empty());
assert!(user.is_active);
}
#[test]
fn test_create_test_role_model() {
let role = test_utils::create_test_role_model();
assert!(!role.name.is_empty());
assert!(role.permissions.is_some());
assert!(!role.is_system_role);
}
}
+10
View File
@@ -0,0 +1,10 @@
use imphnen_gateway::gateway_service;
use imphnen_libs::axum_init;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let _ =
axum_init(|postgres_conn| async { gateway_service(postgres_conn).await }).await;
}
+41
View File
@@ -0,0 +1,41 @@
[package]
name = "imphnen-cms"
version = "0.3.0"
edition = "2024"
[dependencies]
async-trait.workspace = true
imphnen-iam.workspace = true
imphnen-libs.workspace = true
imphnen-utils.workspace = true
imphnen-entities.workspace = true
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
zod-rs.workspace = true
zod-rs-util.workspace = true
axum-test.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
log.workspace = true
tracing.workspace = true
sea-orm.workspace = true
uuid.workspace = true
paginator-rs.workspace = true
paginator-utils.workspace = true
paginator-sea-orm.workspace = true
paginator-axum.workspace = true
sqlx.workspace = true
image.workspace = true
qrcode.workspace = true
[package.metadata.validator.regex]
VALID_URL_REGEX = "^https?://"
@@ -0,0 +1,43 @@
use crate::events::domain::{EventEntity, EventRepository, EventService};
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
pub struct EventServiceImpl {
repo: Arc<dyn EventRepository>,
}
impl EventServiceImpl {
pub fn new(repo: Arc<dyn EventRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl EventService for EventServiceImpl {
async fn list(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<EventEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
self.repo.create(entity).await
}
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
@@ -0,0 +1,3 @@
pub mod event_service;
pub use event_service::EventServiceImpl;
+18
View File
@@ -0,0 +1,18 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct EventEntity {
pub id: Uuid,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub is_deleted: bool,
pub location: Option<String>,
pub start_date: DateTime<Utc>,
pub end_date: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
+7
View File
@@ -0,0 +1,7 @@
pub mod event;
pub mod repository;
pub mod service;
pub use event::EventEntity;
pub use repository::EventRepository;
pub use service::EventService;
@@ -0,0 +1,18 @@
use super::event::EventEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
#[async_trait]
pub trait EventRepository: Send + Sync {
async fn find_all(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<EventEntity>, AppError>;
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError>;
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
+18
View File
@@ -0,0 +1,18 @@
use super::event::EventEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
#[async_trait]
pub trait EventService: Send + Sync {
async fn list(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<EventEntity>, AppError>;
async fn get(&self, id: Uuid) -> Result<EventEntity, AppError>;
async fn create(&self, entity: EventEntity) -> Result<(), AppError>;
async fn update(&self, entity: EventEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,131 @@
use crate::events::domain::event::EventEntity;
use chrono::{DateTime, Utc};
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsCreateRequestDto {
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
pub end_date: DateTime<Utc>,
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
pub start_date: DateTime<Utc>,
pub location: Option<String>,
pub is_online: bool,
}
impl ZodValidate for EventsCreateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
impl From<EventsCreateRequestDto> for EventEntity {
fn from(dto: EventsCreateRequestDto) -> Self {
EventEntity {
id: Uuid::new_v4(),
name: dto.name,
description: dto.description,
detail_link: dto.detail_link,
price: dto.price,
is_online: dto.is_online,
is_deleted: false,
location: dto.location,
start_date: dto.start_date,
end_date: dto.end_date,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsUpdateRequestDto {
pub name: String,
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
pub end_date: DateTime<Utc>,
#[schema(example = "2025-09-20T13:00:00Z", value_type = String)]
pub start_date: DateTime<Utc>,
pub price: f64,
pub is_online: bool,
pub description: String,
pub detail_link: String,
pub location: Option<String>,
}
impl ZodValidate for EventsUpdateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsListItemDto {
pub id: String,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub start_date: String,
pub end_date: String,
pub created_at: String,
pub location: Option<String>,
pub is_deleted: bool,
}
impl From<EventEntity> for EventsListItemDto {
fn from(e: EventEntity) -> Self {
EventsListItemDto {
id: e.id.to_string(),
name: e.name,
description: e.description,
detail_link: e.detail_link,
price: e.price,
is_online: e.is_online,
start_date: e.start_date.to_rfc3339(),
end_date: e.end_date.to_rfc3339(),
created_at: e.created_at.to_rfc3339(),
location: e.location,
is_deleted: e.is_deleted,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct EventsDetailItemDto {
pub id: String,
pub name: String,
pub description: String,
pub detail_link: String,
pub price: f64,
pub is_online: bool,
pub start_date: String,
pub end_date: String,
pub created_at: String,
pub updated_at: String,
pub location: Option<String>,
}
impl From<EventEntity> for EventsDetailItemDto {
fn from(e: EventEntity) -> Self {
EventsDetailItemDto {
id: e.id.to_string(),
name: e.name,
description: e.description,
detail_link: e.detail_link,
price: e.price,
is_online: e.is_online,
start_date: e.start_date.to_rfc3339(),
end_date: e.end_date.to_rfc3339(),
created_at: e.created_at.to_rfc3339(),
updated_at: e.updated_at.to_rfc3339(),
location: e.location,
}
}
}
@@ -0,0 +1,180 @@
use super::dto::{
EventsCreateRequestDto, EventsDetailItemDto, EventsListItemDto,
EventsUpdateRequestDto,
};
use crate::events::domain::EventService;
use axum::{
Extension,
extract::Path,
http::HeaderMap,
response::{IntoResponse, Response},
};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::AppError;
use imphnen_utils::{ApiMessage, ApiPaginated, ApiSuccess};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
#[utoipa::path(
get,
path = "/v1/landing/cms/events",
params(
("page" = Option<i64>, Query, description = "Page number"),
("per_page" = Option<i64>, Query, description = "Items per page"),
("search" = Option<String>, Query, description = "Search keyword"),
("sort_by" = Option<String>, Query, description = "Sort by field"),
("order" = Option<String>, Query, description = "Order ASC or DESC"),
),
responses(
(status = 200, description = "[PUBLIC] Get event list")
),
tag = "Events"
)]
pub async fn get_event_list(
Extension(service): Extension<Arc<dyn EventService>>,
PaginationQuery(params): PaginationQuery,
) -> Response {
match service.list(params).await {
Ok(result) => {
let mapped = PaginatorResponse {
data: result
.data
.into_iter()
.map(EventsListItemDto::from)
.collect::<Vec<_>>(),
meta: result.meta,
};
ApiPaginated(mapped).into_response()
}
Err(e) => ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, e.to_string())
.into_response(),
}
}
#[utoipa::path(
get,
path = "/v1/landing/cms/events/detail/{id}",
params(
("id" = String, Path, description = "Event ID")
),
responses(
(status = 200, description = "[PUBLIC] Get event by ID", body = ResponseSuccessDto<EventsDetailItemDto>)
),
tag = "Events"
)]
pub async fn get_event_by_id(
Extension(service): Extension<Arc<dyn EventService>>,
Path(id): Path<String>,
) -> Response {
let uuid = match Uuid::parse_str(&id) {
Ok(u) => u,
Err(e) => {
return ApiMessage::new(
axum::http::StatusCode::BAD_REQUEST,
format!("Invalid UUID: {e}"),
)
.into_response();
}
};
match service.get(uuid).await {
Ok(event) => ApiSuccess(EventsDetailItemDto::from(event)).into_response(),
Err(e) => ApiMessage::new(axum::http::StatusCode::NOT_FOUND, e.to_string())
.into_response(),
}
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/landing/cms/events/create",
request_body = EventsCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new event")
),
tag = "Events"
)]
pub async fn post_create_event(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn EventService>>,
ValidatedJson(payload): ValidatedJson<EventsCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let entity = payload.into();
service.create(entity).await?;
Ok(ApiMessage::created("Event created"))
})
}
#[utoipa::path(
patch,
security(("Bearer" = [])),
path = "/v1/landing/cms/events/update/{id}",
params(
("id" = String, Path, description = "Event ID")
),
request_body = EventsUpdateRequestDto,
responses(
(status = 200, description = "[ADMIN] Update event")
),
tag = "Events"
)]
pub async fn patch_update_event(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn EventService>>,
Path(id): Path<String>,
ValidatedJson(payload): ValidatedJson<EventsUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let existing = service.get(uuid).await?;
let entity = crate::events::domain::EventEntity {
id: existing.id,
name: payload.name,
description: payload.description,
detail_link: payload.detail_link,
price: payload.price,
is_online: payload.is_online,
location: payload.location,
start_date: payload.start_date,
end_date: payload.end_date,
is_deleted: existing.is_deleted,
created_at: existing.created_at,
updated_at: chrono::Utc::now(),
};
service.update(entity).await?;
Ok(ApiMessage::ok("Event updated"))
})
}
#[utoipa::path(
delete,
security(("Bearer" = [])),
path = "/v1/landing/cms/events/delete/{id}",
params(
("id" = String, Path, description = "Event ID")
),
responses(
(status = 200, description = "[ADMIN] Soft delete event")
),
tag = "Events"
)]
pub async fn delete_event(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn EventService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete(uuid).await?;
Ok(ApiMessage::ok("Event deleted"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::{events_protected_routes, events_public_routes};
@@ -0,0 +1,35 @@
use super::handlers::{
delete_event, get_event_by_id, get_event_list, patch_update_event,
post_create_event,
};
use crate::events::application::EventServiceImpl;
use crate::events::domain::EventService;
use crate::events::infrastructure::persistence::PostgresEventRepository;
use axum::{
Extension, Router,
routing::{delete, get, patch, post},
};
use sea_orm::DatabaseConnection;
use std::sync::Arc;
fn build_service(db: DatabaseConnection) -> Arc<dyn EventService> {
let repo = Arc::new(PostgresEventRepository::new(db));
Arc::new(EventServiceImpl::new(repo))
}
pub fn events_public_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/events", get(get_event_list))
.route("/events/detail/{id}", get(get_event_by_id))
.layer(Extension(service))
}
pub fn events_protected_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/events/create", post(post_create_event))
.route("/events/update/{id}", patch(patch_update_event))
.route("/events/delete/{id}", delete(delete_event))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_event_repository;
pub use postgres_event_repository::PostgresEventRepository;
@@ -0,0 +1,161 @@
use crate::events::domain::{event::EventEntity, repository::EventRepository};
use async_trait::async_trait;
use imphnen_entities::seaorm::common::events::{
ActiveModel as EventsActiveModel, Column as EventsColumn, Entity as EventsEntity,
Model as EventsModel,
};
use imphnen_utils::AppError;
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, PaginatorTrait, QueryOrder};
use std::sync::Arc;
use uuid::Uuid;
fn to_entity(model: EventsModel) -> EventEntity {
EventEntity {
id: model.id,
name: model.name,
description: model.description,
detail_link: model.detail_link,
price: model.price,
is_online: model.is_online,
is_deleted: model.is_deleted,
location: model.location,
start_date: model.start_date,
end_date: model.end_date,
created_at: model.created_at,
updated_at: model.updated_at,
}
}
pub struct PostgresEventRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresEventRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl EventRepository for PostgresEventRepository {
async fn find_all(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<EventEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = EventsEntity::find().filter(EventsColumn::IsDeleted.eq(false));
if let Some(ref search) = params.search {
query = query.filter(EventsColumn::Name.contains(&search.query));
}
query = match params.sort_by.as_deref() {
Some("name") => match params.sort_direction {
Some(SortDirection::Desc) => query.order_by(EventsColumn::Name, Order::Desc),
_ => query.order_by(EventsColumn::Name, Order::Asc),
},
_ => match params.sort_direction {
Some(SortDirection::Asc) => {
query.order_by(EventsColumn::CreatedAt, Order::Asc)
}
_ => query.order_by(EventsColumn::CreatedAt, Order::Desc),
},
};
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
let total = paginator
.num_items()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let events = paginator
.fetch_page((page - 1) as u64)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data = events.into_iter().map(to_entity).collect();
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: Uuid) -> Result<EventEntity, AppError> {
let event = EventsEntity::find_by_id(id)
.filter(EventsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?;
Ok(to_entity(event))
}
async fn create(&self, entity: EventEntity) -> Result<(), AppError> {
let active_model = EventsActiveModel {
id: ActiveValue::Set(entity.id),
name: ActiveValue::Set(entity.name),
description: ActiveValue::Set(entity.description),
detail_link: ActiveValue::Set(entity.detail_link),
price: ActiveValue::Set(entity.price),
is_online: ActiveValue::Set(entity.is_online),
is_deleted: ActiveValue::Set(false),
location: ActiveValue::Set(entity.location),
start_date: ActiveValue::Set(entity.start_date),
end_date: ActiveValue::Set(entity.end_date),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
};
EventsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn update(&self, entity: EventEntity) -> Result<(), AppError> {
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(entity.id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
.into();
active_model.name = ActiveValue::Set(entity.name);
active_model.description = ActiveValue::Set(entity.description);
active_model.detail_link = ActiveValue::Set(entity.detail_link);
active_model.price = ActiveValue::Set(entity.price);
active_model.is_online = ActiveValue::Set(entity.is_online);
active_model.location = ActiveValue::Set(entity.location);
active_model.start_date = ActiveValue::Set(entity.start_date);
active_model.end_date = ActiveValue::Set(entity.end_date);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
let mut active_model: EventsActiveModel = EventsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Event not found".to_string()))?
.into();
active_model.is_deleted = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::{events_protected_routes, events_public_routes};
+9
View File
@@ -0,0 +1,9 @@
pub mod events;
pub mod roadmap;
pub mod testimonials;
pub mod qr;
pub use events::{events_protected_routes, events_public_routes};
pub use roadmap::{roadmap_protected_routes, roadmap_public_routes};
pub use testimonials::{testimonials_protected_routes, testimonials_public_routes};
pub use qr::qr_router;
@@ -0,0 +1,101 @@
use async_trait::async_trait;
use image::{DynamicImage, GenericImageView, ImageFormat, imageops};
use imphnen_utils::errors::AppError;
use qrcode::QrCode;
use std::io::Cursor;
use std::sync::Arc;
use uuid::Uuid;
use crate::qr::campaigns::domain::{
entity::{CampaignEntity, CreateCampaignInput},
repository::CampaignRepository,
service::QrCampaignService,
};
pub struct QrCampaignServiceImpl {
repo: Arc<dyn CampaignRepository>,
}
impl QrCampaignServiceImpl {
pub fn new(repo: Arc<dyn CampaignRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl QrCampaignService for QrCampaignServiceImpl {
async fn create(
&self,
name: String,
url: String,
created_by: Uuid,
) -> Result<CampaignEntity, AppError> {
let qr = QrCode::new(url.as_bytes())
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let qr_img = qr
.render::<image::Luma<u8>>()
.min_dimensions(256, 256)
.build();
let mut qr_bytes = Vec::new();
DynamicImage::ImageLuma8(qr_img)
.write_to(&mut Cursor::new(&mut qr_bytes), ImageFormat::Png)
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let input = CreateCampaignInput {
name,
url,
created_by,
qr_code_data: qr_bytes,
};
self.repo.create(input).await
}
async fn list_all(&self) -> Result<Vec<CampaignEntity>, AppError> {
self.repo.find_all().await
}
async fn get_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError> {
self.repo.find_active_qr_data().await
}
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError> {
self.repo.set_active(id).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
async fn process_image(&self, image_bytes: Vec<u8>) -> Result<Vec<u8>, AppError> {
let qr_data = self
.repo
.find_active_qr_data()
.await?
.ok_or_else(|| AppError::NotFoundError("No active campaign".to_string()))?;
let img = image::load_from_memory(&image_bytes)
.map_err(|_| AppError::BadRequestError("Invalid image format".to_string()))?;
let qr_img = image::load_from_memory(&qr_data).map_err(|_| {
AppError::InternalServerError("Failed to load QR data".to_string())
})?;
let (w, h) = img.dimensions();
let qr_size = (std::cmp::min(w, h) / 5).max(100);
let qr_resized =
qr_img.resize_exact(qr_size, qr_size, imageops::FilterType::Nearest);
let mut output = img.to_rgba8();
let x = (w - qr_size - 10) as i64;
let y = (h - qr_size - 10) as i64;
imageops::overlay(&mut output, &qr_resized.to_rgba8(), x, y);
let mut out_bytes = Vec::new();
DynamicImage::ImageRgba8(output)
.write_to(&mut Cursor::new(&mut out_bytes), ImageFormat::Png)
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(out_bytes)
}
}
@@ -0,0 +1 @@
pub mod campaign_service;
@@ -0,0 +1,22 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CampaignEntity {
pub id: Uuid,
pub name: String,
pub url: String,
pub is_active: bool,
pub created_by: Uuid,
pub expires_at: DateTime<Utc>,
pub created_at: Option<DateTime<Utc>>,
pub updated_at: Option<DateTime<Utc>>,
}
pub struct CreateCampaignInput {
pub name: String,
pub url: String,
pub created_by: Uuid,
pub qr_code_data: Vec<u8>,
}
@@ -0,0 +1,3 @@
pub mod entity;
pub mod repository;
pub mod service;
@@ -0,0 +1,17 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use uuid::Uuid;
use super::entity::{CampaignEntity, CreateCampaignInput};
#[async_trait]
pub trait CampaignRepository: Send + Sync {
async fn create(
&self,
input: CreateCampaignInput,
) -> Result<CampaignEntity, AppError>;
async fn find_all(&self) -> Result<Vec<CampaignEntity>, AppError>;
async fn find_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError>;
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,20 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use uuid::Uuid;
use super::entity::CampaignEntity;
#[async_trait]
pub trait QrCampaignService: Send + Sync {
async fn create(
&self,
name: String,
url: String,
created_by: Uuid,
) -> Result<CampaignEntity, AppError>;
async fn list_all(&self) -> Result<Vec<CampaignEntity>, AppError>;
async fn get_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError>;
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
async fn process_image(&self, image_bytes: Vec<u8>) -> Result<Vec<u8>, AppError>;
}
@@ -0,0 +1,22 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
#[derive(Debug, Deserialize, ToSchema)]
pub struct CreateCampaignRequest {
pub name: String,
pub url: String,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct CampaignResponse {
pub id: Uuid,
pub name: String,
pub url: String,
pub is_active: bool,
pub created_by: Uuid,
pub expires_at: DateTime<Utc>,
pub created_at: Option<DateTime<Utc>>,
pub updated_at: Option<DateTime<Utc>>,
}
@@ -0,0 +1,204 @@
use axum::{
Extension, Json,
extract::{Multipart, Path},
response::{IntoResponse, Response},
};
use imphnen_utils::{errors::AppError, response_format::ApiSuccess};
use std::sync::Arc;
use uuid::Uuid;
use crate::qr::{
campaigns::{
domain::service::QrCampaignService,
infrastructure::http::dto::CreateCampaignRequest,
},
middleware::qr_auth::QrAuthUser,
};
#[utoipa::path(
post,
path = "/v1/qr/campaigns",
request_body = CreateCampaignRequest,
responses(
(status = 201, description = "Create a QR campaign",
example = json!({
"data": {
"id": "e5f6a7b8-c9d0-1234-efab-345678901234",
"name": "Imphnen Hackathon 2025",
"url": "https://imphnen.dev/register",
"is_active": false,
"created_by": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"expires_at": "2025-12-31T23:59:59Z",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-01T00:00:00Z"
},
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Campaigns",
security(("Bearer" = []))
)]
pub async fn create_campaign_handler(
Extension(service): Extension<Arc<dyn QrCampaignService>>,
Extension(auth_user): Extension<QrAuthUser>,
Json(body): Json<CreateCampaignRequest>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
let campaign = service
.create(body.name, body.url, auth_user.user_id)
.await?;
Ok(imphnen_utils::response_format::ApiCreated(campaign).into_response())
}
#[utoipa::path(
get,
path = "/v1/qr/campaigns",
responses(
(status = 200, description = "Admin: list all QR campaigns",
example = json!({
"data": [
{
"id": "e5f6a7b8-c9d0-1234-efab-345678901234",
"name": "Imphnen Hackathon 2025",
"url": "https://imphnen.dev/register",
"is_active": true,
"created_by": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"expires_at": "2025-12-31T23:59:59Z",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-05T00:00:00Z"
}
],
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Campaigns",
security(("Bearer" = []))
)]
pub async fn list_campaigns_handler(
Extension(service): Extension<Arc<dyn QrCampaignService>>,
Extension(auth_user): Extension<QrAuthUser>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
let campaigns = service.list_all().await?;
Ok(ApiSuccess(campaigns).into_response())
}
#[utoipa::path(
put,
path = "/v1/qr/campaigns/{id}/activate",
params(("id" = Uuid, Path, description = "Campaign ID")),
responses(
(status = 200, description = "Admin: activate a campaign (deactivates all others)",
example = json!({
"data": {
"id": "e5f6a7b8-c9d0-1234-efab-345678901234",
"name": "Imphnen Hackathon 2025",
"url": "https://imphnen.dev/register",
"is_active": true,
"created_by": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"expires_at": "2025-12-31T23:59:59Z",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-05T10:00:00Z"
},
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Campaigns",
security(("Bearer" = []))
)]
pub async fn activate_campaign_handler(
Extension(service): Extension<Arc<dyn QrCampaignService>>,
Extension(auth_user): Extension<QrAuthUser>,
Path(id): Path<Uuid>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
let campaign = service.set_active(id).await?;
Ok(ApiSuccess(campaign).into_response())
}
#[utoipa::path(
delete,
path = "/v1/qr/campaigns/{id}",
params(("id" = Uuid, Path, description = "Campaign ID")),
responses(
(status = 200, description = "Admin: delete a campaign",
example = json!({"message": "Campaign deleted successfully", "version": "0.3.0"})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Campaigns",
security(("Bearer" = []))
)]
pub async fn delete_campaign_handler(
Extension(service): Extension<Arc<dyn QrCampaignService>>,
Extension(auth_user): Extension<QrAuthUser>,
Path(id): Path<Uuid>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
service.delete(id).await?;
Ok(
imphnen_utils::response_format::ApiMessage::ok("Campaign deleted successfully")
.into_response(),
)
}
#[utoipa::path(
post,
path = "/v1/qr/campaigns/process-image",
responses(
(status = 200, description = "Process QR code image — send multipart/form-data with field 'file'. Returns PNG image bytes.",
content_type = "image/png"),
(status = 400, description = "No file provided or invalid image"),
(status = 401, description = "Unauthorized")
),
tag = "QR - Campaigns",
security(("Bearer" = []))
)]
pub async fn process_image_handler(
Extension(service): Extension<Arc<dyn QrCampaignService>>,
Extension(_auth_user): Extension<QrAuthUser>,
mut multipart: Multipart,
) -> Result<Response, AppError> {
let mut image_bytes = Vec::new();
while let Some(field) = multipart
.next_field()
.await
.map_err(|e| AppError::BadRequestError(e.to_string()))?
{
if field.name() == Some("file") {
image_bytes = field
.bytes()
.await
.map_err(|e| AppError::BadRequestError(e.to_string()))?
.to_vec();
break;
}
}
if image_bytes.is_empty() {
return Err(AppError::BadRequestError("No file provided".to_string()));
}
let png_bytes = service.process_image(image_bytes).await?;
Ok(([(axum::http::header::CONTENT_TYPE, "image/png")], png_bytes).into_response())
}
@@ -0,0 +1,3 @@
pub mod dto;
pub mod handlers;
pub mod routes;
@@ -0,0 +1,41 @@
use axum::{
Extension, Router,
middleware::from_fn,
routing::{delete, post, put},
};
use sqlx::PgPool;
use std::sync::Arc;
use crate::qr::{
campaigns::{
application::campaign_service::QrCampaignServiceImpl,
domain::{repository::CampaignRepository, service::QrCampaignService},
infrastructure::{
http::handlers::{
activate_campaign_handler, create_campaign_handler, delete_campaign_handler,
list_campaigns_handler, process_image_handler,
},
persistence::postgres_campaign_repository::PostgresCampaignRepository,
},
},
middleware::qr_auth::qr_auth_middleware,
};
pub fn qr_campaigns_routes(pool: Arc<PgPool>) -> Router {
let repo: Arc<dyn CampaignRepository> =
Arc::new(PostgresCampaignRepository::new(pool.clone()));
let service: Arc<dyn QrCampaignService> =
Arc::new(QrCampaignServiceImpl::new(repo));
Router::new()
.route(
"/campaigns",
post(create_campaign_handler).get(list_campaigns_handler),
)
.route("/campaigns/{id}/activate", put(activate_campaign_handler))
.route("/campaigns/{id}", delete(delete_campaign_handler))
.route("/campaigns/process-image", post(process_image_handler))
.layer(Extension(service))
.layer(from_fn(qr_auth_middleware))
.layer(Extension(pool))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1 @@
pub mod postgres_campaign_repository;
@@ -0,0 +1,147 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use sqlx::FromRow;
use sqlx::PgPool;
use std::sync::Arc;
use uuid::Uuid;
use crate::qr::campaigns::domain::{
entity::{CampaignEntity, CreateCampaignInput},
repository::CampaignRepository,
};
#[derive(FromRow)]
struct CampaignRow {
pub id: Uuid,
pub name: String,
pub url: String,
pub is_active: bool,
pub created_by: Uuid,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
}
impl From<CampaignRow> for CampaignEntity {
fn from(row: CampaignRow) -> Self {
CampaignEntity {
id: row.id,
name: row.name,
url: row.url,
is_active: row.is_active,
created_by: row.created_by,
expires_at: row.expires_at,
created_at: row.created_at,
updated_at: row.updated_at,
}
}
}
pub struct PostgresCampaignRepository {
pool: Arc<PgPool>,
}
impl PostgresCampaignRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
}
#[async_trait]
impl CampaignRepository for PostgresCampaignRepository {
async fn create(
&self,
input: CreateCampaignInput,
) -> Result<CampaignEntity, AppError> {
let mut tx = self
.pool
.begin()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
sqlx::query("UPDATE qr_campaigns SET is_active = false, updated_at = NOW()")
.execute(&mut *tx)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let id = Uuid::new_v4();
let campaign = sqlx::query_as::<_, CampaignRow>(
"INSERT INTO qr_campaigns (id, name, url, qr_code_data, is_active, created_by, expires_at) \
VALUES ($1, $2, $3, $4, true, $5, NOW() + INTERVAL '30 days') \
RETURNING id, name, url, is_active, created_by, expires_at, created_at, updated_at",
)
.bind(id)
.bind(&input.name)
.bind(&input.url)
.bind(&input.qr_code_data)
.bind(input.created_by)
.fetch_one(&mut *tx)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
tx.commit()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(campaign.into())
}
async fn find_all(&self) -> Result<Vec<CampaignEntity>, AppError> {
sqlx::query_as::<_, CampaignRow>(
"SELECT id, name, url, is_active, created_by, expires_at, created_at, updated_at \
FROM qr_campaigns ORDER BY created_at DESC",
)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))
.map(|rows| rows.into_iter().map(Into::into).collect())
}
async fn find_active_qr_data(&self) -> Result<Option<Vec<u8>>, AppError> {
let row = sqlx::query_as::<_, (Vec<u8>,)>(
"SELECT qr_code_data FROM qr_campaigns WHERE is_active = true LIMIT 1",
)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(row.map(|r| r.0))
}
async fn set_active(&self, id: Uuid) -> Result<CampaignEntity, AppError> {
let mut tx = self
.pool
.begin()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
sqlx::query("UPDATE qr_campaigns SET is_active = false, updated_at = NOW()")
.execute(&mut *tx)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let campaign = sqlx::query_as::<_, CampaignRow>(
"UPDATE qr_campaigns SET is_active = true, updated_at = NOW() WHERE id = $1 \
RETURNING id, name, url, is_active, created_by, expires_at, created_at, updated_at",
)
.bind(id)
.fetch_one(&mut *tx)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
tx.commit()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(campaign.into())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
sqlx::query("DELETE FROM qr_campaigns WHERE id = $1")
.bind(id)
.execute(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::routes::qr_campaigns_routes;
+1
View File
@@ -0,0 +1 @@
pub mod qr_auth;
+69
View File
@@ -0,0 +1,69 @@
use axum::http::StatusCode;
use axum::{
body::Body,
extract::Request,
middleware::Next,
response::{IntoResponse, Response},
};
use imphnen_libs::decode_access_token;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::sync::Arc;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QrAuthUser {
pub user_id: Uuid,
pub role: String,
}
pub async fn qr_auth_middleware(
axum::Extension(pool): axum::Extension<Arc<PgPool>>,
mut request: Request<Body>,
next: Next,
) -> Result<Response, Response> {
let auth_header = request
.headers()
.get("Authorization")
.and_then(|h| h.to_str().ok())
.ok_or_else(|| {
(StatusCode::UNAUTHORIZED, "Missing Authorization header").into_response()
})?;
let token = auth_header.strip_prefix("Bearer ").ok_or_else(|| {
(
StatusCode::UNAUTHORIZED,
"Invalid Authorization header format",
)
.into_response()
})?;
let token_data = decode_access_token(token).map_err(|_| {
(StatusCode::UNAUTHORIZED, "Invalid or expired token").into_response()
})?;
let user_id = Uuid::parse_str(&token_data.claims.user_id).map_err(|_| {
(StatusCode::UNAUTHORIZED, "Invalid user ID in token").into_response()
})?;
let _ = sqlx::query(
"INSERT INTO qr_users (id, email, name, role, provider) VALUES ($1, $2, $2, 'user', 'external') ON CONFLICT (id) DO NOTHING"
)
.bind(user_id)
.bind(&token_data.claims.sub)
.execute(pool.as_ref())
.await;
let role: String = sqlx::query_scalar("SELECT role FROM qr_users WHERE id = $1")
.bind(user_id)
.fetch_optional(pool.as_ref())
.await
.ok()
.flatten()
.unwrap_or_else(|| "user".to_string());
request
.extensions_mut()
.insert(QrAuthUser { user_id, role });
Ok(next.run(request).await)
}
+15
View File
@@ -0,0 +1,15 @@
pub mod campaigns;
pub mod middleware;
pub mod users;
use axum::Router;
use sea_orm::DatabaseConnection;
use sqlx::PgPool;
use std::sync::Arc;
pub fn qr_router(db: DatabaseConnection) -> Router {
let pool: Arc<PgPool> = Arc::new(db.get_postgres_connection_pool().clone());
Router::new()
.merge(users::infrastructure::http::routes::qr_users_routes(pool.clone()))
.merge(campaigns::infrastructure::http::routes::qr_campaigns_routes(pool))
}
@@ -0,0 +1 @@
pub mod user_service;
@@ -0,0 +1,62 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use std::sync::Arc;
use uuid::Uuid;
use crate::qr::users::domain::{
entity::{UpdateUserInput, UserEntity},
repository::UserRepository,
service::QrUserService,
};
pub struct QrUserServiceImpl {
repo: Arc<dyn UserRepository>,
}
impl QrUserServiceImpl {
pub fn new(repo: Arc<dyn UserRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl QrUserService for QrUserServiceImpl {
async fn get_profile(&self, user_id: Uuid) -> Result<UserEntity, AppError> {
self
.repo
.find_by_id(user_id)
.await?
.ok_or_else(|| AppError::NotFoundError("User not found".to_string()))
}
async fn update_profile(
&self,
user_id: Uuid,
input: UpdateUserInput,
) -> Result<UserEntity, AppError> {
if let Some(ref email) = input.email
&& email.trim().is_empty()
{
return Err(AppError::ValidationError(
"Email cannot be empty".to_string(),
));
}
self.repo.update(user_id, input).await
}
async fn list_all(&self) -> Result<Vec<UserEntity>, AppError> {
self.repo.find_all().await
}
async fn update_role(
&self,
id: Uuid,
role: String,
) -> Result<UserEntity, AppError> {
self.repo.update_role(id, role).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
+19
View File
@@ -0,0 +1,19 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserEntity {
pub id: Uuid,
pub email: String,
pub name: String,
pub role: String,
pub provider: String,
pub created_at: Option<DateTime<Utc>>,
pub updated_at: Option<DateTime<Utc>>,
}
pub struct UpdateUserInput {
pub name: Option<String>,
pub email: Option<String>,
}
+3
View File
@@ -0,0 +1,3 @@
pub mod entity;
pub mod repository;
pub mod service;
@@ -0,0 +1,22 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use uuid::Uuid;
use super::entity::{UpdateUserInput, UserEntity};
#[async_trait]
pub trait UserRepository: Send + Sync {
async fn find_by_id(&self, id: Uuid) -> Result<Option<UserEntity>, AppError>;
async fn find_all(&self) -> Result<Vec<UserEntity>, AppError>;
async fn update(
&self,
id: Uuid,
input: UpdateUserInput,
) -> Result<UserEntity, AppError>;
async fn update_role(
&self,
id: Uuid,
role: String,
) -> Result<UserEntity, AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,22 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use uuid::Uuid;
use super::entity::{UpdateUserInput, UserEntity};
#[async_trait]
pub trait QrUserService: Send + Sync {
async fn get_profile(&self, user_id: Uuid) -> Result<UserEntity, AppError>;
async fn update_profile(
&self,
user_id: Uuid,
input: UpdateUserInput,
) -> Result<UserEntity, AppError>;
async fn list_all(&self) -> Result<Vec<UserEntity>, AppError>;
async fn update_role(
&self,
id: Uuid,
role: String,
) -> Result<UserEntity, AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Deserialize, ToSchema)]
pub struct UpdateProfileRequest {
pub name: Option<String>,
pub email: Option<String>,
}
#[derive(Debug, Deserialize, ToSchema)]
pub struct UpdateRoleRequest {
pub role: String,
}
#[derive(Debug, Serialize, ToSchema)]
pub struct UserResponse {
pub id: String,
pub email: String,
pub name: String,
pub role: String,
pub provider: String,
}
@@ -0,0 +1,199 @@
use axum::{
Extension, Json,
extract::Path,
response::{IntoResponse, Response},
};
use imphnen_utils::{errors::AppError, response_format::ApiSuccess};
use std::sync::Arc;
use uuid::Uuid;
use crate::qr::{
middleware::qr_auth::QrAuthUser,
users::{
domain::{entity::UpdateUserInput, service::QrUserService},
infrastructure::http::dto::{UpdateProfileRequest, UpdateRoleRequest},
},
};
#[utoipa::path(
get,
path = "/v1/qr/users/me",
responses(
(status = 200, description = "Get my QR user profile",
example = json!({
"data": {
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"email": "user@example.com",
"name": "Budi Santoso",
"role": "user",
"provider": "google",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-01T00:00:00Z"
},
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized")
),
tag = "QR - Users",
security(("Bearer" = []))
)]
pub async fn get_me_handler(
Extension(service): Extension<Arc<dyn QrUserService>>,
Extension(auth_user): Extension<QrAuthUser>,
) -> Result<Response, AppError> {
let user = service.get_profile(auth_user.user_id).await?;
Ok(ApiSuccess(user).into_response())
}
#[utoipa::path(
put,
path = "/v1/qr/users/me",
request_body = UpdateProfileRequest,
responses(
(status = 200, description = "Update my QR user profile",
example = json!({
"data": {
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"email": "updated@example.com",
"name": "Budi Santoso Updated",
"role": "user",
"provider": "google",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-15T00:00:00Z"
},
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized")
),
tag = "QR - Users",
security(("Bearer" = []))
)]
pub async fn update_me_handler(
Extension(service): Extension<Arc<dyn QrUserService>>,
Extension(auth_user): Extension<QrAuthUser>,
Json(body): Json<UpdateProfileRequest>,
) -> Result<Response, AppError> {
let input = UpdateUserInput {
name: body.name,
email: body.email,
};
let user = service.update_profile(auth_user.user_id, input).await?;
Ok(ApiSuccess(user).into_response())
}
#[utoipa::path(
get,
path = "/v1/qr/users",
responses(
(status = 200, description = "Admin: list all QR users",
example = json!({
"data": [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"email": "user@example.com",
"name": "Budi Santoso",
"role": "user",
"provider": "google",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-01T00:00:00Z"
},
{
"id": "4gb96g75-6828-5673-c4gd-3d074g77bgb7",
"email": "admin@example.com",
"name": "Admin User",
"role": "admin",
"provider": "google",
"created_at": "2024-12-01T00:00:00Z",
"updated_at": "2024-12-01T00:00:00Z"
}
],
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Users",
security(("Bearer" = []))
)]
pub async fn list_users_handler(
Extension(service): Extension<Arc<dyn QrUserService>>,
Extension(auth_user): Extension<QrAuthUser>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
let users = service.list_all().await?;
Ok(ApiSuccess(users).into_response())
}
#[utoipa::path(
put,
path = "/v1/qr/users/{id}/role",
params(("id" = Uuid, Path, description = "User ID")),
request_body = UpdateRoleRequest,
responses(
(status = 200, description = "Admin: update user role",
example = json!({
"data": {
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"email": "user@example.com",
"name": "Budi Santoso",
"role": "admin",
"provider": "google",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-20T00:00:00Z"
},
"version": "0.3.0"
})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Users",
security(("Bearer" = []))
)]
pub async fn update_role_handler(
Extension(service): Extension<Arc<dyn QrUserService>>,
Extension(auth_user): Extension<QrAuthUser>,
Path(id): Path<Uuid>,
Json(body): Json<UpdateRoleRequest>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
let user = service.update_role(id, body.role).await?;
Ok(ApiSuccess(user).into_response())
}
#[utoipa::path(
delete,
path = "/v1/qr/users/{id}",
params(("id" = Uuid, Path, description = "User ID")),
responses(
(status = 200, description = "Admin: delete QR user",
example = json!({"message": "User deleted successfully", "version": "0.3.0"})),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - admin only")
),
tag = "QR - Users",
security(("Bearer" = []))
)]
pub async fn delete_user_handler(
Extension(service): Extension<Arc<dyn QrUserService>>,
Extension(auth_user): Extension<QrAuthUser>,
Path(id): Path<Uuid>,
) -> Result<Response, AppError> {
if auth_user.role != "admin" {
return Err(AppError::ForbiddenError(
"Admin access required".to_string(),
));
}
service.delete(id).await?;
Ok(
imphnen_utils::response_format::ApiMessage::ok("User deleted successfully")
.into_response(),
)
}
@@ -0,0 +1,3 @@
pub mod dto;
pub mod handlers;
pub mod routes;
@@ -0,0 +1,37 @@
use axum::{
Extension, Router,
middleware::from_fn,
routing::{delete, get, put},
};
use sqlx::PgPool;
use std::sync::Arc;
use crate::qr::{
middleware::qr_auth::qr_auth_middleware,
users::{
application::user_service::QrUserServiceImpl,
domain::{repository::UserRepository, service::QrUserService},
infrastructure::{
http::handlers::{
delete_user_handler, get_me_handler, list_users_handler, update_me_handler,
update_role_handler,
},
persistence::postgres_user_repository::PostgresUserRepository,
},
},
};
pub fn qr_users_routes(pool: Arc<PgPool>) -> Router {
let repo: Arc<dyn UserRepository> =
Arc::new(PostgresUserRepository::new(pool.clone()));
let service: Arc<dyn QrUserService> = Arc::new(QrUserServiceImpl::new(repo));
Router::new()
.route("/users/me", get(get_me_handler).put(update_me_handler))
.route("/users", get(list_users_handler))
.route("/users/{id}/role", put(update_role_handler))
.route("/users/{id}", delete(delete_user_handler))
.layer(Extension(service))
.layer(from_fn(qr_auth_middleware))
.layer(Extension(pool))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1 @@
pub mod postgres_user_repository;
@@ -0,0 +1,112 @@
use async_trait::async_trait;
use imphnen_utils::errors::AppError;
use sqlx::FromRow;
use sqlx::PgPool;
use std::sync::Arc;
use uuid::Uuid;
use crate::qr::users::domain::{
entity::{UpdateUserInput, UserEntity},
repository::UserRepository,
};
#[derive(FromRow)]
struct UserRow {
pub id: Uuid,
pub email: String,
pub name: String,
pub role: String,
pub provider: String,
pub created_at: Option<chrono::DateTime<chrono::Utc>>,
pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
}
impl From<UserRow> for UserEntity {
fn from(row: UserRow) -> Self {
UserEntity {
id: row.id,
email: row.email,
name: row.name,
role: row.role,
provider: row.provider,
created_at: row.created_at,
updated_at: row.updated_at,
}
}
}
pub struct PostgresUserRepository {
pool: Arc<PgPool>,
}
impl PostgresUserRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
}
#[async_trait]
impl UserRepository for PostgresUserRepository {
async fn find_by_id(&self, id: Uuid) -> Result<Option<UserEntity>, AppError> {
sqlx::query_as::<_, UserRow>(
"SELECT id, email, name, role, provider, created_at, updated_at FROM qr_users WHERE id = $1",
)
.bind(id)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))
.map(|opt| opt.map(Into::into))
}
async fn find_all(&self) -> Result<Vec<UserEntity>, AppError> {
sqlx::query_as::<_, UserRow>(
"SELECT id, email, name, role, provider, created_at, updated_at FROM qr_users ORDER BY created_at DESC",
)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))
.map(|rows| rows.into_iter().map(Into::into).collect())
}
async fn update(
&self,
id: Uuid,
input: UpdateUserInput,
) -> Result<UserEntity, AppError> {
sqlx::query_as::<_, UserRow>(
"UPDATE qr_users SET name = COALESCE($1, name), email = COALESCE($2, email), updated_at = NOW() WHERE id = $3 RETURNING id, email, name, role, provider, created_at, updated_at",
)
.bind(input.name)
.bind(input.email)
.bind(id)
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))
.map(Into::into)
}
async fn update_role(
&self,
id: Uuid,
role: String,
) -> Result<UserEntity, AppError> {
sqlx::query_as::<_, UserRow>(
"UPDATE qr_users SET role = $1, updated_at = NOW() WHERE id = $2 RETURNING id, email, name, role, provider, created_at, updated_at",
)
.bind(role)
.bind(id)
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))
.map(Into::into)
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
sqlx::query("DELETE FROM qr_users WHERE id = $1")
.bind(id)
.execute(self.pool.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::routes::qr_users_routes;
@@ -0,0 +1,3 @@
pub mod roadmap_service;
pub use roadmap_service::RoadmapServiceImpl;
@@ -0,0 +1,47 @@
use crate::roadmap::domain::{RoadmapEntity, RoadmapRepository, RoadmapService};
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
pub struct RoadmapServiceImpl {
repo: Arc<dyn RoadmapRepository>,
}
impl RoadmapServiceImpl {
pub fn new(repo: Arc<dyn RoadmapRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl RoadmapService for RoadmapServiceImpl {
async fn list(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<RoadmapEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: Uuid) -> Result<RoadmapEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, entity: RoadmapEntity) -> Result<(), AppError> {
self.repo.create(entity).await
}
async fn update(&self, entity: RoadmapEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
async fn vote(&self, id: Uuid) -> Result<(), AppError> {
self.repo.increment_votes(id).await
}
}
+7
View File
@@ -0,0 +1,7 @@
pub mod roadmap;
pub mod repository;
pub mod service;
pub use roadmap::RoadmapEntity;
pub use repository::RoadmapRepository;
pub use service::RoadmapService;
@@ -0,0 +1,19 @@
use super::roadmap::RoadmapEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
#[async_trait]
pub trait RoadmapRepository: Send + Sync {
async fn find_all(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<RoadmapEntity>, AppError>;
async fn find_by_id(&self, id: Uuid) -> Result<RoadmapEntity, AppError>;
async fn create(&self, entity: RoadmapEntity) -> Result<(), AppError>;
async fn update(&self, entity: RoadmapEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
async fn increment_votes(&self, id: Uuid) -> Result<(), AppError>;
}
+14
View File
@@ -0,0 +1,14 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct RoadmapEntity {
pub id: Uuid,
pub title: String,
pub description: String,
pub status: String,
pub votes: i32,
pub is_deleted: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
+19
View File
@@ -0,0 +1,19 @@
use super::roadmap::RoadmapEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
#[async_trait]
pub trait RoadmapService: Send + Sync {
async fn list(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<RoadmapEntity>, AppError>;
async fn get(&self, id: Uuid) -> Result<RoadmapEntity, AppError>;
async fn create(&self, entity: RoadmapEntity) -> Result<(), AppError>;
async fn update(&self, entity: RoadmapEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
async fn vote(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,98 @@
use crate::roadmap::domain::roadmap::RoadmapEntity;
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct RoadmapCreateRequestDto {
pub title: String,
pub description: String,
#[schema(example = "upcoming")]
pub status: String,
}
impl ZodValidate for RoadmapCreateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
impl From<RoadmapCreateRequestDto> for RoadmapEntity {
fn from(dto: RoadmapCreateRequestDto) -> Self {
RoadmapEntity {
id: Uuid::new_v4(),
title: dto.title,
description: dto.description,
status: dto.status,
votes: 0,
is_deleted: false,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct RoadmapUpdateRequestDto {
pub title: String,
pub description: String,
#[schema(example = "upcoming")]
pub status: String,
}
impl ZodValidate for RoadmapUpdateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct RoadmapListItemDto {
pub id: String,
pub title: String,
pub description: String,
pub status: String,
pub votes: i32,
pub is_deleted: bool,
pub created_at: String,
}
impl From<RoadmapEntity> for RoadmapListItemDto {
fn from(e: RoadmapEntity) -> Self {
RoadmapListItemDto {
id: e.id.to_string(),
title: e.title,
description: e.description,
status: e.status,
votes: e.votes,
is_deleted: e.is_deleted,
created_at: e.created_at.to_rfc3339(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct RoadmapDetailItemDto {
pub id: String,
pub title: String,
pub description: String,
pub status: String,
pub votes: i32,
pub created_at: String,
pub updated_at: String,
}
impl From<RoadmapEntity> for RoadmapDetailItemDto {
fn from(e: RoadmapEntity) -> Self {
RoadmapDetailItemDto {
id: e.id.to_string(),
title: e.title,
description: e.description,
status: e.status,
votes: e.votes,
created_at: e.created_at.to_rfc3339(),
updated_at: e.updated_at.to_rfc3339(),
}
}
}
@@ -0,0 +1,208 @@
use super::dto::{
RoadmapCreateRequestDto, RoadmapDetailItemDto, RoadmapListItemDto,
RoadmapUpdateRequestDto,
};
use crate::roadmap::domain::RoadmapService;
use axum::{
Extension,
extract::Path,
http::HeaderMap,
response::{IntoResponse, Response},
};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::AppError;
use imphnen_utils::{ApiMessage, ApiPaginated, ApiSuccess};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
#[utoipa::path(
get,
path = "/v1/landing/cms/roadmap",
params(
("page" = Option<i64>, Query, description = "Page number"),
("per_page" = Option<i64>, Query, description = "Items per page"),
("search" = Option<String>, Query, description = "Search keyword"),
("sort_by" = Option<String>, Query, description = "Sort by field"),
("order" = Option<String>, Query, description = "Order ASC or DESC"),
),
responses(
(status = 200, description = "[PUBLIC] Get roadmap list")
),
tag = "Roadmap"
)]
pub async fn get_roadmap_list(
Extension(service): Extension<Arc<dyn RoadmapService>>,
PaginationQuery(params): PaginationQuery,
) -> Response {
match service.list(params).await {
Ok(result) => {
let mapped = PaginatorResponse {
data: result
.data
.into_iter()
.map(RoadmapListItemDto::from)
.collect::<Vec<_>>(),
meta: result.meta,
};
ApiPaginated(mapped).into_response()
}
Err(e) => ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, e.to_string())
.into_response(),
}
}
#[utoipa::path(
get,
path = "/v1/landing/cms/roadmap/detail/{id}",
params(
("id" = String, Path, description = "Roadmap item ID")
),
responses(
(status = 200, description = "[PUBLIC] Get roadmap item by ID", body = ResponseSuccessDto<RoadmapDetailItemDto>)
),
tag = "Roadmap"
)]
pub async fn get_roadmap_by_id(
Extension(service): Extension<Arc<dyn RoadmapService>>,
Path(id): Path<String>,
) -> Response {
let uuid = match Uuid::parse_str(&id) {
Ok(u) => u,
Err(e) => {
return ApiMessage::new(
axum::http::StatusCode::BAD_REQUEST,
format!("Invalid UUID: {e}"),
)
.into_response();
}
};
match service.get(uuid).await {
Ok(item) => ApiSuccess(RoadmapDetailItemDto::from(item)).into_response(),
Err(e) => ApiMessage::new(axum::http::StatusCode::NOT_FOUND, e.to_string())
.into_response(),
}
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/landing/cms/roadmap/create",
request_body = RoadmapCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new roadmap item")
),
tag = "Roadmap"
)]
pub async fn post_create_roadmap(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoadmapService>>,
ValidatedJson(payload): ValidatedJson<RoadmapCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let entity = payload.into();
service.create(entity).await?;
Ok(ApiMessage::created("Roadmap item created"))
})
}
#[utoipa::path(
patch,
security(("Bearer" = [])),
path = "/v1/landing/cms/roadmap/update/{id}",
params(
("id" = String, Path, description = "Roadmap item ID")
),
request_body = RoadmapUpdateRequestDto,
responses(
(status = 200, description = "[ADMIN] Update roadmap item")
),
tag = "Roadmap"
)]
pub async fn patch_update_roadmap(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoadmapService>>,
Path(id): Path<String>,
ValidatedJson(payload): ValidatedJson<RoadmapUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let existing = service.get(uuid).await?;
let entity = crate::roadmap::domain::RoadmapEntity {
id: existing.id,
title: payload.title,
description: payload.description,
status: payload.status,
votes: existing.votes,
is_deleted: existing.is_deleted,
created_at: existing.created_at,
updated_at: chrono::Utc::now(),
};
service.update(entity).await?;
Ok(ApiMessage::ok("Roadmap item updated"))
})
}
#[utoipa::path(
delete,
security(("Bearer" = [])),
path = "/v1/landing/cms/roadmap/delete/{id}",
params(
("id" = String, Path, description = "Roadmap item ID")
),
responses(
(status = 200, description = "[ADMIN] Soft delete roadmap item")
),
tag = "Roadmap"
)]
pub async fn delete_roadmap(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoadmapService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::Administrator], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete(uuid).await?;
Ok(ApiMessage::ok("Roadmap item deleted"))
})
}
#[utoipa::path(
post,
path = "/v1/landing/cms/roadmap/vote/{id}",
params(
("id" = String, Path, description = "Roadmap item ID")
),
responses(
(status = 200, description = "[PUBLIC] Vote for a roadmap item")
),
tag = "Roadmap"
)]
pub async fn post_vote_roadmap(
Extension(service): Extension<Arc<dyn RoadmapService>>,
Path(id): Path<String>,
) -> Response {
let uuid = match Uuid::parse_str(&id) {
Ok(u) => u,
Err(e) => {
return ApiMessage::new(
axum::http::StatusCode::BAD_REQUEST,
format!("Invalid UUID: {e}"),
)
.into_response();
}
};
match service.vote(uuid).await {
Ok(()) => ApiMessage::ok("Vote recorded").into_response(),
Err(e) => ApiMessage::new(axum::http::StatusCode::BAD_REQUEST, e.to_string())
.into_response(),
}
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::{roadmap_protected_routes, roadmap_public_routes};
@@ -0,0 +1,36 @@
use super::handlers::{
delete_roadmap, get_roadmap_by_id, get_roadmap_list, patch_update_roadmap,
post_create_roadmap, post_vote_roadmap,
};
use crate::roadmap::application::RoadmapServiceImpl;
use crate::roadmap::domain::RoadmapService;
use crate::roadmap::infrastructure::persistence::PostgresRoadmapRepository;
use axum::{
Extension, Router,
routing::{delete, get, patch, post},
};
use sea_orm::DatabaseConnection;
use std::sync::Arc;
fn build_service(db: DatabaseConnection) -> Arc<dyn RoadmapService> {
let repo = Arc::new(PostgresRoadmapRepository::new(db));
Arc::new(RoadmapServiceImpl::new(repo))
}
pub fn roadmap_public_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/roadmap", get(get_roadmap_list))
.route("/roadmap/detail/{id}", get(get_roadmap_by_id))
.route("/roadmap/vote/{id}", post(post_vote_roadmap))
.layer(Extension(service))
}
pub fn roadmap_protected_routes(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/roadmap/create", post(post_create_roadmap))
.route("/roadmap/update/{id}", patch(patch_update_roadmap))
.route("/roadmap/delete/{id}", delete(delete_roadmap))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_roadmap_repository;
pub use postgres_roadmap_repository::PostgresRoadmapRepository;
@@ -0,0 +1,171 @@
use crate::roadmap::domain::{roadmap::RoadmapEntity, repository::RoadmapRepository};
use async_trait::async_trait;
use imphnen_entities::seaorm::common::roadmap_items::{
ActiveModel as RoadmapActiveModel, Column as RoadmapColumn, Entity as RoadmapEntity_,
Model as RoadmapModel,
};
use imphnen_utils::AppError;
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, PaginatorTrait, QueryOrder};
use std::sync::Arc;
use uuid::Uuid;
fn to_entity(model: RoadmapModel) -> RoadmapEntity {
RoadmapEntity {
id: model.id,
title: model.title,
description: model.description,
status: model.status,
votes: model.votes,
is_deleted: model.is_deleted,
created_at: model.created_at,
updated_at: model.updated_at,
}
}
pub struct PostgresRoadmapRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresRoadmapRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl RoadmapRepository for PostgresRoadmapRepository {
async fn find_all(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<RoadmapEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = RoadmapEntity_::find().filter(RoadmapColumn::IsDeleted.eq(false));
if let Some(ref search) = params.search {
query = query.filter(RoadmapColumn::Title.contains(&search.query));
}
query = match params.sort_by.as_deref() {
Some("title") => match params.sort_direction {
Some(SortDirection::Desc) => query.order_by(RoadmapColumn::Title, Order::Desc),
_ => query.order_by(RoadmapColumn::Title, Order::Asc),
},
Some("votes") => match params.sort_direction {
Some(SortDirection::Asc) => query.order_by(RoadmapColumn::Votes, Order::Asc),
_ => query.order_by(RoadmapColumn::Votes, Order::Desc),
},
_ => match params.sort_direction {
Some(SortDirection::Asc) => {
query.order_by(RoadmapColumn::CreatedAt, Order::Asc)
}
_ => query.order_by(RoadmapColumn::CreatedAt, Order::Desc),
},
};
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
let total = paginator
.num_items()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let items = paginator
.fetch_page((page - 1) as u64)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data = items.into_iter().map(to_entity).collect();
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: Uuid) -> Result<RoadmapEntity, AppError> {
let item = RoadmapEntity_::find_by_id(id)
.filter(RoadmapColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Roadmap item not found".to_string()))?;
Ok(to_entity(item))
}
async fn create(&self, entity: RoadmapEntity) -> Result<(), AppError> {
let active_model = RoadmapActiveModel {
id: ActiveValue::Set(entity.id),
title: ActiveValue::Set(entity.title),
description: ActiveValue::Set(entity.description),
status: ActiveValue::Set(entity.status),
votes: ActiveValue::Set(0),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
};
RoadmapEntity_::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn update(&self, entity: RoadmapEntity) -> Result<(), AppError> {
let mut active_model: RoadmapActiveModel = RoadmapEntity_::find_by_id(entity.id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Roadmap item not found".to_string()))?
.into();
active_model.title = ActiveValue::Set(entity.title);
active_model.description = ActiveValue::Set(entity.description);
active_model.status = ActiveValue::Set(entity.status);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
let mut active_model: RoadmapActiveModel = RoadmapEntity_::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Roadmap item not found".to_string()))?
.into();
active_model.is_deleted = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn increment_votes(&self, id: Uuid) -> Result<(), AppError> {
let item = RoadmapEntity_::find_by_id(id)
.filter(RoadmapColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Roadmap item not found".to_string()))?;
let new_votes = item.votes + 1;
let mut active_model: RoadmapActiveModel = item.into();
active_model.votes = ActiveValue::Set(new_votes);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::{roadmap_protected_routes, roadmap_public_routes};
@@ -0,0 +1,3 @@
pub mod testimonial_service;
pub use testimonial_service::TestimonialServiceImpl;
@@ -0,0 +1,48 @@
use crate::testimonials::domain::{
TestimonialEntity, TestimonialRepository, TestimonialService,
};
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
pub struct TestimonialServiceImpl {
repo: Arc<dyn TestimonialRepository>,
}
impl TestimonialServiceImpl {
pub fn new(repo: Arc<dyn TestimonialRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl TestimonialService for TestimonialServiceImpl {
async fn list(
&self,
params: PaginationParams,
) -> Result<PaginatorResponse<TestimonialEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: Uuid) -> Result<TestimonialEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(
&self,
entity: TestimonialEntity,
) -> Result<TestimonialEntity, AppError> {
self.repo.create(entity).await
}
async fn update(&self, entity: TestimonialEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
@@ -0,0 +1,7 @@
pub mod repository;
pub mod service;
pub mod testimonial;
pub use repository::TestimonialRepository;
pub use service::TestimonialService;
pub use testimonial::TestimonialEntity;

Some files were not shown because too many files have changed in this diff Show More