ok
This commit is contained in:
38
.env.example
Normal file
38
.env.example
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
NODE_ENV=development
|
||||||
|
HOST=0.0.0.0
|
||||||
|
PORT=3000
|
||||||
|
APP_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DB_HOST=localhost
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PASSWORD=password
|
||||||
|
DB_NAME=nestjs_blog
|
||||||
|
DB_SSL=false
|
||||||
|
|
||||||
|
# JWT
|
||||||
|
JWT_ACCESS_SECRET=change-me-access-secret-at-least-32-chars
|
||||||
|
JWT_REFRESH_SECRET=change-me-refresh-secret-at-least-32-chars
|
||||||
|
JWT_ACCESS_EXPIRES_IN=15m
|
||||||
|
JWT_REFRESH_EXPIRES_IN=7d
|
||||||
|
|
||||||
|
# Tokens
|
||||||
|
MAGIC_LINK_TTL_MINUTES=20
|
||||||
|
PASSWORD_RESET_TTL_MINUTES=30
|
||||||
|
|
||||||
|
# Cookies
|
||||||
|
COOKIE_SECURE=false
|
||||||
|
COOKIE_DOMAIN=
|
||||||
|
|
||||||
|
# Email (leave blank to use console fallback in dev)
|
||||||
|
MAIL_FROM=no-reply@blog.local
|
||||||
|
SMTP_HOST=
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_USER=
|
||||||
|
SMTP_PASS=
|
||||||
|
|
||||||
|
# Google OAuth
|
||||||
|
GOOGLE_CLIENT_ID=
|
||||||
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
|
||||||
100
.gitignore
vendored
Normal file
100
.gitignore
vendored
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
# -----------------------------
|
||||||
|
# Dependencies
|
||||||
|
# -----------------------------
|
||||||
|
node_modules/
|
||||||
|
jspm_packages/
|
||||||
|
|
||||||
|
# Optional npm cache directory
|
||||||
|
.npm
|
||||||
|
|
||||||
|
# Optional eslint cache
|
||||||
|
.eslintcache
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Build Output
|
||||||
|
# -----------------------------
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
|
||||||
|
# TypeScript
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Environment Variables
|
||||||
|
# -----------------------------
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Logs
|
||||||
|
# -----------------------------
|
||||||
|
logs/
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# OS Files
|
||||||
|
# -----------------------------
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# IDE / Editor
|
||||||
|
# -----------------------------
|
||||||
|
.vscode/
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Testing
|
||||||
|
# -----------------------------
|
||||||
|
/jest-cache/
|
||||||
|
coverage/
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Misc
|
||||||
|
# -----------------------------
|
||||||
|
tmp/
|
||||||
|
temp/
|
||||||
|
.cache/
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Docker (optional)
|
||||||
|
# -----------------------------
|
||||||
|
docker-compose.override.yml
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Package Managers
|
||||||
|
# -----------------------------
|
||||||
|
.pnp/
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Nest CLI
|
||||||
|
# -----------------------------
|
||||||
|
nest-cli.json.lock
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Firebase / Serverless (optional)
|
||||||
|
# -----------------------------
|
||||||
|
.firebase/
|
||||||
|
.serverless/
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Mac
|
||||||
|
# -----------------------------
|
||||||
|
|
||||||
|
.AppleDouble
|
||||||
|
.LSOverride
|
||||||
|
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
4
.prettierrc
Normal file
4
.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
71
README.md
Normal file
71
README.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project init
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Set up PostgreSQL and fill in .env
|
||||||
|
cp .env.example .env
|
||||||
|
# edit .env with your DB credentials
|
||||||
|
|
||||||
|
# 2. Run DB schema (or let TypeORM synchronize on first start)
|
||||||
|
psql -U postgres -d nestjs_blog -f database/init.sql
|
||||||
|
|
||||||
|
# 3. Seed admin users
|
||||||
|
npm run seed:admin
|
||||||
|
|
||||||
|
# 4. Seed blog posts
|
||||||
|
npm run seed:posts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
94
database/init.sql
Normal file
94
database/init.sql
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
-- USERS
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
name VARCHAR(120),
|
||||||
|
role VARCHAR(20) NOT NULL DEFAULT 'MEMBER'
|
||||||
|
CHECK (role IN ('ADMIN', 'MANAGER', 'MEMBER')),
|
||||||
|
password_hash VARCHAR(255),
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_users_email UNIQUE (email)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
||||||
|
|
||||||
|
-- REFRESH TOKENS
|
||||||
|
CREATE TABLE IF NOT EXISTS refresh_tokens (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token_hash VARCHAR(255) NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
revoked_at TIMESTAMPTZ,
|
||||||
|
replaced_by_token_hash VARCHAR(255),
|
||||||
|
user_agent TEXT,
|
||||||
|
ip VARCHAR(64),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_refresh_token_hash UNIQUE (token_hash)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user_expires ON refresh_tokens(user_id, expires_at);
|
||||||
|
|
||||||
|
-- MAGIC LINK TOKENS
|
||||||
|
CREATE TABLE IF NOT EXISTS magic_link_tokens (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
token_hash VARCHAR(255) NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
consumed_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_magic_link_token_hash UNIQUE (token_hash)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_magic_link_email ON magic_link_tokens(email);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_magic_link_expires ON magic_link_tokens(expires_at);
|
||||||
|
|
||||||
|
-- PASSWORD RESET TOKENS
|
||||||
|
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token_hash VARCHAR(255) NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
consumed_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_password_reset_token_hash UNIQUE (token_hash)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- OAUTH ACCOUNTS
|
||||||
|
CREATE TABLE IF NOT EXISTS oauth_accounts (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
provider VARCHAR(50) NOT NULL,
|
||||||
|
provider_id VARCHAR(255) NOT NULL,
|
||||||
|
email VARCHAR(255),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_oauth_provider_provider_id UNIQUE (provider, provider_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- BLOG POSTS
|
||||||
|
CREATE TABLE IF NOT EXISTS blog_posts (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title VARCHAR(255) NOT NULL,
|
||||||
|
slug VARCHAR(300),
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'draft'
|
||||||
|
CHECK (status IN ('draft', 'published', 'archived')),
|
||||||
|
excerpt TEXT NOT NULL DEFAULT '',
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
content_format VARCHAR(20) NOT NULL DEFAULT 'markdown'
|
||||||
|
CHECK (content_format IN ('markdown', 'html')),
|
||||||
|
author_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||||
|
featured_image_url VARCHAR(500),
|
||||||
|
featured_image_alt VARCHAR(255),
|
||||||
|
is_featured BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
views INTEGER NOT NULL DEFAULT 0,
|
||||||
|
tags TEXT NOT NULL DEFAULT '',
|
||||||
|
categories TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT uq_blog_posts_slug UNIQUE (slug)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_blog_posts_status_created ON blog_posts(status, created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_blog_posts_featured ON blog_posts(is_featured, created_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_blog_posts_views ON blog_posts(views DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_blog_posts_author ON blog_posts(author_id);
|
||||||
35
eslint.config.mjs
Normal file
35
eslint.config.mjs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
// @ts-check
|
||||||
|
import eslint from '@eslint/js';
|
||||||
|
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{
|
||||||
|
ignores: ['eslint.config.mjs'],
|
||||||
|
},
|
||||||
|
eslint.configs.recommended,
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
eslintPluginPrettierRecommended,
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.jest,
|
||||||
|
},
|
||||||
|
sourceType: 'commonjs',
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-floating-promises': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
|
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
11274
package-lock.json
generated
Normal file
11274
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
103
package.json
Normal file
103
package.json
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
{
|
||||||
|
"name": "FullStack-Blog-Nestjs-HTMX",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
|
"seed:admin": "ts-node -P tsconfig.json scripts/seed-admin.ts",
|
||||||
|
"seed:posts": "ts-node -P tsconfig.json scripts/seed-blog-posts.ts",
|
||||||
|
"db:init": "psql -U $DB_USER -d $DB_NAME -f database/init.sql"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^11.0.1",
|
||||||
|
"@nestjs/config": "^4.0.3",
|
||||||
|
"@nestjs/core": "^11.0.1",
|
||||||
|
"@nestjs/jwt": "^11.0.2",
|
||||||
|
"@nestjs/mapped-types": "^2.1.0",
|
||||||
|
"@nestjs/passport": "^11.0.5",
|
||||||
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/typeorm": "^11.0.0",
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.3",
|
||||||
|
"cookie-parser": "^1.4.7",
|
||||||
|
"dotenv": "^17.3.1",
|
||||||
|
"marked": "^17.0.3",
|
||||||
|
"nodemailer": "^8.0.1",
|
||||||
|
"nunjucks": "^3.2.4",
|
||||||
|
"passport": "^0.7.0",
|
||||||
|
"passport-google-oauth20": "^2.0.0",
|
||||||
|
"pg": "^8.18.0",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"typeorm": "^0.3.28",
|
||||||
|
"uuid": "^13.0.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
|
"@eslint/js": "^9.18.0",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/bcrypt": "^6.0.0",
|
||||||
|
"@types/cookie-parser": "^1.4.10",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/marked": "^5.0.2",
|
||||||
|
"@types/node": "^22.10.7",
|
||||||
|
"@types/nodemailer": "^7.0.10",
|
||||||
|
"@types/nunjucks": "^3.2.6",
|
||||||
|
"@types/passport": "^1.0.17",
|
||||||
|
"@types/passport-google-oauth20": "^2.0.17",
|
||||||
|
"@types/supertest": "^6.0.2",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
|
"eslint": "^9.18.0",
|
||||||
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
"eslint-plugin-prettier": "^5.2.2",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"prettier": "^3.4.2",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"typescript-eslint": "^8.20.0"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"transformIgnorePatterns": [
|
||||||
|
"/node_modules/(?!(uuid)/)"
|
||||||
|
],
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
}
|
||||||
55
scripts/seed-admin.ts
Normal file
55
scripts/seed-admin.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* Run: npx ts-node -P tsconfig.json scripts/seed-admin.ts
|
||||||
|
*/
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { DataSource } from 'typeorm';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
import { User, UserRole } from '../src/users/entities/user.entity';
|
||||||
|
|
||||||
|
const dataSource = new DataSource({
|
||||||
|
type: 'postgres',
|
||||||
|
host: process.env.DB_HOST || 'localhost',
|
||||||
|
port: parseInt(process.env.DB_PORT || '5432', 10),
|
||||||
|
username: process.env.DB_USER || 'postgres',
|
||||||
|
password: process.env.DB_PASSWORD || 'password',
|
||||||
|
database: process.env.DB_NAME || 'nestjs_blog',
|
||||||
|
entities: [User],
|
||||||
|
synchronize: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
async function seed() {
|
||||||
|
await dataSource.initialize();
|
||||||
|
console.log('✅ Database connected');
|
||||||
|
|
||||||
|
const users = [
|
||||||
|
{ email: 'admin@gmail.com', role: UserRole.ADMIN, name: 'Admin' },
|
||||||
|
{ email: 'manager@gmail.com', role: UserRole.MANAGER, name: 'Manager' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const repo = dataSource.getRepository(User);
|
||||||
|
const passwordHash = await bcrypt.hash('Whatever123$', 12);
|
||||||
|
|
||||||
|
for (const u of users) {
|
||||||
|
let user = await repo.findOne({ where: { email: u.email } });
|
||||||
|
if (!user) {
|
||||||
|
user = repo.create({ id: uuidv4(), ...u, passwordHash, isActive: true });
|
||||||
|
await repo.save(user);
|
||||||
|
console.log(`✅ Created ${u.role}: ${u.email}`);
|
||||||
|
} else {
|
||||||
|
user.role = u.role;
|
||||||
|
user.passwordHash = passwordHash;
|
||||||
|
user.isActive = true;
|
||||||
|
await repo.save(user);
|
||||||
|
console.log(`♻️ Updated ${u.role}: ${u.email}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await dataSource.destroy();
|
||||||
|
console.log('🎉 Seeding complete');
|
||||||
|
}
|
||||||
|
|
||||||
|
seed().catch((err) => {
|
||||||
|
console.error('❌ Seed failed:', err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
1358
scripts/seed-blog-posts.ts
Normal file
1358
scripts/seed-blog-posts.ts
Normal file
File diff suppressed because it is too large
Load Diff
22
src/app.controller.spec.ts
Normal file
22
src/app.controller.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
import { AppService } from './app.service';
|
||||||
|
|
||||||
|
describe('AppController', () => {
|
||||||
|
let appController: AppController;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const app: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [AppController],
|
||||||
|
providers: [AppService],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
appController = app.get<AppController>(AppController);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('root', () => {
|
||||||
|
it('should return "Hello World!"', () => {
|
||||||
|
expect(appController.getHello()).toBe('Hello World!');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
12
src/app.controller.ts
Normal file
12
src/app.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { AppService } from './app.service';
|
||||||
|
|
||||||
|
@Controller()
|
||||||
|
export class AppController {
|
||||||
|
constructor(private readonly appService: AppService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
getHello(): string {
|
||||||
|
return this.appService.getHello();
|
||||||
|
}
|
||||||
|
}
|
||||||
85
src/app.module.ts
Normal file
85
src/app.module.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
|
||||||
|
|
||||||
|
import { validate } from './config/env.validation';
|
||||||
|
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||||
|
import { JwtAuthGuard } from './common/guards/jwt-auth.guard';
|
||||||
|
import { RolesGuard } from './common/guards/roles.guard';
|
||||||
|
import { CsrfMiddleware } from './common/middleware/csrf.middleware';
|
||||||
|
|
||||||
|
import { AuthModule } from './auth/auth.module';
|
||||||
|
import { UsersModule } from './users/users.module';
|
||||||
|
import { BlogPostsModule } from './blog-posts/blog-posts.module';
|
||||||
|
import { PagesModule } from './pages/pages.module';
|
||||||
|
import { TokensModule } from './tokens/tokens.module';
|
||||||
|
|
||||||
|
import { User } from './users/entities/user.entity';
|
||||||
|
import { BlogPost } from './blog-posts/entities/blog-post.entity';
|
||||||
|
import { RefreshToken } from './tokens/entities/refresh-token.entity';
|
||||||
|
import { MagicLinkToken } from './tokens/entities/magic-link-token.entity';
|
||||||
|
import { PasswordResetToken } from './tokens/entities/password-reset-token.entity';
|
||||||
|
import { OAuthAccount } from './tokens/entities/oauth-account.entity';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
envFilePath: '.env',
|
||||||
|
validate,
|
||||||
|
}),
|
||||||
|
TypeOrmModule.forRootAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
type: 'postgres',
|
||||||
|
host: configService.get<string>('DB_HOST'),
|
||||||
|
port: configService.get<number>('DB_PORT'),
|
||||||
|
username: configService.get<string>('DB_USER'),
|
||||||
|
password: configService.get<string>('DB_PASSWORD'),
|
||||||
|
database: configService.get<string>('DB_NAME'),
|
||||||
|
ssl:
|
||||||
|
configService.get<string>('DB_SSL') === 'true'
|
||||||
|
? { rejectUnauthorized: false }
|
||||||
|
: false,
|
||||||
|
entities: [
|
||||||
|
User,
|
||||||
|
BlogPost,
|
||||||
|
RefreshToken,
|
||||||
|
MagicLinkToken,
|
||||||
|
PasswordResetToken,
|
||||||
|
OAuthAccount,
|
||||||
|
],
|
||||||
|
synchronize: configService.get<string>('NODE_ENV') !== 'production',
|
||||||
|
logging: configService.get<string>('NODE_ENV') === 'development',
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
AuthModule,
|
||||||
|
UsersModule,
|
||||||
|
BlogPostsModule,
|
||||||
|
PagesModule,
|
||||||
|
TokensModule,
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: APP_FILTER,
|
||||||
|
useClass: AllExceptionsFilter,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: APP_GUARD,
|
||||||
|
useClass: JwtAuthGuard,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
provide: APP_GUARD,
|
||||||
|
useClass: RolesGuard,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule implements NestModule {
|
||||||
|
configure(consumer: MiddlewareConsumer) {
|
||||||
|
consumer
|
||||||
|
.apply(CsrfMiddleware)
|
||||||
|
.forRoutes({ path: '*', method: RequestMethod.ALL });
|
||||||
|
}
|
||||||
|
}
|
||||||
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AppService {
|
||||||
|
getHello(): string {
|
||||||
|
return 'Hello World!';
|
||||||
|
}
|
||||||
|
}
|
||||||
93
src/auth/auth.controller.ts
Normal file
93
src/auth/auth.controller.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
Res,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { AuthGuard } from '@nestjs/passport';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { MagicLinkRequestDto } from './dto/magic-link-request.dto';
|
||||||
|
import { PasswordResetConfirmDto } from './dto/password-reset-confirm.dto';
|
||||||
|
import { PasswordResetRequestDto } from './dto/password-reset-request.dto';
|
||||||
|
import { RegisterDto } from './dto/register.dto';
|
||||||
|
import { Public } from '../common/decorators/public.decorator';
|
||||||
|
|
||||||
|
@Controller('auth')
|
||||||
|
@Public()
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private readonly authService: AuthService) {}
|
||||||
|
|
||||||
|
@Post('register')
|
||||||
|
register(@Body() dto: RegisterDto, @Req() req: Request, @Res() res: Response) {
|
||||||
|
return this.authService.register(dto, req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
login(@Body() dto: LoginDto, @Req() req: Request, @Res() res: Response) {
|
||||||
|
return this.authService.login(dto, req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('refresh')
|
||||||
|
refresh(@Req() req: Request, @Res() res: Response) {
|
||||||
|
return this.authService.refresh(req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('logout')
|
||||||
|
logout(@Req() req: Request, @Res() res: Response) {
|
||||||
|
return this.authService.logout(req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('magic-link')
|
||||||
|
requestMagicLink(
|
||||||
|
@Body() dto: MagicLinkRequestDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
return this.authService.requestMagicLink(dto.email, req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('magic-link/verify')
|
||||||
|
verifyMagicLink(
|
||||||
|
@Query('token') token: string,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
return this.authService.verifyMagicLink(token, req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('password-reset/request')
|
||||||
|
requestPasswordReset(
|
||||||
|
@Body() dto: PasswordResetRequestDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
return this.authService.requestPasswordReset(dto.email, req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('password-reset/confirm')
|
||||||
|
confirmPasswordReset(
|
||||||
|
@Body() dto: PasswordResetConfirmDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
return this.authService.confirmPasswordReset(dto, req, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('google')
|
||||||
|
@UseGuards(AuthGuard('google'))
|
||||||
|
googleAuth() {
|
||||||
|
// Passport redirects to Google
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('google/callback')
|
||||||
|
@UseGuards(AuthGuard('google'))
|
||||||
|
googleCallback(@Req() req: Request, @Res() res: Response) {
|
||||||
|
return this.authService.handleGoogleCallback((req as any).user, req, res);
|
||||||
|
}
|
||||||
|
}
|
||||||
38
src/auth/auth.module.ts
Normal file
38
src/auth/auth.module.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { PassportModule } from '@nestjs/passport';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { User } from '../users/entities/user.entity';
|
||||||
|
import { RefreshToken } from '../tokens/entities/refresh-token.entity';
|
||||||
|
import { MagicLinkToken } from '../tokens/entities/magic-link-token.entity';
|
||||||
|
import { PasswordResetToken } from '../tokens/entities/password-reset-token.entity';
|
||||||
|
import { OAuthAccount } from '../tokens/entities/oauth-account.entity';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { GoogleStrategy } from './strategies/google.strategy';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
PassportModule,
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
useFactory: (configService: ConfigService) => ({
|
||||||
|
secret: configService.get<string>('JWT_ACCESS_SECRET'),
|
||||||
|
signOptions: { expiresIn: (configService.get<string>('JWT_ACCESS_EXPIRES_IN') || '15m') as any },
|
||||||
|
}),
|
||||||
|
inject: [ConfigService],
|
||||||
|
}),
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
User,
|
||||||
|
RefreshToken,
|
||||||
|
MagicLinkToken,
|
||||||
|
PasswordResetToken,
|
||||||
|
OAuthAccount,
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [AuthService, GoogleStrategy],
|
||||||
|
exports: [AuthService],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
380
src/auth/auth.service.ts
Normal file
380
src/auth/auth.service.ts
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { IsNull, LessThan, Repository } from 'typeorm';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
import { User, UserRole } from '../users/entities/user.entity';
|
||||||
|
import { RefreshToken } from '../tokens/entities/refresh-token.entity';
|
||||||
|
import { MagicLinkToken } from '../tokens/entities/magic-link-token.entity';
|
||||||
|
import { PasswordResetToken } from '../tokens/entities/password-reset-token.entity';
|
||||||
|
import { OAuthAccount } from '../tokens/entities/oauth-account.entity';
|
||||||
|
import {
|
||||||
|
generateRawToken,
|
||||||
|
hashToken,
|
||||||
|
signAccessToken,
|
||||||
|
signRefreshToken,
|
||||||
|
verifyRefreshToken,
|
||||||
|
} from '../common/helpers/jwt.helper';
|
||||||
|
import { sendMail } from '../common/helpers/mailer.helper';
|
||||||
|
import { RegisterDto } from './dto/register.dto';
|
||||||
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { PasswordResetConfirmDto } from './dto/password-reset-confirm.dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(User)
|
||||||
|
private readonly userRepo: Repository<User>,
|
||||||
|
@InjectRepository(RefreshToken)
|
||||||
|
private readonly refreshTokenRepo: Repository<RefreshToken>,
|
||||||
|
@InjectRepository(MagicLinkToken)
|
||||||
|
private readonly magicLinkRepo: Repository<MagicLinkToken>,
|
||||||
|
@InjectRepository(PasswordResetToken)
|
||||||
|
private readonly pwdResetRepo: Repository<PasswordResetToken>,
|
||||||
|
@InjectRepository(OAuthAccount)
|
||||||
|
private readonly oauthRepo: Repository<OAuthAccount>,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ─── Token helpers ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private issueTokens(user: User) {
|
||||||
|
const accessSecret = this.configService.get<string>('JWT_ACCESS_SECRET');
|
||||||
|
const refreshSecret = this.configService.get<string>('JWT_REFRESH_SECRET');
|
||||||
|
const accessExpiresIn = this.configService.get<string>('JWT_ACCESS_EXPIRES_IN') || '15m';
|
||||||
|
const refreshExpiresIn = this.configService.get<string>('JWT_REFRESH_EXPIRES_IN') || '7d';
|
||||||
|
|
||||||
|
const accessToken = signAccessToken(
|
||||||
|
{ sub: user.id, email: user.email, role: user.role },
|
||||||
|
accessSecret,
|
||||||
|
accessExpiresIn,
|
||||||
|
);
|
||||||
|
const rawRefresh = generateRawToken();
|
||||||
|
const refreshToken = signRefreshToken({ sub: user.id }, refreshSecret, refreshExpiresIn);
|
||||||
|
|
||||||
|
return { accessToken, rawRefresh, refreshToken };
|
||||||
|
}
|
||||||
|
|
||||||
|
private cookieOptions(res: any, accessToken: string, refreshToken: string) {
|
||||||
|
const secure = this.configService.get<string>('COOKIE_SECURE') === 'true';
|
||||||
|
const domain = this.configService.get<string>('COOKIE_DOMAIN') || undefined;
|
||||||
|
const opts = { httpOnly: true, sameSite: 'lax' as const, secure, domain };
|
||||||
|
res.cookie('accessToken', accessToken, { ...opts, maxAge: 15 * 60 * 1000 });
|
||||||
|
res.cookie('refreshToken', refreshToken, { ...opts, maxAge: 7 * 24 * 60 * 60 * 1000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearCookies(res: any) {
|
||||||
|
res.clearCookie('accessToken');
|
||||||
|
res.clearCookie('refreshToken');
|
||||||
|
}
|
||||||
|
|
||||||
|
private safeUser(user: User) {
|
||||||
|
const { passwordHash, ...safe } = user as any;
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Register ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async register(dto: RegisterDto, req: any, res: any) {
|
||||||
|
const existing = await this.userRepo.findOne({ where: { email: dto.email } });
|
||||||
|
if (existing) throw new ConflictException('Email already in use');
|
||||||
|
|
||||||
|
const passwordHash = await bcrypt.hash(dto.password, 12);
|
||||||
|
const user = this.userRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
email: dto.email,
|
||||||
|
name: dto.name,
|
||||||
|
role: UserRole.MEMBER,
|
||||||
|
passwordHash,
|
||||||
|
});
|
||||||
|
await this.userRepo.save(user);
|
||||||
|
|
||||||
|
const { accessToken, rawRefresh, refreshToken } = this.issueTokens(user);
|
||||||
|
await this.storeRefreshToken(user.id, rawRefresh, req);
|
||||||
|
this.cookieOptions(res, accessToken, refreshToken);
|
||||||
|
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
res.set('HX-Redirect', '/dashboard');
|
||||||
|
return res.render('partials/flash', { type: 'success', message: 'Welcome! Account created.' });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, accessToken, refreshToken, user: this.safeUser(user) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Login ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async login(dto: LoginDto, req: any, res: any) {
|
||||||
|
const user = await this.userRepo.findOne({ where: { email: dto.email } });
|
||||||
|
if (!user || !user.passwordHash) {
|
||||||
|
throw new UnauthorizedException('Invalid email or password');
|
||||||
|
}
|
||||||
|
|
||||||
|
const valid = await bcrypt.compare(dto.password, user.passwordHash);
|
||||||
|
if (!valid) throw new UnauthorizedException('Invalid email or password');
|
||||||
|
if (!user.isActive) throw new UnauthorizedException('Account is deactivated');
|
||||||
|
|
||||||
|
const { accessToken, rawRefresh, refreshToken } = this.issueTokens(user);
|
||||||
|
await this.storeRefreshToken(user.id, rawRefresh, req);
|
||||||
|
this.cookieOptions(res, accessToken, refreshToken);
|
||||||
|
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
res.set('HX-Redirect', '/dashboard');
|
||||||
|
return res.render('partials/flash', { type: 'success', message: `Welcome back, ${user.name || user.email}!` });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, accessToken, refreshToken, user: this.safeUser(user) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Refresh ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async refresh(req: any, res: any) {
|
||||||
|
const rawToken = req.cookies?.refreshToken || req.body?.refreshToken;
|
||||||
|
if (!rawToken) throw new UnauthorizedException('No refresh token provided');
|
||||||
|
|
||||||
|
const refreshSecret = this.configService.get<string>('JWT_REFRESH_SECRET');
|
||||||
|
let payload: any;
|
||||||
|
try {
|
||||||
|
payload = verifyRefreshToken(rawToken, refreshSecret);
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Invalid or expired refresh token');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenHash = hashToken(rawToken);
|
||||||
|
const stored = await this.refreshTokenRepo.findOne({
|
||||||
|
where: { tokenHash },
|
||||||
|
relations: ['user'],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!stored || stored.revokedAt || stored.expiresAt < new Date()) {
|
||||||
|
throw new UnauthorizedException('Refresh token invalid or revoked');
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = stored.user;
|
||||||
|
|
||||||
|
// Rotate: revoke old, issue new
|
||||||
|
const newRaw = generateRawToken();
|
||||||
|
const refreshExpiresIn = this.configService.get<string>('JWT_REFRESH_EXPIRES_IN') || '7d';
|
||||||
|
const newRefreshSecret = this.configService.get<string>('JWT_REFRESH_SECRET');
|
||||||
|
const newRefreshToken = signRefreshToken({ sub: user.id }, newRefreshSecret, refreshExpiresIn);
|
||||||
|
const newHash = hashToken(newRaw);
|
||||||
|
|
||||||
|
stored.revokedAt = new Date();
|
||||||
|
stored.replacedByTokenHash = newHash;
|
||||||
|
await this.refreshTokenRepo.save(stored);
|
||||||
|
|
||||||
|
await this.storeRefreshToken(user.id, newRaw, req);
|
||||||
|
|
||||||
|
const { accessToken } = this.issueTokens(user);
|
||||||
|
this.cookieOptions(res, accessToken, newRefreshToken);
|
||||||
|
|
||||||
|
return res.json({ success: true, accessToken, refreshToken: newRefreshToken });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Logout ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async logout(req: any, res: any) {
|
||||||
|
const rawToken = req.cookies?.refreshToken || req.body?.refreshToken;
|
||||||
|
if (rawToken) {
|
||||||
|
const tokenHash = hashToken(rawToken);
|
||||||
|
await this.refreshTokenRepo.update({ tokenHash }, { revokedAt: new Date() });
|
||||||
|
}
|
||||||
|
this.clearCookies(res);
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
res.set('HX-Redirect', '/');
|
||||||
|
return res.render('partials/flash', { type: 'success', message: 'Logged out successfully' });
|
||||||
|
}
|
||||||
|
return res.json({ success: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Magic Link ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async requestMagicLink(email: string, req: any, res: any) {
|
||||||
|
const appUrl = this.configService.get<string>('APP_URL') || 'http://localhost:3000';
|
||||||
|
const ttl = this.configService.get<number>('MAGIC_LINK_TTL_MINUTES') || 20;
|
||||||
|
|
||||||
|
const user = await this.userRepo.findOne({ where: { email } });
|
||||||
|
const rawToken = generateRawToken();
|
||||||
|
const tokenHash = hashToken(rawToken);
|
||||||
|
const expiresAt = new Date(Date.now() + ttl * 60 * 1000);
|
||||||
|
|
||||||
|
await this.magicLinkRepo.save(
|
||||||
|
this.magicLinkRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
userId: user?.id || null,
|
||||||
|
email,
|
||||||
|
tokenHash,
|
||||||
|
expiresAt,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const link = `${appUrl}/auth/magic-link/verify?token=${rawToken}`;
|
||||||
|
|
||||||
|
await sendMail({
|
||||||
|
to: email,
|
||||||
|
subject: 'Your Magic Link',
|
||||||
|
html: `<p>Click <a href="${link}">here</a> to sign in. Link expires in ${ttl} minutes.</p><p>${link}</p>`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: 'Magic link sent! Check your email.' });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, message: 'Magic link sent' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyMagicLink(rawToken: string, req: any, res: any) {
|
||||||
|
const tokenHash = hashToken(rawToken);
|
||||||
|
const record = await this.magicLinkRepo.findOne({ where: { tokenHash } });
|
||||||
|
|
||||||
|
if (!record || record.consumedAt || record.expiresAt < new Date()) {
|
||||||
|
throw new UnauthorizedException('Invalid or expired magic link');
|
||||||
|
}
|
||||||
|
|
||||||
|
record.consumedAt = new Date();
|
||||||
|
await this.magicLinkRepo.save(record);
|
||||||
|
|
||||||
|
// Find or create user
|
||||||
|
let user = await this.userRepo.findOne({ where: { email: record.email } });
|
||||||
|
if (!user) {
|
||||||
|
user = this.userRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
email: record.email,
|
||||||
|
role: UserRole.MEMBER,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
await this.userRepo.save(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { accessToken, rawRefresh, refreshToken } = this.issueTokens(user);
|
||||||
|
await this.storeRefreshToken(user.id, rawRefresh, req);
|
||||||
|
this.cookieOptions(res, accessToken, refreshToken);
|
||||||
|
|
||||||
|
return res.redirect('/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Password Reset ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async requestPasswordReset(email: string, req: any, res: any) {
|
||||||
|
const appUrl = this.configService.get<string>('APP_URL') || 'http://localhost:3000';
|
||||||
|
const ttl = this.configService.get<number>('PASSWORD_RESET_TTL_MINUTES') || 30;
|
||||||
|
|
||||||
|
const user = await this.userRepo.findOne({ where: { email } });
|
||||||
|
if (!user) {
|
||||||
|
// Return success to avoid enumeration
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) return res.render('partials/flash', { type: 'success', message: 'If that email exists, a reset link was sent.' });
|
||||||
|
return res.json({ success: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawToken = generateRawToken();
|
||||||
|
const tokenHash = hashToken(rawToken);
|
||||||
|
const expiresAt = new Date(Date.now() + ttl * 60 * 1000);
|
||||||
|
|
||||||
|
await this.pwdResetRepo.save(
|
||||||
|
this.pwdResetRepo.create({ id: uuidv4(), userId: user.id, tokenHash, expiresAt }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const link = `${appUrl}/auth?tab=reset&token=${rawToken}`;
|
||||||
|
await sendMail({
|
||||||
|
to: email,
|
||||||
|
subject: 'Password Reset',
|
||||||
|
html: `<p>Click <a href="${link}">here</a> to reset your password. Expires in ${ttl} minutes.</p>`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) return res.render('partials/flash', { type: 'success', message: 'Reset link sent!' });
|
||||||
|
return res.json({ success: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async confirmPasswordReset(dto: PasswordResetConfirmDto, req: any, res: any) {
|
||||||
|
const tokenHash = hashToken(dto.token);
|
||||||
|
const record = await this.pwdResetRepo.findOne({
|
||||||
|
where: { tokenHash },
|
||||||
|
relations: ['user'],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!record || record.consumedAt || record.expiresAt < new Date()) {
|
||||||
|
throw new BadRequestException('Invalid or expired reset token');
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordHash = await bcrypt.hash(dto.password, 12);
|
||||||
|
await this.userRepo.update(record.userId, { passwordHash });
|
||||||
|
|
||||||
|
record.consumedAt = new Date();
|
||||||
|
await this.pwdResetRepo.save(record);
|
||||||
|
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) return res.render('partials/flash', { type: 'success', message: 'Password updated! You can now log in.' });
|
||||||
|
return res.json({ success: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Google OAuth ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async handleGoogleCallback(googleUser: any, req: any, res: any) {
|
||||||
|
const { providerId, email, name } = googleUser;
|
||||||
|
|
||||||
|
let oauthAccount = await this.oauthRepo.findOne({
|
||||||
|
where: { provider: 'google', providerId },
|
||||||
|
relations: ['user'],
|
||||||
|
});
|
||||||
|
|
||||||
|
let user: User;
|
||||||
|
if (oauthAccount) {
|
||||||
|
user = oauthAccount.user;
|
||||||
|
} else {
|
||||||
|
// Find or create user by email
|
||||||
|
user = await this.userRepo.findOne({ where: { email } });
|
||||||
|
if (!user) {
|
||||||
|
user = this.userRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
email,
|
||||||
|
name,
|
||||||
|
role: UserRole.MEMBER,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
await this.userRepo.save(user);
|
||||||
|
}
|
||||||
|
oauthAccount = this.oauthRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
userId: user.id,
|
||||||
|
provider: 'google',
|
||||||
|
providerId,
|
||||||
|
email,
|
||||||
|
});
|
||||||
|
await this.oauthRepo.save(oauthAccount);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { accessToken, rawRefresh, refreshToken } = this.issueTokens(user);
|
||||||
|
await this.storeRefreshToken(user.id, rawRefresh, req);
|
||||||
|
this.cookieOptions(res, accessToken, refreshToken);
|
||||||
|
|
||||||
|
return res.redirect('/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Private ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private async storeRefreshToken(userId: string, rawToken: string, req: any) {
|
||||||
|
const tokenHash = hashToken(rawToken);
|
||||||
|
const refreshExpiresIn = this.configService.get<string>('JWT_REFRESH_EXPIRES_IN') || '7d';
|
||||||
|
const days = parseInt(refreshExpiresIn.replace('d', ''), 10) || 7;
|
||||||
|
const expiresAt = new Date(Date.now() + days * 24 * 60 * 60 * 1000);
|
||||||
|
|
||||||
|
await this.refreshTokenRepo.save(
|
||||||
|
this.refreshTokenRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
userId,
|
||||||
|
tokenHash,
|
||||||
|
expiresAt,
|
||||||
|
userAgent: req.headers?.['user-agent'] || null,
|
||||||
|
ip: req.ip || null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/auth/dto/login.dto.ts
Normal file
10
src/auth/dto/login.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class LoginDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
6
src/auth/dto/magic-link-request.dto.ts
Normal file
6
src/auth/dto/magic-link-request.dto.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsEmail } from 'class-validator';
|
||||||
|
|
||||||
|
export class MagicLinkRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
6
src/auth/dto/magic-link-verify.dto.ts
Normal file
6
src/auth/dto/magic-link-verify.dto.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class MagicLinkVerifyDto {
|
||||||
|
@IsString()
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
10
src/auth/dto/password-reset-confirm.dto.ts
Normal file
10
src/auth/dto/password-reset-confirm.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class PasswordResetConfirmDto {
|
||||||
|
@IsString()
|
||||||
|
token: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(8)
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
6
src/auth/dto/password-reset-request.dto.ts
Normal file
6
src/auth/dto/password-reset-request.dto.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsEmail } from 'class-validator';
|
||||||
|
|
||||||
|
export class PasswordResetRequestDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
15
src/auth/dto/register.dto.ts
Normal file
15
src/auth/dto/register.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { IsEmail, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class RegisterDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(8)
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(120)
|
||||||
|
@IsOptional()
|
||||||
|
name?: string;
|
||||||
|
}
|
||||||
32
src/auth/strategies/google.strategy.ts
Normal file
32
src/auth/strategies/google.strategy.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { PassportStrategy } from '@nestjs/passport';
|
||||||
|
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
||||||
|
constructor(configService: ConfigService) {
|
||||||
|
super({
|
||||||
|
clientID: configService.get<string>('GOOGLE_CLIENT_ID') || 'dummy',
|
||||||
|
clientSecret: configService.get<string>('GOOGLE_CLIENT_SECRET') || 'dummy',
|
||||||
|
callbackURL: configService.get<string>('GOOGLE_CALLBACK_URL'),
|
||||||
|
scope: ['email', 'profile'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async validate(
|
||||||
|
accessToken: string,
|
||||||
|
refreshToken: string,
|
||||||
|
profile: any,
|
||||||
|
done: VerifyCallback,
|
||||||
|
): Promise<any> {
|
||||||
|
const { id, displayName, emails } = profile;
|
||||||
|
const user = {
|
||||||
|
providerId: id,
|
||||||
|
provider: 'google',
|
||||||
|
email: emails?.[0]?.value,
|
||||||
|
name: displayName,
|
||||||
|
};
|
||||||
|
done(null, user);
|
||||||
|
}
|
||||||
|
}
|
||||||
145
src/blog-posts/blog-posts.controller.ts
Normal file
145
src/blog-posts/blog-posts.controller.ts
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
Res,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { BlogPostsService } from './blog-posts.service';
|
||||||
|
import { CreatePostDto } from './dto/create-post.dto';
|
||||||
|
import { UpdatePostDto } from './dto/update-post.dto';
|
||||||
|
import { ListPostsQueryDto } from './dto/list-posts-query.dto';
|
||||||
|
import { Public } from '../common/decorators/public.decorator';
|
||||||
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
|
import { CurrentUser } from '../common/decorators/current-user.decorator';
|
||||||
|
import { UserRole } from '../users/entities/user.entity';
|
||||||
|
|
||||||
|
@Controller('blog-posts')
|
||||||
|
export class BlogPostsController {
|
||||||
|
constructor(private readonly blogPostsService: BlogPostsService) {}
|
||||||
|
|
||||||
|
// ─── Public endpoints ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get('public')
|
||||||
|
@Public()
|
||||||
|
async findPublished(@Query() query: ListPostsQueryDto) {
|
||||||
|
return this.blogPostsService.findPublished(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('public/featured')
|
||||||
|
@Public()
|
||||||
|
async findFeatured() {
|
||||||
|
return this.blogPostsService.findFeatured();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('public/:slug')
|
||||||
|
@Public()
|
||||||
|
async findBySlug(@Param('slug') slug: string) {
|
||||||
|
const post = await this.blogPostsService.findBySlug(slug);
|
||||||
|
return { success: true, post };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('public/:slug/view')
|
||||||
|
@Public()
|
||||||
|
async incrementViews(@Param('slug') slug: string) {
|
||||||
|
await this.blogPostsService.incrementViews(slug);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── HTMX partials (public) ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the post-grid partial.
|
||||||
|
* Templates expect:
|
||||||
|
* result → { items, page, pageSize, total, totalPages }
|
||||||
|
* query → the raw query params (q, tags, category, sort, page, pageSize)
|
||||||
|
*/
|
||||||
|
@Get('partials/grid')
|
||||||
|
@Public()
|
||||||
|
async gridPartial(@Query() query: ListPostsQueryDto, @Res() res: Response) {
|
||||||
|
const result = await this.blogPostsService.findPublished(query);
|
||||||
|
return res.render('partials/post-grid', {
|
||||||
|
result,
|
||||||
|
query: {
|
||||||
|
q: query.q || '',
|
||||||
|
tags: query.tags || '',
|
||||||
|
category: query.category || '',
|
||||||
|
sort: query.sort || 'newest',
|
||||||
|
page: result.page,
|
||||||
|
pageSize: result.pageSize,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── HTMX partials (authenticated) ───────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the dashboard-post-table partial.
|
||||||
|
* Template expects: posts[], currentUser
|
||||||
|
*/
|
||||||
|
@Get('partials/table')
|
||||||
|
async tablePartial(
|
||||||
|
@Query() query: ListPostsQueryDto,
|
||||||
|
@CurrentUser() currentUser: any,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
const data = await this.blogPostsService.findAll(query, currentUser);
|
||||||
|
return res.render('partials/dashboard-post-table', {
|
||||||
|
posts: data.posts,
|
||||||
|
currentUser,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Authenticated CRUD ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
async findAll(@Query() query: ListPostsQueryDto, @CurrentUser() user: any) {
|
||||||
|
return this.blogPostsService.findAll(query, user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@Roles(UserRole.ADMIN, UserRole.MANAGER)
|
||||||
|
async create(@Body() dto: CreatePostDto, @CurrentUser() user: any, @Res() res: Response, @Req() req: Request) {
|
||||||
|
const post = await this.blogPostsService.create(dto, user);
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: `Post "${post.title}" created!` });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, post });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@Roles(UserRole.ADMIN)
|
||||||
|
async update(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdatePostDto,
|
||||||
|
@CurrentUser() user: any,
|
||||||
|
@Res() res: Response,
|
||||||
|
@Req() req: Request,
|
||||||
|
) {
|
||||||
|
const post = await this.blogPostsService.update(id, dto, user);
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: `Post "${post.title}" updated!` });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, post });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@Roles(UserRole.ADMIN)
|
||||||
|
async remove(@Param('id') id: string, @Res() res: Response, @Req() req: Request) {
|
||||||
|
await this.blogPostsService.remove(id);
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: 'Post deleted.' });
|
||||||
|
}
|
||||||
|
return res.json({ success: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/blog-posts/blog-posts.module.ts
Normal file
14
src/blog-posts/blog-posts.module.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { BlogPost } from './entities/blog-post.entity';
|
||||||
|
import { User } from '../users/entities/user.entity';
|
||||||
|
import { BlogPostsController } from './blog-posts.controller';
|
||||||
|
import { BlogPostsService } from './blog-posts.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([BlogPost, User])],
|
||||||
|
controllers: [BlogPostsController],
|
||||||
|
providers: [BlogPostsService],
|
||||||
|
exports: [BlogPostsService],
|
||||||
|
})
|
||||||
|
export class BlogPostsModule {}
|
||||||
150
src/blog-posts/blog-posts.service.spec.ts
Normal file
150
src/blog-posts/blog-posts.service.spec.ts
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { NotFoundException } from '@nestjs/common';
|
||||||
|
import { BlogPostsService } from './blog-posts.service';
|
||||||
|
import { BlogPost, PostStatus, ContentFormat } from './entities/blog-post.entity';
|
||||||
|
import { UserRole } from '../users/entities/user.entity';
|
||||||
|
|
||||||
|
const mockPost: Partial<BlogPost> = {
|
||||||
|
id: 'post-uuid-1',
|
||||||
|
title: 'Test Post',
|
||||||
|
slug: 'test-post-abc',
|
||||||
|
status: PostStatus.PUBLISHED,
|
||||||
|
excerpt: 'A test post',
|
||||||
|
content: '# Test',
|
||||||
|
contentFormat: ContentFormat.MARKDOWN,
|
||||||
|
authorId: 'user-1',
|
||||||
|
isFeatured: false,
|
||||||
|
views: 100,
|
||||||
|
tags: ['test'],
|
||||||
|
categories: ['Testing'],
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockQueryBuilder = {
|
||||||
|
leftJoin: jest.fn().mockReturnThis(),
|
||||||
|
leftJoinAndSelect: jest.fn().mockReturnThis(),
|
||||||
|
addSelect: jest.fn().mockReturnThis(),
|
||||||
|
select: jest.fn().mockReturnThis(),
|
||||||
|
where: jest.fn().mockReturnThis(),
|
||||||
|
andWhere: jest.fn().mockReturnThis(),
|
||||||
|
orderBy: jest.fn().mockReturnThis(),
|
||||||
|
addOrderBy: jest.fn().mockReturnThis(),
|
||||||
|
skip: jest.fn().mockReturnThis(),
|
||||||
|
take: jest.fn().mockReturnThis(),
|
||||||
|
getCount: jest.fn().mockResolvedValue(1),
|
||||||
|
getMany: jest.fn().mockResolvedValue([mockPost]),
|
||||||
|
getOne: jest.fn().mockResolvedValue(mockPost),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockRepo = {
|
||||||
|
createQueryBuilder: jest.fn().mockReturnValue(mockQueryBuilder),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
find: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
increment: jest.fn(),
|
||||||
|
remove: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('BlogPostsService', () => {
|
||||||
|
let service: BlogPostsService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
BlogPostsService,
|
||||||
|
{ provide: getRepositoryToken(BlogPost), useValue: mockRepo },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<BlogPostsService>(BlogPostsService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
mockRepo.createQueryBuilder.mockReturnValue(mockQueryBuilder);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findPublished', () => {
|
||||||
|
it('should return paginated published posts', async () => {
|
||||||
|
const result = await service.findPublished({});
|
||||||
|
expect(result.items).toHaveLength(1);
|
||||||
|
expect(result.total).toBe(1);
|
||||||
|
expect(mockQueryBuilder.where).toHaveBeenCalledWith(
|
||||||
|
'post.status = :status',
|
||||||
|
{ status: PostStatus.PUBLISHED },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findBySlug', () => {
|
||||||
|
it('should return published post by slug', async () => {
|
||||||
|
mockQueryBuilder.getOne.mockResolvedValue(mockPost);
|
||||||
|
const post = await service.findBySlug('test-post-abc');
|
||||||
|
expect(post.slug).toBe('test-post-abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException for draft post', async () => {
|
||||||
|
mockQueryBuilder.getOne.mockResolvedValue({ ...mockPost, status: PostStatus.DRAFT });
|
||||||
|
await expect(service.findBySlug('test-post-abc')).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException for non-existent slug', async () => {
|
||||||
|
mockQueryBuilder.getOne.mockResolvedValue(null);
|
||||||
|
await expect(service.findBySlug('nonexistent')).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create', () => {
|
||||||
|
const adminUser = { sub: 'user-1', role: UserRole.ADMIN };
|
||||||
|
const managerUser = { sub: 'user-2', role: UserRole.MANAGER };
|
||||||
|
|
||||||
|
it('ADMIN can create published post', async () => {
|
||||||
|
mockRepo.create.mockReturnValue({ ...mockPost });
|
||||||
|
mockRepo.save.mockResolvedValue({ ...mockPost, status: PostStatus.PUBLISHED });
|
||||||
|
|
||||||
|
const result = await service.create(
|
||||||
|
{ title: 'New Post', content: 'Content', status: PostStatus.PUBLISHED },
|
||||||
|
adminUser,
|
||||||
|
);
|
||||||
|
expect(mockRepo.save).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('MANAGER is forced to draft', async () => {
|
||||||
|
mockRepo.create.mockImplementation((data) => ({ ...data }));
|
||||||
|
mockRepo.save.mockImplementation((data) => Promise.resolve(data));
|
||||||
|
|
||||||
|
const result = await service.create(
|
||||||
|
{ title: 'Manager Post', content: 'Content', status: PostStatus.PUBLISHED },
|
||||||
|
managerUser,
|
||||||
|
);
|
||||||
|
expect(mockRepo.create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ status: PostStatus.DRAFT }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('incrementViews', () => {
|
||||||
|
it('should increment post views', async () => {
|
||||||
|
mockRepo.increment.mockResolvedValue({});
|
||||||
|
await service.incrementViews('test-post-abc');
|
||||||
|
expect(mockRepo.increment).toHaveBeenCalledWith(
|
||||||
|
{ slug: 'test-post-abc' },
|
||||||
|
'views',
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove', () => {
|
||||||
|
it('should remove a post', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue(mockPost);
|
||||||
|
mockRepo.remove.mockResolvedValue({});
|
||||||
|
await service.remove('post-uuid-1');
|
||||||
|
expect(mockRepo.remove).toHaveBeenCalledWith(mockPost);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException for non-existent post', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue(null);
|
||||||
|
await expect(service.remove('nonexistent')).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
284
src/blog-posts/blog-posts.service.ts
Normal file
284
src/blog-posts/blog-posts.service.ts
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
import { BlogPost, PostStatus } from './entities/blog-post.entity';
|
||||||
|
import { UserRole } from '../users/entities/user.entity';
|
||||||
|
import { CreatePostDto } from './dto/create-post.dto';
|
||||||
|
import { UpdatePostDto } from './dto/update-post.dto';
|
||||||
|
import { ListPostsQueryDto } from './dto/list-posts-query.dto';
|
||||||
|
import { generateSlug } from '../common/helpers/slug.helper';
|
||||||
|
|
||||||
|
// Safe author columns — never include passwordHash
|
||||||
|
const AUTHOR_COLS: string[] = [
|
||||||
|
'author.id',
|
||||||
|
'author.email',
|
||||||
|
'author.name',
|
||||||
|
'author.role',
|
||||||
|
'author.isActive',
|
||||||
|
'author.createdAt',
|
||||||
|
];
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class BlogPostsService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(BlogPost)
|
||||||
|
private readonly postRepo: Repository<BlogPost>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ─── Public (published) posts ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
async findPublished(query: ListPostsQueryDto) {
|
||||||
|
const page = parseInt(query.page || '1', 10);
|
||||||
|
const pageSize = parseInt(query.pageSize || '9', 10);
|
||||||
|
|
||||||
|
const qb = this.postRepo
|
||||||
|
.createQueryBuilder('post')
|
||||||
|
.leftJoin('post.author', 'author')
|
||||||
|
.addSelect(AUTHOR_COLS)
|
||||||
|
.where('post.status = :status', { status: PostStatus.PUBLISHED });
|
||||||
|
|
||||||
|
if (query.q) {
|
||||||
|
qb.andWhere(
|
||||||
|
'(post.title ILIKE :q OR post.excerpt ILIKE :q)',
|
||||||
|
{ q: `%${query.q}%` },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Support comma-separated tags (from HTMX filter form: name="tags")
|
||||||
|
if (query.tags) {
|
||||||
|
const tagList = query.tags.split(',').map((t) => t.trim()).filter(Boolean);
|
||||||
|
tagList.forEach((tag, i) => {
|
||||||
|
qb.andWhere(`post.tags LIKE :tag${i}`, { [`tag${i}`]: `%${tag}%` });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query.category) {
|
||||||
|
qb.andWhere('post.categories LIKE :cat', { cat: `%${query.category}%` });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort options matching the home page template values
|
||||||
|
switch (query.sort) {
|
||||||
|
case 'oldest':
|
||||||
|
qb.orderBy('post.createdAt', 'ASC');
|
||||||
|
break;
|
||||||
|
case 'most_viewed':
|
||||||
|
qb.orderBy('post.views', 'DESC');
|
||||||
|
break;
|
||||||
|
case 'featured':
|
||||||
|
qb.orderBy('post.isFeatured', 'DESC').addOrderBy('post.createdAt', 'DESC');
|
||||||
|
break;
|
||||||
|
default: // 'newest' or undefined
|
||||||
|
qb.orderBy('post.createdAt', 'DESC');
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = await qb.getCount();
|
||||||
|
const posts = await qb.skip((page - 1) * pageSize).take(pageSize).getMany();
|
||||||
|
|
||||||
|
return {
|
||||||
|
items: posts,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages: Math.ceil(total / pageSize),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async findFeatured(limit = 3) {
|
||||||
|
return this.postRepo
|
||||||
|
.createQueryBuilder('post')
|
||||||
|
.leftJoin('post.author', 'author')
|
||||||
|
.addSelect(AUTHOR_COLS)
|
||||||
|
.where('post.status = :status', { status: PostStatus.PUBLISHED })
|
||||||
|
.andWhere('post.isFeatured = true')
|
||||||
|
.orderBy('post.createdAt', 'DESC')
|
||||||
|
.take(limit)
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
async findPopular(limit = 5) {
|
||||||
|
return this.postRepo
|
||||||
|
.createQueryBuilder('post')
|
||||||
|
.where('post.status = :status', { status: PostStatus.PUBLISHED })
|
||||||
|
.orderBy('post.views', 'DESC')
|
||||||
|
.take(limit)
|
||||||
|
.select(['post.slug', 'post.title', 'post.views'])
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
|
||||||
|
async findRelated(post: BlogPost, limit = 4) {
|
||||||
|
const qb = this.postRepo
|
||||||
|
.createQueryBuilder('p')
|
||||||
|
.where('p.status = :status', { status: PostStatus.PUBLISHED })
|
||||||
|
.andWhere('p.id != :id', { id: post.id })
|
||||||
|
.orderBy('p.createdAt', 'DESC')
|
||||||
|
.take(limit);
|
||||||
|
|
||||||
|
// Prefer posts sharing at least one category or tag
|
||||||
|
const cats = (post.categories || []).filter(Boolean);
|
||||||
|
const tags = (post.tags || []).filter(Boolean);
|
||||||
|
|
||||||
|
if (cats.length > 0) {
|
||||||
|
qb.andWhere(
|
||||||
|
'(' + cats.map((_, i) => `p.categories LIKE :rc${i}`).join(' OR ') + ')',
|
||||||
|
Object.fromEntries(cats.map((c, i) => [`rc${i}`, `%${c}%`])),
|
||||||
|
);
|
||||||
|
} else if (tags.length > 0) {
|
||||||
|
qb.andWhere(
|
||||||
|
'(' + tags.map((_, i) => `p.tags LIKE :rt${i}`).join(' OR ') + ')',
|
||||||
|
Object.fromEntries(tags.map((t, i) => [`rt${i}`, `%${t}%`])),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await qb.getMany();
|
||||||
|
// Fallback: if nothing related, return latest posts
|
||||||
|
if (results.length === 0) {
|
||||||
|
return this.postRepo
|
||||||
|
.createQueryBuilder('p')
|
||||||
|
.where('p.status = :status', { status: PostStatus.PUBLISHED })
|
||||||
|
.andWhere('p.id != :id', { id: post.id })
|
||||||
|
.orderBy('p.createdAt', 'DESC')
|
||||||
|
.take(limit)
|
||||||
|
.getMany();
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findBySlug(slug: string): Promise<BlogPost> {
|
||||||
|
const post = await this.postRepo
|
||||||
|
.createQueryBuilder('post')
|
||||||
|
.leftJoin('post.author', 'author')
|
||||||
|
.addSelect(AUTHOR_COLS)
|
||||||
|
.where('post.slug = :slug', { slug })
|
||||||
|
.getOne();
|
||||||
|
|
||||||
|
if (!post || post.status !== PostStatus.PUBLISHED) {
|
||||||
|
throw new NotFoundException('Post not found');
|
||||||
|
}
|
||||||
|
return post;
|
||||||
|
}
|
||||||
|
|
||||||
|
async incrementViews(slug: string) {
|
||||||
|
await this.postRepo.increment({ slug }, 'views', 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Admin / authenticated ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async findAll(query: ListPostsQueryDto, user: any) {
|
||||||
|
const page = parseInt(query.page || '1', 10);
|
||||||
|
const pageSize = parseInt(query.pageSize || '20', 10);
|
||||||
|
const qb = this.postRepo
|
||||||
|
.createQueryBuilder('post')
|
||||||
|
.leftJoin('post.author', 'author')
|
||||||
|
.addSelect(AUTHOR_COLS);
|
||||||
|
|
||||||
|
if (user.role !== UserRole.ADMIN) {
|
||||||
|
qb.where('post.authorId = :uid', { uid: user.sub });
|
||||||
|
}
|
||||||
|
if (query.status) {
|
||||||
|
qb.andWhere('post.status = :status', { status: query.status });
|
||||||
|
}
|
||||||
|
if (query.q) {
|
||||||
|
qb.andWhere('post.title ILIKE :q', { q: `%${query.q}%` });
|
||||||
|
}
|
||||||
|
|
||||||
|
qb.orderBy('post.createdAt', 'DESC');
|
||||||
|
const total = await qb.getCount();
|
||||||
|
const posts = await qb.skip((page - 1) * pageSize).take(pageSize).getMany();
|
||||||
|
|
||||||
|
return { posts, total, page, pageSize, totalPages: Math.ceil(total / pageSize) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(dto: CreatePostDto, user: any): Promise<BlogPost> {
|
||||||
|
let status = dto.status || PostStatus.DRAFT;
|
||||||
|
// MANAGER can only create drafts
|
||||||
|
if (user.role === UserRole.MANAGER) {
|
||||||
|
status = PostStatus.DRAFT;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use provided slug or generate from title
|
||||||
|
const slug = dto.slug ? dto.slug.trim() : generateSlug(dto.title);
|
||||||
|
|
||||||
|
const post = this.postRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
title: dto.title,
|
||||||
|
slug,
|
||||||
|
status,
|
||||||
|
excerpt: dto.excerpt || '',
|
||||||
|
content: dto.content,
|
||||||
|
contentFormat: dto.contentFormat,
|
||||||
|
authorId: user.sub,
|
||||||
|
featuredImageUrl: dto.featuredImageUrl,
|
||||||
|
featuredImageAlt: dto.featuredImageAlt,
|
||||||
|
isFeatured: dto.isFeatured || false,
|
||||||
|
tags: dto.tags || [],
|
||||||
|
categories: dto.categories || [],
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.postRepo.save(post);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, dto: UpdatePostDto, user: any): Promise<BlogPost> {
|
||||||
|
const post = await this.postRepo.findOne({ where: { id } });
|
||||||
|
if (!post) throw new NotFoundException('Post not found');
|
||||||
|
|
||||||
|
// Regenerate slug if title changed and no explicit slug provided
|
||||||
|
if (dto.title && dto.title !== post.title && !dto.slug) {
|
||||||
|
(dto as any).slug = generateSlug(dto.title);
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.assign(post, dto);
|
||||||
|
return this.postRepo.save(post);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: string): Promise<void> {
|
||||||
|
const post = await this.postRepo.findOne({ where: { id } });
|
||||||
|
if (!post) throw new NotFoundException('Post not found');
|
||||||
|
await this.postRepo.remove(post);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Tag cloud ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getTagCloud(): Promise<Array<{ name: string; count: number }>> {
|
||||||
|
const posts = await this.postRepo.find({
|
||||||
|
where: { status: PostStatus.PUBLISHED },
|
||||||
|
select: ['tags'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const counts: Record<string, number> = {};
|
||||||
|
for (const post of posts) {
|
||||||
|
for (const tag of post.tags || []) {
|
||||||
|
const t = tag.trim();
|
||||||
|
if (t) counts[t] = (counts[t] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.entries(counts)
|
||||||
|
.map(([name, count]) => ({ name, count }))
|
||||||
|
.sort((a, b) => b.count - a.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Category cloud ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async getCategoryCloud(): Promise<Array<{ name: string; count: number }>> {
|
||||||
|
const posts = await this.postRepo.find({
|
||||||
|
where: { status: PostStatus.PUBLISHED },
|
||||||
|
select: ['categories'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const counts: Record<string, number> = {};
|
||||||
|
for (const post of posts) {
|
||||||
|
for (const cat of post.categories || []) {
|
||||||
|
const c = cat.trim();
|
||||||
|
if (c) counts[c] = (counts[c] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.entries(counts)
|
||||||
|
.map(([name, count]) => ({ name, count }))
|
||||||
|
.sort((a, b) => b.count - a.count);
|
||||||
|
}
|
||||||
|
}
|
||||||
78
src/blog-posts/dto/create-post.dto.ts
Normal file
78
src/blog-posts/dto/create-post.dto.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { Transform } from 'class-transformer';
|
||||||
|
import {
|
||||||
|
IsBoolean,
|
||||||
|
IsEnum,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MaxLength,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { ContentFormat, PostStatus } from '../entities/blog-post.entity';
|
||||||
|
|
||||||
|
/** Parse "true"/"false" strings into a real boolean */
|
||||||
|
function transformBoolean({ value }: { value: unknown }): boolean | undefined {
|
||||||
|
if (value === 'true' || value === true) return true;
|
||||||
|
if (value === 'false' || value === false) return false;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a comma-separated string OR an array into a trimmed string[] */
|
||||||
|
function transformCSV({ value }: { value: unknown }): string[] {
|
||||||
|
if (Array.isArray(value)) return (value as unknown[]).map((v) => String(v).trim()).filter(Boolean);
|
||||||
|
if (typeof value === 'string') return value.split(',').map((s) => s.trim()).filter(Boolean);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreatePostDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(255)
|
||||||
|
title: string;
|
||||||
|
|
||||||
|
/** Optional custom slug; if omitted the service generates one from the title */
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
@MaxLength(300)
|
||||||
|
slug?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
excerpt?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
content: string;
|
||||||
|
|
||||||
|
@IsEnum(ContentFormat)
|
||||||
|
@IsOptional()
|
||||||
|
contentFormat?: ContentFormat;
|
||||||
|
|
||||||
|
@IsEnum(PostStatus)
|
||||||
|
@IsOptional()
|
||||||
|
status?: PostStatus;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
featuredImageUrl?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
featuredImageAlt?: string;
|
||||||
|
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(transformBoolean)
|
||||||
|
isFeatured?: boolean;
|
||||||
|
|
||||||
|
/** Accepts a comma-separated string "tag1,tag2" or a plain string[] */
|
||||||
|
@IsString({ each: true })
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(transformCSV)
|
||||||
|
tags?: string[];
|
||||||
|
|
||||||
|
/** Accepts a comma-separated string "cat1,cat2" or a plain string[] */
|
||||||
|
@IsString({ each: true })
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(transformCSV)
|
||||||
|
categories?: string[];
|
||||||
|
}
|
||||||
37
src/blog-posts/dto/list-posts-query.dto.ts
Normal file
37
src/blog-posts/dto/list-posts-query.dto.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { IsEnum, IsNumberString, IsOptional, IsString } from 'class-validator';
|
||||||
|
import { PostStatus } from '../entities/blog-post.entity';
|
||||||
|
|
||||||
|
export class ListPostsQueryDto {
|
||||||
|
@IsNumberString()
|
||||||
|
@IsOptional()
|
||||||
|
page?: string;
|
||||||
|
|
||||||
|
@IsNumberString()
|
||||||
|
@IsOptional()
|
||||||
|
pageSize?: string;
|
||||||
|
|
||||||
|
/** Full-text search on title + excerpt */
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
q?: string;
|
||||||
|
|
||||||
|
/** Comma-separated tags e.g. "nestjs,htmx" */
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
tags?: string;
|
||||||
|
|
||||||
|
/** Single category filter */
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
category?: string;
|
||||||
|
|
||||||
|
/** Sort order: newest | oldest | most_viewed | featured */
|
||||||
|
@IsEnum(['newest', 'oldest', 'most_viewed', 'featured'])
|
||||||
|
@IsOptional()
|
||||||
|
sort?: string;
|
||||||
|
|
||||||
|
/** Admin/manager status filter */
|
||||||
|
@IsEnum(PostStatus)
|
||||||
|
@IsOptional()
|
||||||
|
status?: PostStatus;
|
||||||
|
}
|
||||||
4
src/blog-posts/dto/update-post.dto.ts
Normal file
4
src/blog-posts/dto/update-post.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import { PartialType } from '@nestjs/mapped-types';
|
||||||
|
import { CreatePostDto } from './create-post.dto';
|
||||||
|
|
||||||
|
export class UpdatePostDto extends PartialType(CreatePostDto) {}
|
||||||
82
src/blog-posts/entities/blog-post.entity.ts
Normal file
82
src/blog-posts/entities/blog-post.entity.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { User } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
export enum PostStatus {
|
||||||
|
DRAFT = 'draft',
|
||||||
|
PUBLISHED = 'published',
|
||||||
|
ARCHIVED = 'archived',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum ContentFormat {
|
||||||
|
MARKDOWN = 'markdown',
|
||||||
|
HTML = 'html',
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity('blog_posts')
|
||||||
|
export class BlogPost {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ length: 255 })
|
||||||
|
title: string;
|
||||||
|
|
||||||
|
@Column({ length: 300, nullable: true, unique: true })
|
||||||
|
slug: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 20, default: PostStatus.DRAFT })
|
||||||
|
status: PostStatus;
|
||||||
|
|
||||||
|
@Column({ type: 'text', default: '' })
|
||||||
|
excerpt: string;
|
||||||
|
|
||||||
|
@Column({ type: 'text' })
|
||||||
|
content: string;
|
||||||
|
|
||||||
|
@Column({ name: 'content_format', type: 'varchar', length: 20, default: ContentFormat.MARKDOWN })
|
||||||
|
contentFormat: ContentFormat;
|
||||||
|
|
||||||
|
@Column({ name: 'author_id' })
|
||||||
|
authorId: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, { onDelete: 'RESTRICT' })
|
||||||
|
@JoinColumn({ name: 'author_id' })
|
||||||
|
author: User;
|
||||||
|
|
||||||
|
@Column({ name: 'featured_image_url', length: 500, nullable: true })
|
||||||
|
featuredImageUrl: string;
|
||||||
|
|
||||||
|
@Column({ name: 'featured_image_alt', length: 255, nullable: true })
|
||||||
|
featuredImageAlt: string;
|
||||||
|
|
||||||
|
@Column({ name: 'is_featured', default: false })
|
||||||
|
isFeatured: boolean;
|
||||||
|
|
||||||
|
@Column({ default: 0 })
|
||||||
|
views: number;
|
||||||
|
|
||||||
|
@Column({ type: 'simple-array', default: '' })
|
||||||
|
tags: string[];
|
||||||
|
|
||||||
|
@Column({ type: 'simple-array', default: '' })
|
||||||
|
categories: string[];
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
|
||||||
|
updatedAt: Date;
|
||||||
|
|
||||||
|
/** Virtual getter — templates use `post.featuredImage.url` and `post.featuredImage.alt` */
|
||||||
|
get featuredImage(): { url: string; alt: string } | null {
|
||||||
|
if (!this.featuredImageUrl) return null;
|
||||||
|
return { url: this.featuredImageUrl, alt: this.featuredImageAlt || '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/common/decorators/current-user.decorator.ts
Normal file
9
src/common/decorators/current-user.decorator.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const CurrentUser = createParamDecorator(
|
||||||
|
(data: string | undefined, ctx: ExecutionContext) => {
|
||||||
|
const request = ctx.switchToHttp().getRequest();
|
||||||
|
const user = request.user;
|
||||||
|
return data ? user?.[data] : user;
|
||||||
|
},
|
||||||
|
);
|
||||||
4
src/common/decorators/public.decorator.ts
Normal file
4
src/common/decorators/public.decorator.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const IS_PUBLIC_KEY = 'isPublic';
|
||||||
|
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||||
5
src/common/decorators/roles.decorator.ts
Normal file
5
src/common/decorators/roles.decorator.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
import { UserRole } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
export const ROLES_KEY = 'roles';
|
||||||
|
export const Roles = (...roles: UserRole[]) => SetMetadata(ROLES_KEY, roles);
|
||||||
51
src/common/filters/all-exceptions.filter.ts
Normal file
51
src/common/filters/all-exceptions.filter.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import {
|
||||||
|
ArgumentsHost,
|
||||||
|
Catch,
|
||||||
|
ExceptionFilter,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
|
Logger,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
|
||||||
|
@Catch()
|
||||||
|
export class AllExceptionsFilter implements ExceptionFilter {
|
||||||
|
private readonly logger = new Logger(AllExceptionsFilter.name);
|
||||||
|
|
||||||
|
catch(exception: unknown, host: ArgumentsHost) {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const req = ctx.getRequest<Request>();
|
||||||
|
const res = ctx.getResponse<Response>();
|
||||||
|
|
||||||
|
let status = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
let message = 'Internal server error';
|
||||||
|
|
||||||
|
if (exception instanceof HttpException) {
|
||||||
|
status = exception.getStatus();
|
||||||
|
const responseBody = exception.getResponse();
|
||||||
|
if (typeof responseBody === 'string') {
|
||||||
|
message = responseBody;
|
||||||
|
} else if (typeof responseBody === 'object' && responseBody !== null) {
|
||||||
|
const body = responseBody as any;
|
||||||
|
message = body.message || body.error || message;
|
||||||
|
if (Array.isArray(message)) {
|
||||||
|
message = message[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (exception instanceof Error) {
|
||||||
|
message = exception.message;
|
||||||
|
this.logger.error(exception.message, exception.stack);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
|
||||||
|
if (isHtmx) {
|
||||||
|
res.status(status).render('partials/flash', { type: 'error', message });
|
||||||
|
} else {
|
||||||
|
res.status(status).json({
|
||||||
|
success: false,
|
||||||
|
error: { code: status, message },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
56
src/common/guards/jwt-auth.guard.ts
Normal file
56
src/common/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import {
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||||
|
import { verifyAccessToken } from '../helpers/jwt.helper';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtAuthGuard {
|
||||||
|
constructor(
|
||||||
|
private reflector: Reflector,
|
||||||
|
private configService: ConfigService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass(),
|
||||||
|
]);
|
||||||
|
if (isPublic) return true;
|
||||||
|
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const token = this.extractToken(request);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
const isHtmx = request.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) throw new UnauthorizedException('Please log in to continue');
|
||||||
|
throw new UnauthorizedException('Missing authentication token');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const secret = this.configService.get<string>('JWT_ACCESS_SECRET');
|
||||||
|
const payload = verifyAccessToken(token, secret);
|
||||||
|
request.user = payload;
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Invalid or expired token');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractToken(request: any): string | null {
|
||||||
|
// Check Authorization header
|
||||||
|
const authHeader = request.headers?.authorization as string;
|
||||||
|
if (authHeader?.startsWith('Bearer ')) {
|
||||||
|
return authHeader.substring(7);
|
||||||
|
}
|
||||||
|
// Check cookie
|
||||||
|
if (request.cookies?.accessToken) {
|
||||||
|
return request.cookies.accessToken;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
44
src/common/guards/roles.guard.ts
Normal file
44
src/common/guards/roles.guard.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
ForbiddenException,
|
||||||
|
Injectable,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||||
|
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';
|
||||||
|
import { UserRole } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RolesGuard implements CanActivate {
|
||||||
|
constructor(private reflector: Reflector) {}
|
||||||
|
|
||||||
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass(),
|
||||||
|
]);
|
||||||
|
if (isPublic) return true;
|
||||||
|
|
||||||
|
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
||||||
|
context.getHandler(),
|
||||||
|
context.getClass(),
|
||||||
|
]);
|
||||||
|
if (!requiredRoles || requiredRoles.length === 0) return true;
|
||||||
|
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const user = request.user;
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
throw new ForbiddenException('Access denied');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!requiredRoles.includes(user.role)) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
`Access denied. Required roles: ${requiredRoles.join(', ')}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
46
src/common/helpers/jwt.helper.ts
Normal file
46
src/common/helpers/jwt.helper.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import * as crypto from 'crypto';
|
||||||
|
import * as jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
|
export interface AccessTokenPayload {
|
||||||
|
sub: string;
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
type: 'access';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RefreshTokenPayload {
|
||||||
|
sub: string;
|
||||||
|
type: 'refresh';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function signAccessToken(
|
||||||
|
payload: Omit<AccessTokenPayload, 'type'>,
|
||||||
|
secret: string,
|
||||||
|
expiresIn: string,
|
||||||
|
): string {
|
||||||
|
return jwt.sign({ ...payload, type: 'access' }, secret, { expiresIn } as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function signRefreshToken(
|
||||||
|
payload: Omit<RefreshTokenPayload, 'type'>,
|
||||||
|
secret: string,
|
||||||
|
expiresIn: string,
|
||||||
|
): string {
|
||||||
|
return jwt.sign({ ...payload, type: 'refresh' }, secret, { expiresIn } as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyAccessToken(token: string, secret: string): AccessTokenPayload {
|
||||||
|
return jwt.verify(token, secret) as AccessTokenPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function verifyRefreshToken(token: string, secret: string): RefreshTokenPayload {
|
||||||
|
return jwt.verify(token, secret) as RefreshTokenPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hashToken(raw: string): string {
|
||||||
|
return crypto.createHash('sha256').update(raw).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateRawToken(): string {
|
||||||
|
return crypto.randomBytes(48).toString('hex');
|
||||||
|
}
|
||||||
45
src/common/helpers/mailer.helper.ts
Normal file
45
src/common/helpers/mailer.helper.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import * as nodemailer from 'nodemailer';
|
||||||
|
|
||||||
|
export interface MailOptions {
|
||||||
|
to: string;
|
||||||
|
subject: string;
|
||||||
|
html: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let transporter: nodemailer.Transporter | null = null;
|
||||||
|
|
||||||
|
function getTransporter(): nodemailer.Transporter {
|
||||||
|
if (transporter) return transporter;
|
||||||
|
|
||||||
|
const host = process.env.SMTP_HOST;
|
||||||
|
if (!host) {
|
||||||
|
// Console fallback for development
|
||||||
|
transporter = nodemailer.createTransport({ jsonTransport: true });
|
||||||
|
return transporter;
|
||||||
|
}
|
||||||
|
|
||||||
|
transporter = nodemailer.createTransport({
|
||||||
|
host,
|
||||||
|
port: parseInt(process.env.SMTP_PORT || '587', 10),
|
||||||
|
auth: {
|
||||||
|
user: process.env.SMTP_USER,
|
||||||
|
pass: process.env.SMTP_PASS,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return transporter;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function sendMail(options: MailOptions): Promise<void> {
|
||||||
|
const from = process.env.MAIL_FROM || 'no-reply@blog.local';
|
||||||
|
const t = getTransporter();
|
||||||
|
|
||||||
|
if (!process.env.SMTP_HOST) {
|
||||||
|
console.log('[MAIL CONSOLE FALLBACK]');
|
||||||
|
console.log(` TO: ${options.to}`);
|
||||||
|
console.log(` SUBJECT: ${options.subject}`);
|
||||||
|
console.log(` BODY: ${options.html}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await t.sendMail({ from, ...options });
|
||||||
|
}
|
||||||
14
src/common/helpers/slug.helper.ts
Normal file
14
src/common/helpers/slug.helper.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
|
||||||
|
export function generateSlug(title: string): string {
|
||||||
|
const base = title
|
||||||
|
.toLowerCase()
|
||||||
|
.trim()
|
||||||
|
.replace(/[^\w\s-]/g, '')
|
||||||
|
.replace(/\s+/g, '-')
|
||||||
|
.replace(/-+/g, '-')
|
||||||
|
.substring(0, 200);
|
||||||
|
|
||||||
|
const suffix = uuidv4().split('-')[0]; // 8-char UUID segment
|
||||||
|
return `${base}-${suffix}`;
|
||||||
|
}
|
||||||
55
src/common/middleware/csrf.middleware.ts
Normal file
55
src/common/middleware/csrf.middleware.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { ForbiddenException, Injectable, NestMiddleware } from '@nestjs/common';
|
||||||
|
import { NextFunction, Request, Response } from 'express';
|
||||||
|
import * as crypto from 'crypto';
|
||||||
|
|
||||||
|
const EXEMPT_PATHS = [
|
||||||
|
'/auth/login',
|
||||||
|
'/auth/register',
|
||||||
|
'/auth/magic-link',
|
||||||
|
'/auth/refresh',
|
||||||
|
'/auth/google',
|
||||||
|
'/auth/google/callback',
|
||||||
|
'/auth/password-reset',
|
||||||
|
'/health',
|
||||||
|
];
|
||||||
|
|
||||||
|
const STATE_CHANGING_METHODS = ['POST', 'PATCH', 'PUT', 'DELETE'];
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CsrfMiddleware implements NestMiddleware {
|
||||||
|
use(req: Request, res: Response, next: NextFunction) {
|
||||||
|
// Read or generate CSRF token
|
||||||
|
let csrfToken: string = req.cookies?.csrfToken;
|
||||||
|
if (!csrfToken) {
|
||||||
|
csrfToken = crypto.randomBytes(24).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set as non-httpOnly cookie so JS can read it
|
||||||
|
res.cookie('csrfToken', csrfToken, {
|
||||||
|
httpOnly: false,
|
||||||
|
sameSite: 'lax',
|
||||||
|
secure: process.env.COOKIE_SECURE === 'true',
|
||||||
|
});
|
||||||
|
|
||||||
|
(req as any).csrfToken = csrfToken;
|
||||||
|
|
||||||
|
// Validate on state-changing methods
|
||||||
|
if (STATE_CHANGING_METHODS.includes(req.method)) {
|
||||||
|
const isExempt = EXEMPT_PATHS.some((p) => req.path.startsWith(p));
|
||||||
|
if (!isExempt) {
|
||||||
|
const hasCookieAuth =
|
||||||
|
req.cookies?.accessToken || req.cookies?.refreshToken;
|
||||||
|
if (hasCookieAuth) {
|
||||||
|
const tokenFromHeader = req.headers['x-csrf-token'] as string;
|
||||||
|
const tokenFromBody = (req.body as any)?._csrf;
|
||||||
|
const provided = tokenFromHeader || tokenFromBody;
|
||||||
|
if (!provided || provided !== csrfToken) {
|
||||||
|
throw new ForbiddenException('Invalid CSRF token');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
}
|
||||||
131
src/config/env.validation.ts
Normal file
131
src/config/env.validation.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import { plainToClass, Transform } from 'class-transformer';
|
||||||
|
import { IsEnum, IsNotEmpty, IsNumber, IsOptional, IsString, validateSync } from 'class-validator';
|
||||||
|
|
||||||
|
enum Environment {
|
||||||
|
Development = 'development',
|
||||||
|
Production = 'production',
|
||||||
|
Test = 'test',
|
||||||
|
}
|
||||||
|
|
||||||
|
class EnvironmentVariables {
|
||||||
|
@IsEnum(Environment)
|
||||||
|
@IsOptional()
|
||||||
|
NODE_ENV: Environment = Environment.Development;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
HOST: string = '0.0.0.0';
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(({ value }) => parseInt(value, 10))
|
||||||
|
PORT: number = 3000;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
APP_URL: string = 'http://localhost:3000';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
DB_HOST: string;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(({ value }) => parseInt(value, 10))
|
||||||
|
DB_PORT: number = 5432;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
DB_USER: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
DB_PASSWORD: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
DB_NAME: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
DB_SSL: string = 'false';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
JWT_ACCESS_SECRET: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
JWT_REFRESH_SECRET: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
JWT_ACCESS_EXPIRES_IN: string = '15m';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
JWT_REFRESH_EXPIRES_IN: string = '7d';
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(({ value }) => parseInt(value, 10))
|
||||||
|
MAGIC_LINK_TTL_MINUTES: number = 20;
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(({ value }) => parseInt(value, 10))
|
||||||
|
PASSWORD_RESET_TTL_MINUTES: number = 30;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
COOKIE_SECURE: string = 'false';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
COOKIE_DOMAIN: string = '';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
MAIL_FROM: string = 'no-reply@blog.local';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
SMTP_HOST: string = '';
|
||||||
|
|
||||||
|
@IsNumber()
|
||||||
|
@IsOptional()
|
||||||
|
@Transform(({ value }) => parseInt(value, 10))
|
||||||
|
SMTP_PORT: number = 587;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
SMTP_USER: string = '';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
SMTP_PASS: string = '';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
GOOGLE_CLIENT_ID: string = '';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
GOOGLE_CLIENT_SECRET: string = '';
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
GOOGLE_CALLBACK_URL: string = 'http://localhost:3000/auth/google/callback';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validate(config: Record<string, unknown>) {
|
||||||
|
const validatedConfig = plainToClass(EnvironmentVariables, config, {
|
||||||
|
enableImplicitConversion: true,
|
||||||
|
});
|
||||||
|
const errors = validateSync(validatedConfig, { skipMissingProperties: false });
|
||||||
|
|
||||||
|
if (errors.length > 0) {
|
||||||
|
throw new Error(errors.toString());
|
||||||
|
}
|
||||||
|
return validatedConfig;
|
||||||
|
}
|
||||||
65
src/main.ts
Normal file
65
src/main.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { join } from 'path';
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const cookieParser = require('cookie-parser');
|
||||||
|
import * as nunjucks from 'nunjucks';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||||
|
|
||||||
|
// ─── Static assets ──────────────────────────────────────────────────────────
|
||||||
|
app.useStaticAssets(join(process.cwd(), 'public'));
|
||||||
|
|
||||||
|
// ─── Nunjucks view engine ────────────────────────────────────────────────────
|
||||||
|
// process.cwd() is always the project root, regardless of __dirname in dist/
|
||||||
|
const viewsDir = join(process.cwd(), 'src', 'views');
|
||||||
|
app.setBaseViewsDir(viewsDir);
|
||||||
|
app.setViewEngine('njk');
|
||||||
|
|
||||||
|
const nunjucksEnv = nunjucks.configure(viewsDir, {
|
||||||
|
autoescape: true,
|
||||||
|
throwOnUndefined: false,
|
||||||
|
watch: process.env.NODE_ENV === 'development',
|
||||||
|
express: app.getHttpAdapter().getInstance(),
|
||||||
|
});
|
||||||
|
|
||||||
|
nunjucksEnv.addFilter('urlencode', (s: string) => encodeURIComponent(s ?? ''));
|
||||||
|
nunjucksEnv.addFilter('truncate', (s: string, len: number) => {
|
||||||
|
if (!s) return '';
|
||||||
|
return s.length > len ? s.substring(0, len) + '...' : s;
|
||||||
|
});
|
||||||
|
nunjucksEnv.addFilter('date', (d: Date | string, fmt?: string) => {
|
||||||
|
if (!d) return '';
|
||||||
|
const date = new Date(d);
|
||||||
|
return date.toLocaleDateString('en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
nunjucksEnv.addGlobal('appName', 'Duc Binh Blog');
|
||||||
|
nunjucksEnv.addGlobal('year', new Date().getFullYear());
|
||||||
|
|
||||||
|
// ─── Middleware ──────────────────────────────────────────────────────────────
|
||||||
|
app.use(cookieParser());
|
||||||
|
|
||||||
|
// ─── Global pipes ────────────────────────────────────────────────────────────
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
forbidNonWhitelisted: false,
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ─── Start ───────────────────────────────────────────────────────────────────
|
||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
const host = process.env.HOST || '0.0.0.0';
|
||||||
|
await app.listen(port, host);
|
||||||
|
console.log(`🚀 Server running at http://${host}:${port}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
bootstrap();
|
||||||
149
src/pages/pages.controller.ts
Normal file
149
src/pages/pages.controller.ts
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { BlogPostsService } from '../blog-posts/blog-posts.service';
|
||||||
|
import { UsersService } from '../users/users.service';
|
||||||
|
import { Public } from '../common/decorators/public.decorator';
|
||||||
|
import { marked } from 'marked';
|
||||||
|
|
||||||
|
@Controller()
|
||||||
|
export class PagesController {
|
||||||
|
constructor(
|
||||||
|
private readonly blogPostsService: BlogPostsService,
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get('health')
|
||||||
|
@Public()
|
||||||
|
health() {
|
||||||
|
return { status: 'ok', timestamp: new Date().toISOString() };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Home page ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@Public()
|
||||||
|
async home(@Req() req: Request, @Res() res: Response, @Query() rawQuery: Record<string, string>) {
|
||||||
|
const currentUser = (req as any).user || null;
|
||||||
|
|
||||||
|
// Determine query params with defaults
|
||||||
|
const query = {
|
||||||
|
q: rawQuery.q || '',
|
||||||
|
tags: rawQuery.tags || '',
|
||||||
|
category: rawQuery.category || '',
|
||||||
|
sort: rawQuery.sort || 'newest',
|
||||||
|
page: rawQuery.page || '1',
|
||||||
|
pageSize: rawQuery.pageSize || '9',
|
||||||
|
};
|
||||||
|
|
||||||
|
const [featured, postsResult, topTags, topCategories, popularPosts] = await Promise.all([
|
||||||
|
this.blogPostsService.findFeatured(3),
|
||||||
|
this.blogPostsService.findPublished(query),
|
||||||
|
this.blogPostsService.getTagCloud(),
|
||||||
|
this.blogPostsService.getCategoryCloud(),
|
||||||
|
this.blogPostsService.findPopular(5),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return res.render('pages/home', {
|
||||||
|
title: 'Duc Binh Blog',
|
||||||
|
currentUser,
|
||||||
|
featured,
|
||||||
|
// home.njk does {% set result = posts %} then includes post-grid.njk
|
||||||
|
// so `posts` must be the result shape { items, page, pageSize, total, totalPages }
|
||||||
|
posts: postsResult,
|
||||||
|
query,
|
||||||
|
topTags: topTags.slice(0, 20),
|
||||||
|
topCategories: topCategories.slice(0, 10),
|
||||||
|
popularPosts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Blog detail ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get('blog/:slug')
|
||||||
|
@Public()
|
||||||
|
async blogDetail(
|
||||||
|
@Param('slug') slug: string,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
const post = await this.blogPostsService.findBySlug(slug);
|
||||||
|
// Increment views
|
||||||
|
await this.blogPostsService.incrementViews(slug);
|
||||||
|
|
||||||
|
const contentHtml =
|
||||||
|
post.contentFormat === 'markdown'
|
||||||
|
? await marked(post.content)
|
||||||
|
: post.content;
|
||||||
|
|
||||||
|
const currentUser = (req as any).user || null;
|
||||||
|
|
||||||
|
const [relatedPosts, popularPosts, topTags] = await Promise.all([
|
||||||
|
this.blogPostsService.findRelated(post, 4),
|
||||||
|
this.blogPostsService.findPopular(5),
|
||||||
|
this.blogPostsService.getTagCloud(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return res.render('pages/blog-detail', {
|
||||||
|
title: post.title,
|
||||||
|
currentUser,
|
||||||
|
post,
|
||||||
|
contentHtml,
|
||||||
|
relatedPosts,
|
||||||
|
popularPosts,
|
||||||
|
topTags: topTags.slice(0, 20),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Auth page ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get('auth')
|
||||||
|
@Public()
|
||||||
|
async authPage(
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
@Query('token') resetToken?: string,
|
||||||
|
) {
|
||||||
|
// If already logged in, redirect to dashboard
|
||||||
|
if ((req as any).user) {
|
||||||
|
return res.redirect('/dashboard');
|
||||||
|
}
|
||||||
|
return res.render('pages/auth', {
|
||||||
|
title: 'Sign In — Duc Binh Blog',
|
||||||
|
currentUser: null,
|
||||||
|
resetToken: resetToken || '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Dashboard ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get('dashboard')
|
||||||
|
async dashboard(@Req() req: Request, @Res() res: Response) {
|
||||||
|
const currentUser = (req as any).user;
|
||||||
|
const [postsResult, usersResult] = await Promise.all([
|
||||||
|
this.blogPostsService.findAll({ page: '1', pageSize: '10' }, currentUser),
|
||||||
|
currentUser.role === 'ADMIN'
|
||||||
|
? this.usersService.findAll(1, 10)
|
||||||
|
: Promise.resolve(null),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return res.render('pages/dashboard', {
|
||||||
|
title: 'Dashboard — Duc Binh Blog',
|
||||||
|
currentUser,
|
||||||
|
// dashboard-post-table.njk uses `posts` directly (flat array)
|
||||||
|
posts: postsResult.posts,
|
||||||
|
postsPagination: {
|
||||||
|
page: postsResult.page,
|
||||||
|
totalPages: postsResult.totalPages,
|
||||||
|
total: postsResult.total,
|
||||||
|
},
|
||||||
|
users: usersResult?.users || null,
|
||||||
|
usersPagination: usersResult
|
||||||
|
? {
|
||||||
|
page: usersResult.page,
|
||||||
|
totalPages: usersResult.totalPages,
|
||||||
|
total: usersResult.total,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/pages/pages.module.ts
Normal file
10
src/pages/pages.module.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { BlogPostsModule } from '../blog-posts/blog-posts.module';
|
||||||
|
import { UsersModule } from '../users/users.module';
|
||||||
|
import { PagesController } from './pages.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [BlogPostsModule, UsersModule],
|
||||||
|
controllers: [PagesController],
|
||||||
|
})
|
||||||
|
export class PagesModule {}
|
||||||
37
src/tokens/entities/magic-link-token.entity.ts
Normal file
37
src/tokens/entities/magic-link-token.entity.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { User } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
@Entity('magic_link_tokens')
|
||||||
|
export class MagicLinkToken {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'user_id', nullable: true })
|
||||||
|
userId: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, { onDelete: 'SET NULL', nullable: true })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user: User;
|
||||||
|
|
||||||
|
@Column({ length: 255 })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@Column({ name: 'token_hash', length: 255, unique: true })
|
||||||
|
tokenHash: string;
|
||||||
|
|
||||||
|
@Column({ name: 'expires_at', type: 'timestamptz' })
|
||||||
|
expiresAt: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'consumed_at', type: 'timestamptz', nullable: true })
|
||||||
|
consumedAt: Date;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
40
src/tokens/entities/oauth-account.entity.ts
Normal file
40
src/tokens/entities/oauth-account.entity.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
Unique,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { User } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
@Entity('oauth_accounts')
|
||||||
|
@Unique('uq_oauth_provider_provider_id', ['provider', 'providerId'])
|
||||||
|
export class OAuthAccount {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'user_id' })
|
||||||
|
userId: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user: User;
|
||||||
|
|
||||||
|
@Column({ length: 50 })
|
||||||
|
provider: string;
|
||||||
|
|
||||||
|
@Column({ name: 'provider_id', length: 255 })
|
||||||
|
providerId: string;
|
||||||
|
|
||||||
|
@Column({ length: 255, nullable: true })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
34
src/tokens/entities/password-reset-token.entity.ts
Normal file
34
src/tokens/entities/password-reset-token.entity.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { User } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
@Entity('password_reset_tokens')
|
||||||
|
export class PasswordResetToken {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'user_id' })
|
||||||
|
userId: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user: User;
|
||||||
|
|
||||||
|
@Column({ name: 'token_hash', length: 255, unique: true })
|
||||||
|
tokenHash: string;
|
||||||
|
|
||||||
|
@Column({ name: 'expires_at', type: 'timestamptz' })
|
||||||
|
expiresAt: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'consumed_at', type: 'timestamptz', nullable: true })
|
||||||
|
consumedAt: Date;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
47
src/tokens/entities/refresh-token.entity.ts
Normal file
47
src/tokens/entities/refresh-token.entity.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
JoinColumn,
|
||||||
|
ManyToOne,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { User } from '../../users/entities/user.entity';
|
||||||
|
|
||||||
|
@Entity('refresh_tokens')
|
||||||
|
export class RefreshToken {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ name: 'user_id' })
|
||||||
|
userId: string;
|
||||||
|
|
||||||
|
@ManyToOne(() => User, { onDelete: 'CASCADE' })
|
||||||
|
@JoinColumn({ name: 'user_id' })
|
||||||
|
user: User;
|
||||||
|
|
||||||
|
@Column({ name: 'token_hash', length: 255, unique: true })
|
||||||
|
tokenHash: string;
|
||||||
|
|
||||||
|
@Column({ name: 'expires_at', type: 'timestamptz' })
|
||||||
|
expiresAt: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'revoked_at', type: 'timestamptz', nullable: true })
|
||||||
|
revokedAt: Date;
|
||||||
|
|
||||||
|
@Column({ name: 'replaced_by_token_hash', nullable: true })
|
||||||
|
replacedByTokenHash: string;
|
||||||
|
|
||||||
|
@Column({ name: 'user_agent', type: 'text', nullable: true })
|
||||||
|
userAgent: string;
|
||||||
|
|
||||||
|
@Column({ name: 'ip', length: 64, nullable: true })
|
||||||
|
ip: string;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
19
src/tokens/tokens.module.ts
Normal file
19
src/tokens/tokens.module.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { RefreshToken } from './entities/refresh-token.entity';
|
||||||
|
import { MagicLinkToken } from './entities/magic-link-token.entity';
|
||||||
|
import { PasswordResetToken } from './entities/password-reset-token.entity';
|
||||||
|
import { OAuthAccount } from './entities/oauth-account.entity';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
TypeOrmModule.forFeature([
|
||||||
|
RefreshToken,
|
||||||
|
MagicLinkToken,
|
||||||
|
PasswordResetToken,
|
||||||
|
OAuthAccount,
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
exports: [TypeOrmModule],
|
||||||
|
})
|
||||||
|
export class TokensModule {}
|
||||||
20
src/users/dto/create-user.dto.ts
Normal file
20
src/users/dto/create-user.dto.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { IsEmail, IsEnum, IsOptional, IsString, MinLength } from 'class-validator';
|
||||||
|
import { UserRole } from '../entities/user.entity';
|
||||||
|
|
||||||
|
export class CreateUserDto {
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
@IsEnum(UserRole)
|
||||||
|
@IsOptional()
|
||||||
|
role?: UserRole;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(8)
|
||||||
|
@IsOptional()
|
||||||
|
password?: string;
|
||||||
|
}
|
||||||
8
src/users/dto/update-user-name.dto.ts
Normal file
8
src/users/dto/update-user-name.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { IsOptional, IsString, MaxLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateUserNameDto {
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(120)
|
||||||
|
@IsOptional()
|
||||||
|
name?: string;
|
||||||
|
}
|
||||||
7
src/users/dto/update-user-role.dto.ts
Normal file
7
src/users/dto/update-user-role.dto.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { IsEnum } from 'class-validator';
|
||||||
|
import { UserRole } from '../entities/user.entity';
|
||||||
|
|
||||||
|
export class UpdateUserRoleDto {
|
||||||
|
@IsEnum(UserRole)
|
||||||
|
role: UserRole;
|
||||||
|
}
|
||||||
41
src/users/entities/user.entity.ts
Normal file
41
src/users/entities/user.entity.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
OneToMany,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
export enum UserRole {
|
||||||
|
ADMIN = 'ADMIN',
|
||||||
|
MANAGER = 'MANAGER',
|
||||||
|
MEMBER = 'MEMBER',
|
||||||
|
}
|
||||||
|
|
||||||
|
@Entity('users')
|
||||||
|
export class User {
|
||||||
|
@PrimaryGeneratedColumn('uuid')
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
@Column({ length: 255, unique: true })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@Column({ length: 120, nullable: true })
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 20, default: UserRole.MEMBER })
|
||||||
|
role: UserRole;
|
||||||
|
|
||||||
|
@Column({ name: 'password_hash', nullable: true })
|
||||||
|
passwordHash: string;
|
||||||
|
|
||||||
|
@Column({ name: 'is_active', default: true })
|
||||||
|
isActive: boolean;
|
||||||
|
|
||||||
|
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
91
src/users/users.controller.ts
Normal file
91
src/users/users.controller.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
Res,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
|
import { UpdateUserNameDto } from './dto/update-user-name.dto';
|
||||||
|
import { UpdateUserRoleDto } from './dto/update-user-role.dto';
|
||||||
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
|
import { UserRole } from './entities/user.entity';
|
||||||
|
|
||||||
|
@Controller('users')
|
||||||
|
@Roles(UserRole.ADMIN)
|
||||||
|
export class UsersController {
|
||||||
|
constructor(private readonly usersService: UsersService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
async findAll(
|
||||||
|
@Query('page') page = '1',
|
||||||
|
@Query('pageSize') pageSize = '20',
|
||||||
|
@Query('q') q?: string,
|
||||||
|
) {
|
||||||
|
return this.usersService.findAll(parseInt(page, 10), parseInt(pageSize, 10), q);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
async create(@Body() dto: CreateUserDto, @Req() req: Request, @Res() res: Response) {
|
||||||
|
const user = await this.usersService.create(dto);
|
||||||
|
const { passwordHash, ...safe } = user as any;
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: `User "${safe.email}" created!` });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, user: safe });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
async updateName(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateUserNameDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
const user = await this.usersService.updateName(id, dto);
|
||||||
|
const { passwordHash, ...safe } = user as any;
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: `User "${safe.email}" renamed.` });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, user: safe });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id/role')
|
||||||
|
async updateRole(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateUserRoleDto,
|
||||||
|
@Req() req: Request,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
const user = await this.usersService.updateRole(id, dto);
|
||||||
|
const { passwordHash, ...safe } = user as any;
|
||||||
|
const isHtmx = req.headers['hx-request'] === 'true';
|
||||||
|
if (isHtmx) {
|
||||||
|
return res.render('partials/flash', { type: 'success', message: `Role updated to ${safe.role}.` });
|
||||||
|
}
|
||||||
|
return res.json({ success: true, user: safe });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('partials/table')
|
||||||
|
async tablePartial(
|
||||||
|
@Query('page') page = '1',
|
||||||
|
@Query('pageSize') pageSize = '20',
|
||||||
|
@Query('q') q: string,
|
||||||
|
@Res() res: Response,
|
||||||
|
) {
|
||||||
|
const data = await this.usersService.findAll(
|
||||||
|
parseInt(page, 10),
|
||||||
|
parseInt(pageSize, 10),
|
||||||
|
q,
|
||||||
|
);
|
||||||
|
return res.render('partials/dashboard-user-table', { users: data.users });
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/users/users.module.ts
Normal file
13
src/users/users.module.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { User } from './entities/user.entity';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
import { UsersController } from './users.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [TypeOrmModule.forFeature([User])],
|
||||||
|
controllers: [UsersController],
|
||||||
|
providers: [UsersService],
|
||||||
|
exports: [UsersService],
|
||||||
|
})
|
||||||
|
export class UsersModule {}
|
||||||
91
src/users/users.service.spec.ts
Normal file
91
src/users/users.service.spec.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
import { User, UserRole } from './entities/user.entity';
|
||||||
|
|
||||||
|
const mockUser: Partial<User> = {
|
||||||
|
id: 'uuid-1',
|
||||||
|
email: 'test@test.com',
|
||||||
|
name: 'Test User',
|
||||||
|
role: UserRole.MEMBER,
|
||||||
|
isActive: true,
|
||||||
|
passwordHash: 'hash',
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockRepo = {
|
||||||
|
findAndCount: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
save: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('UsersService', () => {
|
||||||
|
let service: UsersService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
UsersService,
|
||||||
|
{ provide: getRepositoryToken(User), useValue: mockRepo },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<UsersService>(UsersService);
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findAll', () => {
|
||||||
|
it('should return paginated users', async () => {
|
||||||
|
mockRepo.findAndCount.mockResolvedValue([[mockUser], 1]);
|
||||||
|
const result = await service.findAll(1, 20);
|
||||||
|
expect(result.users).toHaveLength(1);
|
||||||
|
expect(result.total).toBe(1);
|
||||||
|
expect(result.totalPages).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findById', () => {
|
||||||
|
it('should return user by id', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue(mockUser);
|
||||||
|
const user = await service.findById('uuid-1');
|
||||||
|
expect(user.id).toBe('uuid-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException for unknown id', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue(null);
|
||||||
|
await expect(service.findById('unknown')).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create', () => {
|
||||||
|
it('should create a new user', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue(null); // no existing user
|
||||||
|
mockRepo.create.mockReturnValue({ ...mockUser });
|
||||||
|
mockRepo.save.mockResolvedValue({ ...mockUser });
|
||||||
|
|
||||||
|
const result = await service.create({ email: 'new@test.com', password: 'password123' });
|
||||||
|
expect(mockRepo.save).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException for duplicate email', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue(mockUser); // existing user
|
||||||
|
await expect(
|
||||||
|
service.create({ email: mockUser.email, password: 'password123' }),
|
||||||
|
).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('updateRole', () => {
|
||||||
|
it('should update user role', async () => {
|
||||||
|
mockRepo.findOne.mockResolvedValue({ ...mockUser });
|
||||||
|
mockRepo.update.mockResolvedValue({});
|
||||||
|
mockRepo.findOne.mockResolvedValueOnce({ ...mockUser })
|
||||||
|
.mockResolvedValueOnce({ ...mockUser, role: UserRole.MANAGER });
|
||||||
|
|
||||||
|
const result = await service.updateRole('uuid-1', { role: UserRole.MANAGER });
|
||||||
|
expect(mockRepo.update).toHaveBeenCalledWith('uuid-1', { role: UserRole.MANAGER });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
96
src/users/users.service.ts
Normal file
96
src/users/users.service.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
|
import { ILike, Repository } from 'typeorm';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
import { User, UserRole } from './entities/user.entity';
|
||||||
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
|
import { UpdateUserNameDto } from './dto/update-user-name.dto';
|
||||||
|
import { UpdateUserRoleDto } from './dto/update-user-role.dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UsersService {
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(User)
|
||||||
|
private readonly userRepo: Repository<User>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async findAll(page = 1, pageSize = 20, q?: string) {
|
||||||
|
const where = q
|
||||||
|
? [{ email: ILike(`%${q}%`) }, { name: ILike(`%${q}%`) }]
|
||||||
|
: {};
|
||||||
|
|
||||||
|
const [users, total] = await this.userRepo.findAndCount({
|
||||||
|
where,
|
||||||
|
order: { createdAt: 'DESC' },
|
||||||
|
skip: (page - 1) * pageSize,
|
||||||
|
take: pageSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
users,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalPages: Math.ceil(total / pageSize),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async findById(id: string): Promise<User> {
|
||||||
|
const user = await this.userRepo.findOne({ where: { id } });
|
||||||
|
if (!user) throw new NotFoundException(`User ${id} not found`);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByEmail(email: string): Promise<User | null> {
|
||||||
|
return this.userRepo.findOne({ where: { email } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(dto: CreateUserDto): Promise<User> {
|
||||||
|
const existing = await this.findByEmail(dto.email);
|
||||||
|
if (existing) throw new ConflictException('Email already in use');
|
||||||
|
|
||||||
|
const user = this.userRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
email: dto.email,
|
||||||
|
name: dto.name,
|
||||||
|
role: dto.role || UserRole.MEMBER,
|
||||||
|
passwordHash: dto.password ? await bcrypt.hash(dto.password, 12) : null,
|
||||||
|
});
|
||||||
|
return this.userRepo.save(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateName(id: string, dto: UpdateUserNameDto): Promise<User> {
|
||||||
|
await this.findById(id);
|
||||||
|
await this.userRepo.update(id, { name: dto.name });
|
||||||
|
return this.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateRole(id: string, dto: UpdateUserRoleDto): Promise<User> {
|
||||||
|
await this.findById(id);
|
||||||
|
await this.userRepo.update(id, { role: dto.role });
|
||||||
|
return this.findById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setPassword(id: string, password: string): Promise<void> {
|
||||||
|
const hash = await bcrypt.hash(password, 12);
|
||||||
|
await this.userRepo.update(id, { passwordHash: hash });
|
||||||
|
}
|
||||||
|
|
||||||
|
async upsertByEmail(
|
||||||
|
email: string,
|
||||||
|
data: Partial<Pick<User, 'name' | 'role' | 'passwordHash' | 'isActive'>>,
|
||||||
|
): Promise<User> {
|
||||||
|
let user = await this.findByEmail(email);
|
||||||
|
if (!user) {
|
||||||
|
user = this.userRepo.create({ id: uuidv4(), email, ...data });
|
||||||
|
} else {
|
||||||
|
Object.assign(user, data);
|
||||||
|
}
|
||||||
|
return this.userRepo.save(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
80
src/views/layouts/base.njk
Normal file
80
src/views/layouts/base.njk
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>{{ title or "Duc Binh Blog" }}</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&family=Source+Serif+4:wght@400;600;700&display=swap" rel="stylesheet" />
|
||||||
|
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
|
||||||
|
</head>
|
||||||
|
<body class="min-h-screen bg-gradient-to-b from-amber-50 via-stone-50 to-emerald-50 font-[Space_Grotesk] text-zinc-900 antialiased">
|
||||||
|
<div class="mx-auto w-full max-w-7xl px-4 pb-10 pt-4 sm:px-6 lg:px-8">
|
||||||
|
<header class="sticky top-3 z-20 mb-4 rounded-2xl border border-zinc-200/80 bg-white/90 shadow-sm backdrop-blur">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
|
||||||
|
<a class="inline-flex items-center gap-2 text-zinc-900 no-underline transition hover:text-teal-700" href="/">
|
||||||
|
<span class="inline-flex h-8 w-8 items-center justify-center rounded-full bg-teal-600 text-xs font-bold text-white">DB</span>
|
||||||
|
<span class="text-base font-semibold">Duc Binh Blog</span>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<nav class="flex flex-wrap items-center gap-2 text-sm">
|
||||||
|
<a class="rounded-full border border-zinc-200 bg-white px-3 py-1.5 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="/">Home</a>
|
||||||
|
{% if currentUser %}
|
||||||
|
<a class="rounded-full border border-zinc-200 bg-white px-3 py-1.5 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="/dashboard">Dashboard</a>
|
||||||
|
<form hx-post="/auth/logout" hx-target="#flash" hx-swap="innerHTML" class="m-0">
|
||||||
|
<button class="rounded-full border border-rose-200 bg-white px-3 py-1.5 text-sm font-medium text-rose-700 transition hover:bg-rose-50" type="submit">Logout</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<a class="rounded-full border border-zinc-200 bg-white px-3 py-1.5 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="/auth">Auth</a>
|
||||||
|
{% endif %}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="space-y-4">
|
||||||
|
{% block body %}{% endblock %}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="flash" class="pointer-events-none fixed right-4 top-4 z-50 flex w-[min(26rem,calc(100%-2rem))] flex-col gap-2">
|
||||||
|
{% include "partials/flash.njk" %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function readCookie(name) {
|
||||||
|
const cookie = document.cookie
|
||||||
|
.split(";")
|
||||||
|
.map((entry) => entry.trim())
|
||||||
|
.find((entry) => entry.startsWith(name + "="));
|
||||||
|
return cookie ? decodeURIComponent(cookie.split("=").slice(1).join("=")) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
document.body.addEventListener("htmx:configRequest", function(event) {
|
||||||
|
const csrfToken = readCookie("csrfToken");
|
||||||
|
if (csrfToken) {
|
||||||
|
event.detail.headers["x-csrf-token"] = csrfToken;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.refreshDashboardPosts = function() {
|
||||||
|
if (document.querySelector("#dashboard-posts-table")) {
|
||||||
|
htmx.ajax("GET", "/blog-posts/partials/table", {
|
||||||
|
target: "#dashboard-posts-table",
|
||||||
|
swap: "innerHTML"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.refreshDashboardUsers = function() {
|
||||||
|
if (document.querySelector("#dashboard-users-table")) {
|
||||||
|
htmx.ajax("GET", "/users/partials/table?page=1&pageSize=50", {
|
||||||
|
target: "#dashboard-users-table",
|
||||||
|
swap: "innerHTML"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
23
src/views/layouts/dashboard.njk
Normal file
23
src/views/layouts/dashboard.njk
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
{% extends "layouts/base.njk" %}
|
||||||
|
|
||||||
|
{% block body %}
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm sm:p-5">
|
||||||
|
<div class="grid items-start gap-4 lg:grid-cols-[15rem_minmax(0,1fr)]">
|
||||||
|
<aside class="rounded-xl border border-zinc-200 bg-amber-50 p-4">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-xl font-semibold text-zinc-900">Control Panel</h3>
|
||||||
|
<p class="mt-1 text-sm text-zinc-600">Role: <span class="font-semibold text-zinc-800">{{ currentUser.role }}</span></p>
|
||||||
|
<nav class="mt-4 grid gap-2 text-sm">
|
||||||
|
<a class="rounded-lg border border-zinc-200 bg-white px-3 py-2 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="#profile">Profile</a>
|
||||||
|
<a class="rounded-lg border border-zinc-200 bg-white px-3 py-2 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="#posts">Posts</a>
|
||||||
|
{% if currentUser.role == "ADMIN" %}
|
||||||
|
<a class="rounded-lg border border-zinc-200 bg-white px-3 py-2 font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700" href="#users">Users</a>
|
||||||
|
{% endif %}
|
||||||
|
</nav>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="space-y-4">
|
||||||
|
{% block dashboardBody %}{% endblock %}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
200
src/views/pages/auth.njk
Normal file
200
src/views/pages/auth.njk
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
{% extends "layouts/base.njk" %}
|
||||||
|
|
||||||
|
{% block body %}
|
||||||
|
<div class="mx-auto w-full max-w-[42rem] space-y-5">
|
||||||
|
<section id="auth-tabs" data-initial-tab="{% if resetToken %}reset{% else %}signin{% endif %}" class="rounded-[2rem] border border-zinc-200 bg-zinc-50 p-6 shadow-sm sm:p-8">
|
||||||
|
<p class="text-center text-xs font-medium tracking-[0.5em] text-slate-500">SIGN IN TO CONTINUE</p>
|
||||||
|
|
||||||
|
<div class="mt-6 grid grid-cols-3 gap-1 rounded-full bg-zinc-200 p-1.5">
|
||||||
|
<button type="button" data-tab-button data-tab="signin" class="rounded-full px-3 py-3 text-center text-sm font-semibold text-slate-500 transition">Sign In</button>
|
||||||
|
<button type="button" data-tab-button data-tab="signup" class="rounded-full px-3 py-3 text-center text-sm font-semibold text-slate-500 transition">Sign Up</button>
|
||||||
|
<button type="button" data-tab-button data-tab="reset" class="rounded-full px-3 py-3 text-center text-sm font-semibold text-slate-500 transition">Reset Password</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section data-tab-panel="signin" class="mt-7 space-y-4">
|
||||||
|
<form hx-post="/auth/login" hx-target="#flash" hx-swap="innerHTML" class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label for="login-email" class="mb-2 block text-sm font-semibold text-slate-700">Email address</label>
|
||||||
|
<input id="login-email" name="email" type="email" placeholder="name@email.com" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="login-password" class="mb-2 block text-sm font-semibold text-slate-700">Password</label>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input id="login-password" name="password" type="password" placeholder="Enter your password" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
<button type="button" data-toggle-password data-target="login-password" class="rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-white">Show</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="w-full rounded-2xl bg-blue-600 px-4 py-3 text-lg font-semibold text-white transition hover:bg-blue-700">Sign In</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="magic-link-form" hx-post="/auth/magic-link" hx-target="#flash" hx-swap="innerHTML">
|
||||||
|
<input id="magic-link-email" type="hidden" name="email" value="" />
|
||||||
|
<button type="submit" class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-lg font-semibold text-zinc-500 transition hover:bg-white hover:text-zinc-700">Send magic link</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<a href="/auth/google" class="block w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-center text-lg font-semibold text-slate-700 no-underline transition hover:bg-white">Continue with Google</a>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section data-tab-panel="signup" class="mt-7 hidden space-y-4">
|
||||||
|
<form hx-post="/auth/register" hx-target="#flash" hx-swap="innerHTML" class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label for="signup-name" class="mb-2 block text-sm font-semibold text-slate-700">Name</label>
|
||||||
|
<input id="signup-name" name="name" placeholder="Your full name" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="signup-email" class="mb-2 block text-sm font-semibold text-slate-700">Email address</label>
|
||||||
|
<input id="signup-email" name="email" type="email" placeholder="name@email.com" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="signup-password" class="mb-2 block text-sm font-semibold text-slate-700">Password</label>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input id="signup-password" name="password" type="password" placeholder="Create a password" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
<button type="button" data-toggle-password data-target="signup-password" class="rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-white">Show</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="w-full rounded-2xl bg-blue-600 px-4 py-3 text-lg font-semibold text-white transition hover:bg-blue-700">Create Account</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p class="rounded-2xl border border-blue-100 bg-blue-50 px-4 py-3 text-sm text-blue-700">New sign-ups are assigned the default <strong>MEMBER</strong> role.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section data-tab-panel="reset" class="mt-7 hidden space-y-4">
|
||||||
|
<form hx-post="/auth/password-reset/request" hx-target="#flash" hx-swap="innerHTML" class="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label for="reset-email" class="mb-2 block text-sm font-semibold text-slate-700">Email address</label>
|
||||||
|
<input id="reset-email" name="email" type="email" placeholder="name@email.com" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-lg font-semibold text-zinc-700 transition hover:bg-white">Request reset token</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form hx-post="/auth/password-reset/confirm" hx-target="#flash" hx-swap="innerHTML" class="space-y-4 rounded-2xl border border-zinc-200 bg-white p-4">
|
||||||
|
<p class="text-sm font-semibold text-slate-700">Confirm reset</p>
|
||||||
|
<input name="token" placeholder="Reset token" value="{{ resetToken }}" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input id="reset-password" name="password" type="password" placeholder="New password" required class="w-full rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-base text-zinc-800 placeholder:text-zinc-400 focus:border-blue-500 focus:bg-white focus:outline-none" />
|
||||||
|
<button type="button" data-toggle-password data-target="reset-password" class="rounded-2xl border border-zinc-300 bg-zinc-100 px-4 py-3 text-sm font-semibold text-slate-600 transition hover:bg-white">Show</button>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="w-full rounded-2xl bg-blue-600 px-4 py-3 text-lg font-semibold text-white transition hover:bg-blue-700">Update password</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-3xl border border-zinc-200 bg-zinc-50 p-6 shadow-sm">
|
||||||
|
<div class="rounded-2xl border border-zinc-200 bg-zinc-100 p-4">
|
||||||
|
<h2 class="text-2xl font-semibold text-slate-800">Default Admin Account</h2>
|
||||||
|
<p class="mt-2 text-lg text-slate-700">Email: <strong>admin@gmail.com</strong></p>
|
||||||
|
<p class="text-lg text-slate-700">Password: <strong>Whatever123$</strong></p>
|
||||||
|
<button type="button" data-try-login data-demo-email="admin@gmail.com" data-demo-password="Whatever123$" class="mt-3 rounded-xl border border-blue-200 bg-blue-50 px-4 py-2 text-sm font-semibold text-blue-700 transition hover:bg-blue-100">Use these credentials</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ul class="mt-4 list-disc space-y-1 pl-5 text-zinc-700">
|
||||||
|
<li><strong>Sign in with the credentials above to access an <span class="font-bold text-red-600">ADMIN</span> account.</strong></li>
|
||||||
|
<li><strong>New sign-ups are assigned the default <span class="font-bold text-blue-600">MEMBER</span> role.</strong></li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<h3 class="mt-5 text-2xl font-bold text-zinc-800">Role Permissions Overview</h3>
|
||||||
|
|
||||||
|
<div class="mt-4 space-y-4 text-zinc-700">
|
||||||
|
<section>
|
||||||
|
<h4 class="text-xl font-bold text-blue-600">MEMBER</h4>
|
||||||
|
<ul class="list-disc space-y-1 pl-5">
|
||||||
|
<li>Can view the list of blog posts only.</li>
|
||||||
|
<li>No permission to create, edit, or delete posts.</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h4 class="text-xl font-bold text-amber-600">MANAGER</h4>
|
||||||
|
<ul class="list-disc space-y-1 pl-5">
|
||||||
|
<li>Can view all blog posts.</li>
|
||||||
|
<li>Can create new blog posts.</li>
|
||||||
|
<li>Newly created posts are always saved as Draft by default.</li>
|
||||||
|
<li>Cannot update or delete any post.</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h4 class="text-xl font-bold text-red-600">ADMIN</h4>
|
||||||
|
<ul class="list-disc space-y-1 pl-5">
|
||||||
|
<li>Full access to the system.</li>
|
||||||
|
<li>Can create, read, update, and delete any blog post.</li>
|
||||||
|
<li>Can manage all content without restrictions.</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function() {
|
||||||
|
const container = document.getElementById("auth-tabs");
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
const buttons = Array.from(container.querySelectorAll("[data-tab-button]"));
|
||||||
|
const panels = Array.from(container.querySelectorAll("[data-tab-panel]"));
|
||||||
|
const magicLinkForm = document.getElementById("magic-link-form");
|
||||||
|
const magicLinkEmail = document.getElementById("magic-link-email");
|
||||||
|
|
||||||
|
function setActiveTab(tabName) {
|
||||||
|
buttons.forEach((button) => {
|
||||||
|
const isActive = button.getAttribute("data-tab") === tabName;
|
||||||
|
button.classList.toggle("bg-white", isActive);
|
||||||
|
button.classList.toggle("text-zinc-800", isActive);
|
||||||
|
button.classList.toggle("shadow-sm", isActive);
|
||||||
|
button.classList.toggle("text-slate-500", !isActive);
|
||||||
|
});
|
||||||
|
|
||||||
|
panels.forEach((panel) => {
|
||||||
|
panel.classList.toggle("hidden", panel.getAttribute("data-tab-panel") !== tabName);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const initialTab = container.getAttribute("data-initial-tab") || "signin";
|
||||||
|
setActiveTab(initialTab);
|
||||||
|
|
||||||
|
container.addEventListener("click", function(event) {
|
||||||
|
const tabButton = event.target.closest("[data-tab-button]");
|
||||||
|
if (!tabButton) return;
|
||||||
|
setActiveTab(tabButton.getAttribute("data-tab") || "signin");
|
||||||
|
});
|
||||||
|
|
||||||
|
if (magicLinkForm && magicLinkEmail) {
|
||||||
|
magicLinkForm.addEventListener("submit", function() {
|
||||||
|
const emailInput = document.getElementById("login-email");
|
||||||
|
magicLinkEmail.value = emailInput ? emailInput.value.trim() : "";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("click", function(event) {
|
||||||
|
const toggleButton = event.target.closest("[data-toggle-password]");
|
||||||
|
if (toggleButton) {
|
||||||
|
const targetId = toggleButton.getAttribute("data-target");
|
||||||
|
const input = targetId ? document.getElementById(targetId) : null;
|
||||||
|
if (input) {
|
||||||
|
const isPassword = input.getAttribute("type") === "password";
|
||||||
|
input.setAttribute("type", isPassword ? "text" : "password");
|
||||||
|
toggleButton.textContent = isPassword ? "Hide" : "Show";
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const demoButton = event.target.closest("[data-try-login]");
|
||||||
|
if (!demoButton) return;
|
||||||
|
|
||||||
|
const emailInput = document.getElementById("login-email");
|
||||||
|
const passwordInput = document.getElementById("login-password");
|
||||||
|
if (!emailInput || !passwordInput) return;
|
||||||
|
|
||||||
|
setActiveTab("signin");
|
||||||
|
emailInput.value = demoButton.getAttribute("data-demo-email") || "";
|
||||||
|
passwordInput.value = demoButton.getAttribute("data-demo-password") || "";
|
||||||
|
passwordInput.focus();
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
82
src/views/pages/blog-detail.njk
Normal file
82
src/views/pages/blog-detail.njk
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
{% extends "layouts/base.njk" %}
|
||||||
|
|
||||||
|
{% block body %}
|
||||||
|
<article class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">
|
||||||
|
<p class="text-sm font-medium uppercase tracking-wide text-zinc-500">{{ post.categories | join(", ") }}</p>
|
||||||
|
<h1 class="mt-2 font-[Source_Serif_4] text-4xl font-semibold leading-tight text-zinc-900">{{ post.title }}</h1>
|
||||||
|
<p class="mt-3 text-zinc-600">{{ post.excerpt }}</p>
|
||||||
|
|
||||||
|
{% if post.featuredImage %}
|
||||||
|
<img src="{{ post.featuredImage.url }}" alt="{{ post.featuredImage.alt }}" class="mt-4 w-full rounded-xl border border-zinc-200 object-cover" />
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="mt-4 flex flex-wrap gap-2">
|
||||||
|
{% for tag in post.tags %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-1 text-xs font-medium text-teal-700">#{{ tag }}</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="mt-3 text-sm text-zinc-500">Views: {{ post.views }}</p>
|
||||||
|
|
||||||
|
<div class="mt-5 space-y-4 text-zinc-700 [&_a]:text-teal-700 [&_a]:underline [&_blockquote]:border-l-4 [&_blockquote]:border-zinc-300 [&_blockquote]:pl-4 [&_h1]:font-[Source_Serif_4] [&_h1]:text-3xl [&_h1]:font-semibold [&_h2]:font-[Source_Serif_4] [&_h2]:text-2xl [&_h2]:font-semibold [&_h3]:font-[Source_Serif_4] [&_h3]:text-xl [&_h3]:font-semibold [&_li]:ml-5 [&_li]:list-disc [&_p]:leading-7">
|
||||||
|
{{ contentHtml | safe }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div hx-post="/blog-posts/public/{{ post.slug }}/view" hx-trigger="load" hx-swap="none"></div>
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<section class="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
|
||||||
|
<div class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">
|
||||||
|
<div class="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">More from the blog</h2>
|
||||||
|
<a class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white no-underline transition hover:bg-teal-700" href="/">Back to Home</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if relatedPosts and relatedPosts.length > 0 %}
|
||||||
|
<div class="grid gap-3 sm:grid-cols-2">
|
||||||
|
{% for related in relatedPosts %}
|
||||||
|
<article class="rounded-xl border border-zinc-200 bg-zinc-50/60 p-4">
|
||||||
|
<div class="mb-2 flex flex-wrap gap-1.5">
|
||||||
|
{% for cat in related.categories %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ cat }}</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<h3 class="font-[Source_Serif_4] text-xl font-semibold leading-tight text-zinc-900">
|
||||||
|
<a href="/blog/{{ related.slug }}" class="transition hover:text-teal-700">{{ related.title }}</a>
|
||||||
|
</h3>
|
||||||
|
<p class="mt-2 text-sm text-zinc-600">{{ related.excerpt }}</p>
|
||||||
|
<p class="mt-2 text-xs text-zinc-500">{{ related.views }} views</p>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="rounded-xl border border-zinc-200 bg-zinc-50 p-4">
|
||||||
|
<p class="text-sm text-zinc-600">No related posts yet. Try exploring tags and categories from the home page.</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="grid gap-4">
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Popular Posts</h3>
|
||||||
|
<div class="mt-3 grid gap-2">
|
||||||
|
{% for item in popularPosts %}
|
||||||
|
<a href="/blog/{{ item.slug }}" class="flex items-center justify-between rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700">
|
||||||
|
<span>{{ item.title }}</span>
|
||||||
|
<strong class="text-zinc-500">{{ item.views }}</strong>
|
||||||
|
</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Tags</h3>
|
||||||
|
<div class="mt-3 flex flex-wrap gap-2">
|
||||||
|
{% for tag in topTags %}
|
||||||
|
<a class="rounded-full border border-teal-200 bg-teal-50 px-2.5 py-1 text-xs font-medium text-teal-700 no-underline transition hover:border-teal-400 hover:bg-teal-100" href="/?tags={{ tag.name | urlencode }}">#{{ tag.name }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</aside>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
120
src/views/pages/dashboard.njk
Normal file
120
src/views/pages/dashboard.njk
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
{% extends "layouts/dashboard.njk" %}
|
||||||
|
|
||||||
|
{% block dashboardBody %}
|
||||||
|
<section id="profile" class="rounded-2xl border border-zinc-200 bg-gradient-to-r from-white via-white to-zinc-50 p-4 shadow-sm">
|
||||||
|
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">Profile</h2>
|
||||||
|
<div class="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<div class="rounded-lg border border-zinc-200 bg-white p-3">
|
||||||
|
<p class="text-xs uppercase tracking-wide text-zinc-500">Name</p>
|
||||||
|
<p class="mt-1 font-semibold text-zinc-900">{{ currentUser.name or "-" }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-lg border border-zinc-200 bg-white p-3">
|
||||||
|
<p class="text-xs uppercase tracking-wide text-zinc-500">Email</p>
|
||||||
|
<p class="mt-1 font-semibold text-zinc-900">{{ currentUser.email }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-lg border border-zinc-200 bg-white p-3">
|
||||||
|
<p class="text-xs uppercase tracking-wide text-zinc-500">Role</p>
|
||||||
|
<p class="mt-1 font-semibold text-zinc-900">{{ currentUser.role }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="posts" class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">Posts</h2>
|
||||||
|
<p class="text-sm text-zinc-500">{{ posts.length }} post{% if posts.length != 1 %}s{% endif %}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if currentUser.role == "ADMIN" or currentUser.role == "MANAGER" %}
|
||||||
|
<form
|
||||||
|
hx-post="/blog-posts"
|
||||||
|
hx-target="#flash"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-on::after-request="refreshDashboardPosts()"
|
||||||
|
class="mt-4 space-y-3 rounded-xl border border-zinc-200 bg-zinc-50/60 p-4"
|
||||||
|
>
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Create New Post</h3>
|
||||||
|
<span class="rounded-full border border-zinc-200 bg-white px-3 py-1 text-xs font-semibold uppercase tracking-wide text-zinc-500">Editor</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 md:grid-cols-2">
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="title" placeholder="Title" required />
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="slug" placeholder="Slug (optional)" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea class="min-h-20 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="excerpt" placeholder="Excerpt"></textarea>
|
||||||
|
<textarea class="min-h-36 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="content" placeholder="Content" required></textarea>
|
||||||
|
|
||||||
|
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<select name="contentFormat" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="markdown" selected>Markdown</option>
|
||||||
|
<option value="html">HTML</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
{% if currentUser.role == "ADMIN" %}
|
||||||
|
<select name="status" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="draft" selected>Draft</option>
|
||||||
|
<option value="published">Published</option>
|
||||||
|
<option value="archived">Archived</option>
|
||||||
|
</select>
|
||||||
|
<select name="isFeatured" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="false" selected>Not featured</option>
|
||||||
|
<option value="true">Featured</option>
|
||||||
|
</select>
|
||||||
|
{% else %}
|
||||||
|
<input type="hidden" name="status" value="draft" />
|
||||||
|
<input type="hidden" name="isFeatured" value="false" />
|
||||||
|
<p class="text-sm text-zinc-500">Status is forced to draft for manager accounts.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 md:grid-cols-2">
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="categories" placeholder="Categories: backend,api" />
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="tags" placeholder="Tags: rest,pagination" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 md:grid-cols-2">
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="featuredImageUrl" placeholder="Featured image URL (optional)" />
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="featuredImageAlt" placeholder="Featured image ALT (optional)" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<p class="text-xs text-zinc-500">Image URL + ALT will be saved into `featuredImage`. Leave URL empty to skip.</p>
|
||||||
|
<button class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Create post</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div id="dashboard-posts-table" class="mt-4">
|
||||||
|
{% include "partials/dashboard-post-table.njk" %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{% if currentUser.role == "ADMIN" %}
|
||||||
|
<section id="users" class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<h2 class="font-[Source_Serif_4] text-3xl font-semibold text-zinc-900">Users</h2>
|
||||||
|
<form
|
||||||
|
hx-post="/users"
|
||||||
|
hx-target="#flash"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-on::after-request="refreshDashboardUsers()"
|
||||||
|
class="mt-3 grid gap-2 lg:grid-cols-5"
|
||||||
|
>
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="name" placeholder="Name" required />
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="email" type="email" placeholder="Email" required />
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="password" type="password" placeholder="Password" required />
|
||||||
|
<select name="role" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="MEMBER" selected>MEMBER</option>
|
||||||
|
<option value="MANAGER">MANAGER</option>
|
||||||
|
<option value="ADMIN">ADMIN</option>
|
||||||
|
</select>
|
||||||
|
<button class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Create user</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="dashboard-users-table" class="mt-4">
|
||||||
|
{% include "partials/dashboard-user-table.njk" %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
160
src/views/pages/home.njk
Normal file
160
src/views/pages/home.njk
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
{% extends "layouts/base.njk" %}
|
||||||
|
|
||||||
|
{% block body %}
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm">
|
||||||
|
<div class="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
<div class="max-w-3xl">
|
||||||
|
<h1 class="font-[Source_Serif_4] text-4xl font-semibold leading-tight text-zinc-900">Practical Engineering Stories</h1>
|
||||||
|
<p class="mt-2 text-zinc-600">Fast backend patterns, frontend craft, and product lessons from shipping real systems.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap justify-end gap-2">
|
||||||
|
{% for c in topCategories %}
|
||||||
|
<button
|
||||||
|
class="rounded-full border border-zinc-200 bg-zinc-50 px-3 py-1.5 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700"
|
||||||
|
type="button"
|
||||||
|
hx-get="/blog-posts/partials/grid?page=1&pageSize={{ query.pageSize }}&q=&tags=&category={{ c.name | urlencode }}&sort={{ query.sort }}"
|
||||||
|
hx-target="#post-grid-container"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
>
|
||||||
|
{{ c.name }} ({{ c.count }})
|
||||||
|
</button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-gradient-to-r from-white via-sky-50 to-emerald-50 p-5 shadow-sm">
|
||||||
|
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)]">
|
||||||
|
{% if featured and featured.length > 0 %}
|
||||||
|
<article class="rounded-xl border border-dashed border-teal-200 bg-white/80 p-5">
|
||||||
|
<p class="mb-3 inline-flex items-center rounded-full border border-amber-200 bg-amber-50 px-2.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-amber-700">Featured pick</p>
|
||||||
|
<h2 class="font-[Source_Serif_4] text-3xl font-semibold leading-tight text-zinc-900">
|
||||||
|
<a href="/blog/{{ featured[0].slug }}" class="transition hover:text-teal-700">{{ featured[0].title }}</a>
|
||||||
|
</h2>
|
||||||
|
<p class="mt-3 text-zinc-600">{{ featured[0].excerpt }}</p>
|
||||||
|
<p class="mt-3 text-sm font-medium text-zinc-500">{{ featured[0].views }} views</p>
|
||||||
|
</article>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="grid gap-3">
|
||||||
|
{% for post in featured %}
|
||||||
|
{% if loop.index0 > 0 %}
|
||||||
|
<article class="rounded-xl border border-zinc-200 bg-white/80 p-4">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-xl font-semibold text-zinc-900">
|
||||||
|
<a href="/blog/{{ post.slug }}" class="transition hover:text-teal-700">{{ post.title }}</a>
|
||||||
|
</h3>
|
||||||
|
<p class="mt-2 text-sm text-zinc-600">{{ post.excerpt }}</p>
|
||||||
|
</article>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
|
||||||
|
<div>
|
||||||
|
<form
|
||||||
|
id="home-filter-form"
|
||||||
|
class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm"
|
||||||
|
hx-get="/blog-posts/partials/grid"
|
||||||
|
hx-target="#post-grid-container"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-trigger="submit, keyup changed delay:450ms from:#q, keyup changed delay:450ms from:#tags, change delay:150ms from:#category, change delay:150ms from:#sort"
|
||||||
|
>
|
||||||
|
<div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
|
||||||
|
<div class="md:col-span-2">
|
||||||
|
<label for="q" class="mb-1 block text-sm font-medium text-zinc-600">Search title + excerpt</label>
|
||||||
|
<input id="q" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="q" type="search" placeholder="Search posts" value="{{ query.q }}" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="category" class="mb-1 block text-sm font-medium text-zinc-600">Category</label>
|
||||||
|
<select id="category" name="category" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="">All</option>
|
||||||
|
{% for c in topCategories %}
|
||||||
|
<option value="{{ c.name }}" {% if query.category == c.name %}selected{% endif %}>{{ c.name }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="sort" class="mb-1 block text-sm font-medium text-zinc-600">Sort</label>
|
||||||
|
<select id="sort" name="sort" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="newest" {% if query.sort == "newest" %}selected{% endif %}>Newest</option>
|
||||||
|
<option value="oldest" {% if query.sort == "oldest" %}selected{% endif %}>Oldest</option>
|
||||||
|
<option value="most_viewed" {% if query.sort == "most_viewed" %}selected{% endif %}>Most viewed</option>
|
||||||
|
<option value="featured" {% if query.sort == "featured" %}selected{% endif %}>Featured first</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-3 grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
|
||||||
|
<div>
|
||||||
|
<label for="tags" class="mb-1 block text-sm font-medium text-zinc-600">Tags (comma separated)</label>
|
||||||
|
<input id="tags" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="tags" value="{{ query.tags }}" placeholder="nextjs, ui" />
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input type="hidden" name="page" value="1" />
|
||||||
|
<input type="hidden" name="pageSize" value="{{ query.pageSize }}" />
|
||||||
|
<button type="submit" class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700">Apply</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="post-grid-container" class="mt-4">
|
||||||
|
{% set result = posts %}
|
||||||
|
{% include "partials/post-grid.njk" %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside class="grid gap-4">
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Popular Posts</h3>
|
||||||
|
<div class="mt-3 grid gap-2">
|
||||||
|
{% for item in popularPosts %}
|
||||||
|
<a href="/blog/{{ item.slug }}" class="flex items-center justify-between rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700">
|
||||||
|
<span>{{ item.title }}</span>
|
||||||
|
<span class="text-zinc-500">{{ item.views }}</span>
|
||||||
|
</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Newsletter</h3>
|
||||||
|
<p class="mt-1 text-sm text-zinc-600">One practical note every Friday.</p>
|
||||||
|
<form hx-post="/auth/magic-link" hx-target="#flash" hx-swap="innerHTML" class="mt-3">
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" type="email" name="email" placeholder="you@example.com" required />
|
||||||
|
<button class="mt-2 w-full rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Join</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Tag Cloud</h3>
|
||||||
|
<div class="mt-3 flex flex-wrap gap-2">
|
||||||
|
{% for tag in topTags %}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-full border border-teal-200 bg-teal-50 px-2.5 py-1 text-xs font-medium text-teal-700 transition hover:border-teal-400 hover:bg-teal-100"
|
||||||
|
hx-get="/blog-posts/partials/grid?page=1&pageSize={{ query.pageSize }}&q=&tags={{ tag.name | urlencode }}&category=&sort={{ query.sort }}"
|
||||||
|
hx-target="#post-grid-container"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
>
|
||||||
|
#{{ tag.name }} ({{ tag.count }})
|
||||||
|
</button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-2xl border border-zinc-200 bg-gradient-to-r from-amber-50 to-orange-50 p-4 shadow-sm">
|
||||||
|
<h3 class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900">Ad Space</h3>
|
||||||
|
<p class="mt-1 text-sm text-zinc-600">Placeholder for sponsor content.</p>
|
||||||
|
</section>
|
||||||
|
</aside>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<footer class="rounded-2xl border border-zinc-200 bg-white p-4 text-center text-sm text-zinc-600 shadow-sm">
|
||||||
|
Built with Fastify + HTMX + Mongoose
|
||||||
|
</footer>
|
||||||
|
{% endblock %}
|
||||||
112
src/views/partials/dashboard-post-table.njk
Normal file
112
src/views/partials/dashboard-post-table.njk
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
{% if posts.length == 0 %}
|
||||||
|
<div class="rounded-xl border border-dashed border-zinc-300 bg-zinc-50 p-5 text-sm text-zinc-600">
|
||||||
|
No posts yet.
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="grid gap-4">
|
||||||
|
{% for post in posts %}
|
||||||
|
<article class="rounded-xl border border-zinc-200 bg-white p-4 shadow-sm">
|
||||||
|
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div class="space-y-1">
|
||||||
|
<a href="/blog/{{ post.slug }}" class="font-[Source_Serif_4] text-2xl font-semibold text-zinc-900 transition hover:text-teal-700">{{ post.title }}</a>
|
||||||
|
<p class="text-xs text-zinc-500">/{{ post.slug }}</p>
|
||||||
|
<div class="flex flex-wrap gap-2 pt-1">
|
||||||
|
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ post.status }}</span>
|
||||||
|
<span class="inline-flex items-center rounded-full border border-zinc-200 bg-zinc-100 px-2.5 py-0.5 text-xs font-medium text-zinc-600">{{ post.views }} views</span>
|
||||||
|
{% if post.isFeatured %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-amber-200 bg-amber-50 px-2.5 py-0.5 text-xs font-medium text-amber-700">featured</span>
|
||||||
|
{% endif %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-zinc-200 bg-zinc-50 px-2.5 py-0.5 text-xs font-medium text-zinc-600">Author: {{ post.author.name if post.author else "Unknown" }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="/blog/{{ post.slug }}" class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-medium text-zinc-700 no-underline transition hover:border-teal-500 hover:text-teal-700">View post</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if post.featuredImage %}
|
||||||
|
<div class="mt-3 overflow-hidden rounded-lg border border-zinc-200">
|
||||||
|
<img src="{{ post.featuredImage.url }}" alt="{{ post.featuredImage.alt }}" class="h-44 w-full object-cover" loading="lazy" />
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<p class="mt-3 text-sm text-zinc-600">{{ post.excerpt or "No excerpt." }}</p>
|
||||||
|
|
||||||
|
<div class="mt-3 flex flex-wrap gap-2">
|
||||||
|
{% for cat in post.categories %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-indigo-200 bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700">{{ cat }}</span>
|
||||||
|
{% endfor %}
|
||||||
|
{% for tag in post.tags %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-sky-200 bg-sky-50 px-2 py-0.5 text-xs font-medium text-sky-700">#{{ tag }}</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if currentUser.role == "ADMIN" %}
|
||||||
|
<details class="mt-4 rounded-lg border border-zinc-200 bg-zinc-50 p-3">
|
||||||
|
<summary class="cursor-pointer text-sm font-semibold text-zinc-800">Edit this post</summary>
|
||||||
|
|
||||||
|
<form
|
||||||
|
hx-patch="/blog-posts/{{ post.id }}"
|
||||||
|
hx-target="#flash"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-on::after-request="refreshDashboardPosts()"
|
||||||
|
class="mt-3 space-y-3"
|
||||||
|
>
|
||||||
|
<div class="grid gap-2 md:grid-cols-2">
|
||||||
|
<input name="title" value="{{ post.title }}" required class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
|
||||||
|
<input name="slug" value="{{ post.slug }}" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea name="excerpt" class="min-h-20 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">{{ post.excerpt }}</textarea>
|
||||||
|
<textarea name="content" class="min-h-36 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">{{ post.content }}</textarea>
|
||||||
|
|
||||||
|
<div class="grid gap-2 sm:grid-cols-3">
|
||||||
|
<select name="contentFormat" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="markdown" {% if post.contentFormat == "markdown" %}selected{% endif %}>Markdown</option>
|
||||||
|
<option value="html" {% if post.contentFormat == "html" %}selected{% endif %}>HTML</option>
|
||||||
|
</select>
|
||||||
|
<select name="status" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="draft" {% if post.status == "draft" %}selected{% endif %}>draft</option>
|
||||||
|
<option value="published" {% if post.status == "published" %}selected{% endif %}>published</option>
|
||||||
|
<option value="archived" {% if post.status == "archived" %}selected{% endif %}>archived</option>
|
||||||
|
</select>
|
||||||
|
<select name="isFeatured" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="false" {% if not post.isFeatured %}selected{% endif %}>not featured</option>
|
||||||
|
<option value="true" {% if post.isFeatured %}selected{% endif %}>featured</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 md:grid-cols-2">
|
||||||
|
<input name="categories" value="{{ post.categories | join(',') }}" placeholder="Categories: backend,api" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
|
||||||
|
<input name="tags" value="{{ post.tags | join(',') }}" placeholder="Tags: rest,pagination" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-2 md:grid-cols-2">
|
||||||
|
<input name="featuredImageUrl" value="{{ post.featuredImage.url if post.featuredImage else '' }}" placeholder="Featured image URL (optional)" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
|
||||||
|
<input name="featuredImageAlt" value="{{ post.featuredImage.alt if post.featuredImage else '' }}" placeholder="Featured image ALT (optional)" class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<p class="text-xs text-zinc-500">To remove image: clear the URL field and save changes.</p>
|
||||||
|
<button class="rounded-lg bg-teal-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-teal-700" type="submit">Save changes</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<button
|
||||||
|
class="mt-3 rounded-lg border border-rose-200 bg-white px-3 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-50"
|
||||||
|
type="button"
|
||||||
|
hx-delete="/blog-posts/{{ post.id }}"
|
||||||
|
hx-target="#flash"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-confirm="Delete this post permanently?"
|
||||||
|
hx-on::after-request="refreshDashboardPosts()"
|
||||||
|
>
|
||||||
|
Delete post
|
||||||
|
</button>
|
||||||
|
{% else %}
|
||||||
|
<p class="mt-3 text-sm text-zinc-500">Read-only for {{ currentUser.role }} role.</p>
|
||||||
|
{% endif %}
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
57
src/views/partials/dashboard-user-table.njk
Normal file
57
src/views/partials/dashboard-user-table.njk
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
{% if users.length == 0 %}
|
||||||
|
<p class="text-sm text-zinc-600">No users found.</p>
|
||||||
|
{% else %}
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table class="min-w-full divide-y divide-zinc-200 text-sm">
|
||||||
|
<thead class="bg-zinc-50 text-left text-xs uppercase tracking-wide text-zinc-500">
|
||||||
|
<tr>
|
||||||
|
<th class="px-3 py-2 font-semibold">Name</th>
|
||||||
|
<th class="px-3 py-2 font-semibold">Email</th>
|
||||||
|
<th class="px-3 py-2 font-semibold">Role</th>
|
||||||
|
<th class="px-3 py-2 font-semibold">Active</th>
|
||||||
|
<th class="px-3 py-2 font-semibold">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-zinc-200 bg-white text-zinc-700">
|
||||||
|
{% for user in users %}
|
||||||
|
<tr class="align-top">
|
||||||
|
<td class="px-3 py-3">{{ user.name }}</td>
|
||||||
|
<td class="px-3 py-3">{{ user.email }}</td>
|
||||||
|
<td class="px-3 py-3">
|
||||||
|
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ user.role }}</span>
|
||||||
|
</td>
|
||||||
|
<td class="px-3 py-3">{{ "yes" if user.isActive else "no" }}</td>
|
||||||
|
<td class="px-3 py-3">
|
||||||
|
<div class="grid min-w-[18rem] gap-2">
|
||||||
|
<form
|
||||||
|
hx-patch="/users/{{ user.id }}"
|
||||||
|
hx-target="#flash"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-on::after-request="refreshDashboardUsers()"
|
||||||
|
class="flex gap-2"
|
||||||
|
>
|
||||||
|
<input class="w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none" name="name" value="{{ user.name }}" required />
|
||||||
|
<button class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700" type="submit">Rename</button>
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
hx-patch="/users/{{ user.id }}/role"
|
||||||
|
hx-target="#flash"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
hx-on::after-request="refreshDashboardUsers()"
|
||||||
|
class="flex flex-wrap gap-2"
|
||||||
|
>
|
||||||
|
<select name="role" class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm text-zinc-800 focus:border-teal-500 focus:outline-none">
|
||||||
|
<option value="MEMBER" {% if user.role == "MEMBER" %}selected{% endif %}>MEMBER</option>
|
||||||
|
<option value="MANAGER" {% if user.role == "MANAGER" %}selected{% endif %}>MANAGER</option>
|
||||||
|
<option value="ADMIN" {% if user.role == "ADMIN" %}selected{% endif %}>ADMIN</option>
|
||||||
|
</select>
|
||||||
|
<button class="rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700" type="submit">Set role</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
9
src/views/partials/flash.njk
Normal file
9
src/views/partials/flash.njk
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{% if message %}
|
||||||
|
<div class="pointer-events-auto rounded-xl border px-4 py-3 text-sm font-medium shadow-lg {% if type == 'success' %}border-emerald-200 bg-emerald-50 text-emerald-800{% elif type == 'error' %}border-rose-200 bg-rose-50 text-rose-800{% else %}border-amber-200 bg-amber-50 text-amber-800{% endif %}">
|
||||||
|
{{ message }}
|
||||||
|
</div>
|
||||||
|
{% elif flash %}
|
||||||
|
<div class="pointer-events-auto rounded-xl border px-4 py-3 text-sm font-medium shadow-lg {% if flash.type == 'success' %}border-emerald-200 bg-emerald-50 text-emerald-800{% elif flash.type == 'error' %}border-rose-200 bg-rose-50 text-rose-800{% else %}border-amber-200 bg-amber-50 text-amber-800{% endif %}">
|
||||||
|
{{ flash.message }}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
44
src/views/partials/pagination.njk
Normal file
44
src/views/partials/pagination.njk
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{% set pages = (result.total / result.pageSize) | round(0, "ceil") %}
|
||||||
|
|
||||||
|
{% if pages > 1 %}
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3 border-t border-zinc-200 pt-4">
|
||||||
|
<p class="text-sm text-zinc-600">Page {{ result.page }} of {{ pages }}</p>
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
{% if result.page > 1 %}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700"
|
||||||
|
hx-get="/blog-posts/partials/grid?page={{ result.page - 1 }}&pageSize={{ result.pageSize }}&q={{ query.q | urlencode }}&tags={{ query.tags | urlencode }}&category={{ query.category | urlencode }}&sort={{ query.sort }}"
|
||||||
|
hx-target="#post-grid-container"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
>
|
||||||
|
Prev
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% for n in range(1, pages + 1) %}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border px-3 py-1.5 text-sm font-medium transition {% if n == result.page %}border-teal-600 bg-teal-600 text-white{% else %}border-zinc-200 bg-white text-zinc-700 hover:border-teal-500 hover:text-teal-700{% endif %}"
|
||||||
|
hx-get="/blog-posts/partials/grid?page={{ n }}&pageSize={{ result.pageSize }}&q={{ query.q | urlencode }}&tags={{ query.tags | urlencode }}&category={{ query.category | urlencode }}&sort={{ query.sort }}"
|
||||||
|
hx-target="#post-grid-container"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
>
|
||||||
|
{{ n }}
|
||||||
|
</button>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
{% if result.page < pages %}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition hover:border-teal-500 hover:text-teal-700"
|
||||||
|
hx-get="/blog-posts/partials/grid?page={{ result.page + 1 }}&pageSize={{ result.pageSize }}&q={{ query.q | urlencode }}&tags={{ query.tags | urlencode }}&category={{ query.category | urlencode }}&sort={{ query.sort }}"
|
||||||
|
hx-target="#post-grid-container"
|
||||||
|
hx-swap="innerHTML"
|
||||||
|
>
|
||||||
|
Next
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
37
src/views/partials/post-grid.njk
Normal file
37
src/views/partials/post-grid.njk
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<section class="rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm sm:p-5">
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
{% for post in result.items %}
|
||||||
|
<article class="rounded-xl border border-zinc-200 bg-zinc-50/60 p-4">
|
||||||
|
{% if post.featuredImage %}
|
||||||
|
<a href="/blog/{{ post.slug }}" class="mb-3 block overflow-hidden rounded-lg border border-zinc-200">
|
||||||
|
<img
|
||||||
|
src="{{ post.featuredImage.url }}"
|
||||||
|
alt="{{ post.featuredImage.alt or post.title }}"
|
||||||
|
class="h-48 w-full object-cover transition duration-200 hover:scale-[1.02]"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="mb-3 flex flex-wrap gap-2">
|
||||||
|
{% for cat in post.categories %}
|
||||||
|
<span class="inline-flex items-center rounded-full border border-teal-200 bg-teal-50 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wide text-teal-700">{{ cat }}</span>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<h3 class="mb-2 font-[Source_Serif_4] text-xl font-semibold leading-tight text-zinc-900">
|
||||||
|
<a href="/blog/{{ post.slug }}" class="transition hover:text-teal-700">{{ post.title }}</a>
|
||||||
|
</h3>
|
||||||
|
<p class="mb-3 text-sm text-zinc-600">{{ post.excerpt }}</p>
|
||||||
|
<p class="text-sm font-medium text-zinc-500">{{ post.views }} views</p>
|
||||||
|
</article>
|
||||||
|
{% else %}
|
||||||
|
<div class="rounded-xl border border-zinc-200 bg-zinc-50 p-5 sm:col-span-2">
|
||||||
|
<p class="text-sm text-zinc-600">No published posts found for this filter.</p>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-4">
|
||||||
|
{% include "partials/pagination.njk" %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
25
test/app.e2e-spec.ts
Normal file
25
test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { App } from 'supertest/types';
|
||||||
|
import { AppModule } from './../src/app.module';
|
||||||
|
|
||||||
|
describe('AppController (e2e)', () => {
|
||||||
|
let app: INestApplication<App>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/ (GET)', () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get('/')
|
||||||
|
.expect(200)
|
||||||
|
.expect('Hello World!');
|
||||||
|
});
|
||||||
|
});
|
||||||
141
test/auth.e2e-spec.ts
Normal file
141
test/auth.e2e-spec.ts
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import * as cookieParser from 'cookie-parser';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { User } from '../src/users/entities/user.entity';
|
||||||
|
|
||||||
|
describe('Auth (e2e)', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let userRepo: Repository<User>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
app.use(cookieParser());
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||||
|
await app.init();
|
||||||
|
|
||||||
|
userRepo = moduleFixture.get<Repository<User>>(getRepositoryToken(User));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
const testEmail = `test-${Date.now()}@example.com`;
|
||||||
|
const testPassword = 'Test1234!';
|
||||||
|
|
||||||
|
describe('POST /auth/register', () => {
|
||||||
|
it('should register a new user and return tokens', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.post('/auth/register')
|
||||||
|
.send({ email: testEmail, password: testPassword, name: 'Test User' })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(res.body.success).toBe(true);
|
||||||
|
expect(res.body.accessToken).toBeDefined();
|
||||||
|
expect(res.body.user.email).toBe(testEmail);
|
||||||
|
expect(res.body.user.passwordHash).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject duplicate email', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/register')
|
||||||
|
.send({ email: testEmail, password: testPassword })
|
||||||
|
.expect(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject short password', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/register')
|
||||||
|
.send({ email: 'new@example.com', password: '123' })
|
||||||
|
.expect(400);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /auth/login', () => {
|
||||||
|
it('should login with correct credentials', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.post('/auth/login')
|
||||||
|
.send({ email: testEmail, password: testPassword })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(res.body.success).toBe(true);
|
||||||
|
expect(res.body.accessToken).toBeDefined();
|
||||||
|
|
||||||
|
// Cookies should be set
|
||||||
|
const cookies = res.headers['set-cookie'] as string[];
|
||||||
|
expect(cookies).toBeDefined();
|
||||||
|
const hasAccessCookie = cookies.some((c) => c.startsWith('accessToken='));
|
||||||
|
expect(hasAccessCookie).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject wrong password', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/login')
|
||||||
|
.send({ email: testEmail, password: 'wrongpassword' })
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject non-existent email', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/login')
|
||||||
|
.send({ email: 'nonexistent@example.com', password: testPassword })
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /auth/refresh', () => {
|
||||||
|
it('should rotate refresh token', async () => {
|
||||||
|
// First login to get refresh token
|
||||||
|
const loginRes = await request(app.getHttpServer())
|
||||||
|
.post('/auth/login')
|
||||||
|
.send({ email: testEmail, password: testPassword });
|
||||||
|
|
||||||
|
const cookies = loginRes.headers['set-cookie'] as string[];
|
||||||
|
const refreshCookie = cookies.find((c) => c.startsWith('refreshToken='));
|
||||||
|
expect(refreshCookie).toBeDefined();
|
||||||
|
|
||||||
|
// Use refresh token
|
||||||
|
const refreshRes = await request(app.getHttpServer())
|
||||||
|
.post('/auth/refresh')
|
||||||
|
.set('Cookie', cookies)
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(refreshRes.body.success).toBe(true);
|
||||||
|
expect(refreshRes.body.accessToken).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject missing refresh token', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/refresh')
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /auth/magic-link', () => {
|
||||||
|
it('should accept magic link request for existing email', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.post('/auth/magic-link')
|
||||||
|
.send({ email: testEmail })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(res.body.success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept magic link request for non-existing email (no enumeration)', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.post('/auth/magic-link')
|
||||||
|
.send({ email: 'nobody@nowhere.com' })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(res.body.success).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
12
test/jest-e2e.json
Normal file
12
test/jest-e2e.json
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"transformIgnorePatterns": [
|
||||||
|
"/node_modules/(?!(uuid)/)"
|
||||||
|
]
|
||||||
|
}
|
||||||
133
test/public-posts.e2e-spec.ts
Normal file
133
test/public-posts.e2e-spec.ts
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import * as cookieParser from 'cookie-parser';
|
||||||
|
import { getRepositoryToken } from '@nestjs/typeorm';
|
||||||
|
import { Repository } from 'typeorm';
|
||||||
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { BlogPost, PostStatus, ContentFormat } from '../src/blog-posts/entities/blog-post.entity';
|
||||||
|
import { User, UserRole } from '../src/users/entities/user.entity';
|
||||||
|
|
||||||
|
describe('Public Posts (e2e)', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let postRepo: Repository<BlogPost>;
|
||||||
|
let userRepo: Repository<User>;
|
||||||
|
let testAuthorId: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
app.use(cookieParser());
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||||
|
await app.init();
|
||||||
|
|
||||||
|
postRepo = moduleFixture.get<Repository<BlogPost>>(getRepositoryToken(BlogPost));
|
||||||
|
userRepo = moduleFixture.get<Repository<User>>(getRepositoryToken(User));
|
||||||
|
|
||||||
|
// Create test author
|
||||||
|
const author = userRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
email: `author-${Date.now()}@test.com`,
|
||||||
|
role: UserRole.ADMIN,
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
await userRepo.save(author);
|
||||||
|
testAuthorId = author.id;
|
||||||
|
|
||||||
|
// Create test posts
|
||||||
|
await postRepo.save([
|
||||||
|
postRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
title: 'Published Test Post',
|
||||||
|
slug: `published-test-${Date.now()}`,
|
||||||
|
status: PostStatus.PUBLISHED,
|
||||||
|
excerpt: 'A published post for testing',
|
||||||
|
content: 'Test content',
|
||||||
|
contentFormat: ContentFormat.MARKDOWN,
|
||||||
|
authorId: testAuthorId,
|
||||||
|
tags: ['test', 'published'],
|
||||||
|
categories: ['Test'],
|
||||||
|
}),
|
||||||
|
postRepo.create({
|
||||||
|
id: uuidv4(),
|
||||||
|
title: 'Draft Test Post',
|
||||||
|
slug: `draft-test-${Date.now()}`,
|
||||||
|
status: PostStatus.DRAFT,
|
||||||
|
excerpt: 'A draft post',
|
||||||
|
content: 'Draft content',
|
||||||
|
contentFormat: ContentFormat.MARKDOWN,
|
||||||
|
authorId: testAuthorId,
|
||||||
|
tags: ['test', 'draft'],
|
||||||
|
categories: ['Test'],
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /blog-posts/public', () => {
|
||||||
|
it('should return only published posts', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.get('/blog-posts/public')
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(Array.isArray(res.body.posts)).toBe(true);
|
||||||
|
const allPublished = res.body.posts.every((p: any) => p.status === 'published');
|
||||||
|
expect(allPublished).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should support search by query', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.get('/blog-posts/public?q=Published+Test')
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(res.body.posts.length).toBeGreaterThanOrEqual(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should support pagination', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.get('/blog-posts/public?page=1&pageSize=2')
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(res.body.posts.length).toBeLessThanOrEqual(2);
|
||||||
|
expect(res.body.page).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /blog-posts/public/:slug', () => {
|
||||||
|
it('should return a published post by slug', async () => {
|
||||||
|
// First get a published post slug
|
||||||
|
const listRes = await request(app.getHttpServer()).get('/blog-posts/public');
|
||||||
|
const slug = listRes.body.posts[0]?.slug;
|
||||||
|
expect(slug).toBeDefined();
|
||||||
|
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.get(`/blog-posts/public/${slug}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(res.body.post.slug).toBe(slug);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return 404 for draft post', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get(`/blog-posts/public/draft-test-99999`)
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /blog-posts/public/featured', () => {
|
||||||
|
it('should return featured published posts', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.get('/blog-posts/public/featured')
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(Array.isArray(res.body)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
125
test/rbac.e2e-spec.ts
Normal file
125
test/rbac.e2e-spec.ts
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import * as cookieParser from 'cookie-parser';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
|
||||||
|
describe('RBAC (e2e)', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
|
||||||
|
// We'll store cookies per user role
|
||||||
|
let adminCookies: string[];
|
||||||
|
let managerCookies: string[];
|
||||||
|
let memberCookies: string[];
|
||||||
|
|
||||||
|
const ts = Date.now();
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
app.use(cookieParser());
|
||||||
|
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
|
||||||
|
await app.init();
|
||||||
|
|
||||||
|
// Register three users, then promote via direct DB or use existing seed
|
||||||
|
// For simplicity, register all as MEMBER — we test permission differences
|
||||||
|
|
||||||
|
const adminEmail = `admin-rbac-${ts}@test.com`;
|
||||||
|
const managerEmail = `manager-rbac-${ts}@test.com`;
|
||||||
|
const memberEmail = `member-rbac-${ts}@test.com`;
|
||||||
|
const pw = 'RbacTest123!';
|
||||||
|
|
||||||
|
// Register all
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/register')
|
||||||
|
.send({ email: adminEmail, password: pw });
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/auth/register')
|
||||||
|
.send({ email: managerEmail, password: pw });
|
||||||
|
|
||||||
|
const memberReg = await request(app.getHttpServer())
|
||||||
|
.post('/auth/register')
|
||||||
|
.send({ email: memberEmail, password: pw });
|
||||||
|
|
||||||
|
// Store member cookies
|
||||||
|
memberCookies = memberReg.headers['set-cookie'] as string[];
|
||||||
|
|
||||||
|
// Login as the newly registered users
|
||||||
|
const adminLogin = await request(app.getHttpServer())
|
||||||
|
.post('/auth/login')
|
||||||
|
.send({ email: adminEmail, password: pw });
|
||||||
|
adminCookies = adminLogin.headers['set-cookie'] as string[];
|
||||||
|
|
||||||
|
const managerLogin = await request(app.getHttpServer())
|
||||||
|
.post('/auth/login')
|
||||||
|
.send({ email: managerEmail, password: pw });
|
||||||
|
managerCookies = managerLogin.headers['set-cookie'] as string[];
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MEMBER permissions', () => {
|
||||||
|
it('should NOT be able to create a blog post', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/blog-posts')
|
||||||
|
.set('Cookie', memberCookies)
|
||||||
|
.send({ title: 'Member Post', content: 'Content' })
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should NOT be able to list users', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/users')
|
||||||
|
.set('Cookie', memberCookies)
|
||||||
|
.expect(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should be able to view dashboard', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/dashboard')
|
||||||
|
.set('Cookie', memberCookies)
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Unauthenticated access', () => {
|
||||||
|
it('should allow access to public posts', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/blog-posts/public')
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should deny access to dashboard', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/dashboard')
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should deny access to users list', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/users')
|
||||||
|
.expect(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Public endpoints', () => {
|
||||||
|
it('GET /health should be publicly accessible', async () => {
|
||||||
|
const res = await request(app.getHttpServer())
|
||||||
|
.get('/health')
|
||||||
|
.expect(200);
|
||||||
|
expect(res.body.status).toBe('ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET / should be publicly accessible', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/')
|
||||||
|
.expect(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
28
tsconfig.json
Normal file
28
tsconfig.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2021",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": false,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"noFallthroughCasesInSwitch": false,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src/**/*", "scripts/**/*"],
|
||||||
|
"exclude": ["node_modules", "dist", "test"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user