Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1715e366c6 | ||
|
|
3d22e0dfc0 | ||
|
|
99e7ff0a13 |
@@ -0,0 +1,58 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
APLP Backend — backend for **aplp-web** (Adaptive Personal Learning Platform, learner-facing app). Java 21, Spring Boot 3.5 (parent pin: `spring-boot-starter-parent` 4.1.0), Maven, modular monolith with Clean Architecture layers, DDD-oriented, vertical-slice per business module.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
docker compose up -d db # start Postgres (see docker-compose.yml for port)
|
||||
./mvnw spring-boot:run # run app, dev profile, port 8080
|
||||
./mvnw test # run tests (H2, Postgres-compatible mode)
|
||||
./mvnw test -Dtest=AuthFlowIntegrationTest # run a single test class
|
||||
./mvnw package # build jar
|
||||
curl http://localhost:8080/actuator/health # liveness/readiness check
|
||||
```
|
||||
|
||||
No lint/format command is configured in `pom.xml`.
|
||||
|
||||
## Architecture
|
||||
|
||||
Request flow: `Controller → Application/Service (use case) → Domain → Persistence → DB`. Dependencies point inward only (API → Application → Domain); persistence implements repository interfaces defined in domain.
|
||||
|
||||
Each business module is a vertical slice under `src/main/java/aplp/backend/web/<module>/`:
|
||||
|
||||
```
|
||||
<module>/
|
||||
├── api/controller/ # REST controllers
|
||||
├── application/
|
||||
│ ├── dtos/ # request/response DTOs
|
||||
│ ├── mappers/ # manual DTO <-> domain mapping (no MapStruct despite it being on the classpath)
|
||||
│ └── services/ # use case orchestration, @Transactional
|
||||
├── domain/
|
||||
│ ├── entities/ # domain model — in practice these ARE the JPA entities (@Entity, jakarta.persistence.* live here directly, not layered out into a separate persistence model)
|
||||
│ ├── exceptions/ # DomainException-style, mapped to HTTP in GlobalExceptionHandler
|
||||
│ └── repositories/ # repository interfaces (impl lives in infrastructure/persistence)
|
||||
└── infrastructure/persistence/ # Spring Data JPA repos + Repository interface implementations
|
||||
```
|
||||
|
||||
Note: `docs/ARCHITECTURE.md`, `docs/CONVENTIONS.md`, `docs/MODULES.md` describe the intended design (package `com.aplp.backend`, a `persistence` layer with entities split from domain model). The actual code uses base package `aplp.backend.web` and puts JPA entities directly in `domain/entities`, with only repository *implementations* in `infrastructure/persistence`. Follow the existing code pattern (`identity`, `learner` modules), not the docs, when in doubt — the docs are aspirational/Phase 0 drafts and known to be stale on this point.
|
||||
|
||||
Modules present today: `common` (shared infra — no business logic), `identity` (auth: register/login/refresh/logout, JWT), `learner` (learner profile). Planned modules (`content`, `learning`, `assessment`, `progress`, `adaptive`, `recommendation`, `assistance`, `subscription`, `notification`) are documented in `docs/MODULES.md` but not yet implemented. Modules must only talk to each other through public interfaces — no reaching into another module's internals.
|
||||
|
||||
`common/` holds: `GlobalExceptionHandler` (exception → HTTP mapping), JWT (`JwtTokenProvider`, `JwtAuthenticationFilter`, `SecurityConfig`), `RequestIdFilter` (`X-Request-Id`), CORS config.
|
||||
|
||||
Depends on an external artifact `aplp.backend:core` (separate Maven module, not in this repo tree).
|
||||
|
||||
## Database
|
||||
|
||||
PostgreSQL in dev/prod (docker-compose), H2 in Postgres-compatible mode for tests (`src/test/resources/application-test.yml`). Flyway migrations in `src/main/resources/db/migration` (`ddl-auto=validate` — entities must match migrations exactly, migrations are the source of truth). Write migrations portable across Postgres and H2.
|
||||
|
||||
## Conventions worth knowing
|
||||
|
||||
- Error responses go through a global `ErrorCode` enum (in `common/api`) + `GlobalExceptionHandler`; add new codes there for new failure cases.
|
||||
- DTO mapping is manual (static mapper methods), not MapStruct, despite mapstruct being a dependency.
|
||||
- Domain exceptions extend the project's `DomainException` and get mapped to HTTP status in the API layer, not thrown as raw HTTP errors from domain/application code.
|
||||
@@ -0,0 +1,116 @@
|
||||
# APLP Backend — Architecture
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Module** | `aplp.backend.spring` |
|
||||
| **Role** | Backend cho **aplp-web** (learner application) |
|
||||
| **Status** | Draft |
|
||||
|
||||
---
|
||||
|
||||
## 1. Architectural Direction
|
||||
|
||||
Backend theo **Modular Monolith**, kết hợp:
|
||||
|
||||
```
|
||||
Modular Monolith
|
||||
+ Clean Architecture 4 Layers
|
||||
+ DDD-oriented
|
||||
+ Vertical Slice / Business Module
|
||||
```
|
||||
|
||||
Nguyên tắc nền tảng:
|
||||
|
||||
> **Business behavior first, database second.**
|
||||
|
||||
> **Modular Monolith first; extract service chỉ khi có demonstrated need.**
|
||||
|
||||
## 2. Request Flow
|
||||
|
||||
```
|
||||
Controller (API layer)
|
||||
↓
|
||||
Application / Service (use case)
|
||||
↓
|
||||
Domain (business rules / model)
|
||||
↓
|
||||
Persistence (repository)
|
||||
↓
|
||||
Database
|
||||
```
|
||||
|
||||
## 3. Clean Architecture — 4 Layers
|
||||
|
||||
Mỗi business module có 4 layer rõ ràng:
|
||||
|
||||
| Layer | Trách nhiệm | Should NOT do |
|
||||
| --- | --- | --- |
|
||||
| **Interface/API** | HTTP entry point, DTO request/response, validation cơ bản, tách biệt khỏi domain | Chứa business logic |
|
||||
| **Application** | Use case orchestration, transactions, authorization | Chứa domain business rules |
|
||||
| **Domain** | Entities, value objects, business rules, domain services | Phụ thuộc DB/HTTP |
|
||||
| **Persistence** | Repository implementation, mapping, DB access | Chứa business rules |
|
||||
|
||||
**Dependency rule:** chỉ phụ thuộc từ ngoài vào trong (API → Application → Domain); Persistence implement interface do Domain/Application định nghĩa.
|
||||
|
||||
## 4. Modular Monolith
|
||||
|
||||
- Code tổ chức theo **business module** (vertical slice), không theo technical layer toàn cục.
|
||||
- Mỗi module đóng gói `interface + application + domain + persistence` cho một business capability.
|
||||
- Module giao tiếp qua public API/interface; **không** import nội bộ module khác.
|
||||
- Module registry/config ở application root.
|
||||
|
||||
### Module Boundary
|
||||
|
||||
```
|
||||
com.aplp.backend
|
||||
└── <module> (vd: identity, learner, content, learning, assessment, adaptive, ...)
|
||||
├── api (controller, dto)
|
||||
├── application (use case, service)
|
||||
├── domain (model, domain service, rules, repository interface)
|
||||
└── persistence (repository impl, entity mapping, jpa)
|
||||
```
|
||||
|
||||
## 5. DDD Orientation
|
||||
|
||||
- **Aggregate** là ranh giới bảo toàn bất biến (invariant) trong cùng transaction.
|
||||
- **Value Objects** dùng cho khái niệm không có identity riêng (Score, Money, MasteryLevel).
|
||||
- **Domain Event** (optional, temporal) dùng khi cần tách rời side-effect giữa modules — **không** lạm dụng cho tất cả luồng.
|
||||
- **Repository interface** ở domain, implementation ở persistence.
|
||||
|
||||
## 6. Database
|
||||
|
||||
- Relational database: **PostgreSQL** (chosen). Dev chạy qua `docker-compose` (port 5433); test dùng H2 (PostgreSQL mode).
|
||||
- Migrations: **Flyway** (chosen) tại `src/main/resources/db/migration`. `spring.jpa.hibernate.ddl-auto=validate`.
|
||||
- Schema phản ánh domain model, không thiết kế "database-first".
|
||||
|
||||
## 7. Cross-Cutting Concerns
|
||||
|
||||
- **Security / AuthN**: xử lý ở API/boundary layer (Phase 0).
|
||||
- **Validation**: input validation ở API; business invariant validation ở domain.
|
||||
- **Logging & Observability**: structured logging, common config (Phase 9 mở rộng metrics/tracing).
|
||||
- **Errors**: exception mapping, đồng nhất response format.
|
||||
|
||||
## 8. Deferred (tránh dùng khi chưa có justification)
|
||||
|
||||
- Microservices split
|
||||
- API Gateway
|
||||
- Kafka / Event-driven
|
||||
- Redis
|
||||
- Elasticsearch
|
||||
- CQRS / Event Sourcing
|
||||
|
||||
## 9. Deployment
|
||||
|
||||
- **Docker first** (containerize backend).
|
||||
- **Kubernetes later** khi có nhu cầu scale/ops.
|
||||
|
||||
## 10. Open Questions (backend-specific)
|
||||
|
||||
| ID | Question | Impact | Proposed Direction | Status |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| ARC-001 | Spring Boot version nào cho foundation? | Setup | Dùng phiên bản ổn định mới nhất hỗ trợ Java LTS | **Resolved**: Spring Boot 3.5.16 + Java 21 (Maven) |
|
||||
| ARC-002 | JWT hay session cho authentication? | Security | JWT stateless + refresh flow | **Resolved**: JWT (access + rotating refresh, refresh token hash lưu DB) |
|
||||
| ARC-003 | DB: PostgreSQL vs MySQL? | Setup | PostgreSQL | **Resolved**: PostgreSQL 17 (docker-compose) |
|
||||
| ARC-004 | Migration: Flyway vs Liquibase? | Setup | Flyway | **Resolved**: Flyway |
|
||||
| ARC-005 | Content đọc từ LMS qua API hay shared read model? | Module boundary | API/read model của LMS | Open (Phase 2) |
|
||||
| ARC-006 | Transaction boundary giữa module nào cần được phân tách? | Data consistency | Ghi rõ trong từng use case | Open |
|
||||
@@ -0,0 +1,91 @@
|
||||
# APLP Backend — Conventions
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Status** | Draft |
|
||||
|
||||
## 1. Naming & Package
|
||||
|
||||
- Base package: `com.aplp.backend`
|
||||
- Mỗi module: `com.aplp.backend.<module>.<layer>` với layer = `api | application | domain | persistence` (xem `ARCHITECTURE.md`).
|
||||
- Tên class theo responsibility:
|
||||
- Controller: `XxxController`
|
||||
- Use case: `XxxUseCase` hoặc `XxxService`
|
||||
- Request/Response DTO: `XxxRequest`, `XxxResponse`
|
||||
- Aggregate/Root: tên domain concept (vd `Learner`, `Course`)
|
||||
- Repository interface: `XxxRepository` (định nghĩa ở domain)
|
||||
|
||||
## 2. Layer Rules
|
||||
|
||||
| Layer | Được phép | Cấm |
|
||||
| --- | --- | --- |
|
||||
| `api` | AuthN/authorization (framework), input validation, DTO mapping | Business rules |
|
||||
| `application` | Orchestrate use case, transaction, call domain/persistence | Nhúng business rules riêng |
|
||||
| `domain` | Business logic, invariants, domain services, repository interface | Spring/JPA/HTTP dependencies |
|
||||
| `persistence` | Repository impl, JPA entities, mappers | Business logic |
|
||||
|
||||
- **Domain không import Spring/JPA/HTTP.**
|
||||
- Persistence entities tách biệt (hoặc mappers) khỏi domain model nếu cần.
|
||||
|
||||
## 3. Transaction
|
||||
|
||||
- Transaction mở ở **Application** layer (`@Transactional` trên use case/service).
|
||||
- Không ném transaction qua domain khi chỉ để đọc.
|
||||
- Repository phương thức read nên read-only transaction khi cần.
|
||||
|
||||
## 4. Validation
|
||||
|
||||
- **Input/API validation** ở `api` layer (bean validation trên DTO).
|
||||
- **Business invariant** trong `domain` (domain exception).
|
||||
- Response lỗi dùng format đồng nhất (vd `ApiError` với code + message).
|
||||
|
||||
## 5. Errors & Exceptions
|
||||
|
||||
- `DomainException` cho lỗi business; mapping sang HTTP status ở `api` layer.
|
||||
- Error response nhất quán: `code`, `message`, `details` (tuỳ thỏa thuận).
|
||||
- Kèm `traceId`/requestId để dễ debug (Phase 0).
|
||||
- Error code dùng **global enum `ErrorCode`** ở `common/api` (kèm HTTP status); mở rộng bằng cách thêm hằng số khi có module mới.
|
||||
|
||||
## 6. DTO Mapping
|
||||
|
||||
- Không để JPA entity lọt ra ngoài `persistence`/`api` response.
|
||||
- **Mapping thủ công** (static method) trong repository impl / DTO factory — quyết định ở Phase 0 (không dùng MapStruct cho giai đoạn này; thêm khi có justification).
|
||||
|
||||
## 7. Repository
|
||||
|
||||
- Interface repository của module ở `domain`; implementation ở `persistence`.
|
||||
- Chỉ expose các method cần thiết cho use case, không leek Query/spec toàn module.
|
||||
- Query đặc thù (search, aggregation) nằm trong repository implementation.
|
||||
|
||||
## 8. Domain Events (khi cần)
|
||||
|
||||
- Dùng để tách rời side-effect giữa module (vd assessment hoàn thành → cập nhật adaptive state).
|
||||
- Không lạm dụng: nếu đồng bộ đơn giản và cùng transaction, gọi trực tiếp qua interface.
|
||||
- Nếu dùng Spring events: publish ở application layer, không trong domain.
|
||||
|
||||
## 9. Config & Secrets
|
||||
|
||||
- Cấu hình theo environment (`application.yml`, profile dev/prod).
|
||||
- **Không commit secret/key vào repo.** Dùng env vars hoặc bí quyết quản lý (vault) khi có.
|
||||
- Không log secret/token/password.
|
||||
|
||||
## 10. Testing
|
||||
|
||||
- Unit test cho `domain` + `application`.
|
||||
- Test repository/persistence khi cần.
|
||||
- Integration test cho API layer.
|
||||
- Quyết định framework/test DB ở Phase 0.
|
||||
|
||||
## 11. Code Style
|
||||
|
||||
- Java theo tiêu chuẩn project (indent 4 spaces — xác nhận khi setup).
|
||||
- Code của backend **không comment thừa**; tên rõ nghĩa.
|
||||
- `@author`/metadata không bắt buộc.
|
||||
|
||||
## 12. Open Questions
|
||||
|
||||
| ID | Question | Status |
|
||||
| --- | --- | --- |
|
||||
| CON-001 | Dùng MapStruct hay mapping thủ công? | **Resolved**: thủ công (Phase 0) |
|
||||
| CON-002 | Error code convention (enum per module vs global)? | **Resolved**: global `ErrorCode` trong `common/api` |
|
||||
| CON-003 | JPA entities tách hay dùng chung domain model? | **Resolved**: tách riêng (`*JpaEntity` trong `persistence`, domain model trong `domain`) |
|
||||
@@ -0,0 +1,82 @@
|
||||
# APLP Backend — Modules
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Status** | Draft (Candidate) |
|
||||
|
||||
Danh sách business module của backend `aplp.backend.spring`, ánh xạ từ từng phase trong `APLP-Project-Phases.md`.
|
||||
|
||||
| Module | Phase | Type | Mô tả |
|
||||
| --- | --- | --- | --- |
|
||||
| `identity` | 0 ✅ | Generic | AuthN, user credential, session/token, identity provider hook. Nếu dùng IdP: không quản lý password khi không cần. |
|
||||
| `learner` | 1 | Supporting (cân nhắc Core) | Learner profile, learning preferences, learning goals, mapping với identity. |
|
||||
| `content` | 2 | Supporting | Content read model (course/module/lesson/activity từ LMS), catalog, enrollment/selection, publication status. |
|
||||
| `learning` | 3 | Core | Learning experience: start/resume/continue, lesson completion, navigation, activity records, progress. |
|
||||
| `assessment` | 4 | Supporting | Question, attempt, answer, evaluation, scoring, assessment result. |
|
||||
| `progress` | 4 | Supporting | Learning progress computation & history (tách khỏi assessment để không lẫn). |
|
||||
| `adaptive` | 5 | **Core** | Learner state, knowledge/skill state, mastery, prerequisite, adaptation decision, next activity. |
|
||||
| `recommendation` | 6 | Core (defer) | Recommendation generation, personalized path. `Proposed`: có thể là decision/result. |
|
||||
| `assistance` | 7 | Supporting | Hint, explanation, Q&A, feedback (AI integration) — phải qua domain validation. |
|
||||
| `subscription` | 8 | Supporting | Plan, entitlement, usage limit, notification, account. Deferred tới productization. |
|
||||
| `notification` | 8 | Generic | Notification delivery. |
|
||||
| `common` | 0 ✅ | Infrastructure | Shared code: error handling, security config, base patterns, DTO conventions. |
|
||||
|
||||
> Lưu ý: `common` chỉ chứa infrastructure/shared plumbing, **không** chứa business logic của module khác.
|
||||
|
||||
## Phân loại bounded context
|
||||
|
||||
| Type | Modules |
|
||||
| --- | --- |
|
||||
| Core Domain | `learning`, `adaptive`, `recommendation` (recommendation defer) |
|
||||
| Supporting Domain | `learner`, `content`, `assessment`, `progress`, `assistance`, `subscription` |
|
||||
| Generic Domain | `identity`, `notification`, `configuration`/`common` |
|
||||
|
||||
## Cấu trúc thư mục gợi ý
|
||||
|
||||
```text
|
||||
src/main/java/com/aplp/backend/
|
||||
├── common/ # infrastructure & shared
|
||||
├── identity/
|
||||
│ ├── api/
|
||||
│ ├── application/
|
||||
│ ├── domain/
|
||||
│ └── persistence/
|
||||
├── learner/
|
||||
├── content/
|
||||
├── learning/
|
||||
├── assessment/
|
||||
├── progress/
|
||||
├── adaptive/
|
||||
├── recommendation/
|
||||
├── assistance/
|
||||
└── subscription/
|
||||
```
|
||||
|
||||
## Quy tắc module
|
||||
|
||||
1. Module A **chỉ** giao tiếp với module B qua public interface/API của B.
|
||||
2. Không share DB table trực tiếp giữa module; dùng repository/read model.
|
||||
3. Cross-module side-effect dùng domain event/callback nếu cần rõ ràng, không hard-code import.
|
||||
4. Mỗi module phải đứng độc lập được về compile (dependency hướng trong ra ngoài).
|
||||
|
||||
## Khởi tạo theo phase
|
||||
|
||||
- **Phase 0 (done)**: `common`, `identity` (minimal), `learner` (basic profile).
|
||||
- **Phase 2**: `content`.
|
||||
- **Phase 3**: `learning`.
|
||||
- **Phase 4**: `assessment`, `progress`.
|
||||
- **Phase 5**: `adaptive`.
|
||||
- **Phase 6**: `recommendation`.
|
||||
- **Phase 7**: `assistance`.
|
||||
- **Phase 8**: `subscription`, `notification`.
|
||||
|
||||
> Ghi chú Phase 0: `learner` chỉ có basic profile (display name + mapping user identity). Preferences/goals thuộc Phase 1.
|
||||
|
||||
## Open Questions
|
||||
|
||||
| ID | Question | Impact | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| MOD-001 | `progress` tách riêng hay gộp vào `learning`? | Module boundary | Open |
|
||||
| MOD-002 | `assessment` module độc lập hay trong `learning`? | Cohesion | Open |
|
||||
| MOD-003 | Cách chia sẻ content model giữa `content` và `learning` (snapshot vs reference)? | Consistency | Open |
|
||||
| MOD-004 | `recommendation` có cần là module riêng hay chỉ service trong `adaptive`? | Boundary | Open |
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
# APLP Backend — Setup
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Status** | Implemented (Phase 0 — Foundation) |
|
||||
| **Stack** | Java 21 (LTS) · Maven · Spring Boot 3.5 · PostgreSQL · Flyway · H2 (test) |
|
||||
|
||||
## 1. Prerequisites
|
||||
|
||||
- JDK 21+ (build chạy được trên JDK 25; target release 21)
|
||||
- Maven (hoặc dùng `./mvnw`)
|
||||
- Docker (database local)
|
||||
|
||||
## 2. Cấu trúc dự án
|
||||
|
||||
```text
|
||||
aplp.backend.spring/
|
||||
├── GOAL.md
|
||||
├── APLP-Project-Phases.md
|
||||
├── README.md
|
||||
├── docs/
|
||||
├── pom.xml
|
||||
├── mvnw
|
||||
├── Dockerfile
|
||||
├── docker-compose.yml # PostgreSQL local (port 5432)
|
||||
└── src/
|
||||
├── main/java/com/aplp/backend/
|
||||
│ ├── AplpBackendApplication.java
|
||||
│ ├── common/ # infra: api (errors), security (JWT), web (requestId), config
|
||||
│ ├── identity/ # api / application / domain / persistence
|
||||
│ └── learner/ # api / application / domain / persistence
|
||||
├── main/resources/
|
||||
│ ├── application.yml # base config
|
||||
│ ├── application-dev.yml # Postgres local
|
||||
│ ├── application-prod.yml # Postgres via env vars
|
||||
│ └── db/migration/ # Flyway migrations
|
||||
└── test/...
|
||||
```
|
||||
|
||||
## 3. Chạy local (dev)
|
||||
|
||||
```bash
|
||||
# 1. Start database
|
||||
docker compose up -d db
|
||||
|
||||
# 2. Chạy app (dev profile, port 8080)
|
||||
./mvnw spring-boot:run
|
||||
|
||||
# 3. Kiểm tra
|
||||
curl http://localhost:8080/actuator/health
|
||||
# => {"status":"UP","groups":["liveness","readiness"]}
|
||||
```
|
||||
|
||||
Flyway tự migrate schema khi app khởi động (`ddl-auto: validate` để kiểm tra entity khớp schema).
|
||||
|
||||
## 4. Verification
|
||||
|
||||
```bash
|
||||
./mvnw test # integration test với H2 (PostgreSQL mode)
|
||||
./mvnw package # build jar
|
||||
```
|
||||
|
||||
## 5. Endpoints (Phase 0)
|
||||
|
||||
| Method | Path | Auth | Mô tả |
|
||||
| --- | --- | --- | --- |
|
||||
| POST | `/api/v1/auth/register` | Public | Đăng ký + cấp token |
|
||||
| POST | `/api/v1/auth/login` | Public | Đăng nhập |
|
||||
| POST | `/api/v1/auth/refresh` | Public | Refresh access token (rotate refresh token) |
|
||||
| POST | `/api/v1/auth/logout` | Bearer | Thu hồi refresh token |
|
||||
| GET | `/api/v1/learners/me` | Bearer | Xem learner profile (UC-0.2) |
|
||||
| PATCH | `/api/v1/learners/me` | Bearer | Cập nhật display name |
|
||||
| GET | `/actuator/health` | Public | Health/liveness/readiness |
|
||||
|
||||
## 6. Environment Variables
|
||||
|
||||
| Var | Mô tả | Default (dev) |
|
||||
| --- | --- |--------------------------------------------|
|
||||
| `DB_URL` | JDBC url | `jdbc:postgresql://localhost:5432/aplp` |
|
||||
| `DB_USERNAME` | db user | `postgres` |
|
||||
| `DB_PASSWORD` | db password | `Pa55w0rd` |
|
||||
| `DB_PORT` | host port map | `5432` |
|
||||
| `JWT_SECRET` | Base64 secret (HS256, ≥ 32 bytes) | dev-only default — **phải set khi deploy** |
|
||||
| `JWT_ACCESS_TTL` | Access token TTL | `15m` |
|
||||
| `JWT_REFRESH_TTL` | Refresh token TTL | `30d` |
|
||||
| `CORS_ALLOWED_ORIGINS` | Allowed origins | `http://localhost:5173` |
|
||||
| `SERVER_PORT` | App port | `8080` |
|
||||
|
||||
> Dev default secret chỉ dùng cho local. **Không commit secret thật**; set `JWT_SECRET` trong môi trường không phải dev.
|
||||
|
||||
## 7. Test Database
|
||||
|
||||
Integration test dùng H2 in-memory (PostgreSQL mode) tại `src/test/resources/application-test.yml`. Migration viết portable (chạy được trên cả Postgres và H2).
|
||||
|
||||
## 8. Docker
|
||||
|
||||
```bash
|
||||
docker build -t aplp-backend .
|
||||
docker run -p 8080:8080 -e JWT_SECRET=... -e DB_URL=... aplp-backend
|
||||
```
|
||||
@@ -11,16 +11,17 @@
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.aplp</groupId>
|
||||
<groupId>aplp.backend</groupId>
|
||||
<artifactId>web</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>aplp-backend</name>
|
||||
<description>APLP — Adaptive Personal Learning Platform (backend)</description>
|
||||
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<java.version>17</java.version>
|
||||
<jjwt.version>0.12.6</jjwt.version>
|
||||
<springdoc.version>2.8.6</springdoc.version>
|
||||
<mapstruct.version>1.6.3</mapstruct.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -50,6 +51,12 @@
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>aplp.backend</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
@@ -58,6 +65,10 @@
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-flyway</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
@@ -98,6 +109,11 @@
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-webmvc-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
@@ -108,6 +124,17 @@
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend;
|
||||
package aplp.backend.web;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -6,9 +6,9 @@ import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class AplpBackendApplication {
|
||||
public class AplpBackendWebApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AplpBackendApplication.class, args);
|
||||
SpringApplication.run(AplpBackendWebApplication.class, args);
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -1,6 +1,8 @@
|
||||
package com.aplp.backend.common.api;
|
||||
package aplp.backend.web.common.api;
|
||||
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
import aplp.backend.core.common.response.ApiError;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -26,7 +28,7 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(DomainException.class)
|
||||
public ResponseEntity<ApiError> handleDomainException(DomainException ex) {
|
||||
HttpStatus status = ex.code().httpStatus();
|
||||
HttpStatus status = HttpStatus.valueOf(ex.code().status());
|
||||
return build(status, ex.code().name(), ex.getMessage());
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.config;
|
||||
package aplp.backend.web.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.config;
|
||||
package aplp.backend.web.common.config;
|
||||
|
||||
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
|
||||
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
public record AuthenticatedUser(Long userId, String email, String displayName) {
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import com.aplp.backend.common.api.ApiError;
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
import aplp.backend.core.common.response.ApiError;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpStatus;
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package com.aplp.backend.common.security;
|
||||
package aplp.backend.web.common.security;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.common.web;
|
||||
package aplp.backend.web.common.web;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
+9
-5
@@ -1,6 +1,10 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
package aplp.backend.web.identity.api.controller;
|
||||
|
||||
import com.aplp.backend.identity.application.AuthService;
|
||||
import aplp.backend.web.identity.application.dtos.AuthResponse;
|
||||
import aplp.backend.web.identity.application.dtos.LoginRequest;
|
||||
import aplp.backend.web.identity.application.dtos.RefreshTokenRequest;
|
||||
import aplp.backend.web.identity.application.dtos.RegisterRequest;
|
||||
import aplp.backend.web.identity.application.services.AuthService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
@@ -22,17 +26,17 @@ public class AuthController {
|
||||
@PostMapping("/register")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public AuthResponse register(@Valid @RequestBody RegisterRequest request) {
|
||||
return AuthResponse.from(authService.register(request.email(), request.password(), request.displayName()));
|
||||
return authService.register(request.username(), request.email(), request.password(), request.displayName());
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AuthResponse login(@Valid @RequestBody LoginRequest request) {
|
||||
return AuthResponse.from(authService.login(request.email(), request.password()));
|
||||
return authService.login(request.username(), request.password());
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
public AuthResponse refresh(@Valid @RequestBody RefreshTokenRequest request) {
|
||||
return AuthResponse.from(authService.refresh(request.refreshToken()));
|
||||
return authService.refresh(request.refreshToken());
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@@ -0,0 +1,13 @@
|
||||
package aplp.backend.web.identity.application.dtos;
|
||||
|
||||
public record AuthResponse(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
String tokenType,
|
||||
long expiresIn,
|
||||
UserDto user
|
||||
) {
|
||||
|
||||
public record UserDto(Long id, String email, String displayName) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package aplp.backend.web.identity.application.dtos;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank @Size(min = 3, max = 50) String username,
|
||||
@NotBlank String password
|
||||
) {
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
package aplp.backend.web.identity.application.dtos;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
+2
-1
@@ -1,10 +1,11 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
package aplp.backend.web.identity.application.dtos;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record RegisterRequest(
|
||||
@NotBlank @Size(min = 3, max = 50) String username,
|
||||
@NotBlank @Email(message = "must be a valid email") @Size(max = 320) String email,
|
||||
@NotBlank @Size(min = 8, max = 128, message = "must be between 8 and 128 characters") String password,
|
||||
@NotBlank @Size(max = 100) String displayName
|
||||
@@ -0,0 +1,11 @@
|
||||
package aplp.backend.web.identity.application.mappers;
|
||||
|
||||
import aplp.backend.web.identity.application.dtos.AuthResponse;
|
||||
import aplp.backend.web.identity.domain.entities.User;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface AuthMapper {
|
||||
|
||||
AuthResponse.UserDto toUserDto(User user);
|
||||
}
|
||||
+35
-20
@@ -1,16 +1,21 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
package aplp.backend.web.identity.application.services;
|
||||
|
||||
import com.aplp.backend.common.security.AuthenticatedUser;
|
||||
import com.aplp.backend.common.security.JwtClaims;
|
||||
import com.aplp.backend.common.security.JwtProperties;
|
||||
import com.aplp.backend.common.security.JwtTokenProvider;
|
||||
import com.aplp.backend.identity.domain.EmailAlreadyExistsException;
|
||||
import com.aplp.backend.identity.domain.InvalidCredentialsException;
|
||||
import com.aplp.backend.identity.domain.RefreshToken;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenInvalidException;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenRepository;
|
||||
import com.aplp.backend.identity.domain.User;
|
||||
import com.aplp.backend.identity.domain.UserRepository;
|
||||
import aplp.backend.core.common.util.TokenHasher;
|
||||
import aplp.backend.web.common.security.AuthenticatedUser;
|
||||
import aplp.backend.web.common.security.JwtClaims;
|
||||
import aplp.backend.web.common.security.JwtProperties;
|
||||
import aplp.backend.web.common.security.JwtTokenProvider;
|
||||
import aplp.backend.web.identity.application.dtos.AuthResponse;
|
||||
import aplp.backend.web.identity.application.mappers.AuthMapper;
|
||||
import aplp.backend.web.identity.domain.exceptions.EmailAlreadyExistsException;
|
||||
import aplp.backend.web.identity.domain.exceptions.InvalidCredentialsException;
|
||||
import aplp.backend.web.identity.domain.exceptions.UsernameAlreadyExistsException;
|
||||
import aplp.backend.web.identity.domain.entities.RefreshToken;
|
||||
import aplp.backend.web.identity.domain.exceptions.RefreshTokenInvalidException;
|
||||
import aplp.backend.web.identity.domain.repositories.RefreshTokenRepository;
|
||||
import aplp.backend.web.identity.domain.entities.User;
|
||||
import aplp.backend.web.identity.domain.repositories.UserRepository;
|
||||
import aplp.backend.web.learner.application.services.LearnerProvisioner;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -27,6 +32,7 @@ public class AuthService {
|
||||
private final JwtTokenProvider tokenProvider;
|
||||
private final JwtProperties jwtProperties;
|
||||
private final LearnerProvisioner learnerProvisioner;
|
||||
private final AuthMapper authMapper;
|
||||
private final Clock clock;
|
||||
|
||||
public AuthService(UserRepository userRepository,
|
||||
@@ -35,6 +41,7 @@ public class AuthService {
|
||||
JwtTokenProvider tokenProvider,
|
||||
JwtProperties jwtProperties,
|
||||
LearnerProvisioner learnerProvisioner,
|
||||
AuthMapper authMapper,
|
||||
Clock clock) {
|
||||
this.userRepository = userRepository;
|
||||
this.refreshTokenRepository = refreshTokenRepository;
|
||||
@@ -42,26 +49,29 @@ public class AuthService {
|
||||
this.tokenProvider = tokenProvider;
|
||||
this.jwtProperties = jwtProperties;
|
||||
this.learnerProvisioner = learnerProvisioner;
|
||||
this.authMapper = authMapper;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult register(String email, String rawPassword, String displayName) {
|
||||
public AuthResponse register(String username, String email, String rawPassword, String displayName) {
|
||||
Instant now = clock.instant();
|
||||
String normalizedEmail = email.trim().toLowerCase();
|
||||
if (userRepository.existsByEmail(normalizedEmail)) {
|
||||
throw new EmailAlreadyExistsException(normalizedEmail);
|
||||
}
|
||||
User user = User.register(normalizedEmail, passwordEncoder.encode(rawPassword), displayName, now);
|
||||
if (userRepository.existsByUsername(username)) {
|
||||
throw new UsernameAlreadyExistsException(username);
|
||||
}
|
||||
User user = User.register(username, normalizedEmail, passwordEncoder.encode(rawPassword), displayName, now);
|
||||
User saved = userRepository.save(user);
|
||||
learnerProvisioner.provision(saved.id(), displayName);
|
||||
return issueTokens(saved);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult login(String email, String rawPassword) {
|
||||
String normalizedEmail = email.trim().toLowerCase();
|
||||
User user = userRepository.findByEmail(normalizedEmail).orElseThrow(InvalidCredentialsException::new);
|
||||
public AuthResponse login(String username, String rawPassword) {
|
||||
User user = userRepository.findByUsername(username).orElseThrow(InvalidCredentialsException::new);
|
||||
if (!passwordEncoder.matches(rawPassword, user.passwordHash())) {
|
||||
throw new InvalidCredentialsException();
|
||||
}
|
||||
@@ -69,7 +79,7 @@ public class AuthService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthResult refresh(String rawRefreshToken) {
|
||||
public AuthResponse refresh(String rawRefreshToken) {
|
||||
Instant now = clock.instant();
|
||||
RefreshToken stored = refreshTokenRepository.findByTokenHash(TokenHasher.sha256Hex(rawRefreshToken))
|
||||
.orElseThrow(RefreshTokenInvalidException::new);
|
||||
@@ -112,7 +122,7 @@ public class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
private AuthResult issueTokens(User user) {
|
||||
private AuthResponse issueTokens(User user) {
|
||||
Instant now = clock.instant();
|
||||
AuthenticatedUser principal = new AuthenticatedUser(user.id(), user.email(), user.displayName());
|
||||
String accessToken = tokenProvider.createAccessToken(principal);
|
||||
@@ -123,6 +133,11 @@ public class AuthService {
|
||||
now.plus(jwtProperties.refreshTokenTtl()),
|
||||
now);
|
||||
refreshTokenRepository.save(refresh);
|
||||
return new AuthResult(accessToken, rawRefreshToken, jwtProperties.accessTokenTtl().toSeconds(), principal);
|
||||
return new AuthResponse(
|
||||
accessToken,
|
||||
rawRefreshToken,
|
||||
"Bearer",
|
||||
jwtProperties.accessTokenTtl().toSeconds(),
|
||||
authMapper.toUserDto(user));
|
||||
}
|
||||
}
|
||||
+31
-5
@@ -1,15 +1,41 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Entity
|
||||
@Table(name = "refresh_token")
|
||||
public class RefreshToken {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private final Long userId;
|
||||
private final String tokenHash;
|
||||
private final Instant expiresAt;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, unique = true, length = 64)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
private final Instant createdAt;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
protected RefreshToken() {
|
||||
}
|
||||
|
||||
private RefreshToken(Long id, Long userId, String tokenHash, Instant expiresAt, Instant revokedAt, Instant createdAt) {
|
||||
this.id = id;
|
||||
@@ -0,0 +1,115 @@
|
||||
package aplp.backend.web.identity.domain.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String username;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 320)
|
||||
private String email;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private UserStatus status;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected User() {
|
||||
}
|
||||
|
||||
private User(Long id, String username, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public static User register(String username, String email, String passwordHash, String displayName, Instant now) {
|
||||
return new User(null, username, normalizeEmail(email), passwordHash, displayName, UserStatus.ACTIVE, now, now);
|
||||
}
|
||||
|
||||
public static User reconstruct(Long id, String username, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
return new User(id, username, email, passwordHash, displayName, status, createdAt, updatedAt);
|
||||
}
|
||||
|
||||
public void updatePasswordHash(String newHash, Instant now) {
|
||||
this.passwordHash = newHash;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
public void updateDisplayName(String newDisplayName, Instant now) {
|
||||
this.displayName = newDisplayName;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
private static String normalizeEmail(String email) {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String username() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public String email() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String passwordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public UserStatus status() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Instant updatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.entities;
|
||||
|
||||
public enum UserStatus {
|
||||
ACTIVE,
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.exceptions;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
|
||||
public class EmailAlreadyExistsException extends DomainException {
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.exceptions;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
|
||||
public class InvalidCredentialsException extends DomainException {
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.exceptions;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
|
||||
public class RefreshTokenInvalidException extends DomainException {
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package aplp.backend.web.identity.domain.exceptions;
|
||||
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
|
||||
public class UsernameAlreadyExistsException extends DomainException {
|
||||
|
||||
public UsernameAlreadyExistsException(String username) {
|
||||
super(ErrorCode.USERNAME_ALREADY_EXISTS, "Username is already taken: " + username);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.repositories;
|
||||
|
||||
import aplp.backend.web.identity.domain.entities.RefreshToken;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
+7
-1
@@ -1,4 +1,6 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
package aplp.backend.web.identity.domain.repositories;
|
||||
|
||||
import aplp.backend.web.identity.domain.entities.User;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -6,9 +8,13 @@ public interface UserRepository {
|
||||
|
||||
Optional<User> findByEmail(String email);
|
||||
|
||||
Optional<User> findByUsername(String username);
|
||||
|
||||
Optional<User> findById(Long id);
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
boolean existsByUsername(String username);
|
||||
|
||||
User save(User user);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package aplp.backend.web.identity.infrastructure.persistence;
|
||||
|
||||
import aplp.backend.web.identity.domain.entities.RefreshToken;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RefreshTokenJpaRepository extends JpaRepository<RefreshToken, Long> {
|
||||
|
||||
Optional<RefreshToken> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RefreshToken> findAllByUserId(Long userId);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package aplp.backend.web.identity.infrastructure.persistence;
|
||||
|
||||
import aplp.backend.web.identity.domain.entities.RefreshToken;
|
||||
import aplp.backend.web.identity.domain.repositories.RefreshTokenRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class RefreshTokenRepositoryImpl implements RefreshTokenRepository {
|
||||
|
||||
private final RefreshTokenJpaRepository jpaRepository;
|
||||
|
||||
public RefreshTokenRepositoryImpl(RefreshTokenJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RefreshToken> findByTokenHash(String tokenHash) {
|
||||
return jpaRepository.findByTokenHash(tokenHash);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RefreshToken> findAllByUserId(Long userId) {
|
||||
return jpaRepository.findAllByUserId(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RefreshToken save(RefreshToken token) {
|
||||
return jpaRepository.save(token);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package aplp.backend.web.identity.infrastructure.persistence;
|
||||
|
||||
import aplp.backend.web.identity.domain.entities.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserJpaRepository extends JpaRepository<User, Long> {
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
boolean existsByUsername(String username);
|
||||
|
||||
java.util.Optional<User> findByEmail(String email);
|
||||
|
||||
java.util.Optional<User> findByUsername(String username);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package aplp.backend.web.identity.infrastructure.persistence;
|
||||
|
||||
import aplp.backend.web.identity.domain.entities.User;
|
||||
import aplp.backend.web.identity.domain.repositories.UserRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class UserRepositoryImpl implements UserRepository {
|
||||
|
||||
private final UserJpaRepository jpaRepository;
|
||||
|
||||
public UserRepositoryImpl(UserJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByEmail(String email) {
|
||||
return jpaRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByUsername(String username) {
|
||||
return jpaRepository.findByUsername(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(Long id) {
|
||||
return jpaRepository.findById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByEmail(String email) {
|
||||
return jpaRepository.existsByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByUsername(String username) {
|
||||
return jpaRepository.existsByUsername(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User save(User user) {
|
||||
return jpaRepository.save(user);
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -1,7 +1,10 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
package aplp.backend.web.learner.api.controller;
|
||||
|
||||
import com.aplp.backend.common.security.SecurityUtils;
|
||||
import com.aplp.backend.learner.application.LearnerService;
|
||||
import aplp.backend.web.common.security.SecurityUtils;
|
||||
import aplp.backend.web.learner.application.dtos.LearnerProfileResponse;
|
||||
import aplp.backend.web.learner.application.dtos.UpdateLearnerProfileRequest;
|
||||
import aplp.backend.web.learner.application.mappers.LearnerMapper;
|
||||
import aplp.backend.web.learner.application.services.LearnerService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
@@ -14,19 +17,21 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class LearnerController {
|
||||
|
||||
private final LearnerService learnerService;
|
||||
private final LearnerMapper learnerMapper;
|
||||
|
||||
public LearnerController(LearnerService learnerService) {
|
||||
public LearnerController(LearnerService learnerService, LearnerMapper learnerMapper) {
|
||||
this.learnerService = learnerService;
|
||||
this.learnerMapper = learnerMapper;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public LearnerProfileResponse getMyProfile() {
|
||||
return LearnerProfileResponse.from(learnerService.getProfile(SecurityUtils.currentUserId()));
|
||||
return learnerMapper.toResponse(learnerService.getProfile(SecurityUtils.currentUserId()));
|
||||
}
|
||||
|
||||
@PatchMapping
|
||||
public LearnerProfileResponse updateMyProfile(@Valid @RequestBody UpdateLearnerProfileRequest request) {
|
||||
return LearnerProfileResponse.from(
|
||||
return learnerMapper.toResponse(
|
||||
learnerService.updateDisplayName(SecurityUtils.currentUserId(), request.displayName()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package aplp.backend.web.learner.application.dtos;
|
||||
|
||||
public record LearnerProfileResponse(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
package aplp.backend.web.learner.application.dtos;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
@@ -0,0 +1,11 @@
|
||||
package aplp.backend.web.learner.application.mappers;
|
||||
|
||||
import aplp.backend.web.learner.application.dtos.LearnerProfileResponse;
|
||||
import aplp.backend.web.learner.domain.entities.Learner;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface LearnerMapper {
|
||||
|
||||
LearnerProfileResponse toResponse(Learner learner);
|
||||
}
|
||||
+5
-7
@@ -1,25 +1,23 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
package aplp.backend.web.learner.application.services;
|
||||
|
||||
import com.aplp.backend.identity.application.LearnerProvisioner;
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import aplp.backend.web.learner.domain.entities.Learner;
|
||||
import aplp.backend.web.learner.domain.repositories.LearnerRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
@Service
|
||||
public class LearnerProvisionerImpl implements LearnerProvisioner {
|
||||
public class LearnerProvisioner {
|
||||
|
||||
private final LearnerRepository learnerRepository;
|
||||
private final Clock clock;
|
||||
|
||||
public LearnerProvisionerImpl(LearnerRepository learnerRepository, Clock clock) {
|
||||
public LearnerProvisioner(LearnerRepository learnerRepository, Clock clock) {
|
||||
this.learnerRepository = learnerRepository;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void provision(Long userId, String displayName) {
|
||||
learnerRepository.save(Learner.create(userId, displayName, clock.instant()));
|
||||
+7
-12
@@ -1,8 +1,8 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
package aplp.backend.web.learner.application.services;
|
||||
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerNotFoundException;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import aplp.backend.web.learner.domain.entities.Learner;
|
||||
import aplp.backend.web.learner.domain.exceptions.LearnerNotFoundException;
|
||||
import aplp.backend.web.learner.domain.repositories.LearnerRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -20,20 +20,15 @@ public class LearnerService {
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public LearnerProfile getProfile(Long userId) {
|
||||
public Learner getProfile(Long userId) {
|
||||
return learnerRepository.findByUserId(userId)
|
||||
.map(LearnerService::toProfile)
|
||||
.orElseThrow(LearnerNotFoundException::new);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LearnerProfile updateDisplayName(Long userId, String displayName) {
|
||||
public Learner updateDisplayName(Long userId, String displayName) {
|
||||
Learner learner = learnerRepository.findByUserId(userId).orElseThrow(LearnerNotFoundException::new);
|
||||
learner.updateDisplayName(displayName, clock.instant());
|
||||
return toProfile(learnerRepository.save(learner));
|
||||
}
|
||||
|
||||
private static LearnerProfile toProfile(Learner learner) {
|
||||
return new LearnerProfile(learner.id(), learner.userId(), learner.displayName());
|
||||
return learnerRepository.save(learner);
|
||||
}
|
||||
}
|
||||
+27
-3
@@ -1,15 +1,39 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
package aplp.backend.web.learner.domain.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Getter
|
||||
@Entity
|
||||
@Table(name = "learner")
|
||||
public class Learner {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private final Long userId;
|
||||
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
private final Instant createdAt;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected Learner() {
|
||||
}
|
||||
|
||||
private Learner(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
package aplp.backend.web.learner.domain.exceptions;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
import com.aplp.backend.common.error.DomainException;
|
||||
import aplp.backend.core.common.exception.DomainException;
|
||||
import aplp.backend.core.common.exception.ErrorCode;
|
||||
|
||||
public class LearnerNotFoundException extends DomainException {
|
||||
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
package com.aplp.backend.learner.domain;
|
||||
package aplp.backend.web.learner.domain.repositories;
|
||||
|
||||
import aplp.backend.web.learner.domain.entities.Learner;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package aplp.backend.web.learner.infrastructure.persistence;
|
||||
|
||||
import aplp.backend.web.learner.domain.entities.Learner;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LearnerJpaRepository extends JpaRepository<Learner, Long> {
|
||||
|
||||
Optional<Learner> findByUserId(Long userId);
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package aplp.backend.web.learner.infrastructure.persistence;
|
||||
|
||||
import aplp.backend.web.learner.domain.entities.Learner;
|
||||
import aplp.backend.web.learner.domain.repositories.LearnerRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class LearnerRepositoryImpl implements LearnerRepository {
|
||||
|
||||
private final LearnerJpaRepository jpaRepository;
|
||||
|
||||
public LearnerRepositoryImpl(LearnerJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Learner> findByUserId(Long userId) {
|
||||
return jpaRepository.findByUserId(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Learner save(Learner learner) {
|
||||
return jpaRepository.save(learner);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record ApiError(
|
||||
Instant timestamp,
|
||||
int status,
|
||||
String error,
|
||||
String code,
|
||||
String message,
|
||||
String traceId
|
||||
) {
|
||||
|
||||
public static ApiError of(int status, String error, String code, String message, String traceId) {
|
||||
return new ApiError(Instant.now(), status, error, code, message, traceId);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.aplp.backend.common.api;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public enum ErrorCode {
|
||||
|
||||
INVALID_ARGUMENT(HttpStatus.BAD_REQUEST),
|
||||
VALIDATION_FAILED(HttpStatus.BAD_REQUEST),
|
||||
MALFORMED_REQUEST(HttpStatus.BAD_REQUEST),
|
||||
UNAUTHENTICATED(HttpStatus.UNAUTHORIZED),
|
||||
INVALID_CREDENTIALS(HttpStatus.UNAUTHORIZED),
|
||||
INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED),
|
||||
ACCESS_DENIED(HttpStatus.FORBIDDEN),
|
||||
EMAIL_ALREADY_EXISTS(HttpStatus.CONFLICT),
|
||||
USER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
LEARNER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
INTERNAL_ERROR(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
private final HttpStatus httpStatus;
|
||||
|
||||
ErrorCode(HttpStatus httpStatus) {
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
public HttpStatus httpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.aplp.backend.common.error;
|
||||
|
||||
import com.aplp.backend.common.api.ErrorCode;
|
||||
|
||||
public class DomainException extends RuntimeException {
|
||||
|
||||
private final ErrorCode code;
|
||||
|
||||
public DomainException(ErrorCode code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ErrorCode code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import com.aplp.backend.identity.application.AuthResult;
|
||||
|
||||
public record AuthResponse(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
String tokenType,
|
||||
long expiresIn,
|
||||
UserDto user
|
||||
) {
|
||||
|
||||
public static AuthResponse from(AuthResult result) {
|
||||
return new AuthResponse(
|
||||
result.accessToken(),
|
||||
result.refreshToken(),
|
||||
"Bearer",
|
||||
result.expiresInSeconds(),
|
||||
new UserDto(
|
||||
result.user().userId(),
|
||||
result.user().email(),
|
||||
result.user().displayName()));
|
||||
}
|
||||
|
||||
public record UserDto(Long id, String email, String displayName) {
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.aplp.backend.identity.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank @Email(message = "must be a valid email") String email,
|
||||
@NotBlank String password
|
||||
) {
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import com.aplp.backend.common.security.AuthenticatedUser;
|
||||
|
||||
public record AuthResult(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
long expiresInSeconds,
|
||||
AuthenticatedUser user
|
||||
) {
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
public interface LearnerProvisioner {
|
||||
|
||||
void provision(Long userId, String displayName);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.aplp.backend.identity.application;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
final class TokenHasher {
|
||||
|
||||
private TokenHasher() {
|
||||
}
|
||||
|
||||
static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 not available", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package com.aplp.backend.identity.domain;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class User {
|
||||
|
||||
private Long id;
|
||||
private final String email;
|
||||
private String passwordHash;
|
||||
private String displayName;
|
||||
private UserStatus status;
|
||||
private final Instant createdAt;
|
||||
private Instant updatedAt;
|
||||
|
||||
private User(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public static User register(String email, String passwordHash, String displayName, Instant now) {
|
||||
return new User(null, normalizeEmail(email), passwordHash, displayName, UserStatus.ACTIVE, now, now);
|
||||
}
|
||||
|
||||
public static User reconstruct(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
return new User(id, email, passwordHash, displayName, status, createdAt, updatedAt);
|
||||
}
|
||||
|
||||
public void updatePasswordHash(String newHash, Instant now) {
|
||||
this.passwordHash = newHash;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
public void updateDisplayName(String newDisplayName, Instant now) {
|
||||
this.displayName = newDisplayName;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
private static String normalizeEmail(String email) {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
public Long id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String email() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String passwordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public String displayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public UserStatus status() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Instant createdAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public Instant updatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "refresh_token")
|
||||
public class RefreshTokenJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, unique = true, length = 64)
|
||||
private String tokenHash;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
protected RefreshTokenJpaEntity() {
|
||||
}
|
||||
|
||||
public RefreshTokenJpaEntity(Long id, Long userId, String tokenHash, Instant expiresAt,
|
||||
Instant revokedAt, Instant createdAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.tokenHash = tokenHash;
|
||||
this.expiresAt = expiresAt;
|
||||
this.revokedAt = revokedAt;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getTokenHash() {
|
||||
return tokenHash;
|
||||
}
|
||||
|
||||
public void setTokenHash(String tokenHash) {
|
||||
this.tokenHash = tokenHash;
|
||||
}
|
||||
|
||||
public Instant getExpiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public void setExpiresAt(Instant expiresAt) {
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public Instant getRevokedAt() {
|
||||
return revokedAt;
|
||||
}
|
||||
|
||||
public void setRevokedAt(Instant revokedAt) {
|
||||
this.revokedAt = revokedAt;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface RefreshTokenJpaRepository extends JpaRepository<RefreshTokenJpaEntity, Long> {
|
||||
|
||||
Optional<RefreshTokenJpaEntity> findByTokenHash(String tokenHash);
|
||||
|
||||
List<RefreshTokenJpaEntity> findAllByUserId(Long userId);
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.RefreshToken;
|
||||
import com.aplp.backend.identity.domain.RefreshTokenRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class RefreshTokenRepositoryImpl implements RefreshTokenRepository {
|
||||
|
||||
private final RefreshTokenJpaRepository jpaRepository;
|
||||
|
||||
public RefreshTokenRepositoryImpl(RefreshTokenJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RefreshToken> findByTokenHash(String tokenHash) {
|
||||
return jpaRepository.findByTokenHash(tokenHash).map(RefreshTokenRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RefreshToken> findAllByUserId(Long userId) {
|
||||
return jpaRepository.findAllByUserId(userId).stream()
|
||||
.map(RefreshTokenRepositoryImpl::toDomain)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public RefreshToken save(RefreshToken token) {
|
||||
RefreshTokenJpaEntity entity = toEntity(token);
|
||||
RefreshTokenJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
private static RefreshTokenJpaEntity toEntity(RefreshToken token) {
|
||||
return new RefreshTokenJpaEntity(
|
||||
token.id(),
|
||||
token.userId(),
|
||||
token.tokenHash(),
|
||||
token.expiresAt(),
|
||||
token.revokedAt(),
|
||||
token.createdAt());
|
||||
}
|
||||
|
||||
private static RefreshToken toDomain(RefreshTokenJpaEntity entity) {
|
||||
return RefreshToken.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getUserId(),
|
||||
entity.getTokenHash(),
|
||||
entity.getExpiresAt(),
|
||||
entity.getRevokedAt(),
|
||||
entity.getCreatedAt());
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.UserStatus;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 320)
|
||||
private String email;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private UserStatus status;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected UserJpaEntity() {
|
||||
}
|
||||
|
||||
public UserJpaEntity(Long id, String email, String passwordHash, String displayName,
|
||||
UserStatus status, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.email = email;
|
||||
this.passwordHash = passwordHash;
|
||||
this.displayName = displayName;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPasswordHash() {
|
||||
return passwordHash;
|
||||
}
|
||||
|
||||
public void setPasswordHash(String passwordHash) {
|
||||
this.passwordHash = passwordHash;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public UserStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(UserStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserJpaRepository extends JpaRepository<UserJpaEntity, Long> {
|
||||
|
||||
boolean existsByEmail(String email);
|
||||
|
||||
java.util.Optional<UserJpaEntity> findByEmail(String email);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.aplp.backend.identity.persistence;
|
||||
|
||||
import com.aplp.backend.identity.domain.User;
|
||||
import com.aplp.backend.identity.domain.UserRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class UserRepositoryImpl implements UserRepository {
|
||||
|
||||
private final UserJpaRepository jpaRepository;
|
||||
|
||||
public UserRepositoryImpl(UserJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByEmail(String email) {
|
||||
return jpaRepository.findByEmail(email).map(UserRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findById(Long id) {
|
||||
return jpaRepository.findById(id).map(UserRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean existsByEmail(String email) {
|
||||
return jpaRepository.existsByEmail(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User save(User user) {
|
||||
UserJpaEntity entity = toEntity(user);
|
||||
UserJpaEntity saved = jpaRepository.save(entity);
|
||||
return toDomain(saved);
|
||||
}
|
||||
|
||||
private static UserJpaEntity toEntity(User user) {
|
||||
return new UserJpaEntity(
|
||||
user.id(),
|
||||
user.email(),
|
||||
user.passwordHash(),
|
||||
user.displayName(),
|
||||
user.status(),
|
||||
user.createdAt(),
|
||||
user.updatedAt());
|
||||
}
|
||||
|
||||
private static User toDomain(UserJpaEntity entity) {
|
||||
return User.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getEmail(),
|
||||
entity.getPasswordHash(),
|
||||
entity.getDisplayName(),
|
||||
entity.getStatus(),
|
||||
entity.getCreatedAt(),
|
||||
entity.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.aplp.backend.learner.api;
|
||||
|
||||
import com.aplp.backend.learner.application.LearnerProfile;
|
||||
|
||||
public record LearnerProfileResponse(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
|
||||
public static LearnerProfileResponse from(LearnerProfile profile) {
|
||||
return new LearnerProfileResponse(profile.id(), profile.userId(), profile.displayName());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.aplp.backend.learner.application;
|
||||
|
||||
public record LearnerProfile(
|
||||
Long id,
|
||||
Long userId,
|
||||
String displayName
|
||||
) {
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Table(name = "learner")
|
||||
public class LearnerJpaEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
protected LearnerJpaEntity() {
|
||||
}
|
||||
|
||||
public LearnerJpaEntity(Long id, Long userId, String displayName, Instant createdAt, Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.displayName = displayName;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface LearnerJpaRepository extends JpaRepository<LearnerJpaEntity, Long> {
|
||||
|
||||
Optional<LearnerJpaEntity> findByUserId(Long userId);
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.aplp.backend.learner.persistence;
|
||||
|
||||
import com.aplp.backend.learner.domain.Learner;
|
||||
import com.aplp.backend.learner.domain.LearnerRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class LearnerRepositoryImpl implements LearnerRepository {
|
||||
|
||||
private final LearnerJpaRepository jpaRepository;
|
||||
|
||||
public LearnerRepositoryImpl(LearnerJpaRepository jpaRepository) {
|
||||
this.jpaRepository = jpaRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Learner> findByUserId(Long userId) {
|
||||
return jpaRepository.findByUserId(userId).map(LearnerRepositoryImpl::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Learner save(Learner learner) {
|
||||
LearnerJpaEntity entity = toEntity(learner);
|
||||
return toDomain(jpaRepository.save(entity));
|
||||
}
|
||||
|
||||
private static LearnerJpaEntity toEntity(Learner learner) {
|
||||
return new LearnerJpaEntity(
|
||||
learner.id(),
|
||||
learner.userId(),
|
||||
learner.displayName(),
|
||||
learner.createdAt(),
|
||||
learner.updatedAt());
|
||||
}
|
||||
|
||||
private static Learner toDomain(LearnerJpaEntity entity) {
|
||||
return Learner.reconstruct(
|
||||
entity.getId(),
|
||||
entity.getUserId(),
|
||||
entity.getDisplayName(),
|
||||
entity.getCreatedAt(),
|
||||
entity.getUpdatedAt());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:postgresql://localhost:5432/aplp}
|
||||
url: ${DB_URL:jdbc:postgresql://192.168.2.100:5432/aplp}
|
||||
username: ${DB_USERNAME:postgres}
|
||||
password: ${DB_PASSWORD:Pa55w0rd}
|
||||
hikari:
|
||||
@@ -13,4 +13,4 @@ spring:
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.aplp.backend: DEBUG
|
||||
aplp.backend.web: DEBUG
|
||||
|
||||
@@ -8,4 +8,4 @@ spring:
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.aplp.backend: INFO
|
||||
aplp.backend.web: INFO
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
spring:
|
||||
application:
|
||||
name: aplp-backend
|
||||
name: aplp-backend-web
|
||||
profiles:
|
||||
default: dev
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
properties:
|
||||
hibernate:
|
||||
default_schema: web
|
||||
open-in-view: false
|
||||
flyway:
|
||||
enabled: true
|
||||
locations: classpath:db/migration
|
||||
schemas: web
|
||||
default-schema: web
|
||||
jackson:
|
||||
default-property-inclusion: non_null
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
CREATE TABLE users (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
email VARCHAR(320) NOT NULL,
|
||||
username VARCHAR(50) NOT NULL,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT uq_users_email UNIQUE (email)
|
||||
CONSTRAINT uq_users_email UNIQUE (email),
|
||||
CONSTRAINT uq_users_username UNIQUE (username)
|
||||
);
|
||||
|
||||
CREATE TABLE refresh_token (
|
||||
@@ -32,3 +34,4 @@ CREATE TABLE learner (
|
||||
|
||||
CREATE INDEX idx_refresh_token_user_id ON refresh_token (user_id);
|
||||
CREATE INDEX idx_users_email ON users (email);
|
||||
CREATE INDEX idx_users_username ON users (username);
|
||||
|
||||
+20
-21
@@ -1,10 +1,10 @@
|
||||
package com.aplp.backend;
|
||||
package aplp.backend.web;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
@@ -38,10 +38,10 @@ class AuthFlowIntegrationTest {
|
||||
|
||||
@Test
|
||||
void fullAuthFlow() throws Exception {
|
||||
TokenPair registered = register(EMAIL, PASSWORD, "Learner One");
|
||||
TokenPair registered = register("learnerone", EMAIL, PASSWORD, "Learner One");
|
||||
viewMyProfile(registered.accessToken());
|
||||
|
||||
TokenPair loggedIn = login(EMAIL, PASSWORD);
|
||||
TokenPair loggedIn = login("learnerone", PASSWORD);
|
||||
viewMyProfile(loggedIn.accessToken());
|
||||
|
||||
TokenPair refreshed = refresh(loggedIn.refreshToken());
|
||||
@@ -54,7 +54,7 @@ class AuthFlowIntegrationTest {
|
||||
void registrationSetsXRequestIdAndRejectsDuplicate() throws Exception {
|
||||
MvcResult first = mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", "dup@aplp.dev", "password", PASSWORD, "displayName", "Dup")))
|
||||
.content(json("username", "dupuser", "email", "dup@aplp.dev", "password", PASSWORD, "displayName", "Dup")))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(header().exists("X-Request-Id"))
|
||||
.andReturn();
|
||||
@@ -62,7 +62,7 @@ class AuthFlowIntegrationTest {
|
||||
|
||||
mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", "dup@aplp.dev", "password", PASSWORD, "displayName", "Dup")))
|
||||
.content(json("username", "dupuser2", "email", "dup@aplp.dev", "password", PASSWORD, "displayName", "Dup")))
|
||||
.andExpect(status().isConflict())
|
||||
.andExpect(jsonPath("$.code").value("EMAIL_ALREADY_EXISTS"));
|
||||
}
|
||||
@@ -80,10 +80,10 @@ class AuthFlowIntegrationTest {
|
||||
|
||||
@Test
|
||||
void loginWithWrongPasswordIsRejected() throws Exception {
|
||||
register("wrong@aplp.dev", PASSWORD, "Wrong");
|
||||
register("wronguser", "wrong@aplp.dev", PASSWORD, "Wrong");
|
||||
mockMvc.perform(post("/api/v1/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", "wrong@aplp.dev", "password", "not-the-password")))
|
||||
.content(json("username", "wronguser", "password", "not-the-password")))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.code").value("INVALID_CREDENTIALS"));
|
||||
}
|
||||
@@ -92,14 +92,14 @@ class AuthFlowIntegrationTest {
|
||||
void validationErrorsReturnUniformShape() throws Exception {
|
||||
mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"email\":\"not-an-email\",\"password\":\"x\",\"displayName\":\"\"}"))
|
||||
.content("{\"username\":\"\",\"email\":\"not-an-email\",\"password\":\"x\",\"displayName\":\"\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.code").value("VALIDATION_FAILED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateLearnerDisplayName() throws Exception {
|
||||
TokenPair pair = register("update-me@aplp.dev", PASSWORD, "Old Name");
|
||||
TokenPair pair = register("updateme", "update-me@aplp.dev", PASSWORD, "Old Name");
|
||||
mockMvc.perform(patch("/api/v1/learners/me")
|
||||
.header("Authorization", "Bearer " + pair.accessToken())
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
@@ -110,7 +110,7 @@ class AuthFlowIntegrationTest {
|
||||
|
||||
@Test
|
||||
void refreshWithRevokedTokenIsRejected() throws Exception {
|
||||
TokenPair pair = loginOrRegister("revoked@aplp.dev");
|
||||
TokenPair pair = loginOrRegister("revokeduser", "revoked@aplp.dev");
|
||||
|
||||
mockMvc.perform(post("/api/v1/auth/logout")
|
||||
.header("Authorization", "Bearer " + pair.accessToken())
|
||||
@@ -141,10 +141,10 @@ class AuthFlowIntegrationTest {
|
||||
.andExpect(jsonPath("$.status").value("UP"));
|
||||
}
|
||||
|
||||
private TokenPair register(String email, String password, String displayName) throws Exception {
|
||||
private TokenPair register(String username, String email, String password, String displayName) throws Exception {
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", email, "password", password, "displayName", displayName)))
|
||||
.content(json("username", username, "email", email, "password", password, "displayName", displayName)))
|
||||
.andExpect(status().isCreated())
|
||||
.andReturn();
|
||||
JsonNode body = bodyOf(result);
|
||||
@@ -152,22 +152,21 @@ class AuthFlowIntegrationTest {
|
||||
return new TokenPair(body.get("accessToken").asText(), body.get("refreshToken").asText());
|
||||
}
|
||||
|
||||
private TokenPair login(String email, String password) throws Exception {
|
||||
private TokenPair login(String username, String password) throws Exception {
|
||||
MvcResult result = mockMvc.perform(post("/api/v1/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json("email", email, "password", password)))
|
||||
.content(json("username", username, "password", password)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
JsonNode body = bodyOf(result);
|
||||
assertThat(body.get("user").get("email").asText()).isEqualTo(email);
|
||||
return new TokenPair(body.get("accessToken").asText(), body.get("refreshToken").asText());
|
||||
}
|
||||
|
||||
private TokenPair loginOrRegister(String email) throws Exception {
|
||||
private TokenPair loginOrRegister(String username, String email) throws Exception {
|
||||
try {
|
||||
return register(email, PASSWORD, "Revoked");
|
||||
return register(username, email, PASSWORD, "Revoked");
|
||||
} catch (AssertionError ignored) {
|
||||
return login(email, PASSWORD);
|
||||
return login(username, PASSWORD);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
package com.aplp.backend;
|
||||
package aplp.backend.web;
|
||||
|
||||
import com.aplp.backend.common.security.JwtTokenProvider;
|
||||
import aplp.backend.web.common.security.JwtTokenProvider;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -17,7 +17,7 @@ class JwtTokenProviderTest {
|
||||
|
||||
@Test
|
||||
void createsAndParsesAccessToken() {
|
||||
var user = new com.aplp.backend.common.security.AuthenticatedUser(42L, "a@b.c", "Nam");
|
||||
var user = new aplp.backend.web.common.security.AuthenticatedUser(42L, "a@b.c", "Nam");
|
||||
String token = tokenProvider.createAccessToken(user);
|
||||
|
||||
var claims = tokenProvider.parse(token);
|
||||
@@ -7,8 +7,13 @@ spring:
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
properties:
|
||||
hibernate:
|
||||
default_schema: web
|
||||
flyway:
|
||||
enabled: true
|
||||
schemas: web
|
||||
default-schema: web
|
||||
|
||||
app:
|
||||
jwt:
|
||||
|
||||
Reference in New Issue
Block a user