10 Commits

Author SHA1 Message Date
domrichardson
d793b5ccf2 feat: Light/dark modes
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 1m48s
2026-03-26 17:01:34 +00:00
domrichardson
005a8f4cf0 feat: Updated admin panel providers list & modal 2026-03-26 16:27:14 +00:00
domrichardson
9cf71ab4a0 feat: added search bar and results page
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 1m34s
2026-03-26 12:52:09 +00:00
domrichardson
cf94697d07 feat: Added better md styling
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 58s
2026-03-26 11:41:16 +00:00
domrichardson
94f11be77c fix: Fixed redis user
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 1m48s
2026-03-26 10:10:07 +00:00
domrichardson
6e642da57a fix: fixes to session storage
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 1m27s
2026-03-26 10:06:07 +00:00
domrichardson
6774c401bf feat: updated identity providers in admin panel
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 49s
2026-03-25 15:17:48 +00:00
domrichardson
1f1fd90890 feat: Updated admin panel styles 2026-03-25 14:11:39 +00:00
domrichardson
168f5eac83 feat: file explorer
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 50s
2026-03-25 11:27:15 +00:00
domrichardson
b253bec9fc feat: changes to the note editor
All checks were successful
Build and Push App Image / build-and-push (push) Successful in 31s
2026-03-25 09:55:02 +00:00
66 changed files with 6193 additions and 1678 deletions

View File

@@ -1,98 +1,151 @@
# Environment Configuration
# Environment Setup
Copy `.env.example` files and configure for your environment:
Notely uses three different environment-file locations depending on how you run the app.
## Backend (.env)
## 1. Root `.env`
```env
# MongoDB
MONGODB_URI=mongodb://admin:password@localhost:27017/noteapp?authSource=admin
Use the root `.env` file when running `docker compose` from the repository root.
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters
JWT_ISSUER=noteapp
# Encryption (32 bytes = 32 characters)
ENCRYPTION_KEY=00000000000000000000000000000000
# Server
PORT=8080
ENV=development
LOG_LEVEL=info
# CORS (comma-separated for multiple origins)
CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
# Rate Limiting
RATE_LIMIT_REQUESTS=50
RATE_LIMIT_WINDOW=1s
```
## Frontend (.env)
```env
VITE_API_BASE_URL=http://localhost:8080
VITE_ENV=development
```
## Development vs Production
### Development (.env.development)
- Less strict security (for easier testing)
- Localhost CORS allowed
- JWT secrets can be simple
- Logging more verbose
### Production (.env.production)
- Strict security requirements
- Specific CORS origins only
- Strong random JWT secrets
- Limited logging (performance)
- All environment variables must be set
## Generating Secrets
Start from:
```bash
cp .env.example .env
```
### Variables Used By Docker Compose
Required or commonly used:
- `MONGODB_URI`
- `BACKEND_PORT`
- `JWT_SECRET`
- `ENCRYPTION_KEY`
- `FRONTEND_URL`
- `VITE_API_BASE_URL`
- `DEFAULT_ADMIN_EMAIL`
- `DEFAULT_ADMIN_USERNAME`
- `DEFAULT_ADMIN_PASSWORD`
- `NGINX_HTTP_PORT`
- `NGINX_HTTPS_PORT`
Optional backend runtime values that Docker Compose will also pass through if present:
- `REDIS_ADDR`
- `REDIS_USER`
- `REDIS_PASSWORD`
- `REDIS_DB`
- `SESSION_TTL_HOURS`
### Current Defaults In The Checked-In Example
- MongoDB container: `mongodb://admin:password@mongodb:27017/noteapp?authSource=admin`
- Backend port: `8080`
- Public frontend URL: `http://localhost`
- Browser API base URL for container builds: `http://localhost`
## 2. `backend/.env`
Use `backend/.env` for local backend development.
Start from:
```bash
cd backend
cp .env.example .env
```
### Variables Currently Read By The Backend Runtime
Read in `backend/cmd/server/main.go` or other active handlers:
- `MONGODB_URI`
- `JWT_SECRET`
- `ENCRYPTION_KEY`
- `PORT`
- `REDIS_ADDR`
- `REDIS_USER`
- `REDIS_PASSWORD`
- `REDIS_DB`
- `SESSION_TTL_HOURS`
- `DEFAULT_ADMIN_EMAIL`
- `DEFAULT_ADMIN_USERNAME`
- `DEFAULT_ADMIN_PASSWORD`
- `FRONTEND_URL`
### Variables Present In `backend/.env.example` But Not Currently Consumed By Runtime Code
These values exist in the example file, but the current code path does not read them yet:
- `JWT_ISSUER`
- `ENV`
- `LOG_LEVEL`
- `CORS_ALLOWED_ORIGINS`
- `RATE_LIMIT_REQUESTS`
- `RATE_LIMIT_WINDOW`
### Backend Defaults If A Variable Is Missing
- `MONGODB_URI`: `mongodb://localhost:27017`
- `JWT_SECRET`: `your-secret-key-change-in-production`
- `ENCRYPTION_KEY`: `00000000000000000000000000000000`
- `PORT`: `8080`
- `REDIS_ADDR`: `localhost:6379`
- `REDIS_DB`: `0`
- `SESSION_TTL_HOURS`: `168`
- `FRONTEND_URL`: falls back to `http://localhost:5173` for login redirects
## 3. `frontend/.env`
Use `frontend/.env` for local frontend development.
Start from:
```bash
cd frontend
cp .env.example .env
```
### Frontend Variables In `frontend/.env.example`
- `VITE_API_BASE_URL`
- `VITE_ENV`
- `VITE_ENABLE_ANALYTICS`
### Variables Currently Relevant To The Frontend App
- `VITE_API_BASE_URL`: used by the API client
The other example values are safe to keep, but the current checked-in frontend code does not actively consume them.
## Secret Generation
Examples:
```bash
# JWT Secret (32+ characters)
openssl rand -base64 32
# Encryption Key (32 bytes)
openssl rand -hex 16 # outputs 32 characters
# Random token
openssl rand -hex 16
openssl rand -hex 32
```
## Docker Compose
Use generated values for:
Environment variables are defined in `docker-compose.yml` and will override `.env` files. Update the file for your deployment:
- `JWT_SECRET`
- `ENCRYPTION_KEY`
- provider secrets or other sensitive credentials stored through admin settings
```yaml
environment:
MONGODB_URI: mongodb://admin:password@mongodb:27017/noteapp?authSource=admin
JWT_SECRET: your-secret-key-change-in-production
# ... other vars
```
## Compose Vs Local Development
## Kubernetes
Use the right env file for the right mode:
Use `kubectl create secret` for sensitive data:
- root `.env`: Docker Compose
- `backend/.env`: local backend
- `frontend/.env`: local frontend
```bash
# Create secret from literal values
kubectl create secret generic app-secrets \
--from-literal=mongodb-uri="..." \
--from-literal=jwt-secret="..." \
-n noteapp
Do not assume values from one location are automatically shared with the others.
# Or use ConfigMap for non-sensitive config
kubectl create configmap app-config \
--from-file=config.yaml \
-n noteapp
```
## Important Notes
---
**IMPORTANT**: Never commit .env files or secrets to version control!
- Do not commit real secrets
- Keep `ENCRYPTION_KEY` at 32 characters for the current AES-256 usage
- If OAuth login is enabled, set `FRONTEND_URL` correctly so callback redirects go to the intended UI
- If Redis settings are omitted, the backend assumes a local Redis instance at `localhost:6379`

View File

@@ -14,7 +14,7 @@ This file lists the permissions currently checked by the application.
- space.edit
- Global space edit capability (used as fallback alongside space-scoped settings edit)
- space.delete
- Global space delete capability (used as fallback alongside space-scoped delete)
- Global space delete capability (used as fallback alongside space-scoped settings.delete)
## Space-Scoped Permission Format
@@ -30,7 +30,7 @@ space.<space_permission_key>.<action>
### Space Management
- settings.edit
- delete
- settings.delete
### Member Management

View File

@@ -1,304 +1,151 @@
# 🚀 Quick Start Guide
# Quick Start
## Prerequisites
This guide covers the fastest way to run Notely and the current local-development workflow.
- Docker and Docker Compose (recommended for quickest setup)
- OR: Go 1.21+, Node.js 18+, MongoDB 7.0+
## Option 1: Docker Compose
## Option 1: Docker Compose (Recommended - 1 Command)
From the repository root:
```bash
# Clone/navigate to project
cd noteapp
# Start everything
docker-compose up
# Wait for services to initialize (~30 seconds)
# Then open: http://localhost
cp .env.example .env
docker compose up -d --build
```
**Services running**:
Open:
- Notely: http://localhost:8080
- MongoDB: localhost:27017
- Nginx Reverse Proxy: http://localhost:80
- App UI: `http://localhost`
- Backend health endpoint: `http://localhost:8080/health`
- MongoDB: `localhost:27017`
- Redis: `localhost:6379`
**Test user (after startup)**:
Compose starts four services:
- Register a new account at http://localhost/register
- Login and create a Space
- Add Categories and Notes
- `mongodb`
- `redis`
- `notely`
- `nginx`
## Option 2: Local Development
### Backend Setup
### Prerequisites
- Go 1.25+
- Node.js 18+
- MongoDB
- Redis
If you do not already have MongoDB and Redis running locally, you can start just those services with Docker Compose:
```bash
docker compose up -d mongodb redis
```
### Backend
```bash
cd backend
# Copy environment file
cp .env.example .env
# Install dependencies
go mod download
# Ensure MongoDB is running
# Docker: docker run -d -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=admin \
# -e MONGO_INITDB_ROOT_PASSWORD=password mongo:7.0-alpine
# Run backend
go run ./cmd/server/main.go
# Logs should show: "Server starting on port 8080"
```
### Frontend Setup
The backend listens on `http://localhost:8080` by default.
### Frontend
```bash
cd frontend
# Copy environment file
cp .env.example .env
# Install dependencies
npm install
# Start dev server
npm run dev
# Open: http://localhost:5173 in browser
```
## 🧪 Testing
The Vite dev server listens on `http://localhost:5173` and proxies `/api` to `http://localhost:8080`.
### Backend Tests
## Day-To-Day Commands
### Backend
```bash
cd backend
# Run all tests
go test ./...
# Run with verbose output
go test -v ./...
# Run specific test
go test -v -run TestRegisterUser ./tests/unit/...
# With coverage
go test -cover ./...
go test -v ./tests/unit/...
go test -v ./tests/integration/...
```
### Frontend Tests
### Frontend
```bash
cd frontend
# Run tests
npm run build
npm run lint
npm run test
# Watch mode
npm run test:watch
# Coverage
npm run test:coverage
```
## 📝 Key API Endpoints
## First Run Checklist
### Authentication
1. Register a user or set `DEFAULT_ADMIN_*` values in your env file before startup.
2. Sign in.
3. Create a space.
4. Create categories and notes.
5. Use the top search bar to verify note search.
```bash
# Register
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"username": "myuser",
"password": "SecurePassword123",
"password_confirm": "SecurePassword123",
"first_name": "John",
"last_name": "Doe"
}'
## Useful Endpoints
# Login
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePassword123"
}'
Authentication:
# Response contains: access_token, refresh_token, user data
```
- `POST /api/v1/auth/register`
- `POST /api/v1/auth/login`
- `POST /api/v1/auth/refresh`
- `GET /api/v1/auth/me`
### Create Space
Spaces:
```bash
curl -X POST http://localhost:8080/api/v1/spaces \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "My First Space",
"description": "Notes for my project",
"icon": "📚",
"is_public": false
}'
```
- `GET /api/v1/spaces`
- `POST /api/v1/spaces`
- `PUT /api/v1/spaces/{spaceId}`
- `DELETE /api/v1/spaces/{spaceId}`
### Create Note
Notes:
```bash
curl -X POST http://localhost:8080/api/v1/spaces/{spaceId}/notes \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "My First Note",
"content": "# Markdown Heading\n\nThis is a note",
"tags": ["important", "work"],
"category_id": null,
"is_pinned": false,
"is_favorite": true
}'
```
- `GET /api/v1/spaces/{spaceId}/notes`
- `POST /api/v1/spaces/{spaceId}/notes`
- `GET /api/v1/spaces/{spaceId}/notes/search?q=<query>`
- `POST /api/v1/spaces/{spaceId}/notes/{noteId}/unlock`
### Search Notes
Public access:
```bash
curl "http://localhost:8080/api/v1/spaces/{spaceId}/notes/search?q=important" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```
- `GET /api/v1/public/spaces`
- `GET /api/v1/public/spaces/{spaceId}/notes`
## 🔍 Troubleshooting
## Troubleshooting
### MongoDB Connection Error
### Backend cannot connect to MongoDB
```
Error: Failed to connect to database
Check `MONGODB_URI` in your selected env file and make sure MongoDB is reachable.
Solution:
docker run -d -p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongo:7.0-alpine
```
### Backend cannot connect to Redis
### Port Already in Use
Check `REDIS_ADDR`, `REDIS_PASSWORD`, and `REDIS_DB`. For local defaults, Redis should usually be reachable at `localhost:6379`.
```bash
# Find process on port 8080
lsof -i :8080
### The browser cannot reach the API in local dev
# Kill it
kill -9 <PID>
Check:
# Or use different port
PORT=8081 go run ./cmd/server/main.go
```
- backend is running on port `8080`
- frontend `VITE_API_BASE_URL`
- Vite proxy settings in `frontend/vite.config.js`
### CORS Errors
### OAuth callback redirects to the wrong URL
Make sure frontend and backend URLs match in:
Check `FRONTEND_URL` in your selected env file.
- Frontend: `VITE_API_BASE_URL` in `.env`
- Backend: `CORS_ALLOWED_ORIGINS` in `.env`
### Permission-denied behavior is unclear
### MongoDB Auth Failed
Read `PERMISSIONS.md` and then inspect the relevant backend service in `backend/internal/application/services/`.
If using Docker Compose:
## Related Docs
- Username: `admin`
- Password: `password`
- Connection string includes `?authSource=admin`
## 📚 Project Structure
```
noteapp/
├── backend/ # Go REST API
│ ├── cmd/server/ # Entry point
│ ├── internal/
│ │ ├── domain/ # Business logic
│ │ ├── application/ # Services & DTOs
│ │ ├── infrastructure/ # DB, auth, security
│ │ └── interfaces/ # HTTP handlers
│ ├── tests/ # Test files
│ ├── go.mod & go.sum # Dependencies
│ └── README.md
├── frontend/ # Vue 3 SPA
│ ├── src/
│ │ ├── components/ # UI components
│ │ ├── pages/ # Page components
│ │ ├── stores/ # Pinia state
│ │ ├── services/ # API client
│ │ ├── router/ # Vue Router
│ │ ├── assets/ # Styles & images
│ │ └── main.js # Entry point
│ ├── tests/ # Test files
│ ├── package.json # Dependencies
│ └── vite.config.js # Vite configuration
├── devops/
│ ├── docker/
│ │ ├── Dockerfile.backend
│ │ ├── Dockerfile.frontend
│ │ └── nginx.conf
│ └── kubernetes/
│ └── deployment.yaml
├── docker-compose.yml # Local development setup
├── README.md # Project docs
├── ARCHITECTURE.md # Architecture overview
├── SECURITY.md # Security implementation
└── ENV_SETUP.md # Environment configuration
```
## 🎓 Learning Resources
### Understanding the Code
1. **Start here**: `ARCHITECTURE.md` - Clean architecture pattern
2. **Then read**: Backend `domain/entities/*.go` - Core models
3. **Next**: Backend `application/services/*.go` - Business logic
4. **UI**: Frontend `src/stores/authStore.js` - State management
5. **API**: Backend `interfaces/handlers/*.go` - HTTP layer
### Security Deep Dive
See `SECURITY.md` for:
- Password hashing (Argon2id)
- JWT authentication
- Authorization (RBAC)
- Input validation
- XSS prevention
- CSRF protection
## 🚀 Next Steps
1. **Explore the UI**: Create spaces, notes, categories
2. **Read the code**: Start with `index ARCHITECTURE.md`
3. **Run tests**: `go test ./...` and `npm test`
4. **Deploy**: Use `docker-compose.yml` or Kubernetes
5. **Extend**: Add OAuth2, WebSockets, more features
## 💡 Quick Tips
- **Hot reload**: Changes auto-reload in dev mode
- **Network tab**: Check API calls in browser DevTools
- **Logs**: Docker: `docker-compose logs -f service-name`
- **Database GUI**: MongoDB Compass (free tool to browse data)
- **API testing**: Postman or `curl` commands
## 📞 Support
- Check logs: `docker-compose logs`
- Review `SECURITY.md` for auth issues
- Check `ENV_SETUP.md` for config problems
- See `ARCHITECTURE.md` for code structure
---
**Now you're ready to explore and extend Notely! 🎉**
- `README.md`
- `ENV_SETUP.md`
- `PERMISSIONS.md`

543
README.md
View File

@@ -1,306 +1,174 @@
# Notely - Secure Multi-Space Note-Taking Application
# Notely
A production-ready, secure multi-tenant note-taking platform built with Go, Vue 3, and MongoDB.
Notely is a multi-space note application built with Go, Vue 3, MongoDB, and Redis.
## 🚀 Quick Start
The repository contains a Go backend, a Vue frontend, Docker Compose assets for local deployment, and Kubernetes manifests for cluster deployment. In containerized environments, the frontend is built into the backend image and served by the Go server. Docker Compose also places Nginx in front of the app for HTTP and HTTPS entry points.
### Prerequisites
## What Is In This Repo
- Docker & Docker Compose
- Go 1.21+ (for local development)
- Node.js 18+ (for frontend development)
- MongoDB 7.0+ (for local development)
- Backend API in `backend/`
- Frontend SPA in `frontend/`
- Docker and Nginx assets in `devops/docker/`
- Kubernetes manifests in `devops/kubernetes/`
- Root documentation in `README.md`, `QUICKSTART.md`, `ENV_SETUP.md`, and `PERMISSIONS.md`
### Development with Docker Compose
## Core Features
- Email/password authentication
- Session cookies backed by Redis, with bearer-token fallback for API clients
- Admin bootstrap from environment variables
- Permission-based authorization with wildcard support
- Spaces, categories, and notes
- Full-text note search
- Public spaces and public notes
- Password-protected notes
- OAuth/OIDC provider support
- Feature flags for registration, provider login, public sharing, and file explorer support
- Optional S3-compatible file explorer when enabled through feature flags
## Architecture Overview
### Backend
- Language: Go
- Module: `gitea.hostxtra.co.uk/mrhid6/notely/backend`
- Entry point: `backend/cmd/server/main.go`
- Architecture style: domain/application/infrastructure/interfaces split
- Storage: MongoDB
- Session store: Redis
### Frontend
- Framework: Vue 3
- Router: Vue Router
- State: Pinia
- Build tool: Vite
### Container Layout
- `devops/docker/Dockerfile` builds the frontend and backend into a single app image
- `docker-compose.yml` starts:
- `mongodb`
- `redis`
- `notely` (combined app image)
- `nginx`
## Documentation Map
- `README.md`: project overview and current architecture
- `QUICKSTART.md`: fast setup and day-to-day development commands
- `ENV_SETUP.md`: environment-variable reference and configuration layout
- `PERMISSIONS.md`: enforced permission model and naming
## Getting Started
### Docker Compose
1. Copy the root environment file:
```bash
# Start all services
docker-compose up
# Backend: http://localhost:8080
# Frontend: http://localhost:5173
# MongoDB: localhost:27017
# Nginx: http://localhost:80
cp .env.example .env
```
### Local Development Setup
2. Start the stack:
#### Backend
```bash
docker compose up -d --build
```
3. Open the app:
- UI through Nginx: `http://localhost`
- Backend health check: `http://localhost:8080/health`
- MongoDB: `localhost:27017`
- Redis: `localhost:6379`
### Local Development
Prerequisites:
- Go 1.25+
- Node.js 18+
- MongoDB
- Redis
Backend:
```bash
cd backend
# Install dependencies
cp .env.example .env
go mod download
# Set environment variables
export MONGODB_URI=mongodb://admin:password@localhost:27017/noteapp?authSource=admin
export JWT_SECRET=your-secret-key
export ENCRYPTION_KEY=00000000000000000000000000000000
# Run migrations and server
go run ./cmd/server/main.go
```
#### Frontend
Frontend:
```bash
cd frontend
# Install dependencies
cp .env.example .env
npm install
# Start development server
npm run dev
```
## 📚 Architecture
Local frontend development runs at `http://localhost:5173` and proxies `/api` requests to `http://localhost:8080`.
### Backend (GoClean Architecture)
## API Surface
```
backend/
├── cmd/server/ # Entry point
├── internal/
│ ├── domain/ # Business logic (entities, interfaces)
│ ├── application/ # Use cases (services, DTOs)
│ ├── infrastructure/ # External dependencies (DB, auth)
│ └── interfaces/ # API handlers & middleware
├── pkg/ # Public packages
└── tests/ # Test suites
```
The router in `backend/cmd/server/main.go` currently exposes these endpoint groups.
### Frontend (Vue 3 Composition API)
### Public Endpoints
```
frontend/
├── src/
│ ├── components/ # Reusable Vue components
│ ├── pages/ # Page components
│ ├── stores/ # Pinia state management
│ ├── services/ # API client
│ ├── router/ # Vue Router config
│ ├── assets/ # Styles and assets
│ └── main.js # Entry point
├── index.html
└── vite.config.js
```
- `GET /health`
- `POST /api/v1/auth/register`
- `POST /api/v1/auth/login`
- `POST /api/v1/auth/refresh`
- `POST /api/v1/auth/logout`
- `GET /api/v1/auth/providers`
- `GET /api/v1/auth/providers/{providerId}/start`
- `GET /api/v1/auth/providers/{providerId}/callback`
- `GET /api/v1/settings/feature-flags`
- `GET /api/v1/public/spaces`
- `GET /api/v1/public/spaces/{spaceId}`
- `GET /api/v1/public/spaces/{spaceId}/notes`
- `GET /api/v1/public/spaces/{spaceId}/notes/{noteId}`
- `POST /api/v1/public/spaces/{spaceId}/notes/{noteId}/unlock`
## 🔐 Security Features
### Authenticated User Endpoints
### Authentication
- `GET /api/v1/auth/me`
- Space CRUD under `/api/v1/spaces`
- Space member management under `/api/v1/spaces/{spaceId}/members`
- Note CRUD, search, and unlock under `/api/v1/spaces/{spaceId}/notes`
- Category CRUD and move under `/api/v1/spaces/{spaceId}/categories`
- File explorer operations under `/api/v1/spaces/{spaceId}/files`
- **Argon2id password hashing** - Industry-standard PBKDF2
- **JWT tokens** with short expiration (1 hour)
- **HTTP-only secure cookies** for refresh tokens
- **CSRF protection** via SameSite cookies
- **Brute-force protection** via login attempt tracking
### Admin Endpoints
### Authorization
Admin routes live under `/api/v1/admin` and cover:
- **Role-based access control (RBAC)** per space:
- Owner: Full control
- Editor: Edit notes and categories
- Viewer: Read-only access
- **Space-level data isolation** - all queries include space_id
- **IDOR prevention** - middleware enforces ownership verification
- users
- groups
- spaces
- feature flags
- auth providers
### Data Security
## Permissions
- **Encryption at rest** for sensitive fields (OAuth secrets)
- **HTTPS/TLS** in production (Nginx reverse proxy)
- **Content Security Policy (CSP)** headers
- **XSS protection** - DOMPurify for markdown sanitization
- **SQL injection prevention** - parameterized queries (MongoDB)
Notely uses permission-based authorization, not fixed owner/editor/viewer roles.
### API Security
- Global permissions include `space.create`, `space.edit`, and `space.delete`
- Space-scoped permissions follow `space.<space_key>.<action>`
- Example: `space.product_docs.note.create`
- Example: `space.product_docs.settings.delete`
- Space deletion requires either:
- global `space.delete`, or
- space-scoped `space.<space_key>.settings.delete`
- **Rate limiting** - IP-based and user-based
- **Security headers** - HSTS, X-Frame-Options, X-Content-Type-Options
- **CORS properly configured** - whitelist origin domains
- **Input validation** on all endpoints
See `PERMISSIONS.md` for the current enforced permission set.
## 📦 API Endpoints
## Testing And Quality Checks
### Authentication
```
POST /api/v1/auth/register - Register new user
POST /api/v1/auth/login - Login user
POST /api/v1/auth/refresh - Refresh access token
POST /api/v1/auth/logout - Logout user
GET /health - Health check
```
### Spaces
```
GET /api/v1/spaces - List user's spaces
POST /api/v1/spaces - Create space
GET /api/v1/spaces/{spaceId} - Get space details
PUT /api/v1/spaces/{spaceId} - Update space
DELETE /api/v1/spaces/{spaceId} - Delete space
```
### Notes
```
GET /api/v1/spaces/{spaceId}/notes - List notes
POST /api/v1/spaces/{spaceId}/notes - Create note
GET /api/v1/spaces/{spaceId}/notes/{noteId} - Get note
PUT /api/v1/spaces/{spaceId}/notes/{noteId} - Update note
DELETE /api/v1/spaces/{spaceId}/notes/{noteId} - Delete note
GET /api/v1/spaces/{spaceId}/notes/search?q= - Search notes
```
### Categories
```
GET /api/v1/spaces/{spaceId}/categories - List categories
POST /api/v1/spaces/{spaceId}/categories - Create category
PUT /api/v1/spaces/{spaceId}/categories/{id} - Update category
DELETE /api/v1/spaces/{spaceId}/categories/{id} - Delete category
```
## 🗄️ Database Design
### MongoDB Collections
#### users
```javascript
{
_id: ObjectId,
email: String (unique),
username: String (unique),
password_hash: String,
first_name: String,
last_name: String,
avatar: String,
is_active: Boolean,
email_verified: Boolean,
created_at: Date,
updated_at: Date,
last_login_at: Date
}
```
#### spaces
```javascript
{
_id: ObjectId,
name: String,
description: String,
icon: String,
owner_id: ObjectId,
is_public: Boolean,
created_at: Date,
updated_at: Date
}
```
#### memberships
```javascript
{
_id: ObjectId,
user_id: ObjectId,
space_id: ObjectId,
role: String (owner|editor|viewer),
joined_at: Date,
invited_by: ObjectId,
invited_at: Date
}
```
#### notes
```javascript
{
_id: ObjectId,
space_id: ObjectId,
category_id: ObjectId,
title: String,
content: String (Markdown),
tags: [String],
is_pinned: Boolean,
is_favorite: Boolean,
created_by: ObjectId,
updated_by: ObjectId,
created_at: Date,
updated_at: Date,
viewed_at: Date
}
```
#### categories
```javascript
{
_id: ObjectId,
space_id: ObjectId,
name: String,
description: String,
parent_id: ObjectId (for hierarchical structure),
icon: String,
order: Number,
created_by: ObjectId,
updated_by: ObjectId,
created_at: Date,
updated_at: Date
}
```
#### Indexes
```
users: { email: 1 (unique), username: 1 (unique) }
spaces: { owner_id: 1, created_at: -1 }
memberships: { user_id: 1, space_id: 1 (unique), space_id: 1 }
notes: { space_id: 1, category_id: 1, updated_at: -1, text: "text" }
categories: { space_id: 1, parent_id: 1, order: 1 }
```
## 🐳 Deployment
### Docker Compose (Development/Testing)
```bash
docker-compose up -d
```
Services:
- **MongoDB** (port 27017)
- **Backend API** (port 8080)
- **Frontend** (port 5173)
- **Nginx Reverse Proxy** (port 80)
### Kubernetes (Production)
```bash
# Create namespace and secrets
kubectl apply -f devops/kubernetes/deployment.yaml
# Verify deployment
kubectl get pods -n noteapp
kubectl port-forward svc/frontend 5173:5173 -n noteapp
kubectl port-forward svc/backend 8080:8080 -n noteapp
```
Features:
- **StatefulSet** for MongoDB with persistent storage
- **Deployments** for backend and frontend with horizontal scaling
- **Ingress** for routing (requires ingress controller)
- **HPA** (Horizontal Pod Autoscaler) for automatic scaling
- **Liveness & readiness probes** for health checks
- **Resource limits** for fair resource allocation
## 🧪 Testing
### Backend Tests
Backend:
```bash
cd backend
@@ -309,118 +177,73 @@ go test -v ./tests/unit/...
go test -v ./tests/integration/...
```
### Frontend Tests
Frontend:
```bash
cd frontend
npm run build
npm run lint
npm run test
npm run test:watch
```
## 🔧 Configuration
## Deployment Notes
### Environment Variables
### Docker Compose
#### Backend (.env)
Docker Compose uses the combined application image plus Nginx, MongoDB, and Redis. Configuration is driven by the root `.env` file.
```
MONGODB_URI=mongodb://admin:password@localhost:27017/noteapp
JWT_SECRET=your-secret-key-min-32-chars
ENCRYPTION_KEY=32-char-encryption-key-for-secrets
PORT=8080
LOG_LEVEL=info
ENV=development
```
### Kubernetes
#### Frontend (.env)
The manifest at `devops/kubernetes/deployment.yaml` currently provisions:
```
VITE_API_BASE_URL=http://localhost:8080
```
- `noteapp` namespace
- MongoDB StatefulSet and PVC
- single `noteapp` Deployment for the combined app image
- ClusterIP services
- Ingress
- HorizontalPodAutoscaler
## 📝 Development Guidelines
### Code Structure
- Follow clean architecture principles
- Separate concerns: domain, application, infrastructure
- Use interfaces for dependency injection
- Keep services testable and focused
### Security Best Practices
1. **Never store secrets in code** - use environment variables
2. **Validate all inputs** on backend
3. **Sanitize outputs** before rendering
4. **Use HTTPS in production**
5. **Implement rate limiting** on APIs
6. **Log security events** (login attempts, permission denied)
7. **Audit trail** for sensitive operations
### Commit Message Format
```
[TYPE] Description
types: feat, fix, docs, style, refactor, test, chore
```
## 📖 API Documentation
### Request/Response Format
All API requests and responses use JSON.
Apply it with:
```bash
# Example: Create Note
curl -X POST http://localhost:8080/api/v1/spaces/{spaceId}/notes \
-H "Authorization: Bearer {accessToken}" \
-H "Content-Type: application/json" \
-d '{
"title": "My Note",
"content": "# Markdown content",
"tags": ["tag1", "tag2"],
"category_id": null,
"is_pinned": false,
"is_favorite": false
}'
kubectl apply -f devops/kubernetes/deployment.yaml
```
## 🚨 Error Handling
## Current Repo Layout
All errors return appropriate HTTP status codes:
```text
noteapp/
├── backend/
│ ├── cmd/server/
│ ├── internal/
│ ├── pkg/
│ ├── tests/
│ └── .env.example
├── frontend/
│ ├── src/
│ ├── tests/
│ ├── package.json
│ ├── vite.config.js
│ ├── vitest.config.js
│ └── .env.example
├── devops/
│ ├── docker/
│ │ ├── Dockerfile
│ │ ├── nginx.conf
│ │ └── ssl/
│ └── kubernetes/
│ └── deployment.yaml
├── docker-compose.yml
├── .env.example
├── ENV_SETUP.md
├── PERMISSIONS.md
├── QUICKSTART.md
└── README.md
```
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden (insufficient permissions)
- `404` - Not Found
- `409` - Conflict (e.g., duplicate email)
- `429` - Too Many Requests (rate limit exceeded)
- `500` - Internal Server Error
## Notes For Contributors
## 🎯 Future Enhancements
- [ ] OAuth2/OIDC integration
- [ ] Email notifications
- [ ] Real-time collaboration (WebSockets)
- [ ] Full-text search with Elasticsearch
- [ ] Export to PDF/Markdown
- [ ] Mobile applications
- [ ] Plugin system
- [ ] Advanced permissions management
## 📄 License
MIT License - See LICENSE file
## 👥 Contributing
1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to the branch
5. Create a Pull Request
---
**Built with ❤️ for secure, collaborative note-taking**
- Check `PERMISSIONS.md` when changing authorization behavior
- Check `ENV_SETUP.md` when adding or changing configuration
- Check `backend/cmd/server/main.go` before documenting routes
- Keep docs aligned with actual package scripts and checked-in files

View File

@@ -1,284 +0,0 @@
# Security Implementation Guide
This document outlines the security measures implemented in Notely.
## 🔐 Authentication Security
### Password Hashing
- **Algorithm**: Argon2id (memory-hard, resistant to GPU attacks)
- **Configuration**:
- Memory: 64 MB
- Time: 1 iteration
- Parallelism: 4 threads
- Salt: 16 random bytes (cryptographically secure)
```go
// Generated hash format:
$argon2id$v=19$m=65536,t=1,p=4$salt_hex$hash_hex
```
### JWT Tokens
- **Algorithm**: HS256 (HMAC-SHA256)
- **Access Token TTL**: 1 hour
- **Refresh Token TTL**: 7 days (HTTP-only secure cookie)
- **Claims**:
- `user_id`: User's MongoDB ObjectID
- `email`: User's email address
- `username`: User's username
- `iat`: Issued at timestamp
- `exp`: Expiration timestamp
- `iss`: Issuer (verified against hardcoded value)
### Brute-Force Protection
- Track failed login attempts in `login_attempts` collection
- Rate limit: Max 5 failed attempts per IP per 15 minutes
- Account lockout: 15 minutes after 5 consecutive failures
- Cleanup: Expired records auto-deleted via TTL index
## 🛡️ Authorization Security
### Role-Based Access Control (RBAC)
```
Space Roles:
├── Owner (all permissions)
├── Editor (create/edit/delete notes)
└── Viewer (read-only)
```
### Space-Level Data Isolation
**ALL queries include mandatory `space_id` filter**
```go
// Correct query pattern:
db.notes.find({ space_id: spaceID, ... })
// Never allow:
db.notes.find({ user_id: userID }) // ❌ Cross-space leak possible
```
### Middleware Authorization Flow
```
1. Extract JWT token → Verify signature & expiration
2. Load user credentials → Verify user is active
3. Check space membership → Verify user_id + space_id + role
4. Execute request → With space_id context
```
## 🔑 Data Encryption
### At Rest
- OAuth client secrets encrypted with AES-256-GCM
- Stored in MongoDB with encryption key in environment variables
- Decryption happens only when reading from database
```go
plaintext, err := encryptor.Encrypt(clientSecret) // Stores encrypted blob
recovered, err := encryptor.Decrypt(plaintext) // Decrypts on retrieval
```
### In Transit
- HTTPS/TLS required in production (enforced via Nginx)
- Secure cookies: `Secure`, `HttpOnly`, `SameSite=Lax` flags
- All sensitive data transmitted over encrypted channels
## 🚨 Input Validation
### Backend Validation (MANDATORY)
Every endpoint validates:
1. **Type validation** - JSON schema validation
2. **Length limits** - min/max string lengths
3. **Format validation** - email, ObjectID, URL formats
4. **Range validation** - pagination limits
```go
type CreateNoteRequest struct {
Title string `validate:"required,min=1,max=255"`
Content string `validate:"max=50000"`
Tags []string `validate:"max=100,dive,max=50"`
}
```
### Frontend Validation
- **Input sanitization** - trim whitespace
- **Format validation** - regex patterns
- **Debounced searches** - prevent query spam
- **Client-side feedback** - improve UX
### Output Sanitization
Markdown → HTML conversion sanitized with DOMPurify:
```javascript
// XSS prevention
const dirty = marked.parse(userMarkdown);
const clean = DOMPurify.sanitize(dirty);
// Blocks: scripts, event handlers, dangerous attributes
```
## 🌐 Web Security Headers
Implemented via Nginx and Go middleware:
| Header | Value | Purpose |
| --------------------------- | --------------------------------- | ------------------------------- |
| `Strict-Transport-Security` | `max-age=31536000` | Force HTTPS |
| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |
| `X-Frame-Options` | `DENY` | Prevent clickjacking |
| `X-XSS-Protection` | `1; mode=block` | XSS protection (older browsers) |
| `Content-Security-Policy` | Restrictive policy | Prevent XSS attacks |
| `Referrer-Policy` | `strict-origin-when-cross-origin` | Referrer control |
**CSP Policy:**
```
default-src 'self'
script-src 'self' 'unsafe-inline' (for development only)
style-src 'self' 'unsafe-inline'
img-src 'self' data: https:
font-src 'self'
connect-src 'self'
frame-ancestors 'none'
```
## 🍪 Cookie Security
### Access Token (via Authorization header)
- Stored in **memory** (not localStorage)
- Passed via `Authorization: Bearer {token}`
### Refresh Token (HTTP-only cookie)
```go
http.SetCookie(w, &http.Cookie{
Name: "refresh_token",
Value: token,
Path: "/",
MaxAge: 7 * 24 * 60 * 60, // 7 days
HttpOnly: true, // ✅ Cannot access from JavaScript
Secure: true, // ✅ HTTPS only
SameSite: http.SameSiteLaxMode, // ✅ CSRF protection
})
```
## 🔄 Rate Limiting
### API Rate Limiting
- **General**: 50 requests / second per IP
- **Login**: 10 requests / second per IP
- **Burst allowance**: 20 additional requests
```nginx
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req zone=api_limit burst=20 nodelay;
```
### Login Attempt Tracking
- Track per email + IP combination
- Maximum 5 attempts per 15 minutes
- Exponential backoff on repeated failures
## 🔒 Database Security
### MongoDB
- **Authentication**: Username/password with role-based access
- **Network**: Runs in secure Docker network (not exposed)
- **Admin credentials**: Stored in Kubernetes Secrets (not in code)
- **Backups**: TBD - use MongoDB Atlas or encrypted backups
### Connection String
```
mongodb://admin:password@mongodb:27017/dbname?authSource=admin
```
## 🚨 Logging & Monitoring
### Security Events Logged
- ✅ User registration attempts
- ✅ Login attempts (success/failure)
- ✅ Authorization failures
- ✅ Permission denied events
- ✅ Sensitive data access
### Data NOT logged
- ❌ Passwords/hashes
- ❌ JWT tokens
- ❌ Encryption keys
- ❌ OAuth secrets
## 🧪 Security Testing
### What to Test
1. **Authentication**: Register, login, token refresh, logout
2. **Authorization**: RBAC enforcement, space isolation
3. **Input validation**: Invalid data rejection
4. **XSS prevention**: Markdown sanitization
5. **CSRF protection**: Token validation
6. **Rate limiting**: Too many requests blocked
7. **SQL Injection**: MongoDB-specific (parameterized queries safe)
### Manual Testing Commands
```bash
# Test invalid input
curl -X POST http://localhost:8080/api/v1/auth/login \
-d '{"email":"not-an-email","password":""}'
# Test expired token
curl -H "Authorization: Bearer expired.token.here" \
http://localhost:8080/api/v1/spaces
# Test rate limiting
for i in {1..100}; do
curl http://localhost:8080/api/v1/auth/login &
done
```
## 🛠️ Production Checklist
- [ ] Change default JWT_SECRET (min 32 characters)
- [ ] Change default ENCRYPTION_KEY (32 bytes)
- [ ] Generate TLS certificates (Let's Encrypt recommended)
- [ ] Configure Nginx SSL/TLS
- [ ] Enable HTTPS redirect
- [ ] Set up database backups
- [ ] Configure logging & monitoring
- [ ] Implement CORS whitelist (specific domains)
- [ ] Set up rate limiting (tuned to your traffic)
- [ ] Enable database authentication
- [ ] Use Kubernetes Network Policies
- [ ] Set up Pod Security Policies
- [ ] Enable audit logging
- [ ] Configure Secrets encryption at rest
## 📚 References
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [MongoDB Security](https://docs.mongodb.com/manual/security/)
- [JWT Best Practices](https://tools.ietf.org/html/rfc8949)
- [Argon2 Specification](https://github.com/P-H-C/phc-winner-argon2)
- [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
---
**Last Updated**: March 2026
**Security Level**: Production-Grade

View File

@@ -26,3 +26,9 @@ CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
# Rate Limiting
RATE_LIMIT_REQUESTS=50
RATE_LIMIT_WINDOW=1s
# Redis Sessions
REDIS_ADDR=localhost:6379
REDIS_PASSWORD=
REDIS_DB=0
SESSION_TTL_HOURS=168

View File

@@ -6,19 +6,21 @@ import (
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/auth"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/database"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/security"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/handlers"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/middleware"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"github.com/noteapp/backend/internal/application/services"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"github.com/noteapp/backend/internal/infrastructure/auth"
"github.com/noteapp/backend/internal/infrastructure/database"
"github.com/noteapp/backend/internal/infrastructure/security"
"github.com/noteapp/backend/internal/interfaces/handlers"
"github.com/noteapp/backend/internal/interfaces/middleware"
"github.com/redis/go-redis/v9"
"go.mongodb.org/mongo-driver/v2/bson"
)
@@ -47,6 +49,31 @@ func main() {
port = "8080"
}
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" {
redisAddr = "localhost:6379"
}
redisUser := os.Getenv("REDIS_USER")
redisPassword := os.Getenv("REDIS_PASSWORD")
redisDB := 0
if redisDBText := os.Getenv("REDIS_DB"); redisDBText != "" {
parsedDB, err := strconv.Atoi(redisDBText)
if err != nil {
log.Fatalf("invalid REDIS_DB value: %v", err)
}
redisDB = parsedDB
}
sessionTTL := 7 * 24 * time.Hour
if sessionTTLText := os.Getenv("SESSION_TTL_HOURS"); sessionTTLText != "" {
hours, err := strconv.Atoi(sessionTTLText)
if err != nil || hours <= 0 {
log.Fatalf("invalid SESSION_TTL_HOURS value: %q", sessionTTLText)
}
sessionTTL = time.Duration(hours) * time.Hour
}
// Connect to database
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -57,6 +84,20 @@ func main() {
}
defer db.Close(context.Background())
redisClient := redis.NewClient(&redis.Options{
Addr: redisAddr,
Username: redisUser,
Password: redisPassword,
DB: redisDB,
})
if err := redisClient.Ping(context.Background()).Err(); err != nil {
log.Fatalf("failed to connect to redis: %v", err)
}
defer func() {
_ = redisClient.Close()
}()
// Initialize security components
passwordHasher := security.NewPasswordHasher()
encryptor, err := security.NewEncryptor(encryptionKey)
@@ -66,6 +107,7 @@ func main() {
// Initialize JWT manager
jwtManager := auth.NewJWTManager(jwtSecret, "noteapp", 1*time.Hour)
sessionManager := auth.NewSessionManager(redisClient, sessionTTL)
// Initialize services
permissionService := services.NewPermissionService(
@@ -117,12 +159,15 @@ func main() {
adminService := services.NewAdminService(
db.UserRepo,
db.GroupRepo,
db.ProviderRepo,
db.LinkRepo,
db.SpaceRepo,
db.MembershipRepo,
db.NoteRepo,
db.CategoryRepo,
db.FeatureFlagRepo,
permissionService,
encryptor,
)
if err := permissionService.EnsureAdminGroup(context.Background()); err != nil {
@@ -140,13 +185,15 @@ func main() {
}
// Initialize handlers
authHandler := handlers.NewAuthHandler(authService)
authHandler := handlers.NewAuthHandler(authService, sessionManager)
spaceHandler := handlers.NewSpaceHandler(spaceService)
noteHandler := handlers.NewNoteHandler(noteService)
categoryHandler := handlers.NewCategoryHandler(categoryService)
adminHandler := handlers.NewAdminHandler(adminService)
publicHandler := handlers.NewPublicHandler(spaceService, noteService)
settingsHandler := handlers.NewSettingsHandler(authService)
fileService := services.NewFileService(db.FeatureFlagRepo, db.MembershipRepo, encryptor)
fileHandler := handlers.NewFileHandler(fileService)
// Create router
router := mux.NewRouter()
@@ -155,7 +202,7 @@ func main() {
})
// Middleware
authMiddleware := middleware.NewAuthMiddleware(jwtManager)
authMiddleware := middleware.NewAuthMiddleware(jwtManager, sessionManager)
router.Use(middleware.LoggingMiddleware)
router.Use(middleware.CORSMiddleware)
router.Use(middleware.SecurityHeaders)
@@ -182,6 +229,7 @@ func main() {
// Protected endpoints
api := router.PathPrefix("/api/v1").Subrouter()
api.Use(authMiddleware.Middleware)
api.HandleFunc("/auth/me", authHandler.Me).Methods("GET")
// Space endpoints
api.HandleFunc("/spaces", spaceHandler.GetUserSpaces).Methods("GET")
@@ -210,6 +258,14 @@ func main() {
api.HandleFunc("/spaces/{spaceId}/categories/{categoryId}", categoryHandler.DeleteCategory).Methods("DELETE")
api.HandleFunc("/spaces/{spaceId}/categories/{categoryId}/move", categoryHandler.MoveCategory).Methods("PATCH")
// File explorer endpoints (space-scoped)
api.HandleFunc("/spaces/{spaceId}/files/list", fileHandler.ListFiles).Methods("GET")
api.HandleFunc("/spaces/{spaceId}/files/object", fileHandler.GetFile).Methods("GET")
api.HandleFunc("/spaces/{spaceId}/files/upload", fileHandler.UploadFile).Methods("POST")
api.HandleFunc("/spaces/{spaceId}/files/folder", fileHandler.CreateFolder).Methods("POST")
api.HandleFunc("/spaces/{spaceId}/files/object", fileHandler.DeleteFile).Methods("DELETE")
api.HandleFunc("/spaces/{spaceId}/files/folder", fileHandler.DeleteFolder).Methods("DELETE")
// Admin endpoints
admin := router.PathPrefix("/api/v1/admin").Subrouter()
admin.Use(authMiddleware.Middleware)
@@ -244,10 +300,12 @@ func main() {
})
})
admin.HandleFunc("/users", adminHandler.ListUsers).Methods("GET")
admin.HandleFunc("/users/{userId}", adminHandler.DeleteUser).Methods("DELETE")
admin.HandleFunc("/users/{userId}/groups", adminHandler.UpdateUserGroups).Methods("PUT")
admin.HandleFunc("/groups", adminHandler.ListGroups).Methods("GET")
admin.HandleFunc("/groups", adminHandler.CreateGroup).Methods("POST")
admin.HandleFunc("/groups/{groupId}", adminHandler.UpdateGroup).Methods("PUT")
admin.HandleFunc("/groups/{groupId}", adminHandler.DeleteGroup).Methods("DELETE")
admin.HandleFunc("/spaces", adminHandler.ListAllSpaces).Methods("GET")
admin.HandleFunc("/spaces/{spaceId}", adminHandler.UpdateSpace).Methods("PUT")
admin.HandleFunc("/spaces/{spaceId}", adminHandler.DeleteSpace).Methods("DELETE")
@@ -258,7 +316,10 @@ func main() {
admin.HandleFunc("/feature-flags", adminHandler.GetFeatureFlags).Methods("GET")
admin.HandleFunc("/feature-flags", adminHandler.UpdateFeatureFlags).Methods("PUT")
// manage identity providers — admin-only
admin.HandleFunc("/auth/providers", authHandler.ListProvidersForAdmin).Methods("GET")
admin.HandleFunc("/auth/providers", authHandler.CreateProvider).Methods("POST")
admin.HandleFunc("/auth/providers/{providerId}", authHandler.UpdateProvider).Methods("PUT")
admin.HandleFunc("/auth/providers/{providerId}", adminHandler.DeleteProvider).Methods("DELETE")
// Serve static files (frontend) for all other routes
// This must be after all API route handlers to allow API routes to take precedence

View File

@@ -1,22 +1,38 @@
module github.com/noteapp/backend
module gitea.hostxtra.co.uk/mrhid6/notely/backend
go 1.25.0
require (
github.com/aws/aws-sdk-go-v2 v1.41.4
github.com/aws/aws-sdk-go-v2/credentials v1.19.12
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.2
github.com/golang-jwt/jwt/v5 v5.2.0
github.com/gorilla/mux v1.8.1
github.com/joho/godotenv v1.5.1
github.com/redis/go-redis/v9 v9.18.0
go.mongodb.org/mongo-driver/v2 v2.5.0
golang.org/x/crypto v0.49.0
golang.org/x/oauth2 v0.30.0
)
require (
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.20 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.20 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.20 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.20 // indirect
github.com/aws/smithy-go v1.24.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/klauspost/compress v1.17.6 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.2.0 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.35.0 // indirect

View File

@@ -1,5 +1,37 @@
github.com/aws/aws-sdk-go-v2 v1.41.4 h1:10f50G7WyU02T56ox1wWXq+zTX9I1zxG46HYuG1hH/k=
github.com/aws/aws-sdk-go-v2 v1.41.4/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
github.com/aws/aws-sdk-go-v2/credentials v1.19.12 h1:oqtA6v+y5fZg//tcTWahyN9PEn5eDU/Wpvc2+kJ4aY8=
github.com/aws/aws-sdk-go-v2/credentials v1.19.12/go.mod h1:U3R1RtSHx6NB0DvEQFGyf/0sbrpJrluENHdPy1j/3TE=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.20 h1:CNXO7mvgThFGqOFgbNAP2nol2qAWBOGfqR/7tQlvLmc=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.20/go.mod h1:oydPDJKcfMhgfcgBUZaG+toBbwy8yPWubJXBVERtI4o=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.20 h1:tN6W/hg+pkM+tf9XDkWUbDEjGLb+raoBMFsTodcoYKw=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.20/go.mod h1:YJ898MhD067hSHA6xYCx5ts/jEd8BSOLtQDL3iZsvbc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.21 h1:SwGMTMLIlvDNyhMteQ6r8IJSBPlRdXX5d4idhIGbkXA=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.21/go.mod h1:UUxgWxofmOdAMuqEsSppbDtGKLfR04HGsD0HXzvhI1k=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.12 h1:qtJZ70afD3ISKWnoX3xB0J2otEqu3LqicRcDBqsj0hQ=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.12/go.mod h1:v2pNpJbRNl4vEUWEh5ytQok0zACAKfdmKS51Hotc3pQ=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.20 h1:2HvVAIq+YqgGotK6EkMf+KIEqTISmTYh5zLpYyeTo1Y=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.20/go.mod h1:V4X406Y666khGa8ghKmphma/7C0DAtEQYhkq9z4vpbk=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.20 h1:siU1A6xjUZ2N8zjTHSXFhB9L/2OY8Dqs0xXiLjF30jA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.20/go.mod h1:4TLZCmVJDM3FOu5P5TJP0zOlu9zWgDWU7aUxWbr+rcw=
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.2 h1:MRNiP6nqa20aEl8fQ6PJpEq11b2d40b16sm4WD7QgMU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.97.2/go.mod h1:FrNA56srbsr3WShiaelyWYEo70x80mXnVZ17ZZfbeqg=
github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw=
github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
@@ -10,6 +42,14 @@ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.17.6 h1:60eq2E/jlfwQXtvZEeBUYADs+BwKBWURIY+Gj2eRGjI=
github.com/klauspost/compress v1.17.6/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
@@ -19,8 +59,12 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=

View File

@@ -1,7 +1,7 @@
package dto
import (
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
)
// ========== AUTH DTOs ==========
@@ -57,11 +57,32 @@ type CreateAuthProviderRequest struct {
IsActive bool `json:"is_active"`
}
// UpdateAuthProviderRequest represents an OAuth/OIDC provider update request.
// ClientSecret may be empty to keep the existing secret.
type UpdateAuthProviderRequest struct {
Name string `json:"name"`
Type string `json:"type"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
AuthorizationURL string `json:"authorization_url"`
TokenURL string `json:"token_url"`
UserInfoURL string `json:"userinfo_url"`
Scopes []string `json:"scopes"`
IDTokenClaim string `json:"id_token_claim,omitempty"`
IsActive bool `json:"is_active"`
}
// FeatureFlagsDTO represents app-wide feature flags in API responses.
type FeatureFlagsDTO struct {
RegistrationEnabled bool `json:"registration_enabled"`
ProviderLoginEnabled bool `json:"provider_login_enabled"`
PublicSharingEnabled bool `json:"public_sharing_enabled"`
FileExplorerEnabled bool `json:"file_explorer_enabled"`
S3Endpoint string `json:"s3_endpoint,omitempty"`
S3Bucket string `json:"s3_bucket,omitempty"`
S3Region string `json:"s3_region,omitempty"`
S3AccessKey string `json:"s3_access_key,omitempty"`
S3SecretKeySet bool `json:"s3_secret_key_set"`
}
// UpdateFeatureFlagsRequest represents admin payload for feature flag updates.
@@ -69,6 +90,12 @@ type UpdateFeatureFlagsRequest struct {
RegistrationEnabled bool `json:"registration_enabled"`
ProviderLoginEnabled bool `json:"provider_login_enabled"`
PublicSharingEnabled bool `json:"public_sharing_enabled"`
FileExplorerEnabled bool `json:"file_explorer_enabled"`
S3Endpoint string `json:"s3_endpoint"`
S3Bucket string `json:"s3_bucket"`
S3Region string `json:"s3_region"`
S3AccessKey string `json:"s3_access_key"`
S3SecretKey string `json:"s3_secret_key"` // empty = keep existing encrypted value
}
// UserDTO represents a user in API responses
@@ -206,6 +233,12 @@ func NewFeatureFlagsDTO(flags *entities.FeatureFlags) *FeatureFlagsDTO {
RegistrationEnabled: flags.RegistrationEnabled,
ProviderLoginEnabled: flags.ProviderLoginEnabled,
PublicSharingEnabled: flags.PublicSharingEnabled,
FileExplorerEnabled: flags.FileExplorerEnabled,
S3Endpoint: flags.S3Endpoint,
S3Bucket: flags.S3Bucket,
S3Region: flags.S3Region,
S3AccessKey: flags.S3AccessKey,
S3SecretKeySet: flags.S3SecretKey != "",
}
}

View File

@@ -7,46 +7,164 @@ import (
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/security"
)
// AdminService handles admin-level operations
type AdminService struct {
userRepo repositories.UserRepository
groupRepo repositories.GroupRepository
providerRepo repositories.AuthProviderRepository
linkRepo repositories.UserProviderLinkRepository
spaceRepo repositories.SpaceRepository
membershipRepo repositories.MembershipRepository
noteRepo repositories.NoteRepository
categoryRepo repositories.CategoryRepository
featureFlagRepo repositories.FeatureFlagRepository
permissionService *PermissionService
encryptor *security.Encryptor
}
// NewAdminService creates a new AdminService
func NewAdminService(
userRepo repositories.UserRepository,
groupRepo repositories.GroupRepository,
providerRepo repositories.AuthProviderRepository,
linkRepo repositories.UserProviderLinkRepository,
spaceRepo repositories.SpaceRepository,
membershipRepo repositories.MembershipRepository,
noteRepo repositories.NoteRepository,
categoryRepo repositories.CategoryRepository,
featureFlagRepo repositories.FeatureFlagRepository,
permissionService *PermissionService,
encryptor *security.Encryptor,
) *AdminService {
return &AdminService{
userRepo: userRepo,
groupRepo: groupRepo,
providerRepo: providerRepo,
linkRepo: linkRepo,
spaceRepo: spaceRepo,
membershipRepo: membershipRepo,
noteRepo: noteRepo,
categoryRepo: categoryRepo,
featureFlagRepo: featureFlagRepo,
permissionService: permissionService,
encryptor: encryptor,
}
}
// DeleteUser deletes a user and related memberships/provider links.
func (s *AdminService) DeleteUser(ctx context.Context, currentUserID, targetUserID bson.ObjectID) error {
if currentUserID == targetUserID {
return errors.New("you cannot delete your own account")
}
spaces, err := s.spaceRepo.GetAllSpaces(ctx)
if err != nil {
return err
}
for _, space := range spaces {
if space.OwnerID == targetUserID {
return errors.New("cannot delete user that owns spaces; transfer or delete spaces first")
}
}
memberships, err := s.membershipRepo.GetUserMemberships(ctx, targetUserID)
if err == nil {
for _, membership := range memberships {
if err := s.membershipRepo.DeleteMembership(ctx, membership.ID); err != nil {
return err
}
}
}
if s.linkRepo != nil {
links, err := s.linkRepo.GetUserLinks(ctx, targetUserID)
if err == nil {
for _, link := range links {
if err := s.linkRepo.DeleteLink(ctx, link.ID); err != nil {
return err
}
}
}
}
return s.userRepo.DeleteUser(ctx, targetUserID)
}
// DeleteGroup deletes a non-system group and removes it from users.
func (s *AdminService) DeleteGroup(ctx context.Context, groupID bson.ObjectID) error {
group, err := s.groupRepo.GetGroupByID(ctx, groupID)
if err != nil {
return err
}
if group.IsSystem {
return errors.New("system groups cannot be deleted")
}
users, err := s.userRepo.ListAllUsers(ctx)
if err != nil {
return err
}
for _, user := range users {
filtered := make([]bson.ObjectID, 0, len(user.GroupIDs))
changed := false
for _, assignedGroupID := range user.GroupIDs {
if assignedGroupID == groupID {
changed = true
continue
}
filtered = append(filtered, assignedGroupID)
}
if !changed {
continue
}
user.GroupIDs = filtered
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
return err
}
}
if err := s.groupRepo.DeleteGroup(ctx, groupID); err != nil {
return err
}
return s.refreshAllUserPermissions(ctx)
}
// DeleteProvider deletes an auth provider and all user-provider links connected to it.
func (s *AdminService) DeleteProvider(ctx context.Context, providerID bson.ObjectID) error {
if s.providerRepo == nil {
return errors.New("provider repository unavailable")
}
if s.linkRepo != nil {
users, err := s.userRepo.ListAllUsers(ctx)
if err != nil {
return err
}
for _, user := range users {
links, err := s.linkRepo.GetUserLinks(ctx, user.ID)
if err != nil {
continue
}
for _, link := range links {
if link.ProviderID == providerID {
if err := s.linkRepo.DeleteLink(ctx, link.ID); err != nil {
return err
}
}
}
}
}
return s.providerRepo.DeleteProvider(ctx, providerID)
}
// ListUsers returns all users as admin DTOs
func (s *AdminService) ListUsers(ctx context.Context) ([]*dto.AdminUserDTO, error) {
users, err := s.userRepo.ListAllUsers(ctx)
@@ -299,10 +417,31 @@ func (s *AdminService) UpdateFeatureFlags(ctx context.Context, req *dto.UpdateFe
return nil, errors.New("feature flags are unavailable")
}
// Load existing flags so we can preserve the encrypted S3 secret when not updated
existing, err := s.featureFlagRepo.GetFeatureFlags(ctx)
if err != nil {
existing = entities.NewDefaultFeatureFlags()
}
flags := &entities.FeatureFlags{
RegistrationEnabled: req.RegistrationEnabled,
ProviderLoginEnabled: req.ProviderLoginEnabled,
PublicSharingEnabled: req.PublicSharingEnabled,
FileExplorerEnabled: req.FileExplorerEnabled,
S3Endpoint: strings.TrimSpace(req.S3Endpoint),
S3Bucket: strings.TrimSpace(req.S3Bucket),
S3Region: strings.TrimSpace(req.S3Region),
S3AccessKey: strings.TrimSpace(req.S3AccessKey),
S3SecretKey: existing.S3SecretKey, // keep encrypted secret by default
}
// Only re-encrypt if a new secret was supplied
if s.encryptor != nil && strings.TrimSpace(req.S3SecretKey) != "" {
encrypted, err := s.encryptor.Encrypt(strings.TrimSpace(req.S3SecretKey))
if err != nil {
return nil, err
}
flags.S3SecretKey = encrypted
}
if err := s.featureFlagRepo.UpdateFeatureFlags(ctx, flags); err != nil {

View File

@@ -12,11 +12,11 @@ import (
"strings"
"time"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"github.com/noteapp/backend/internal/infrastructure/auth"
"github.com/noteapp/backend/internal/infrastructure/security"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/auth"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/security"
"go.mongodb.org/mongo-driver/v2/bson"
"golang.org/x/oauth2"
)
@@ -114,20 +114,7 @@ func (s *AuthService) Register(ctx context.Context, req *dto.RegisterRequest) (*
}
}
// Generate tokens
accessToken, err := s.jwtManager.GenerateAccessToken(user.ID.Hex(), user.Email, user.Username)
if err != nil {
return nil, err
}
refreshToken, err := s.jwtManager.GenerateRefreshToken(user.ID.Hex())
if err != nil {
return nil, err
}
return &dto.LoginResponse{
AccessToken: accessToken,
RefreshToken: refreshToken,
User: dto.NewUserDTO(user),
ExpiresIn: 3600, // 1 hour
}, nil
@@ -165,20 +152,7 @@ func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest) (*dto.Lo
// Log error but don't fail the login
}
// Generate tokens
accessToken, err := s.jwtManager.GenerateAccessToken(user.ID.Hex(), user.Email, user.Username)
if err != nil {
return nil, err
}
refreshToken, err := s.jwtManager.GenerateRefreshToken(user.ID.Hex())
if err != nil {
return nil, err
}
return &dto.LoginResponse{
AccessToken: accessToken,
RefreshToken: refreshToken,
User: dto.NewUserDTO(user),
ExpiresIn: 3600,
}, nil
@@ -186,6 +160,10 @@ func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest) (*dto.Lo
// RefreshAccessToken refreshes an access token
func (s *AuthService) RefreshAccessToken(ctx context.Context, refreshToken string) (string, error) {
if s.jwtManager == nil {
return "", errors.New("jwt refresh is unavailable")
}
claims, err := s.jwtManager.VerifyRefreshToken(refreshToken)
if err != nil {
return "", err
@@ -199,6 +177,27 @@ func (s *AuthService) RefreshAccessToken(ctx context.Context, refreshToken strin
return s.jwtManager.GenerateAccessToken(user.ID.Hex(), user.Email, user.Username)
}
// GetUserProfile returns profile DTO for the provided user ID.
func (s *AuthService) GetUserProfile(ctx context.Context, userID string) (*dto.UserDTO, error) {
objID, err := bson.ObjectIDFromHex(strings.TrimSpace(userID))
if err != nil {
return nil, errors.New("invalid user id")
}
user, err := s.userRepo.GetUserByID(ctx, objID)
if err != nil {
return nil, err
}
if s.permissionService != nil {
if err := s.permissionService.UpdateUserEffectivePermissions(ctx, user); err != nil {
return nil, err
}
}
return dto.NewUserDTO(user), nil
}
// RequestPasswordReset initiates password reset flow
func (s *AuthService) RequestPasswordReset(ctx context.Context, email string) error {
user, err := s.userRepo.GetUserByEmail(ctx, email)
@@ -260,6 +259,25 @@ func (s *AuthService) ListProviders(ctx context.Context) ([]*dto.AuthProviderDTO
return result, nil
}
// ListProvidersForAdmin returns all OAuth/OIDC providers, including inactive ones.
func (s *AuthService) ListProvidersForAdmin(ctx context.Context) ([]*dto.AuthProviderDTO, error) {
if s.providerRepo == nil {
return []*dto.AuthProviderDTO{}, nil
}
providers, err := s.providerRepo.GetAllProvidersForAdmin(ctx)
if err != nil {
return nil, err
}
result := make([]*dto.AuthProviderDTO, 0, len(providers))
for _, provider := range providers {
result = append(result, dto.NewAuthProviderDTO(provider))
}
return result, nil
}
// GetFeatureFlags returns current app-wide feature flags.
func (s *AuthService) GetFeatureFlags(ctx context.Context) (*dto.FeatureFlagsDTO, error) {
if s.featureFlagRepo == nil {
@@ -319,6 +337,57 @@ func (s *AuthService) CreateProvider(ctx context.Context, req *dto.CreateAuthPro
return dto.NewAuthProviderDTO(provider), nil
}
// UpdateProvider updates an existing OAuth/OIDC provider.
// If ClientSecret is empty, the existing encrypted secret is preserved.
func (s *AuthService) UpdateProvider(ctx context.Context, providerID bson.ObjectID, req *dto.UpdateAuthProviderRequest) (*dto.AuthProviderDTO, error) {
if s.providerRepo == nil || s.encryptor == nil {
return nil, errors.New("provider configuration unavailable")
}
existing, err := s.providerRepo.GetProviderByID(ctx, providerID)
if err != nil {
return nil, err
}
providerType := strings.ToLower(strings.TrimSpace(req.Type))
if providerType != "oidc" && providerType != "oauth2" {
return nil, errors.New("provider type must be oidc or oauth2")
}
name := strings.TrimSpace(req.Name)
clientID := strings.TrimSpace(req.ClientID)
authorizationURL := strings.TrimSpace(req.AuthorizationURL)
tokenURL := strings.TrimSpace(req.TokenURL)
if name == "" || clientID == "" || authorizationURL == "" || tokenURL == "" {
return nil, errors.New("missing required provider fields")
}
existing.Name = name
existing.Type = providerType
existing.ClientID = clientID
existing.AuthorizationURL = authorizationURL
existing.TokenURL = tokenURL
existing.UserInfoURL = strings.TrimSpace(req.UserInfoURL)
existing.Scopes = normalizeScopes(req.Scopes, providerType)
existing.IDTokenClaim = strings.TrimSpace(req.IDTokenClaim)
existing.IsActive = req.IsActive
clientSecret := strings.TrimSpace(req.ClientSecret)
if clientSecret != "" {
encrypted, err := s.encryptor.Encrypt(clientSecret)
if err != nil {
return nil, err
}
existing.ClientSecret = encrypted
}
if err := s.providerRepo.UpdateProvider(ctx, existing); err != nil {
return nil, err
}
return dto.NewAuthProviderDTO(existing), nil
}
// BuildProviderAuthorizationURL constructs a provider authorization URL.
func (s *AuthService) BuildProviderAuthorizationURL(ctx context.Context, providerID bson.ObjectID, redirectURI, state string) (string, error) {
flags, err := s.GetFeatureFlags(ctx)
@@ -393,17 +462,7 @@ func (s *AuthService) CompleteProviderLogin(ctx context.Context, providerID bson
return nil, err
}
accessToken, err := s.jwtManager.GenerateAccessToken(user.ID.Hex(), user.Email, user.Username)
if err != nil {
return nil, err
}
refreshToken, err := s.jwtManager.GenerateRefreshToken(user.ID.Hex())
if err != nil {
return nil, err
}
return &dto.LoginResponse{AccessToken: accessToken, RefreshToken: refreshToken, User: dto.NewUserDTO(user), ExpiresIn: 3600}, nil
return &dto.LoginResponse{User: dto.NewUserDTO(user), ExpiresIn: 3600}, nil
}
type providerProfile struct {

View File

@@ -7,9 +7,9 @@ import (
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
)
// CategoryService handles category operations

View File

@@ -0,0 +1,389 @@
package services
import (
"bytes"
"context"
"errors"
"io"
"path"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"go.mongodb.org/mongo-driver/v2/bson"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/security"
)
// S3Object represents a file or folder entry with key relative to the space root.
type S3Object struct {
Key string `json:"key"`
Size int64 `json:"size"`
LastModified string `json:"last_modified"`
IsFolder bool `json:"is_folder"`
}
// FileService handles S3 file operations scoped to individual spaces.
type FileService struct {
featureFlagRepo repositories.FeatureFlagRepository
membershipRepo repositories.MembershipRepository
encryptor *security.Encryptor
}
// NewFileService creates a new FileService.
func NewFileService(
featureFlagRepo repositories.FeatureFlagRepository,
membershipRepo repositories.MembershipRepository,
encryptor *security.Encryptor,
) *FileService {
return &FileService{
featureFlagRepo: featureFlagRepo,
membershipRepo: membershipRepo,
encryptor: encryptor,
}
}
type s3Config struct {
client *s3.Client
bucket string
}
// buildS3Config loads feature flags, decrypts credentials, and returns an S3 client + bucket name.
func (s *FileService) buildS3Config(ctx context.Context) (*s3Config, error) {
flags, err := s.featureFlagRepo.GetFeatureFlags(ctx)
if err != nil {
return nil, err
}
if !flags.FileExplorerEnabled {
return nil, errors.New("file explorer is disabled")
}
if flags.S3Endpoint == "" || flags.S3Bucket == "" {
return nil, errors.New("S3 is not configured")
}
secretKey := ""
if flags.S3SecretKey != "" && s.encryptor != nil {
secretKey, err = s.encryptor.Decrypt(flags.S3SecretKey)
if err != nil {
return nil, errors.New("failed to decrypt S3 credentials")
}
}
region := flags.S3Region
if region == "" {
region = "us-east-1"
}
cfg := aws.Config{
Region: region,
Credentials: credentials.NewStaticCredentialsProvider(flags.S3AccessKey, secretKey, ""),
}
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
o.BaseEndpoint = aws.String(flags.S3Endpoint)
o.UsePathStyle = true
})
return &s3Config{client: client, bucket: flags.S3Bucket}, nil
}
// validateAccess ensures file explorer is enabled and the user is a member of the space.
// Returns a ready S3 config on success.
func (s *FileService) validateAccess(ctx context.Context, userIDHex, spaceIDHex string) (*s3Config, error) {
cfg, err := s.buildS3Config(ctx)
if err != nil {
return nil, err
}
userID, err := bson.ObjectIDFromHex(userIDHex)
if err != nil {
return nil, errors.New("access denied")
}
spaceID, err := bson.ObjectIDFromHex(spaceIDHex)
if err != nil {
return nil, errors.New("access denied")
}
if _, err := s.membershipRepo.GetUserMembership(ctx, userID, spaceID); err != nil {
return nil, errors.New("access denied")
}
return cfg, nil
}
// spaceBase returns the S3 key prefix for a space: "spaces/<spaceIDHex>/".
func spaceBase(spaceIDHex string) string {
return "spaces/" + spaceIDHex + "/"
}
// resolveRelKey sanitises a relative key and returns the full S3 key,
// rejecting anything that would escape the space prefix.
func resolveRelKey(spaceIDHex, relKey string) (string, error) {
relKey = strings.TrimLeft(strings.TrimSpace(relKey), "/")
cleaned := path.Clean(relKey)
if cleaned == "." || cleaned == "" {
return "", errors.New("key is empty")
}
if strings.Contains(cleaned, "..") {
return "", errors.New("invalid key")
}
base := spaceBase(spaceIDHex)
full := base + cleaned
if !strings.HasPrefix(full, base) {
return "", errors.New("invalid key: outside space boundary")
}
return full, nil
}
// resolveRelPrefix sanitises a relative folder prefix and returns the full S3 prefix.
// An empty relPrefix maps to the space root folder.
func resolveRelPrefix(spaceIDHex, relPrefix string) (string, error) {
base := spaceBase(spaceIDHex)
relPrefix = strings.TrimLeft(strings.TrimSpace(relPrefix), "/")
if relPrefix == "" {
return base, nil
}
cleaned := path.Clean(relPrefix)
if cleaned == "." {
return base, nil
}
if strings.Contains(cleaned, "..") {
return "", errors.New("invalid prefix")
}
full := base + cleaned + "/"
if !strings.HasPrefix(full, base) {
return "", errors.New("invalid prefix: outside space boundary")
}
return full, nil
}
// ListObjects returns objects and virtual folders directly under relPrefix within the space.
// Returned keys are relative to the space root (no "spaces/<spaceId>/" prefix).
func (s *FileService) ListObjects(ctx context.Context, userIDHex, spaceIDHex, relPrefix string) ([]*S3Object, error) {
cfg, err := s.validateAccess(ctx, userIDHex, spaceIDHex)
if err != nil {
return nil, err
}
fullPrefix, err := resolveRelPrefix(spaceIDHex, relPrefix)
if err != nil {
return nil, err
}
base := spaceBase(spaceIDHex)
result, err := cfg.client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(cfg.bucket),
Prefix: aws.String(fullPrefix),
Delimiter: aws.String("/"),
})
if err != nil {
return nil, err
}
var objects []*S3Object
for _, cp := range result.CommonPrefixes {
if cp.Prefix != nil {
objects = append(objects, &S3Object{
Key: strings.TrimPrefix(*cp.Prefix, base),
IsFolder: true,
})
}
}
for _, obj := range result.Contents {
if obj.Key == nil || *obj.Key == fullPrefix {
continue
}
// Hide virtual .keep placeholder files used for folder creation
if path.Base(*obj.Key) == ".keep" {
continue
}
size := int64(0)
if obj.Size != nil {
size = *obj.Size
}
lastMod := ""
if obj.LastModified != nil {
lastMod = obj.LastModified.Format(time.RFC3339)
}
objects = append(objects, &S3Object{
Key: strings.TrimPrefix(*obj.Key, base),
Size: size,
LastModified: lastMod,
})
}
return objects, nil
}
// GetObjectContent streams an S3 object, enforcing space boundary.
// relKey is relative to the space root.
func (s *FileService) GetObjectContent(ctx context.Context, userIDHex, spaceIDHex, relKey string) (io.ReadCloser, string, error) {
cfg, err := s.validateAccess(ctx, userIDHex, spaceIDHex)
if err != nil {
return nil, "", err
}
fullKey, err := resolveRelKey(spaceIDHex, relKey)
if err != nil {
return nil, "", err
}
result, err := cfg.client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(cfg.bucket),
Key: aws.String(fullKey),
})
if err != nil {
return nil, "", err
}
contentType := "application/octet-stream"
if result.ContentType != nil {
contentType = *result.ContentType
}
return result.Body, contentType, nil
}
// UploadObject stores a file at relKey within the space.
func (s *FileService) UploadObject(ctx context.Context, userIDHex, spaceIDHex, relKey, contentType string, body io.Reader, size int64) error {
cfg, err := s.validateAccess(ctx, userIDHex, spaceIDHex)
if err != nil {
return err
}
fullKey, err := resolveRelKey(spaceIDHex, relKey)
if err != nil {
return err
}
if contentType == "" {
contentType = "application/octet-stream"
}
input := &s3.PutObjectInput{
Bucket: aws.String(cfg.bucket),
Key: aws.String(fullKey),
Body: body,
ContentType: aws.String(contentType),
}
if size > 0 {
input.ContentLength = aws.Int64(size)
}
_, err = cfg.client.PutObject(ctx, input)
return err
}
// CreateFolder creates a virtual folder by uploading a zero-byte .keep placeholder.
func (s *FileService) CreateFolder(ctx context.Context, userIDHex, spaceIDHex, relPath string) error {
cfg, err := s.validateAccess(ctx, userIDHex, spaceIDHex)
if err != nil {
return err
}
base := spaceBase(spaceIDHex)
relPath = strings.Trim(relPath, "/")
cleaned := path.Clean(relPath)
if cleaned == "." || cleaned == "" || strings.Contains(cleaned, "..") {
return errors.New("invalid folder path")
}
fullKey := base + cleaned + "/.keep"
if !strings.HasPrefix(fullKey, base) {
return errors.New("invalid folder path: outside space boundary")
}
zero := int64(0)
_, err = cfg.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(cfg.bucket),
Key: aws.String(fullKey),
Body: bytes.NewReader(nil),
ContentType: aws.String("application/octet-stream"),
ContentLength: aws.Int64(zero),
})
return err
}
// DeleteObject removes a single object within the space.
func (s *FileService) DeleteObject(ctx context.Context, userIDHex, spaceIDHex, relKey string) error {
cfg, err := s.validateAccess(ctx, userIDHex, spaceIDHex)
if err != nil {
return err
}
fullKey, err := resolveRelKey(spaceIDHex, relKey)
if err != nil {
return err
}
_, err = cfg.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(cfg.bucket),
Key: aws.String(fullKey),
})
return err
}
// DeleteFolder recursively deletes all objects under relPrefix within the space.
func (s *FileService) DeleteFolder(ctx context.Context, userIDHex, spaceIDHex, relPrefix string) error {
cfg, err := s.validateAccess(ctx, userIDHex, spaceIDHex)
if err != nil {
return err
}
fullPrefix, err := resolveRelPrefix(spaceIDHex, relPrefix)
if err != nil {
return err
}
// Safety net: refuse to delete the entire space root
if fullPrefix == spaceBase(spaceIDHex) {
return errors.New("cannot delete the space root folder")
}
paginator := s3.NewListObjectsV2Paginator(cfg.client, &s3.ListObjectsV2Input{
Bucket: aws.String(cfg.bucket),
Prefix: aws.String(fullPrefix),
})
var toDelete []types.ObjectIdentifier
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return err
}
for _, obj := range page.Contents {
if obj.Key != nil {
toDelete = append(toDelete, types.ObjectIdentifier{Key: obj.Key})
}
}
}
if len(toDelete) == 0 {
return nil
}
// Delete in batches of 1000 (S3 limit per DeleteObjects call)
for i := 0; i < len(toDelete); i += 1000 {
end := i + 1000
if end > len(toDelete) {
end = len(toDelete)
}
_, err := cfg.client.DeleteObjects(ctx, &s3.DeleteObjectsInput{
Bucket: aws.String(cfg.bucket),
Delete: &types.Delete{
Objects: toDelete[i:end],
Quiet: aws.Bool(true),
},
})
if err != nil {
return err
}
}
return nil
}

View File

@@ -6,10 +6,10 @@ import (
"strings"
"time"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"github.com/noteapp/backend/internal/infrastructure/security"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/security"
"go.mongodb.org/mongo-driver/v2/bson"
)

View File

@@ -5,8 +5,8 @@ import (
"errors"
"strings"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"go.mongodb.org/mongo-driver/v2/bson"
)

View File

@@ -5,9 +5,9 @@ import (
"errors"
"time"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/domain/repositories"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/repositories"
"go.mongodb.org/mongo-driver/v2/bson"
)

View File

@@ -39,6 +39,12 @@ type FeatureFlags struct {
RegistrationEnabled bool `bson:"registration_enabled"`
ProviderLoginEnabled bool `bson:"provider_login_enabled"`
PublicSharingEnabled bool `bson:"public_sharing_enabled"`
FileExplorerEnabled bool `bson:"file_explorer_enabled"`
S3Endpoint string `bson:"s3_endpoint,omitempty"`
S3Bucket string `bson:"s3_bucket,omitempty"`
S3Region string `bson:"s3_region,omitempty"`
S3AccessKey string `bson:"s3_access_key,omitempty"`
S3SecretKey string `bson:"s3_secret_key,omitempty"` // AES-256-GCM encrypted
}
// NewDefaultFeatureFlags returns safe defaults for a new deployment.
@@ -47,5 +53,6 @@ func NewDefaultFeatureFlags() *FeatureFlags {
RegistrationEnabled: true,
ProviderLoginEnabled: true,
PublicSharingEnabled: true,
FileExplorerEnabled: false,
}
}

View File

@@ -3,7 +3,7 @@ package repositories
import (
"context"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"go.mongodb.org/mongo-driver/v2/bson"
)

View File

@@ -3,7 +3,7 @@ package repositories
import (
"context"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"go.mongodb.org/mongo-driver/v2/bson"
)
@@ -174,6 +174,9 @@ type AuthProviderRepository interface {
// GetAllProviders retrieves all active providers
GetAllProviders(ctx context.Context) ([]*entities.AuthProvider, error)
// GetAllProvidersForAdmin retrieves all providers, including inactive ones
GetAllProvidersForAdmin(ctx context.Context) ([]*entities.AuthProvider, error)
// UpdateProvider updates a provider
UpdateProvider(ctx context.Context, provider *entities.AuthProvider) error

View File

@@ -0,0 +1,114 @@
package auth
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/redis/go-redis/v9"
)
// SessionData stores authenticated identity data in Redis.
type SessionData struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Username string `json:"username"`
}
// SessionManager handles Redis-backed session lifecycle operations.
type SessionManager struct {
redis *redis.Client
ttl time.Duration
prefix string
}
func NewSessionManager(redisClient *redis.Client, ttl time.Duration) *SessionManager {
if ttl <= 0 {
ttl = 7 * 24 * time.Hour
}
return &SessionManager{
redis: redisClient,
ttl: ttl,
prefix: "session:",
}
}
func (m *SessionManager) TTL() time.Duration {
return m.ttl
}
func (m *SessionManager) CreateSession(ctx context.Context, data *SessionData) (string, error) {
if data == nil {
return "", errors.New("session data is required")
}
sessionID, err := GenerateRandomToken(32)
if err != nil {
return "", err
}
payload, err := json.Marshal(data)
if err != nil {
return "", err
}
if err := m.redis.Set(ctx, m.key(sessionID), payload, m.ttl).Err(); err != nil {
return "", err
}
return sessionID, nil
}
func (m *SessionManager) GetSession(ctx context.Context, sessionID string) (*SessionData, error) {
if sessionID == "" {
return nil, errors.New("session id is required")
}
payload, err := m.redis.Get(ctx, m.key(sessionID)).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, errors.New("session not found")
}
return nil, err
}
var data SessionData
if err := json.Unmarshal([]byte(payload), &data); err != nil {
return nil, err
}
return &data, nil
}
func (m *SessionManager) RefreshSession(ctx context.Context, sessionID string) error {
if sessionID == "" {
return errors.New("session id is required")
}
if err := m.redis.Expire(ctx, m.key(sessionID), m.ttl).Err(); err != nil {
if errors.Is(err, redis.Nil) {
return errors.New("session not found")
}
return err
}
return nil
}
func (m *SessionManager) DeleteSession(ctx context.Context, sessionID string) error {
if sessionID == "" {
return nil
}
if err := m.redis.Del(ctx, m.key(sessionID)).Err(); err != nil {
return err
}
return nil
}
func (m *SessionManager) key(sessionID string) string {
return m.prefix + sessionID
}

View File

@@ -9,7 +9,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
)
// AccountRecoveryRepository implements account recovery operations
@@ -222,6 +222,23 @@ func (r *AuthProviderRepository) GetAllProviders(ctx context.Context) ([]*entiti
return providers, nil
}
// GetAllProvidersForAdmin retrieves all providers, including inactive ones
func (r *AuthProviderRepository) GetAllProvidersForAdmin(ctx context.Context) ([]*entities.AuthProvider, error) {
var providers []*entities.AuthProvider
cursor, err := r.collection.Find(ctx, bson.M{})
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
if err = cursor.All(ctx, &providers); err != nil {
return nil, err
}
return providers, nil
}
// UpdateProvider updates a provider
func (r *AuthProviderRepository) UpdateProvider(ctx context.Context, provider *entities.AuthProvider) error {
provider.UpdatedAt = time.Now()

View File

@@ -6,7 +6,7 @@ import (
"strings"
"time"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"

View File

@@ -9,7 +9,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
)
// NoteRepository implements the note repository interface

View File

@@ -9,7 +9,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
)
// SpaceRepository implements the space repository interface

View File

@@ -9,7 +9,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"github.com/noteapp/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
)
// UserRepository implements the user repository interface

View File

@@ -4,11 +4,12 @@ import (
"encoding/json"
"net/http"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/middleware"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
)
// AdminHandler handles admin-level HTTP requests
@@ -32,6 +33,33 @@ func (h *AdminHandler) ListUsers(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]interface{}{"users": users})
}
// DeleteUser handles DELETE /admin/users/{userId}
func (h *AdminHandler) DeleteUser(w http.ResponseWriter, r *http.Request) {
targetUserID, err := bson.ObjectIDFromHex(mux.Vars(r)["userId"])
if err != nil {
http.Error(w, "invalid user id", http.StatusBadRequest)
return
}
currentUserIDHex, err := middleware.GetUserIDFromContext(r.Context())
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
currentUserID, err := bson.ObjectIDFromHex(currentUserIDHex)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if err := h.adminService.DeleteUser(r.Context(), currentUserID, targetUserID); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
}
// UpdateUserGroups handles PUT /admin/users/{userId}/groups
func (h *AdminHandler) UpdateUserGroups(w http.ResponseWriter, r *http.Request) {
userID, err := bson.ObjectIDFromHex(mux.Vars(r)["userId"])
@@ -66,6 +94,22 @@ func (h *AdminHandler) UpdateUserGroups(w http.ResponseWriter, r *http.Request)
json.NewEncoder(w).Encode(user)
}
// DeleteGroup handles DELETE /admin/groups/{groupId}
func (h *AdminHandler) DeleteGroup(w http.ResponseWriter, r *http.Request) {
groupID, err := bson.ObjectIDFromHex(mux.Vars(r)["groupId"])
if err != nil {
http.Error(w, "invalid group id", http.StatusBadRequest)
return
}
if err := h.adminService.DeleteGroup(r.Context(), groupID); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
}
// ListGroups handles GET /admin/groups
func (h *AdminHandler) ListGroups(w http.ResponseWriter, r *http.Request) {
groups, err := h.adminService.ListGroups(r.Context())
@@ -292,3 +336,19 @@ func (h *AdminHandler) UpdateFeatureFlags(w http.ResponseWriter, r *http.Request
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(flags)
}
// DeleteProvider handles DELETE /admin/auth/providers/{providerId}
func (h *AdminHandler) DeleteProvider(w http.ResponseWriter, r *http.Request) {
providerID, err := bson.ObjectIDFromHex(mux.Vars(r)["providerId"])
if err != nil {
http.Error(w, "invalid provider id", http.StatusBadRequest)
return
}
if err := h.adminService.DeleteProvider(r.Context(), providerID); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -1,32 +1,35 @@
package handlers
import (
"encoding/base64"
"encoding/json"
"net/http"
"net/url"
"os"
"strings"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/auth"
"github.com/gorilla/mux"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"github.com/noteapp/backend/internal/infrastructure/auth"
"go.mongodb.org/mongo-driver/v2/bson"
)
// AuthHandler handles authentication endpoints
type AuthHandler struct {
authService *services.AuthService
sessionManager *auth.SessionManager
}
// NewAuthHandler creates a new auth handler
func NewAuthHandler(authService *services.AuthService) *AuthHandler {
func NewAuthHandler(authService *services.AuthService, sessionManager *auth.SessionManager) *AuthHandler {
return &AuthHandler{
authService: authService,
sessionManager: sessionManager,
}
}
const sessionCookieName = "session_id"
// Register handles user registration
func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -56,6 +59,11 @@ func (h *AuthHandler) Register(w http.ResponseWriter, r *http.Request) {
return
}
if err := h.setSessionCookie(w, r, response.User); err != nil {
http.Error(w, "Failed to create session", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
@@ -79,16 +87,10 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
return
}
// Set secure HTTP-only cookie for refresh token
http.SetCookie(w, &http.Cookie{
Name: "refresh_token",
Value: response.RefreshToken,
Path: "/",
MaxAge: 7 * 24 * 60 * 60, // 7 days
HttpOnly: true,
Secure: isSecureRequest(r),
SameSite: http.SameSiteLaxMode,
})
if err := h.setSessionCookie(w, r, response.User); err != nil {
http.Error(w, "Failed to create session", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
@@ -96,15 +98,12 @@ func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
// Logout handles user logout
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
// Clear refresh token cookie
http.SetCookie(w, &http.Cookie{
Name: "refresh_token",
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: isSecureRequest(r),
})
sessionCookie, err := r.Cookie(sessionCookieName)
if err == nil {
_ = h.sessionManager.DeleteSession(r.Context(), sessionCookie.Value)
}
h.clearSessionCookie(w, r)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "Logged out successfully"})
@@ -122,6 +121,18 @@ func (h *AuthHandler) ListProviders(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]interface{}{"providers": providers})
}
// ListProvidersForAdmin returns all OAuth/OIDC providers, including inactive ones.
func (h *AuthHandler) ListProvidersForAdmin(w http.ResponseWriter, r *http.Request) {
providers, err := h.authService.ListProvidersForAdmin(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"providers": providers})
}
// CreateProvider stores a new OAuth/OIDC provider configuration.
func (h *AuthHandler) CreateProvider(w http.ResponseWriter, r *http.Request) {
var req dto.CreateAuthProviderRequest
@@ -141,6 +152,30 @@ func (h *AuthHandler) CreateProvider(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(provider)
}
// UpdateProvider updates an existing OAuth/OIDC provider configuration.
func (h *AuthHandler) UpdateProvider(w http.ResponseWriter, r *http.Request) {
providerID, err := bson.ObjectIDFromHex(mux.Vars(r)["providerId"])
if err != nil {
http.Error(w, "Invalid provider ID", http.StatusBadRequest)
return
}
var req dto.UpdateAuthProviderRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
provider, err := h.authService.UpdateProvider(r.Context(), providerID, &req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(provider)
}
// StartProviderLogin redirects the browser to the selected provider.
func (h *AuthHandler) StartProviderLogin(w http.ResponseWriter, r *http.Request) {
providerID, err := bson.ObjectIDFromHex(mux.Vars(r)["providerId"])
@@ -191,7 +226,7 @@ func (h *AuthHandler) CompleteProviderLogin(w http.ResponseWriter, r *http.Reque
response, err := h.authService.CompleteProviderLogin(r.Context(), providerID, r.URL.Query().Get("code"), buildBackendURL(r, "/api/v1/auth/providers/"+providerID.Hex()+"/callback"))
if err != nil {
http.Redirect(w, r, buildFrontendLoginURL("oauth_error", err.Error(), "", nil), http.StatusFound)
http.Redirect(w, r, buildFrontendLoginURL("oauth_error", err.Error()), http.StatusFound)
return
}
@@ -205,17 +240,12 @@ func (h *AuthHandler) CompleteProviderLogin(w http.ResponseWriter, r *http.Reque
SameSite: http.SameSiteLaxMode,
})
http.SetCookie(w, &http.Cookie{
Name: "refresh_token",
Value: response.RefreshToken,
Path: "/",
MaxAge: 7 * 24 * 60 * 60,
HttpOnly: true,
Secure: isSecureRequest(r),
SameSite: http.SameSiteLaxMode,
})
if err := h.setSessionCookie(w, r, response.User); err != nil {
http.Redirect(w, r, buildFrontendLoginURL("oauth_error", "Failed to create session"), http.StatusFound)
return
}
http.Redirect(w, r, buildFrontendLoginURL("oauth_success", "", response.AccessToken, response.User), http.StatusFound)
http.Redirect(w, r, buildFrontendLoginURL("oauth_success", ""), http.StatusFound)
}
// RefreshToken handles token refresh
@@ -225,23 +255,57 @@ func (h *AuthHandler) RefreshToken(w http.ResponseWriter, r *http.Request) {
return
}
// Get refresh token from cookie
cookie, err := r.Cookie("refresh_token")
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
http.Error(w, "Refresh token not found", http.StatusUnauthorized)
http.Error(w, "Session not found", http.StatusUnauthorized)
return
}
accessToken, err := h.authService.RefreshAccessToken(r.Context(), cookie.Value)
sessionData, err := h.sessionManager.GetSession(r.Context(), cookie.Value)
if err != nil {
http.Error(w, "Invalid refresh token", http.StatusUnauthorized)
http.Error(w, "Invalid session", http.StatusUnauthorized)
return
}
if err := h.sessionManager.RefreshSession(r.Context(), cookie.Value); err == nil {
http.SetCookie(w, h.newSessionCookie(r, cookie.Value))
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"access_token": accessToken,
"expires_in": 3600,
"user": sessionData,
"expires_in": int(h.sessionManager.TTL().Seconds()),
})
}
// Me returns the currently authenticated user profile.
func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
sessionCookie, err := r.Cookie(sessionCookieName)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
sessionData, err := h.sessionManager.GetSession(r.Context(), sessionCookie.Value)
if err != nil {
h.clearSessionCookie(w, r)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
user, err := h.authService.GetUserProfile(r.Context(), sessionData.UserID)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if err := h.sessionManager.RefreshSession(r.Context(), sessionCookie.Value); err == nil {
http.SetCookie(w, h.newSessionCookie(r, sessionCookie.Value))
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"user": user,
"expires_in": int(h.sessionManager.TTL().Seconds()),
})
}
@@ -268,7 +332,7 @@ func buildBackendURL(r *http.Request, path string) string {
return scheme + "://" + r.Host + path
}
func buildFrontendLoginURL(status, message, accessToken string, user *dto.UserDTO) string {
func buildFrontendLoginURL(status, message string) string {
frontendURL := os.Getenv("FRONTEND_URL")
if frontendURL == "" {
frontendURL = "http://localhost:5173"
@@ -286,14 +350,48 @@ func buildFrontendLoginURL(status, message, accessToken string, user *dto.UserDT
if message != "" {
query.Set("message", message)
}
if accessToken != "" {
query.Set("access_token", accessToken)
}
if user != nil {
payload, _ := json.Marshal(user)
query.Set("user_json", string(payload))
query.Set("user", base64.RawURLEncoding.EncodeToString(payload))
}
parsed.RawQuery = query.Encode()
return parsed.String()
}
func (h *AuthHandler) setSessionCookie(w http.ResponseWriter, r *http.Request, user *dto.UserDTO) error {
if user == nil {
return nil
}
sessionID, err := h.sessionManager.CreateSession(r.Context(), &auth.SessionData{
UserID: user.ID,
Email: user.Email,
Username: user.Username,
})
if err != nil {
return err
}
http.SetCookie(w, h.newSessionCookie(r, sessionID))
return nil
}
func (h *AuthHandler) newSessionCookie(r *http.Request, sessionID string) *http.Cookie {
return &http.Cookie{
Name: sessionCookieName,
Value: sessionID,
Path: "/",
MaxAge: int(h.sessionManager.TTL().Seconds()),
HttpOnly: true,
Secure: isSecureRequest(r),
SameSite: http.SameSiteLaxMode,
}
}
func (h *AuthHandler) clearSessionCookie(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: isSecureRequest(r),
SameSite: http.SameSiteLaxMode,
})
}

View File

@@ -7,9 +7,9 @@ import (
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"github.com/noteapp/backend/internal/interfaces/middleware"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/middleware"
)
// CategoryHandler handles category endpoints

View File

@@ -0,0 +1,273 @@
package handlers
import (
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"path"
"strings"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/middleware"
"github.com/gorilla/mux"
)
const maxUploadSize = 100 << 20 // 100 MB
// FileHandler exposes S3 file explorer endpoints scoped to spaces.
type FileHandler struct {
fileService *services.FileService
}
// NewFileHandler creates a new FileHandler.
func NewFileHandler(fileService *services.FileService) *FileHandler {
return &FileHandler{fileService: fileService}
}
// extractContext extracts and validates spaceId (URL) and userId (JWT context).
func (h *FileHandler) extractContext(r *http.Request) (spaceID, userID string, err error) {
spaceID = mux.Vars(r)["spaceId"]
if spaceID == "" {
return "", "", fmt.Errorf("missing spaceId")
}
userID, err = middleware.GetUserIDFromContext(r.Context())
return
}
// cleanKey sanitises a user-supplied relative key (strips leading slash, resolves .).
func cleanKey(raw string) string {
k := strings.TrimLeft(strings.TrimSpace(raw), "/")
if c := path.Clean(k); c != "." {
return c
}
return ""
}
// cleanPrefix sanitises a user-supplied relative prefix.
func cleanPrefix(raw string) string {
p := strings.TrimLeft(strings.TrimSpace(raw), "/")
if c := path.Clean(p); c != "." {
return c
}
return ""
}
// respondError maps service errors to appropriate HTTP status codes.
func respondError(w http.ResponseWriter, err error) {
msg := err.Error()
switch {
case strings.Contains(msg, "access denied"), strings.Contains(msg, "disabled"):
http.Error(w, msg, http.StatusForbidden)
default:
http.Error(w, msg, http.StatusBadRequest)
}
}
// ListFiles handles GET /api/v1/spaces/{spaceId}/files/list?prefix=
func (h *FileHandler) ListFiles(w http.ResponseWriter, r *http.Request) {
spaceID, userID, err := h.extractContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
relPrefix := cleanPrefix(r.URL.Query().Get("prefix"))
objects, err := h.fileService.ListObjects(r.Context(), userID, spaceID, relPrefix)
if err != nil {
respondError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"objects": objects,
"prefix": relPrefix,
})
}
// GetFile handles GET /api/v1/spaces/{spaceId}/files/object?key=
// Also accepts ?token= as a fallback auth mechanism so markdown images render in-browser.
func (h *FileHandler) GetFile(w http.ResponseWriter, r *http.Request) {
spaceID, userID, err := h.extractContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
relKey := cleanKey(r.URL.Query().Get("key"))
if relKey == "" {
http.Error(w, "key is required", http.StatusBadRequest)
return
}
body, contentType, err := h.fileService.GetObjectContent(r.Context(), userID, spaceID, relKey)
if err != nil {
if strings.Contains(err.Error(), "access denied") {
http.Error(w, "access denied", http.StatusForbidden)
return
}
http.Error(w, "file not found", http.StatusNotFound)
return
}
defer body.Close()
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", "private, max-age=3600")
io.Copy(w, body) //nolint:errcheck
}
// UploadFile handles POST /api/v1/spaces/{spaceId}/files/upload (multipart/form-data)
// Form fields:
// - path: optional relative folder within the space (e.g. "docs/2024")
// - files: one or more file uploads
func (h *FileHandler) UploadFile(w http.ResponseWriter, r *http.Request) {
spaceID, userID, err := h.extractContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
http.Error(w, "request too large", http.StatusRequestEntityTooLarge)
return
}
relFolder := cleanPrefix(r.FormValue("path"))
fileHeaders := r.MultipartForm.File["files"]
if len(fileHeaders) == 0 {
http.Error(w, "no files provided", http.StatusBadRequest)
return
}
var uploaded []string
for _, fh := range fileHeaders {
filename := path.Base(fh.Filename)
if filename == "." || filename == "" {
continue
}
var relKey string
if relFolder != "" {
relKey = relFolder + "/" + filename
} else {
relKey = filename
}
// Detect content-type from header then extension
ct := fh.Header.Get("Content-Type")
if ct == "" || ct == "application/octet-stream" {
if ext := path.Ext(filename); ext != "" {
if t := mime.TypeByExtension(ext); t != "" {
ct = t
}
}
}
if ct == "" {
ct = "application/octet-stream"
}
f, err := fh.Open()
if err != nil {
http.Error(w, "failed to read uploaded file", http.StatusInternalServerError)
return
}
uploadErr := h.fileService.UploadObject(r.Context(), userID, spaceID, relKey, ct, f, fh.Size)
f.Close()
if uploadErr != nil {
respondError(w, uploadErr)
return
}
uploaded = append(uploaded, relKey)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]interface{}{"uploaded": uploaded})
}
// CreateFolder handles POST /api/v1/spaces/{spaceId}/files/folder
// JSON body: {"path": "new-folder-name"}
func (h *FileHandler) CreateFolder(w http.ResponseWriter, r *http.Request) {
spaceID, userID, err := h.extractContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var body struct {
Path string `json:"path"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
relPath := cleanPrefix(body.Path)
if relPath == "" {
http.Error(w, "path is required", http.StatusBadRequest)
return
}
if err := h.fileService.CreateFolder(r.Context(), userID, spaceID, relPath); err != nil {
respondError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"path": relPath})
}
// DeleteFile handles DELETE /api/v1/spaces/{spaceId}/files/object?key=
func (h *FileHandler) DeleteFile(w http.ResponseWriter, r *http.Request) {
spaceID, userID, err := h.extractContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
relKey := cleanKey(r.URL.Query().Get("key"))
if relKey == "" {
http.Error(w, "key is required", http.StatusBadRequest)
return
}
if err := h.fileService.DeleteObject(r.Context(), userID, spaceID, relKey); err != nil {
if strings.Contains(err.Error(), "access denied") {
http.Error(w, "access denied", http.StatusForbidden)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// DeleteFolder handles DELETE /api/v1/spaces/{spaceId}/files/folder?prefix=
func (h *FileHandler) DeleteFolder(w http.ResponseWriter, r *http.Request) {
spaceID, userID, err := h.extractContext(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
relPrefix := cleanPrefix(r.URL.Query().Get("prefix"))
if relPrefix == "" {
http.Error(w, "prefix is required", http.StatusBadRequest)
return
}
if err := h.fileService.DeleteFolder(r.Context(), userID, spaceID, relPrefix); err != nil {
if strings.Contains(err.Error(), "access denied") {
http.Error(w, "access denied", http.StatusForbidden)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -8,9 +8,9 @@ import (
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"github.com/noteapp/backend/internal/interfaces/middleware"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/middleware"
)
// NoteHandler handles note endpoints

View File

@@ -8,8 +8,8 @@ import (
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/v2/bson"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
)
// PublicHandler handles unauthenticated public read-only requests

View File

@@ -4,7 +4,7 @@ import (
"encoding/json"
"net/http"
"github.com/noteapp/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
)
// SettingsHandler handles public app settings endpoints.

View File

@@ -4,10 +4,10 @@ import (
"encoding/json"
"net/http"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/interfaces/middleware"
"github.com/gorilla/mux"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"github.com/noteapp/backend/internal/interfaces/middleware"
"go.mongodb.org/mongo-driver/v2/bson"
)

View File

@@ -6,7 +6,7 @@ import (
"net/http"
"strings"
"github.com/noteapp/backend/internal/infrastructure/auth"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/auth"
)
// ContextKey is a custom type for context keys
@@ -21,12 +21,14 @@ const (
// AuthMiddleware verifies JWT tokens
type AuthMiddleware struct {
jwtManager *auth.JWTManager
sessionManager *auth.SessionManager
}
// NewAuthMiddleware creates a new auth middleware
func NewAuthMiddleware(jwtManager *auth.JWTManager) *AuthMiddleware {
func NewAuthMiddleware(jwtManager *auth.JWTManager, sessionManager *auth.SessionManager) *AuthMiddleware {
return &AuthMiddleware{
jwtManager: jwtManager,
sessionManager: sessionManager,
}
}
@@ -41,10 +43,23 @@ func (m *AuthMiddleware) Middleware(next http.Handler) http.Handler {
return
}
// Extract token from Authorization header
if sessionCookie, err := r.Cookie("session_id"); err == nil && sessionCookie.Value != "" {
sessionData, sessionErr := m.sessionManager.GetSession(r.Context(), sessionCookie.Value)
if sessionErr == nil {
_ = m.sessionManager.RefreshSession(r.Context(), sessionCookie.Value)
ctx := context.WithValue(r.Context(), UserIDKey, sessionData.UserID)
ctx = context.WithValue(ctx, EmailKey, sessionData.Email)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
return
}
}
// Fall back to Authorization header for backwards compatibility.
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Missing authorization header", http.StatusUnauthorized)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

View File

@@ -79,6 +79,7 @@ func CORSMiddleware(next http.Handler) http.Handler {
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Max-Age", "600")
if r.Method == http.MethodOptions {

View File

@@ -8,7 +8,7 @@ import (
"testing"
"time"
"github.com/noteapp/backend/internal/infrastructure/database"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/database"
)
// TestDatabaseConnection tests MongoDB connection

View File

@@ -4,11 +4,11 @@ import (
"context"
"testing"
"github.com/noteapp/backend/internal/application/dto"
"github.com/noteapp/backend/internal/application/services"
"github.com/noteapp/backend/internal/domain/entities"
"github.com/noteapp/backend/internal/infrastructure/auth"
"github.com/noteapp/backend/internal/infrastructure/security"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/dto"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/application/services"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/domain/entities"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/auth"
"gitea.hostxtra.co.uk/mrhid6/notely/backend/internal/infrastructure/security"
"go.mongodb.org/mongo-driver/v2/bson"
)

View File

@@ -44,20 +44,6 @@ http {
listen 80;
server_name localhost;
# API routes
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://notely;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
# Health check
location /health {
proxy_pass http://notely;

View File

@@ -1,6 +1,17 @@
version: "3.8"
services:
redis:
image: redis:8-alpine
container_name: notely-redis
ports:
- "6379:6379"
networks:
- notely-network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
mongodb:
image: mongo:8.0
container_name: notely-mongodb
@@ -39,9 +50,15 @@ services:
DEFAULT_ADMIN_EMAIL: ${DEFAULT_ADMIN_EMAIL}
DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME}
DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD}
REDIS_ADDR: ${REDIS_ADDR}
REDIS_PASSWORD: ${REDIS_PASSWORD}
REDIS_DB: ${REDIS_DB}
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS}
depends_on:
mongodb:
condition: service_healthy
redis:
condition: service_healthy
networks:
- notely-network

33
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,33 @@
import js from "@eslint/js";
import globals from "globals";
import pluginVue from "eslint-plugin-vue";
export default [
{
ignores: ["dist/**", "node_modules/**"],
},
js.configs.recommended,
...pluginVue.configs["flat/essential"],
{
files: ["**/*.{js,mjs,cjs,vue}"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
globals: {
...globals.browser,
...globals.node,
},
},
rules: {
"no-unused-vars": [
"warn",
{
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
},
],
"no-console": "off",
"vue/multi-word-component-names": "off",
},
},
];

File diff suppressed because it is too large Load Diff

View File

@@ -7,7 +7,9 @@
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs"
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@mdi/font": "^7.4.47",
@@ -15,14 +17,21 @@
"axios": "^1.4.0",
"bootstrap": "^5.3.0",
"dompurify": "^3.0.0",
"highlight.js": "^11.11.1",
"marked": "^9.0.0",
"marked-highlight": "^2.2.3",
"pinia": "^2.1.0",
"vue": "^3.3.0",
"vue-router": "^4.2.0"
},
"devDependencies": {
"@eslint/js": "^9.22.0",
"@vitejs/plugin-vue": "^4.2.0",
"@vue/test-utils": "^2.4.0",
"eslint": "^9.22.0",
"eslint-plugin-vue": "^9.32.0",
"globals": "^16.0.0",
"jsdom": "^29.0.1",
"vite": "^4.3.0",
"vitest": "^0.34.0"
}

View File

@@ -44,9 +44,20 @@
<!-- Search -->
<div class="search-box nav-search" v-if="!isAdminRoute">
<input type="text" class="form-control form-control-sm" placeholder="Search notes..." v-model="searchQuery" @keyup.enter="performSearch" />
<input type="text" class="form-control" placeholder="Search notes..." v-model="searchQuery" @keyup.enter="performSearch" />
</div>
<!-- Theme Toggle -->
<button
class="btn btn-outline-light theme-toggle"
type="button"
:aria-label="isDarkMode ? 'Switch to light mode' : 'Switch to dark mode'"
:title="isDarkMode ? 'Switch to light mode' : 'Switch to dark mode'"
@click="isDarkMode = !isDarkMode"
>
<i :class="isDarkMode ? 'mdi mdi-weather-sunny' : 'mdi mdi-weather-night'" aria-hidden="true"></i>
</button>
<!-- User Menu -->
<div ref="userDropdownRef" class="dropdown nav-user-menu" v-if="currentUser" @mouseleave="showUserMenu = false">
<button class="btn btn-outline-light dropdown-toggle" type="button" @click="toggleUserMenu">
@@ -117,7 +128,7 @@
</h5>
</div>
<div class="col-auto d-flex align-items-center">
<div v-if="!selectedNote" class="btn-group me-2 d-none d-md-flex" role="group" aria-label="View mode">
<div v-if="!selectedNote || isSearchRoute" class="btn-group me-2 d-none d-md-flex" role="group" aria-label="View mode">
<button
type="button"
class="btn action-button"
@@ -140,7 +151,7 @@
</button>
</div>
<button
v-if="canEditNotes && selectedNote && !isEditingNote"
v-if="canEditNotes && selectedNote && !isEditingNote && !isSearchRoute"
class="btn btn-outline-secondary me-2 action-button"
aria-label="Edit note"
title="Edit note"
@@ -150,7 +161,7 @@
<span class="action-label">Edit Note</span>
</button>
<button
v-if="canShareSelectedNote && !isEditingNote"
v-if="canShareSelectedNote && !isEditingNote && !isSearchRoute"
class="btn btn-outline-primary me-2 action-button"
:aria-label="shareCopied ? 'Link copied' : 'Share note'"
:title="shareCopied ? 'Link copied' : 'Share note'"
@@ -169,16 +180,27 @@
<!-- Note Editor or Note List -->
<div class="content p-4">
<SearchResultsPage
v-if="isSearchRoute"
:notes="searchResults"
:query="searchQuery"
:current-page="searchPage"
:page-size="searchPageSize"
:view-mode="noteViewMode"
@select-note="selectSearchResultNote"
@page-change="setSearchPage"
/>
<NoteEditor
v-if="selectedNote && isEditingNote"
v-else-if="selectedNote && isEditingNote"
:note="selectedNote"
:category-options="categoryOptions"
:can-delete="canDeleteNotes"
:space-id="currentSpace?.id"
@save="updateNote"
@delete="deleteNote"
@cancel="cancelEditingNote"
/>
<NoteViewer v-else-if="selectedNote" :note="selectedNote" :category-options="categoryOptions" />
<NoteViewer v-else-if="selectedNote" :note="selectedNote" :category-options="categoryOptions" :space-id="currentSpace?.id" />
<NoteList
v-else
:notes="displayedNotes"
@@ -204,7 +226,7 @@
</div>
</div>
<div v-else-if="currentUser && isAdminRoute" class="container py-4">
<div v-else-if="currentUser && isAdminRoute" class="admin-route-view">
<router-view />
</div>
@@ -277,6 +299,7 @@ import CategoryTree from "./components/CategoryTree.vue";
import NoteEditor from "./components/NoteEditor.vue";
import NoteViewer from "./components/NoteViewer.vue";
import NoteList from "./components/NoteList.vue";
import SearchResultsPage from "./components/SearchResultsPage.vue";
import CreateSpaceModal from "./components/CreateSpaceModal.vue";
import CreateCategoryModal from "./components/CreateCategoryModal.vue";
import CreateNoteModal from "./components/CreateNoteModal.vue";
@@ -310,6 +333,13 @@ const shareCopied = ref(false);
const shareCopyTimeout = ref(null);
const noteViewMode = ref(localStorage.getItem("noteViewMode") || "grid");
watch(noteViewMode, (val) => localStorage.setItem("noteViewMode", val));
const isDarkMode = ref(localStorage.getItem("theme") === "dark");
const applyTheme = (dark) => {
document.documentElement.setAttribute("data-bs-theme", dark ? "dark" : "light");
localStorage.setItem("theme", dark ? "dark" : "light");
};
watch(isDarkMode, applyTheme);
applyTheme(isDarkMode.value);
const showUnlockModal = ref(false);
const unlockTargetNote = ref(null);
const unlockPassword = ref("");
@@ -318,10 +348,20 @@ const unlockingNote = ref(false);
const currentUser = computed(() => authStore.user);
const isAdminRoute = computed(() => route.path === "/admin");
const isSearchRoute = computed(() => route.path === "/search");
const isPublicRoute = computed(() => route.path.startsWith("/s/"));
const isAuthRoute = computed(() => route.path === "/login" || route.path === "/register");
const spaces = computed(() => spaceStore.spaces);
const currentSpace = computed(() => spaceStore.currentSpace);
const searchResults = computed(() => sortNotesByPriority(spaceStore.searchResults));
const searchPageSize = 12;
const searchPage = computed(() => {
const pageValue = Number.parseInt(route.query.page || "1", 10);
if (Number.isNaN(pageValue) || pageValue < 1) {
return 1;
}
return pageValue;
});
const categoryTree = computed(() => spaceStore.categoryTree);
const canCreateSpaces = computed(() => authStore.hasPermission("space.create"));
const canCreateCategories = computed(() => authStore.hasSpacePermission(currentSpace.value, "category.create"));
@@ -342,10 +382,11 @@ const canManageSpaceSettings = computed(
authStore.hasSpacePermission(currentSpace.value, "settings.member.view"),
);
const flattenCategories = (items, level = 0) =>
const flattenCategories = (items, trail = []) =>
items.flatMap((category) => {
const label = `${" ".repeat(level)}${category.name}`;
return [{ id: category.id, name: category.name, label }, ...(category.subcategories?.length ? flattenCategories(category.subcategories, level + 1) : [])];
const nextTrail = [...trail, category.name];
const label = nextTrail.join("/");
return [{ id: category.id, name: category.name, label }, ...(category.subcategories?.length ? flattenCategories(category.subcategories, nextTrail) : [])];
});
const categoryOptions = computed(() => flattenCategories(categoryTree.value));
@@ -380,7 +421,7 @@ const canLoadMoreMainNotes = computed(() => {
if (selectedCategory.value || selectedNote.value) {
return false;
}
if (searchQuery.value.trim()) {
if (isSearchRoute.value) {
return false;
}
return spaceStore.notesHasMore;
@@ -409,6 +450,10 @@ const openSpaceHome = () => {
unlockPassword.value = "";
unlockError.value = "";
searchQuery.value = "";
spaceStore.clearSearchResults();
if (route.path !== "/") {
router.push("/");
}
if (currentSpace.value?.id) {
spaceStore.fetchNotes(currentSpace.value.id, { reset: true });
}
@@ -423,6 +468,21 @@ const breadcrumbItems = computed(() => {
return [];
}
if (isSearchRoute.value) {
return [
{
label: currentSpace.value.name,
clickable: true,
onClick: openSpaceHome,
},
{
label: searchQuery.value.trim() ? `Search: ${searchQuery.value.trim()}` : "Search",
clickable: false,
onClick: null,
},
];
}
const items = [
{
label: currentSpace.value.name,
@@ -525,6 +585,30 @@ watch(
},
);
watch(
[() => route.path, () => route.query.q, () => currentSpace.value?.id],
async ([path, routeQuery, spaceId]) => {
if (path !== "/search") {
return;
}
selectedNote.value = null;
selectedCategory.value = null;
isEditingNote.value = false;
const q = typeof routeQuery === "string" ? routeQuery.trim() : "";
searchQuery.value = q;
if (!spaceId || !q) {
spaceStore.clearSearchResults();
return;
}
await spaceStore.searchNotes(q);
},
{ immediate: true },
);
watch(
() => selectedNote.value?.id,
() => {
@@ -681,11 +765,53 @@ const selectCategory = (category) => {
};
const performSearch = async () => {
if (searchQuery.value.trim()) {
await spaceStore.searchNotes(searchQuery.value);
} else if (currentSpace.value?.id) {
const q = searchQuery.value.trim();
if (!q) {
spaceStore.clearSearchResults();
if (route.path !== "/") {
await router.push("/");
}
if (currentSpace.value?.id) {
await spaceStore.fetchNotes(currentSpace.value.id, { reset: true });
}
return;
}
if (route.path !== "/search" || route.query.q !== q || route.query.page !== "1") {
await router.push({
path: "/search",
query: {
q,
page: "1",
},
});
} else {
await spaceStore.searchNotes(q);
}
};
const setSearchPage = async (page) => {
const q = typeof route.query.q === "string" ? route.query.q : "";
if (!q) {
return;
}
await router.push({
path: "/search",
query: {
q,
page: String(page),
},
});
};
const selectSearchResultNote = async (note) => {
if (!note) {
return;
}
await selectNote(note);
if (route.path === "/search") {
router.push("/");
}
};
const loadMoreMainNotes = async () => {
@@ -700,11 +826,6 @@ const createSpace = async (spaceData) => {
await spaceStore.createSpace(spaceData);
};
const createCategory = async (categoryData) => {
showCreateCategoryModal.value = false;
await spaceStore.createCategory(currentSpace.value.id, categoryData);
};
const openCreateCategoryModal = () => {
if (!canCreateCategories.value) {
return;
@@ -963,6 +1084,16 @@ const logout = () => {
display: block;
}
.admin-route-view {
flex: 1;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
width: 100%;
padding: 0;
}
@media (max-width: 768px) {
.app-navbar {
display: grid;
@@ -1078,4 +1209,21 @@ const logout = () => {
width: 100%;
}
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .sidebar-header {
border-bottom-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .breadcrumb-title {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .breadcrumb-link {
color: #7aa2f7;
}
:root[data-bs-theme="dark"] .breadcrumb-separator {
color: #4a5568;
}
</style>

View File

@@ -6,6 +6,75 @@
--border-color: #dee2e6;
}
[data-bs-theme="dark"] {
--text-color: #e2e8f0;
--bg-color: #1a1d23;
--border-color: #3a3f4b;
}
[data-bs-theme="dark"] body {
background-color: #1a1d23;
color: #e2e8f0;
}
[data-bs-theme="dark"] .sidebar {
background-color: #21252e !important;
border-color: #3a3f4b !important;
}
[data-bs-theme="dark"] .toolbar {
background-color: #21252e;
border-color: #3a3f4b !important;
}
[data-bs-theme="dark"] .main-content {
background-color: #1a1d23;
}
[data-bs-theme="dark"] .markdown-body table {
background: #21252e;
}
[data-bs-theme="dark"] .markdown-body th {
background: #2a2f3a;
}
[data-bs-theme="dark"] .markdown-body tr:nth-child(even) td {
background: #232830;
}
[data-bs-theme="dark"] .markdown-body blockquote {
background: #1e2430;
color: #a0aec0;
}
[data-bs-theme="dark"] .markdown-body :not(pre) > code {
background: #2d3748;
color: #e2e8f0;
}
[data-bs-theme="dark"] .markdown-body pre code {
background: transparent;
color: inherit;
}
[data-bs-theme="dark"] .markdown-body pre {
background: #2d3748;
color: #e2e8f0;
}
[data-bs-theme="dark"] ::-webkit-scrollbar-track {
background: #2d3748;
}
[data-bs-theme="dark"] ::-webkit-scrollbar-thumb {
background: #4a5568;
}
[data-bs-theme="dark"] ::-webkit-scrollbar-thumb:hover {
background: #718096;
}
* {
margin: 0;
padding: 0;
@@ -25,6 +94,70 @@ body,
width: 100%;
}
.markdown-body table {
width: 100%;
margin: 1rem 0;
border-collapse: collapse;
border-spacing: 0;
background: #fff;
}
.markdown-body th,
.markdown-body td {
padding: 0.7rem 0.9rem;
border: 1px solid var(--border-color);
text-align: left;
vertical-align: top;
}
.markdown-body th {
font-weight: 600;
background: #f3f6fb;
}
.markdown-body tr:nth-child(even) td {
background: #fbfcfe;
}
.markdown-body table code {
white-space: nowrap;
}
.markdown-body blockquote {
margin: 1rem 0;
padding: 0.75rem 1rem;
border-left: 4px solid #748ffc;
background: #f8f9ff;
color: #334155;
}
.markdown-body blockquote > :last-child {
margin-bottom: 0;
}
.markdown-body pre {
margin: 1rem 0;
padding: 1rem;
border-radius: 0.75rem;
background: #353943;
color: #f9fafb;
overflow-x: auto;
}
.markdown-body pre code {
background: transparent;
color: inherit;
padding: 0;
}
.markdown-body code {
font-family: "Courier New", monospace;
font-size: 0.95em;
padding: 0.1rem 0.3rem;
border-radius: 0.35rem;
background: #f1f3f5;
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 8px;

View File

@@ -0,0 +1,125 @@
<template>
<teleport to="body">
<div class="modal fade show d-block admin-modal" tabindex="-1" role="dialog" aria-modal="true" @click.self="emit('close')">
<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ mode === "create" ? "Create Group" : "Edit Group" }}</h5>
<button type="button" class="btn-close" aria-label="Close" @click="emit('close')"></button>
</div>
<form @submit.prevent="handleSubmit">
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Group name</label>
<input v-model="form.name" class="form-control" type="text" required :disabled="isSystemGroup" />
</div>
<div class="mb-3">
<label class="form-label">Description</label>
<input v-model="form.description" class="form-control" type="text" :disabled="isSystemGroup" />
</div>
<div>
<label class="form-label">Permissions (one per line)</label>
<textarea
v-model="form.permissionsText"
class="form-control permissions-textarea"
rows="10"
placeholder="space.create&#10;space.project_docs.category.create&#10;space.project_docs.*"
:disabled="isSystemGroup"
></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" @click="emit('close')">Cancel</button>
<button v-if="!isSystemGroup" type="submit" class="btn btn-primary" :disabled="submitting">
{{ submitting ? "Saving..." : mode === "create" ? "Create Group" : "Save Changes" }}
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-backdrop fade show admin-modal-backdrop"></div>
</teleport>
</template>
<script setup>
import { ref, watch } from "vue";
const props = defineProps({
mode: {
type: String,
default: "create",
},
group: {
type: Object,
default: null,
},
isSystemGroup: {
type: Boolean,
default: false,
},
submitting: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["close", "submit"]);
const form = ref({
name: "",
description: "",
permissionsText: "",
});
const hydrateForm = () => {
form.value = {
name: props.group?.name || "",
description: props.group?.description || "",
permissionsText: (props.group?.permissions || []).join("\n"),
};
};
watch(() => [props.mode, props.group], hydrateForm, { immediate: true });
const handleSubmit = () => {
emit("submit", {
name: form.value.name,
description: form.value.description,
permissionsText: form.value.permissionsText,
});
};
</script>
<style scoped>
.admin-modal {
z-index: 2000;
overflow-y: auto;
padding-top: max(0.5rem, env(safe-area-inset-top));
}
.admin-modal-backdrop {
z-index: 1990;
}
.admin-modal .modal-dialog {
margin: 1rem auto;
}
.permissions-textarea {
font-family: "Courier New", monospace;
}
@media (max-width: 767.98px) {
.admin-modal {
padding-top: max(0.75rem, env(safe-area-inset-top));
}
.admin-modal .modal-dialog {
margin: 0.75rem;
max-width: none;
}
}
</style>

View File

@@ -0,0 +1,205 @@
<template>
<teleport to="body">
<div class="modal fade show d-block admin-modal" tabindex="-1" role="dialog" aria-modal="true" @click.self="emit('close')">
<div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ mode === "create" ? "Add Identity Provider" : "Edit Identity Provider" }}</h5>
<button type="button" class="btn-close" aria-label="Close" @click="emit('close')"></button>
</div>
<form @submit.prevent="handleSubmit">
<div class="modal-body">
<div class="row g-3">
<div class="col-md-6">
<label class="form-label">Display Name <span class="text-danger">*</span></label>
<input v-model="form.name" type="text" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">Provider Type <span class="text-danger">*</span></label>
<select v-model="form.type" class="form-select">
<option value="oidc">OIDC</option>
<option value="oauth2">OAuth2</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Client ID <span class="text-danger">*</span></label>
<input v-model="form.client_id" type="text" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">
Client Secret
<span v-if="mode === 'create'" class="text-danger">*</span>
<span v-else class="text-muted small">(leave blank to keep existing)</span>
</label>
<input v-model="form.client_secret" type="password" class="form-control" :required="mode === 'create'" autocomplete="new-password" />
</div>
<div class="col-md-6">
<label class="form-label">Authorization URL <span class="text-danger">*</span></label>
<input v-model="form.authorization_url" type="url" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">Token URL <span class="text-danger">*</span></label>
<input v-model="form.token_url" type="url" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">UserInfo URL</label>
<input v-model="form.userinfo_url" type="url" class="form-control" placeholder="Optional" />
</div>
<div class="col-md-6">
<label class="form-label">ID Token Claim</label>
<input v-model="form.id_token_claim" type="text" class="form-control" placeholder="id_token" />
</div>
<div class="col-12">
<label class="form-label">Scopes</label>
<input v-model="form.scopes" type="text" class="form-control" placeholder="openid, profile, email" />
<div class="form-text">Comma-separated list of OAuth scopes.</div>
</div>
<div class="col-12">
<div class="form-check">
<input id="provider-active" v-model="form.is_active" type="checkbox" class="form-check-input" />
<label for="provider-active" class="form-check-label">Provider is active</label>
</div>
</div>
<div v-if="mode === 'edit'" class="col-12">
<div class="danger-zone border border-danger-subtle rounded p-3 mt-2">
<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2">
<div>
<div class="fw-semibold text-danger">Danger Zone</div>
<div class="small text-muted">Permanently delete this provider configuration.</div>
</div>
<button type="button" class="btn btn-sm btn-outline-danger" :disabled="submitting || deleting" @click="emit('delete', props.provider)">
<i class="mdi mdi-trash-can-outline me-1" aria-hidden="true"></i>Delete Provider
</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" @click="emit('close')">Cancel</button>
<button type="submit" class="btn btn-primary" :disabled="submitting">
{{ submitting ? "Saving..." : mode === "create" ? "Add Provider" : "Save Changes" }}
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-backdrop fade show admin-modal-backdrop"></div>
</teleport>
</template>
<script setup>
import { ref, watch } from "vue";
const props = defineProps({
mode: {
type: String,
default: "create",
},
provider: {
type: Object,
default: null,
},
submitting: {
type: Boolean,
default: false,
},
deleting: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["close", "submit", "delete"]);
const form = ref({
name: "",
type: "oidc",
client_id: "",
client_secret: "",
authorization_url: "",
token_url: "",
userinfo_url: "",
id_token_claim: "id_token",
scopes: "openid, profile, email",
is_active: true,
});
const hydrateForm = () => {
if (props.mode === "edit" && props.provider) {
form.value = {
name: props.provider.name || "",
type: props.provider.type || "oidc",
client_id: props.provider.client_id || "",
client_secret: "",
authorization_url: props.provider.authorization_url || "",
token_url: props.provider.token_url || "",
userinfo_url: props.provider.userinfo_url || "",
id_token_claim: props.provider.id_token_claim || "id_token",
scopes: (props.provider.scopes || []).join(", "),
is_active: props.provider.is_active ?? true,
};
} else {
form.value = {
name: "",
type: "oidc",
client_id: "",
client_secret: "",
authorization_url: "",
token_url: "",
userinfo_url: "",
id_token_claim: "id_token",
scopes: "openid, profile, email",
is_active: true,
};
}
};
watch(() => [props.mode, props.provider], hydrateForm, { immediate: true });
const handleSubmit = () => {
emit("submit", {
name: form.value.name,
type: form.value.type,
client_id: form.value.client_id,
client_secret: form.value.client_secret,
authorization_url: form.value.authorization_url,
token_url: form.value.token_url,
userinfo_url: form.value.userinfo_url,
id_token_claim: form.value.id_token_claim,
scopes: form.value.scopes
.split(",")
.map((s) => s.trim())
.filter(Boolean),
is_active: form.value.is_active,
});
};
</script>
<style scoped>
.admin-modal {
z-index: 2000;
overflow-y: auto;
padding-top: max(0.5rem, env(safe-area-inset-top));
}
.admin-modal-backdrop {
z-index: 1990;
}
.admin-modal .modal-dialog {
margin: 1rem auto;
}
@media (max-width: 767.98px) {
.admin-modal {
padding-top: max(0.75rem, env(safe-area-inset-top));
}
.admin-modal .modal-dialog {
margin: 0.5rem;
}
}
</style>

View File

@@ -1,7 +1,7 @@
<template>
<teleport to="body">
<div class="modal fade show d-block" tabindex="-1" role="dialog" aria-modal="true" @click.self="emit('close')">
<div class="modal-dialog modal-xl modal-dialog-centered" role="document">
<div class="modal fade show d-block admin-modal" tabindex="-1" role="dialog" aria-modal="true" @click.self="emit('close')">
<div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Space</h5>
@@ -96,7 +96,7 @@
</div>
</div>
</div>
<div class="modal-backdrop fade show"></div>
<div class="modal-backdrop fade show admin-modal-backdrop"></div>
</teleport>
</template>
@@ -252,3 +252,30 @@ const deleteSpace = async () => {
}
};
</script>
<style scoped>
.admin-modal {
z-index: 2000;
overflow-y: auto;
padding-top: max(0.5rem, env(safe-area-inset-top));
}
.admin-modal-backdrop {
z-index: 1990;
}
.admin-modal .modal-dialog {
margin: 1rem auto;
}
@media (max-width: 767.98px) {
.admin-modal {
padding-top: max(0.75rem, env(safe-area-inset-top));
}
.admin-modal .modal-dialog {
margin: 0.75rem;
max-width: none;
}
}
</style>

View File

@@ -0,0 +1,111 @@
<template>
<teleport to="body">
<div class="modal fade show d-block admin-modal" tabindex="-1" role="dialog" aria-modal="true" @click.self="emit('close')">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit User</h5>
<button type="button" class="btn-close" aria-label="Close" @click="emit('close')"></button>
</div>
<form @submit.prevent="handleSubmit">
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Username</label>
<input class="form-control" :value="user?.username || ''" type="text" disabled />
</div>
<div class="mb-3">
<label class="form-label">Email</label>
<input class="form-control" :value="user?.email || ''" type="text" disabled />
</div>
<div class="mb-3">
<label class="form-label">Status</label>
<input class="form-control" :value="user?.is_active ? 'Active' : 'Inactive'" type="text" disabled />
</div>
<div>
<label class="form-label">Groups</label>
<select v-model="groupIds" class="form-select" multiple>
<option v-for="group in groups" :key="group.id" :value="group.id">
{{ group.name }}
</option>
</select>
<div class="small text-muted mt-1">Ctrl/Cmd+Click for multiple groups</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" @click="emit('close')">Cancel</button>
<button type="submit" class="btn btn-primary" :disabled="submitting">
{{ submitting ? "Saving..." : "Save Changes" }}
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-backdrop fade show admin-modal-backdrop"></div>
</teleport>
</template>
<script setup>
import { ref, watch } from "vue";
const props = defineProps({
user: {
type: Object,
default: null,
},
groups: {
type: Array,
default: () => [],
},
submitting: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(["close", "submit"]);
const groupIds = ref([]);
watch(
() => props.user,
(user) => {
groupIds.value = [...(user?.group_ids || [])];
},
{ immediate: true },
);
const handleSubmit = () => {
emit("submit", { group_ids: groupIds.value });
};
</script>
<style scoped>
.admin-modal {
z-index: 2000;
overflow-y: auto;
padding-top: max(0.5rem, env(safe-area-inset-top));
}
.admin-modal-backdrop {
z-index: 1990;
}
.admin-modal .modal-dialog {
margin: 1rem auto;
}
@media (max-width: 767.98px) {
.admin-modal {
padding-top: max(0.75rem, env(safe-area-inset-top));
}
.admin-modal .modal-dialog {
margin: 0.75rem;
max-width: none;
}
}
</style>

View File

@@ -275,4 +275,53 @@ const handleDeleteCategory = (category) => {
.subcategories {
margin-top: 0.25rem;
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .category-header:hover {
background-color: #2d3748;
}
:root[data-bs-theme="dark"] .menu-button {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .menu-button:hover {
background-color: rgba(255, 255, 255, 0.08);
}
:root[data-bs-theme="dark"] .menu-dropdown {
background: #2d3748;
border-color: #4a5568;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
}
:root[data-bs-theme="dark"] .menu-item {
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .menu-item:hover {
background-color: #374151;
}
:root[data-bs-theme="dark"] .note-item:hover {
background-color: #2d3748;
}
:root[data-bs-theme="dark"] .note-item.is-pinned {
background: #1a3a5c;
border-color: #2d6a9f;
}
:root[data-bs-theme="dark"] .note-item.is-pinned:hover {
background: #1e4470;
}
:root[data-bs-theme="dark"] .note-item.is-featured {
background: #3a2e0a;
border-color: #7a5a0a;
}
:root[data-bs-theme="dark"] .note-item.is-featured:hover {
background: #453710;
}
</style>

View File

@@ -0,0 +1,350 @@
<template>
<div
class="file-explorer d-flex flex-column border rounded"
style="min-height: 300px"
@dragover.prevent="dragOver = true"
@dragleave="dragOver = false"
@drop.prevent="handleDrop"
:class="{ 'drag-active': dragOver }"
>
<!-- Breadcrumb toolbar -->
<div class="file-explorer-header px-2 py-1 border-bottom bg-light d-flex align-items-center gap-1 flex-wrap">
<i class="mdi mdi-folder-network-outline text-muted me-1" aria-hidden="true"></i>
<button class="btn btn-link btn-sm p-0 text-decoration-none text-dark" @click="navigateTo('')">Space Files</button>
<template v-for="(seg, idx) in breadcrumbs" :key="idx">
<span class="text-muted">/</span>
<button class="btn btn-link btn-sm p-0 text-decoration-none text-dark" @click="navigateTo(seg.prefix)">{{ seg.name }}</button>
</template>
<div class="ms-auto d-flex gap-1">
<button class="btn btn-sm btn-outline-secondary py-0 px-1" title="Upload files" @click="fileInputRef.click()">
<i class="mdi mdi-upload" aria-hidden="true"></i>
</button>
<button class="btn btn-sm btn-outline-secondary py-0 px-1" title="New folder" @click="showNewFolderInput = !showNewFolderInput">
<i class="mdi mdi-folder-plus-outline" aria-hidden="true"></i>
</button>
<button class="btn btn-sm btn-link p-0 text-muted" title="Refresh" @click="loadFiles">
<i class="mdi mdi-refresh" aria-hidden="true"></i>
</button>
</div>
</div>
<!-- New folder input -->
<div v-if="showNewFolderInput" class="px-2 py-1 border-bottom bg-white d-flex gap-1">
<input
ref="newFolderInputRef"
v-model="newFolderName"
type="text"
class="form-control form-control-sm"
placeholder="Folder name"
@keyup.enter="createFolder"
@keyup.esc="showNewFolderInput = false"
/>
<button class="btn btn-sm btn-primary" @click="createFolder">Create</button>
<button class="btn btn-sm btn-secondary" @click="showNewFolderInput = false">Cancel</button>
</div>
<!-- Upload progress -->
<div v-if="uploading" class="px-2 py-1 bg-light border-bottom">
<div class="d-flex align-items-center gap-2">
<div class="progress flex-grow-1" style="height: 6px">
<div class="progress-bar progress-bar-striped progress-bar-animated" :style="{ width: uploadProgress + '%' }"></div>
</div>
<span class="text-muted" style="font-size: 0.7rem">{{ uploadProgress }}%</span>
</div>
</div>
<!-- Error message -->
<div v-if="error" class="alert alert-danger alert-sm m-1 p-1 small mb-0" role="alert">
<i class="mdi mdi-alert-circle-outline me-1" aria-hidden="true"></i>{{ error }}
<button type="button" class="btn-close float-end" style="font-size: 0.6rem" @click="error = ''"></button>
</div>
<!-- Loading / empty -->
<div v-if="loading" class="p-3 text-muted text-center small flex-grow-1"><i class="mdi mdi-loading mdi-spin me-1" aria-hidden="true"></i> Loading...</div>
<div v-else-if="!error && objects.length === 0" class="p-3 text-muted text-center small flex-grow-1">
<i class="mdi mdi-cloud-upload-outline d-block mb-1" style="font-size: 1.5rem" aria-hidden="true"></i>
Drop files here or click Upload
</div>
<!-- File list -->
<div v-else class="file-list flex-grow-1 overflow-auto">
<div
v-for="obj in objects"
:key="obj.key"
class="file-item d-flex align-items-center gap-1 px-2 py-1"
:title="obj.is_folder ? 'Open folder' : 'Insert into note'"
@click="handleClick(obj)"
>
<i :class="fileIcon(obj)" style="font-size: 1rem; width: 1.1rem; flex-shrink: 0" aria-hidden="true"></i>
<span class="flex-grow-1 text-truncate" style="font-size: 0.82rem">{{ displayName(obj) }}</span>
<span v-if="!obj.is_folder && obj.size > 0" class="text-muted flex-shrink-0" style="font-size: 0.68rem">{{ formatSize(obj.size) }}</span>
<button class="btn-delete btn btn-sm btn-link p-0 text-danger ms-1" :title="obj.is_folder ? 'Delete folder' : 'Delete file'" @click.stop="deleteItem(obj)">
<i class="mdi mdi-trash-can-outline" style="font-size: 0.85rem" aria-hidden="true"></i>
</button>
</div>
</div>
<!-- Hidden file input -->
<input ref="fileInputRef" type="file" multiple class="d-none" @change="handleFilePick" />
</div>
</template>
<script setup>
import { ref, computed, watch, nextTick } from "vue";
import apiClient from "../services/apiClient";
const props = defineProps({
spaceId: {
type: String,
required: true,
},
modelValue: {
type: String,
default: "",
},
});
const emit = defineEmits(["insert", "update:modelValue"]);
const objects = ref([]);
const loading = ref(false);
const error = ref("");
const currentPrefix = ref(props.modelValue || "");
const dragOver = ref(false);
const uploading = ref(false);
const uploadProgress = ref(0);
const showNewFolderInput = ref(false);
const newFolderName = ref("");
const fileInputRef = ref(null);
const newFolderInputRef = ref(null);
const breadcrumbs = computed(() => {
if (!currentPrefix.value) return [];
const parts = currentPrefix.value.replace(/\/$/, "").split("/").filter(Boolean);
return parts.map((name, i) => ({
name,
prefix: parts.slice(0, i + 1).join("/"),
}));
});
const loadFiles = async () => {
if (!props.spaceId) return;
loading.value = true;
error.value = "";
try {
const res = await apiClient.get(`/api/v1/spaces/${props.spaceId}/files/list`, {
params: { prefix: currentPrefix.value },
});
objects.value = res.data.objects || [];
} catch (e) {
error.value = e.response?.data || "Failed to load files";
} finally {
loading.value = false;
}
};
const navigateTo = (prefix) => {
currentPrefix.value = prefix;
emit("update:modelValue", prefix);
loadFiles();
};
const handleClick = (obj) => {
if (obj.is_folder) {
navigateTo(obj.key.replace(/\/$/, ""));
return;
}
const url = `/api/v1/spaces/${props.spaceId}/files/object?key=${encodeURIComponent(obj.key)}`;
const name = displayName(obj);
const ext = name.split(".").pop().toLowerCase();
const imageExts = ["jpg", "jpeg", "png", "gif", "webp", "svg", "bmp", "avif"];
const snippet = imageExts.includes(ext) ? `![${name}](${url})` : `[${name}](${url})`;
emit("insert", snippet);
};
const handleFilePick = (e) => {
const files = Array.from(e.target.files || []);
if (files.length > 0) uploadFiles(files);
e.target.value = "";
};
const handleDrop = (e) => {
dragOver.value = false;
const files = Array.from(e.dataTransfer?.files || []);
if (files.length > 0) uploadFiles(files);
};
const uploadFiles = async (files) => {
if (!props.spaceId || files.length === 0) return;
uploading.value = true;
uploadProgress.value = 0;
error.value = "";
const form = new FormData();
form.append("path", currentPrefix.value);
for (const f of files) form.append("files", f);
try {
await apiClient.post(`/api/v1/spaces/${props.spaceId}/files/upload`, form, {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: (e) => {
uploadProgress.value = e.total ? Math.round((e.loaded * 100) / e.total) : 50;
},
});
await loadFiles();
} catch (e) {
error.value = e.response?.data || "Upload failed";
} finally {
uploading.value = false;
uploadProgress.value = 0;
}
};
const createFolder = async () => {
const name = newFolderName.value.trim();
if (!name || !props.spaceId) return;
const path = currentPrefix.value ? `${currentPrefix.value}/${name}` : name;
error.value = "";
try {
await apiClient.post(`/api/v1/spaces/${props.spaceId}/files/folder`, { path });
newFolderName.value = "";
showNewFolderInput.value = false;
await loadFiles();
} catch (e) {
error.value = e.response?.data || "Failed to create folder";
}
};
const deleteItem = async (obj) => {
const label = displayName(obj);
if (!confirm(`Delete "${label}"?${obj.is_folder ? "\n\nThis will delete all files inside the folder." : ""}`)) return;
error.value = "";
try {
if (obj.is_folder) {
const prefix = obj.key.replace(/\/$/, "");
await apiClient.delete(`/api/v1/spaces/${props.spaceId}/files/folder`, { params: { prefix } });
} else {
await apiClient.delete(`/api/v1/spaces/${props.spaceId}/files/object`, { params: { key: obj.key } });
}
await loadFiles();
} catch (e) {
error.value = e.response?.data || "Delete failed";
}
};
const displayName = (obj) => {
const key = obj.is_folder ? obj.key.replace(/\/$/, "") : obj.key;
return key.split("/").pop() || key;
};
const fileIcon = (obj) => {
if (obj.is_folder) return "mdi mdi-folder text-warning";
const ext = displayName(obj).split(".").pop().toLowerCase();
if (["jpg", "jpeg", "png", "gif", "webp", "svg", "bmp", "avif"].includes(ext)) return "mdi mdi-file-image text-info";
if (["pdf"].includes(ext)) return "mdi mdi-file-pdf-box text-danger";
if (["doc", "docx", "odt"].includes(ext)) return "mdi mdi-file-word text-primary";
if (["xls", "xlsx", "ods"].includes(ext)) return "mdi mdi-file-excel text-success";
if (["zip", "tar", "gz", "rar", "7z"].includes(ext)) return "mdi mdi-folder-zip text-secondary";
if (["mp4", "mov", "avi", "mkv", "webm"].includes(ext)) return "mdi mdi-file-video";
if (["mp3", "wav", "ogg", "flac"].includes(ext)) return "mdi mdi-file-music";
if (["js", "ts", "py", "go", "java", "c", "cpp", "rs", "html", "css", "json", "yaml", "yml", "sh"].includes(ext)) return "mdi mdi-file-code text-success";
return "mdi mdi-file-outline text-muted";
};
const formatSize = (bytes) => {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1048576).toFixed(1)} MB`;
};
// Load on mount and when spaceId or prefix changes from parent
watch(
() => props.spaceId,
(v) => {
if (v) loadFiles();
},
{ immediate: true },
);
watch(
() => props.modelValue,
(val) => {
if (val !== currentPrefix.value) {
currentPrefix.value = val || "";
loadFiles();
}
},
);
watch(showNewFolderInput, async (v) => {
if (v) {
await nextTick();
newFolderInputRef.value?.focus();
}
});
</script>
<style scoped>
.file-explorer {
background: #fff;
overflow: hidden;
}
.file-explorer-header {
font-size: 0.8rem;
min-height: 36px;
}
.file-list {
max-height: 480px;
}
.file-item {
border-bottom: 1px solid #f0f0f0;
cursor: pointer;
transition: background 0.1s;
color: #333;
line-height: 1.3;
}
.file-item:last-child {
border-bottom: none;
}
.file-item:hover {
background-color: #f0f4ff;
}
.drag-active {
outline: 2px dashed #0d6efd;
outline-offset: -2px;
}
.btn-delete {
opacity: 0;
transition: opacity 0.1s;
}
.file-item:hover .btn-delete {
opacity: 1;
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .file-explorer {
background: #21252e;
}
:root[data-bs-theme="dark"] .file-explorer-header {
background: #21252e;
border-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .file-item {
border-bottom-color: #3a3f4b;
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .file-item:hover {
background-color: #2d3748;
}
</style>

View File

@@ -262,4 +262,20 @@ onMounted(loadProviders);
padding-right: 0.85rem;
}
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .modal-panel {
background: #21252e;
border-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .provider-modal-header {
background: linear-gradient(180deg, #2a2f3a 0%, #21252e 100%);
border-bottom-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .provider-section {
background: #2a2f3a;
border-color: #3a3f4b;
}
</style>

View File

@@ -2,10 +2,16 @@
<div class="note-editor">
<div class="editor-toolbar mb-3">
<button class="btn btn-sm btn-primary" @click="saveNote">Save</button>
<button v-if="canDelete" class="btn btn-sm btn-danger ms-2" @click="confirmDelete">Delete</button>
<button class="btn btn-sm btn-outline-secondary ms-2" @click="emit('cancel')">Cancel</button>
<button class="btn btn-sm btn-secondary ms-2" @click="togglePreview">
{{ showPreview ? "Edit" : "Preview" }}
<button
v-if="fileExplorerEnabled"
class="btn btn-sm ms-2"
:class="showFileExplorer ? 'btn-secondary' : 'btn-outline-secondary'"
:title="showFileExplorer ? 'Hide file explorer' : 'Browse & insert files'"
@click="showFileExplorer = !showFileExplorer"
>
<i class="mdi mdi-folder-open-outline me-1" aria-hidden="true"></i>
Files
</button>
<span class="save-status ms-auto" :class="saveState">{{ saveStatusLabel }}</span>
</div>
@@ -19,15 +25,19 @@
</div>
<div class="row">
<div :class="{ 'col-md-6': showPreview, 'col-12': !showPreview }">
<textarea v-model="editingNote.content" class="form-control editor-textarea" placeholder="Write your note in markdown..." @input="autoSave"></textarea>
<div :class="showFileExplorer ? 'col-12 col-md-5' : 'col-12 col-md-6'">
<textarea ref="contentTextareaRef" v-model="editingNote.content" class="form-control editor-textarea" placeholder="Write your note in markdown..." @input="autoSave"></textarea>
</div>
<div v-if="showPreview" class="col-md-6">
<div :class="showFileExplorer ? 'col-12 col-md-4 mt-3 mt-md-0' : 'col-12 col-md-6 mt-3 mt-md-0'">
<div class="preview-pane border rounded p-3">
<div v-html="renderedMarkdown"></div>
<div class="markdown-body" v-html="renderedMarkdown"></div>
</div>
</div>
<div v-if="showFileExplorer" class="col-12 col-md-3 mt-3 mt-md-0">
<FileExplorer v-model="fileExplorerPrefix" :space-id="spaceId" @insert="insertAtCursor" />
</div>
</div>
<div class="mt-3">
@@ -71,15 +81,25 @@
</select>
<input v-if="passwordAction === 'set'" v-model="notePassword" type="password" class="form-control mt-2" minlength="4" maxlength="128" placeholder="Enter a note password" />
</div>
<section v-if="canDelete && editingNote.id" class="danger-zone mt-4" aria-labelledby="danger-zone-title">
<h3 id="danger-zone-title" class="danger-zone-title mb-2">Danger Zone</h3>
<p class="danger-zone-copy mb-3">Deleting this note is permanent and cannot be undone.</p>
<button class="btn btn-danger" type="button" @click="confirmDelete">
<i class="mdi mdi-delete-outline me-1" aria-hidden="true"></i>
Delete Note
</button>
</section>
</div>
</div>
</template>
<script setup>
import { ref, computed, watch, onBeforeUnmount, onMounted } from "vue";
import { marked } from "marked";
import { ref, computed, watch, onBeforeUnmount, onMounted, nextTick } from "vue";
import DOMPurify from "dompurify";
import { useSettingsStore } from "../stores/settingsStore";
import { renderMarkdown } from "../utils/markdown.js";
import FileExplorer from "./FileExplorer.vue";
const props = defineProps({
note: {
@@ -94,14 +114,21 @@ const props = defineProps({
type: Boolean,
default: true,
},
spaceId: {
type: String,
default: "",
},
});
const emit = defineEmits(["save", "delete", "cancel"]);
const settingsStore = useSettingsStore();
const publicSharingEnabled = ref(true);
const fileExplorerEnabled = computed(() => settingsStore.fileExplorerEnabled);
const editingNote = ref({ ...props.note });
const showPreview = ref(false);
const contentTextareaRef = ref(null);
const showFileExplorer = ref(false);
const fileExplorerPrefix = ref("");
const tagsInput = ref(props.note.tags?.join(", ") || "");
const passwordAction = ref("keep");
const notePassword = ref("");
@@ -110,7 +137,7 @@ const saveState = ref("saved");
const saveStateTimeout = ref(null);
const renderedMarkdown = computed(() => {
const html = marked.parse(editingNote.value.content || "");
const html = renderMarkdown(editingNote.value.content || "");
return DOMPurify.sanitize(html);
});
@@ -201,8 +228,25 @@ const confirmDelete = () => {
}
};
const togglePreview = () => {
showPreview.value = !showPreview.value;
/** Insert markdown snippet at the textarea cursor position. */
const insertAtCursor = (snippet) => {
const textarea = contentTextareaRef.value;
if (!textarea) {
editingNote.value.content = (editingNote.value.content || "") + snippet;
autoSave();
return;
}
const start = textarea.selectionStart ?? editingNote.value.content?.length ?? 0;
const end = textarea.selectionEnd ?? start;
const before = (editingNote.value.content || "").substring(0, start);
const after = (editingNote.value.content || "").substring(end);
editingNote.value.content = before + snippet + after;
autoSave();
nextTick(() => {
const newPos = start + snippet.length;
textarea.setSelectionRange(newPos, newPos);
textarea.focus();
});
};
onBeforeUnmount(() => {
@@ -245,7 +289,7 @@ onMounted(async () => {
.editor-textarea {
font-family: "Courier New", monospace;
min-height: 400px;
min-height: 600px;
resize: vertical;
}
@@ -284,4 +328,49 @@ onMounted(async () => {
overflow-y: auto;
max-height: 600px;
}
.danger-zone {
padding: 1rem;
border: 1px solid #f3b5b5;
border-radius: 0.75rem;
background: #fff5f5;
}
.danger-zone-title {
color: #9f1c1c;
font-size: 1rem;
font-weight: 700;
}
.danger-zone-copy {
color: #7a2727;
font-size: 0.9rem;
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .editor-toolbar {
border-bottom-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .flag-check {
background: #2d3748;
border-color: #4a5568;
}
:root[data-bs-theme="dark"] .preview-pane {
background-color: #21252e;
}
:root[data-bs-theme="dark"] .danger-zone {
background: #2d1a1a;
border-color: #7a3030;
}
:root[data-bs-theme="dark"] .danger-zone-title {
color: #fc8181;
}
:root[data-bs-theme="dark"] .danger-zone-copy {
color: #fca5a5;
}
</style>

View File

@@ -180,6 +180,10 @@ const getDescription = (note) => {
.note-list--list .note-card:hover {
transform: none;
box-shadow: none;
background-color: #eef2ff;
border-color: #667eea;
border-left: 3px solid #667eea;
}
.note-list--list .note-title {
@@ -218,4 +222,51 @@ const getDescription = (note) => {
font-size: 1.45rem;
}
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .empty-notes-state {
border-color: #3a3f4b;
background: linear-gradient(180deg, #1e2430 0%, #21252e 100%);
}
:root[data-bs-theme="dark"] .empty-notes-title {
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .empty-notes-message {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .note-card {
border-color: #3a3f4b;
background-color: #21252e;
}
:root[data-bs-theme="dark"] .note-card:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}
:root[data-bs-theme="dark"] .note-list--list .note-card:hover {
background-color: #2a2f3a;
border-color: #7aa2f7;
border-left-color: #7aa2f7;
}
:root[data-bs-theme="dark"] .note-title {
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .note-preview {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .note-card.is-pinned {
background: #1a3a5c;
border-color: #2d6a9f;
}
:root[data-bs-theme="dark"] .note-card.is-featured {
background: #3a2e0a;
border-color: #7a5a0a;
}
</style>

View File

@@ -30,8 +30,8 @@
<script setup>
import { computed } from "vue";
import { marked } from "marked";
import DOMPurify from "dompurify";
import { renderMarkdown } from "../utils/markdown.js";
const props = defineProps({
note: {
@@ -42,10 +42,14 @@ const props = defineProps({
type: Array,
default: () => [],
},
spaceId: {
type: String,
default: "",
},
});
const renderedMarkdown = computed(() => {
const html = marked.parse(props.note.content || "");
const html = renderMarkdown(props.note.content || "");
return DOMPurify.sanitize(html);
});
@@ -157,8 +161,6 @@ const formatDateTime = (dateString) => new Date(dateString).toLocaleString();
.markdown-body :deep(pre) {
padding: 1rem;
border-radius: 0.75rem;
background: #111827;
color: #f9fafb;
overflow-x: auto;
}
@@ -172,4 +174,49 @@ const formatDateTime = (dateString) => new Date(dateString).toLocaleString();
border-left: 4px solid #748ffc;
background: #f8f9ff;
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .note-meta {
border-bottom-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .tag-chip {
background: #1e2d5f;
color: #93b4ff;
}
:root[data-bs-theme="dark"] .pinned-chip {
color: #7dd3fc;
background: #1a3a5c;
border-color: #2d6a9f;
}
:root[data-bs-theme="dark"] .featured-chip {
color: #fbbf24;
background: #3a2e0a;
border-color: #7a5a0a;
}
:root[data-bs-theme="dark"] .public-chip {
color: #67e8f9;
background: #0c2a3a;
border-color: #1d6a7a;
}
:root[data-bs-theme="dark"] .private-chip {
color: #c4b5fd;
background: #2d1f5e;
border-color: #5b3f9a;
}
:root[data-bs-theme="dark"] .protected-chip {
color: #fdba74;
background: #3a1f0a;
border-color: #7a4f1a;
}
:root[data-bs-theme="dark"] .markdown-body :deep(blockquote) {
background: #1e2430;
color: #94a3b8;
}
</style>

View File

@@ -0,0 +1,184 @@
<template>
<section class="search-results-page">
<header class="search-results-header">
<h2>Search Results</h2>
<p v-if="query" class="search-meta">{{ totalResults }} matches for "{{ query }}"</p>
<p v-else class="search-meta">Type in the top bar and press Enter to search notes.</p>
</header>
<div v-if="!query" class="empty-state">
<i class="mdi mdi-magnify empty-state-icon" aria-hidden="true"></i>
<h3>Start your search</h3>
<p>Use a title, content keyword, or tag to find matching notes in the selected space.</p>
</div>
<div v-else-if="totalResults === 0" class="empty-state">
<i class="mdi mdi-file-search-outline empty-state-icon" aria-hidden="true"></i>
<h3>No matching notes</h3>
<p>Try different keywords or a shorter phrase.</p>
</div>
<div v-else>
<NoteList :notes="paginatedNotes" :view-mode="viewMode" @select-note="emit('select-note', $event)" />
<nav v-if="totalPages > 1" class="pagination-bar" aria-label="Search result pages">
<button class="btn btn-outline-secondary" :disabled="currentPage <= 1" @click="goToPage(currentPage - 1)">Previous</button>
<span class="page-indicator">Page {{ currentPage }} of {{ totalPages }}</span>
<button class="btn btn-outline-secondary" :disabled="currentPage >= totalPages" @click="goToPage(currentPage + 1)">Next</button>
</nav>
</div>
</section>
</template>
<script setup>
import { computed } from "vue";
import NoteList from "./NoteList.vue";
const props = defineProps({
query: {
type: String,
default: "",
},
notes: {
type: Array,
default: () => [],
},
currentPage: {
type: Number,
default: 1,
},
pageSize: {
type: Number,
default: 12,
},
viewMode: {
type: String,
default: "grid",
},
});
const emit = defineEmits(["select-note", "page-change"]);
const totalResults = computed(() => props.notes.length);
const totalPages = computed(() => Math.max(1, Math.ceil(totalResults.value / props.pageSize)));
const normalizedPage = computed(() => {
if (!Number.isFinite(props.currentPage) || props.currentPage < 1) {
return 1;
}
return Math.min(props.currentPage, totalPages.value);
});
const paginatedNotes = computed(() => {
const start = (normalizedPage.value - 1) * props.pageSize;
return props.notes.slice(start, start + props.pageSize);
});
const goToPage = (page) => {
if (page < 1 || page > totalPages.value) {
return;
}
emit("page-change", page);
};
</script>
<style scoped>
.search-results-page {
max-width: 1200px;
margin: 0 auto;
}
.search-results-header {
margin-bottom: 1.5rem;
}
.search-results-header h2 {
margin: 0;
font-size: 1.5rem;
color: #223149;
}
.search-meta {
margin: 0.35rem 0 0;
color: #5b6f8b;
}
.pagination-bar {
margin-top: 1.25rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.85rem;
}
.page-indicator {
color: #4f637d;
font-weight: 600;
}
.empty-state {
min-height: 48vh;
border: 1px dashed #cfdae9;
border-radius: 14px;
background: radial-gradient(circle at 20% 20%, #f2f9ff 0%, #edf2ff 70%);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 2rem 1rem;
}
.empty-state-icon {
font-size: 4.2rem;
color: #60789a;
margin-bottom: 0.6rem;
}
.empty-state h3 {
margin: 0;
color: #223149;
}
.empty-state p {
margin: 0.6rem 0 0;
color: #5b6f8b;
max-width: 500px;
}
@media (max-width: 768px) {
.pagination-bar {
flex-direction: column;
}
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .search-results-header h2 {
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .search-meta {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .page-indicator {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .empty-state {
border-color: #3a3f4b;
background: radial-gradient(circle at 20% 20%, #1a2035 0%, #1e2430 70%);
}
:root[data-bs-theme="dark"] .empty-state h3 {
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .empty-state p {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .empty-state-icon {
color: #4a6fa5;
}
</style>

View File

@@ -4,6 +4,7 @@ import router from "./router";
import App from "./App.vue";
import "bootstrap/dist/css/bootstrap.min.css";
import "@mdi/font/css/materialdesignicons.min.css";
import "highlight.js/styles/github-dark.min.css";
import "./assets/styles/main.css";
const app = createApp(App);

View File

@@ -1,34 +1,40 @@
<template>
<div class="admin-page">
<div class="d-flex justify-content-between align-items-start mb-3 flex-wrap gap-2">
<div class="admin-topbar d-flex justify-content-between align-items-center mb-0 gap-2">
<button class="btn btn-outline-secondary d-md-none" type="button" aria-label="Open admin navigation" @click="showMobileSidebar = true">
<i class="mdi mdi-menu" aria-hidden="true"></i>
</button>
<div class="d-flex align-items-start gap-2">
<div>
<h2 class="mb-1">Admin Panel</h2>
<p class="text-muted mb-0">Manage users, groups, spaces, and identity providers.</p>
</div>
</div>
<button class="btn btn-outline-secondary" @click="router.push('/')">Back to Notes</button>
</div>
<div v-if="error" class="alert alert-danger">{{ error }}</div>
<div v-if="successMessage" class="alert alert-success">{{ successMessage }}</div>
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<button class="nav-link" :class="{ active: activeTab === 'users' }" @click="activeTab = 'users'">Users</button>
</li>
<li class="nav-item">
<button class="nav-link" :class="{ active: activeTab === 'groups' }" @click="activeTab = 'groups'">Groups</button>
</li>
<li class="nav-item">
<button class="nav-link" :class="{ active: activeTab === 'spaces' }" @click="activeTab = 'spaces'">Spaces</button>
</li>
<li class="nav-item">
<button class="nav-link" :class="{ active: activeTab === 'providers' }" @click="activeTab = 'providers'">Identity Providers</button>
</li>
<li class="nav-item">
<button class="nav-link" :class="{ active: activeTab === 'featureFlags' }" @click="activeTab = 'featureFlags'">Feature Flags</button>
</li>
</ul>
<div class="admin-shell">
<div v-if="showMobileSidebar" class="admin-sidebar-backdrop" @click="showMobileSidebar = false"></div>
<aside class="admin-sidebar" :class="{ open: showMobileSidebar }">
<div class="admin-sidebar-inner">
<div class="d-flex justify-content-between align-items-center px-2 py-1 d-md-none">
<h6 class="mb-0">Admin Sections</h6>
<button type="button" class="btn-close" aria-label="Close" @click="showMobileSidebar = false"></button>
</div>
<nav class="nav nav-pills flex-column gap-1 admin-nav">
<button v-for="tab in adminTabs" :key="tab.id" class="nav-link text-start" :class="{ active: activeTab === tab.id }" @click="selectTab(tab.id)">
{{ tab.label }}
</button>
</nav>
</div>
</aside>
<main class="admin-content">
<section v-if="activeTab === 'users'" class="admin-section card border-0 shadow-sm">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-2">
@@ -38,48 +44,39 @@
<div v-if="loadingUsers" class="text-muted small">Loading users...</div>
<div v-else-if="users.length === 0" class="border rounded p-3 text-muted">No users found.</div>
<div v-else class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<thead class="table-light">
<tr>
<th>Username</th>
<th>Email</th>
<th>Groups</th>
<th>Status</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
<tr v-for="u in users" :key="u.id">
<td>{{ u.username }}</td>
<td class="text-muted small">{{ u.email }}</td>
<td style="min-width: 260px">
<select
class="form-select form-select-sm"
multiple
:value="u.group_ids || []"
@change="
updateUserGroups(
u.id,
Array.from($event.target.selectedOptions).map((option) => option.value),
)
"
>
<option v-for="group in groups" :key="group.id" :value="group.id">
{{ group.name }}
</option>
</select>
<div class="small text-muted mt-1">Ctrl/Cmd+Click for multiple groups</div>
</td>
<td>
<div v-else class="list-group users-list">
<div v-for="u in users" :key="u.id" class="list-group-item user-row">
<div class="user-row-main">
<div class="user-name-line">
<span class="fw-semibold user-name">{{ u.username }}</span>
<span class="badge" :class="u.is_active ? 'text-bg-success' : 'text-bg-secondary'">
{{ u.is_active ? "Active" : "Inactive" }}
</span>
</td>
<td class="text-muted small">{{ formatDate(u.created_at) }}</td>
</tr>
</tbody>
</table>
</div>
<div class="user-meta-grid">
<div class="user-meta-item">
<div class="user-meta-label">Email</div>
<div class="user-meta-value">{{ u.email }}</div>
</div>
<div class="user-meta-item">
<div class="user-meta-label">Joined</div>
<div class="user-meta-value">{{ formatDate(u.created_at) }}</div>
</div>
<div class="user-meta-item user-meta-item-groups">
<div class="user-meta-label">Groups</div>
<div class="user-meta-value">{{ getUserGroupSummary(u) }}</div>
</div>
</div>
</div>
<div class="user-row-actions">
<div class="d-flex gap-2 user-actions-stack">
<button class="btn btn-sm btn-outline-primary" @click="openEditUserModal(u)">Edit</button>
<button class="btn btn-sm btn-outline-danger" @click="deleteUser(u)">Delete</button>
</div>
</div>
</div>
</div>
</div>
</section>
@@ -106,7 +103,10 @@
<div class="small text-muted">{{ group.description || "No description" }}</div>
<div class="small text-muted">{{ (group.permissions || []).length }} permission{{ (group.permissions || []).length === 1 ? "" : "s" }}</div>
</div>
<div class="d-flex gap-2">
<button class="btn btn-sm btn-outline-primary" @click="openEditGroupModal(group)">Edit</button>
<button class="btn btn-sm btn-outline-danger" :disabled="group.is_system" @click="deleteGroup(group)">Delete</button>
</div>
</div>
</div>
</div>
@@ -140,77 +140,32 @@
<section v-if="activeTab === 'providers'" class="admin-section card border-0 shadow-sm">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-2">
<h5 class="mb-0">Configured Providers</h5>
<div class="d-flex justify-content-between align-items-center mb-3">
<h5 class="mb-0">Identity Providers</h5>
<div class="d-flex gap-2">
<button class="btn btn-sm btn-outline-secondary" :disabled="loadingProviders" @click="loadProviders">Refresh</button>
<button class="btn btn-sm btn-primary" @click="openCreateProviderModal"><i class="mdi mdi-plus me-1" aria-hidden="true"></i>Add Provider</button>
</div>
</div>
<div v-if="loadingProviders" class="text-muted small">Loading providers...</div>
<div v-else-if="providers.length === 0" class="border rounded p-3 text-muted">No providers configured yet.</div>
<div v-else class="list-group mb-3">
<div v-else class="list-group">
<div v-for="provider in providers" :key="provider.id" class="list-group-item d-flex justify-content-between align-items-center">
<div>
<div class="fw-semibold">{{ provider.name }}</div>
<div class="small text-muted">{{ provider.type.toUpperCase() }} · {{ provider.scopes.join(", ") }}</div>
<div class="small text-muted">Callback: {{ buildCallbackUrl(provider.id) }}</div>
<div class="d-flex align-items-center gap-2">
<i
class="mdi"
:class="provider.is_active ? 'mdi-check-circle text-success' : 'mdi-close-circle text-secondary'"
:title="provider.is_active ? 'Provider enabled' : 'Provider disabled'"
aria-hidden="true"
></i>
<span class="fw-semibold">{{ provider.name }}</span>
</div>
<span class="badge" :class="provider.is_active ? 'text-bg-success' : 'text-bg-secondary'">
{{ provider.is_active ? "Active" : "Disabled" }}
</span>
<div class="d-flex gap-2">
<button class="btn btn-sm btn-outline-secondary" @click="openEditProviderModal(provider)">Edit</button>
</div>
</div>
<h6 class="mb-2">Add Provider</h6>
<form class="row g-3" @submit.prevent="createProvider">
<div class="col-md-6">
<label class="form-label">Display Name</label>
<input v-model="providerForm.name" type="text" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">Provider Type</label>
<select v-model="providerForm.type" class="form-select">
<option value="oidc">OIDC</option>
<option value="oauth2">OAuth2</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label">Client ID</label>
<input v-model="providerForm.client_id" type="text" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">Client Secret</label>
<input v-model="providerForm.client_secret" type="password" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">Authorization URL</label>
<input v-model="providerForm.authorization_url" type="url" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">Token URL</label>
<input v-model="providerForm.token_url" type="url" class="form-control" required />
</div>
<div class="col-md-6">
<label class="form-label">UserInfo URL</label>
<input v-model="providerForm.userinfo_url" type="url" class="form-control" placeholder="Optional" />
</div>
<div class="col-md-6">
<label class="form-label">ID Token Field</label>
<input v-model="providerForm.id_token_claim" type="text" class="form-control" placeholder="id_token" />
</div>
<div class="col-12">
<label class="form-label">Scopes</label>
<input v-model="providerForm.scopes" type="text" class="form-control" placeholder="openid, profile, email" />
</div>
<div class="col-12 form-check ms-2">
<input id="provider-active" v-model="providerForm.is_active" type="checkbox" class="form-check-input" />
<label for="provider-active" class="form-check-label">Provider is active</label>
</div>
<div class="col-12 d-flex justify-content-end">
<button type="submit" class="btn btn-primary" :disabled="submittingProvider">
{{ submittingProvider ? "Saving..." : "Add Provider" }}
</button>
</div>
</form>
</div>
</section>
@@ -254,6 +209,49 @@
</div>
</div>
<div class="feature-flag-item border rounded p-3">
<div class="d-flex justify-content-between align-items-center mb-0" :class="{ 'mb-3': featureFlagsForm.file_explorer_enabled }">
<div>
<div class="fw-semibold">Enable File Explorer</div>
<div class="small text-muted">Allow users to browse and insert files from an S3 bucket directly into notes.</div>
</div>
<div class="form-check form-switch m-0">
<input id="flag-file-explorer" v-model="featureFlagsForm.file_explorer_enabled" class="form-check-input" type="checkbox" />
</div>
</div>
<div v-if="featureFlagsForm.file_explorer_enabled" class="row g-2 mt-1">
<div class="col-md-6">
<label class="form-label small mb-1">S3 Endpoint URL</label>
<input v-model="featureFlagsForm.s3_endpoint" type="url" class="form-control form-control-sm" placeholder="https://s3.amazonaws.com or custom endpoint" />
</div>
<div class="col-md-6">
<label class="form-label small mb-1">Bucket Name</label>
<input v-model="featureFlagsForm.s3_bucket" type="text" class="form-control form-control-sm" placeholder="my-bucket" />
</div>
<div class="col-md-4">
<label class="form-label small mb-1">Region</label>
<input v-model="featureFlagsForm.s3_region" type="text" class="form-control form-control-sm" placeholder="us-east-1" />
</div>
<div class="col-md-4">
<label class="form-label small mb-1">Access Key</label>
<input v-model="featureFlagsForm.s3_access_key" type="text" class="form-control form-control-sm" autocomplete="off" />
</div>
<div class="col-md-4">
<label class="form-label small mb-1">Secret Key</label>
<input
v-model="featureFlagsForm.s3_secret_key"
type="password"
class="form-control form-control-sm"
:placeholder="featureFlagsForm.s3_secret_key_set ? 'Leave blank to keep current secret' : 'Enter secret key'"
autocomplete="new-password"
/>
<div v-if="featureFlagsForm.s3_secret_key_set && !featureFlagsForm.s3_secret_key" class="small text-success mt-1">
<i class="mdi mdi-check-circle-outline" aria-hidden="true"></i> Secret key is set
</div>
</div>
</div>
</div>
<div class="d-flex justify-content-end">
<button class="btn btn-primary" :disabled="savingFeatureFlags" @click="saveFeatureFlags">
{{ savingFeatureFlags ? "Saving..." : "Save Feature Flags" }}
@@ -262,53 +260,34 @@
</div>
</div>
</section>
</main>
</div>
</div>
<AdminSpaceModal v-if="showSpaceModal && selectedSpace" :space="selectedSpace" :users="users" @close="showSpaceModal = false" @saved="onSpaceSaved" @deleted="onSpaceDeleted" />
<teleport to="body">
<div v-if="showGroupModal" class="modal fade show d-block" tabindex="-1" role="dialog" aria-modal="true" @click.self="closeGroupModal">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ groupModalMode === "create" ? "Create Group" : "Edit Group" }}</h5>
<button type="button" class="btn-close" aria-label="Close" @click="closeGroupModal"></button>
</div>
<form @submit.prevent="submitGroupModal">
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Group name</label>
<input v-model="groupModalForm.name" class="form-control" type="text" required :disabled="isEditingSystemGroup" />
</div>
<AdminGroupModal
v-if="showGroupModal"
:mode="groupModalMode"
:group="selectedGroup"
:is-system-group="isEditingSystemGroup"
:submitting="submittingGroupModal"
@close="closeGroupModal"
@submit="submitGroupModal"
/>
<div class="mb-3">
<label class="form-label">Description</label>
<input v-model="groupModalForm.description" class="form-control" type="text" :disabled="isEditingSystemGroup" />
</div>
<AdminUserModal v-if="showUserModal && selectedUser" :user="selectedUser" :groups="groups" :submitting="submittingUserModal" @close="closeUserModal" @submit="submitUserModal" />
<div>
<label class="form-label">Permissions (one per line)</label>
<textarea
v-model="groupModalForm.permissionsText"
class="form-control permissions-textarea"
rows="10"
placeholder="space.create&#10;space.project_docs.category.create&#10;space.project_docs.*"
:disabled="isEditingSystemGroup"
></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" @click="closeGroupModal">Cancel</button>
<button v-if="!isEditingSystemGroup" type="submit" class="btn btn-primary" :disabled="submittingGroupModal">
{{ submittingGroupModal ? "Saving..." : groupModalMode === "create" ? "Create Group" : "Save Changes" }}
</button>
</div>
</form>
</div>
</div>
</div>
<div v-if="showGroupModal" class="modal-backdrop fade show"></div>
</teleport>
<AdminProviderModal
v-if="showProviderModal"
:mode="providerModalMode"
:provider="selectedProvider"
:submitting="submittingProviderModal"
:deleting="deletingProviderModal"
@close="closeProviderModal"
@submit="submitProviderModal"
@delete="deleteProviderFromModal"
/>
</template>
<script setup>
@@ -316,14 +295,34 @@ import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import apiClient from "../services/apiClient";
import AdminSpaceModal from "../components/AdminSpaceModal.vue";
import AdminGroupModal from "../components/AdminGroupModal.vue";
import AdminUserModal from "../components/AdminUserModal.vue";
import AdminProviderModal from "../components/AdminProviderModal.vue";
const router = useRouter();
const activeTab = ref("users");
const showMobileSidebar = ref(false);
const error = ref("");
const successMessage = ref("");
const adminTabs = [
{ id: "users", label: "Users" },
{ id: "groups", label: "Groups" },
{ id: "spaces", label: "Spaces" },
{ id: "providers", label: "Identity Providers" },
{ id: "featureFlags", label: "Feature Flags" },
];
const selectTab = (tabId) => {
activeTab.value = tabId;
showMobileSidebar.value = false;
};
const users = ref([]);
const loadingUsers = ref(false);
const showUserModal = ref(false);
const submittingUserModal = ref(false);
const selectedUser = ref(null);
const groups = ref([]);
const loadingGroups = ref(false);
@@ -331,11 +330,7 @@ const showGroupModal = ref(false);
const groupModalMode = ref("create");
const editingGroupId = ref("");
const submittingGroupModal = ref(false);
const groupModalForm = ref({
name: "",
description: "",
permissionsText: "",
});
const selectedGroup = ref(null);
const spaces = ref([]);
const loadingSpaces = ref(false);
@@ -344,19 +339,11 @@ const selectedSpace = ref(null);
const providers = ref([]);
const loadingProviders = ref(false);
const submittingProvider = ref(false);
const providerForm = ref({
name: "",
type: "oidc",
client_id: "",
client_secret: "",
authorization_url: "",
token_url: "",
userinfo_url: "",
id_token_claim: "id_token",
scopes: "openid, profile, email",
is_active: true,
});
const showProviderModal = ref(false);
const providerModalMode = ref("create");
const selectedProvider = ref(null);
const submittingProviderModal = ref(false);
const deletingProviderModal = ref(false);
const loadingFeatureFlags = ref(false);
const savingFeatureFlags = ref(false);
@@ -364,6 +351,13 @@ const featureFlagsForm = ref({
registration_enabled: true,
provider_login_enabled: true,
public_sharing_enabled: true,
file_explorer_enabled: false,
s3_endpoint: "",
s3_bucket: "",
s3_region: "",
s3_access_key: "",
s3_secret_key: "",
s3_secret_key_set: false,
});
const clearMessages = () => {
@@ -389,8 +383,10 @@ const loadUsers = async () => {
}
};
const updateUserGroups = async (userId, groupIds) => {
const updateUserGroups = async (userId, groupIds, options = {}) => {
if (!options.silent) {
clearMessages();
}
try {
const response = await apiClient.put(`/api/v1/admin/users/${userId}/groups`, { group_ids: groupIds });
const updatedUser = response.data;
@@ -398,26 +394,70 @@ const updateUserGroups = async (userId, groupIds) => {
if (userIndex !== -1) {
users.value[userIndex] = { ...users.value[userIndex], ...updatedUser };
}
if (!options.silent) {
successMessage.value = "User groups updated.";
}
return updatedUser;
} catch (e) {
error.value = e.response?.data || "Failed to update user groups.";
throw e;
}
};
const resetGroupModalForm = () => {
groupModalForm.value = {
name: "",
description: "",
permissionsText: "",
};
const getUserGroupSummary = (user) => {
const ids = user?.group_ids || [];
if (!ids.length) {
return "No groups";
}
const names = ids.map((groupID) => groups.value.find((group) => group.id === groupID)?.name).filter(Boolean);
return names.length ? names.join(", ") : "No groups";
};
const openEditUserModal = (user) => {
selectedUser.value = { ...user };
showUserModal.value = true;
};
const closeUserModal = () => {
showUserModal.value = false;
submittingUserModal.value = false;
selectedUser.value = null;
};
const submitUserModal = async ({ group_ids }) => {
submittingUserModal.value = true;
clearMessages();
try {
await updateUserGroups(selectedUser.value.id, group_ids, { silent: true });
successMessage.value = "User updated.";
closeUserModal();
} catch {
// error message handled in updateUserGroups
} finally {
submittingUserModal.value = false;
}
};
const deleteUser = async (user) => {
if (!confirm(`Delete user "${user.username}"? This action cannot be undone.`)) {
return;
}
clearMessages();
try {
await apiClient.delete(`/api/v1/admin/users/${user.id}`);
users.value = users.value.filter((item) => item.id !== user.id);
successMessage.value = `User "${user.username}" deleted.`;
} catch (e) {
error.value = e.response?.data || "Failed to delete user.";
}
};
const isEditingSystemGroup = computed(() => {
if (groupModalMode.value !== "edit") {
return false;
}
const group = groups.value.find((item) => item.id === editingGroupId.value);
return !!group?.is_system;
return !!selectedGroup.value?.is_system;
});
const splitPermissionsByNewline = (raw) =>
@@ -429,24 +469,21 @@ const splitPermissionsByNewline = (raw) =>
const openCreateGroupModal = () => {
groupModalMode.value = "create";
editingGroupId.value = "";
resetGroupModalForm();
selectedGroup.value = null;
showGroupModal.value = true;
};
const openEditGroupModal = (group) => {
groupModalMode.value = "edit";
editingGroupId.value = group.id;
groupModalForm.value = {
name: group.name || "",
description: group.description || "",
permissionsText: (group.permissions || []).join("\n"),
};
selectedGroup.value = { ...group };
showGroupModal.value = true;
};
const closeGroupModal = () => {
showGroupModal.value = false;
submittingGroupModal.value = false;
selectedGroup.value = null;
};
const loadGroups = async () => {
@@ -462,14 +499,14 @@ const loadGroups = async () => {
}
};
const submitGroupModal = async () => {
const submitGroupModal = async (formData) => {
submittingGroupModal.value = true;
clearMessages();
try {
const payload = {
name: groupModalForm.value.name,
description: groupModalForm.value.description,
permissions: splitPermissionsByNewline(groupModalForm.value.permissionsText),
name: formData.name,
description: formData.description,
permissions: splitPermissionsByNewline(formData.permissionsText),
};
if (groupModalMode.value === "create") {
@@ -481,7 +518,6 @@ const submitGroupModal = async () => {
}
closeGroupModal();
resetGroupModalForm();
await Promise.all([loadGroups(), loadUsers()]);
} catch (e) {
error.value = e.response?.data || `Failed to ${groupModalMode.value === "create" ? "create" : "update"} group.`;
@@ -490,6 +526,24 @@ const submitGroupModal = async () => {
}
};
const deleteGroup = async (group) => {
if (group.is_system) {
return;
}
if (!confirm(`Delete group "${group.name}"? This action cannot be undone.`)) {
return;
}
clearMessages();
try {
await apiClient.delete(`/api/v1/admin/groups/${group.id}`);
successMessage.value = `Group "${group.name}" deleted.`;
await Promise.all([loadGroups(), loadUsers()]);
} catch (e) {
error.value = e.response?.data || "Failed to delete group.";
}
};
const loadSpaces = async () => {
loadingSpaces.value = true;
clearMessages();
@@ -524,28 +578,51 @@ const onSpaceDeleted = (deletedSpace) => {
successMessage.value = `Space "${deletedSpace.name}" deleted.`;
};
const buildCallbackUrl = (providerId) => `${apiClient.defaults.baseURL}/api/v1/auth/providers/${providerId}/callback`;
const openCreateProviderModal = () => {
providerModalMode.value = "create";
selectedProvider.value = null;
showProviderModal.value = true;
};
const resetProviderForm = () => {
providerForm.value = {
name: "",
type: "oidc",
client_id: "",
client_secret: "",
authorization_url: "",
token_url: "",
userinfo_url: "",
id_token_claim: "id_token",
scopes: "openid, profile, email",
is_active: true,
};
const openEditProviderModal = (provider) => {
providerModalMode.value = "edit";
selectedProvider.value = { ...provider };
showProviderModal.value = true;
};
const closeProviderModal = () => {
showProviderModal.value = false;
submittingProviderModal.value = false;
deletingProviderModal.value = false;
selectedProvider.value = null;
};
const submitProviderModal = async (formData) => {
submittingProviderModal.value = true;
clearMessages();
try {
if (providerModalMode.value === "create") {
await apiClient.post("/api/v1/admin/auth/providers", formData);
successMessage.value = "Provider added.";
} else {
await apiClient.put(`/api/v1/admin/auth/providers/${selectedProvider.value.id}`, formData);
successMessage.value = "Provider updated.";
}
closeProviderModal();
await loadProviders();
} catch (e) {
error.value = e.response?.data || `Failed to ${providerModalMode.value === "create" ? "create" : "update"} provider.`;
} finally {
submittingProviderModal.value = false;
}
};
const loadProviders = async () => {
loadingProviders.value = true;
clearMessages();
try {
const res = await apiClient.get("/api/v1/auth/providers");
const res = await apiClient.get("/api/v1/admin/auth/providers");
providers.value = res.data.providers || [];
} catch (e) {
error.value = e.response?.data || "Failed to load providers.";
@@ -554,24 +631,26 @@ const loadProviders = async () => {
}
};
const createProvider = async () => {
submittingProvider.value = true;
const deleteProviderFromModal = async (provider) => {
if (!provider?.id) {
return;
}
if (!confirm(`Delete identity provider "${provider.name}"? This action cannot be undone.`)) {
return;
}
deletingProviderModal.value = true;
clearMessages();
try {
await apiClient.post("/api/v1/admin/auth/providers", {
...providerForm.value,
scopes: providerForm.value.scopes
.split(",")
.map((scope) => scope.trim())
.filter(Boolean),
});
successMessage.value = "Provider added.";
resetProviderForm();
await loadProviders();
await apiClient.delete(`/api/v1/admin/auth/providers/${provider.id}`);
providers.value = providers.value.filter((item) => item.id !== provider.id);
successMessage.value = `Provider "${provider.name}" deleted.`;
closeProviderModal();
} catch (e) {
error.value = e.response?.data || "Failed to create provider.";
error.value = e.response?.data || "Failed to delete provider.";
} finally {
submittingProvider.value = false;
deletingProviderModal.value = false;
}
};
@@ -584,6 +663,13 @@ const loadFeatureFlags = async () => {
registration_enabled: !!res.data.registration_enabled,
provider_login_enabled: !!res.data.provider_login_enabled,
public_sharing_enabled: !!res.data.public_sharing_enabled,
file_explorer_enabled: !!res.data.file_explorer_enabled,
s3_endpoint: res.data.s3_endpoint || "",
s3_bucket: res.data.s3_bucket || "",
s3_region: res.data.s3_region || "",
s3_access_key: res.data.s3_access_key || "",
s3_secret_key: "", // never pre-fill the secret
s3_secret_key_set: !!res.data.s3_secret_key_set,
};
} catch (e) {
error.value = e.response?.data || "Failed to load feature flags.";
@@ -596,11 +682,28 @@ const saveFeatureFlags = async () => {
savingFeatureFlags.value = true;
clearMessages();
try {
const res = await apiClient.put("/api/v1/admin/feature-flags", featureFlagsForm.value);
const res = await apiClient.put("/api/v1/admin/feature-flags", {
registration_enabled: featureFlagsForm.value.registration_enabled,
provider_login_enabled: featureFlagsForm.value.provider_login_enabled,
public_sharing_enabled: featureFlagsForm.value.public_sharing_enabled,
file_explorer_enabled: featureFlagsForm.value.file_explorer_enabled,
s3_endpoint: featureFlagsForm.value.s3_endpoint,
s3_bucket: featureFlagsForm.value.s3_bucket,
s3_region: featureFlagsForm.value.s3_region,
s3_access_key: featureFlagsForm.value.s3_access_key,
s3_secret_key: featureFlagsForm.value.s3_secret_key, // blank = keep existing
});
featureFlagsForm.value = {
registration_enabled: !!res.data.registration_enabled,
provider_login_enabled: !!res.data.provider_login_enabled,
public_sharing_enabled: !!res.data.public_sharing_enabled,
file_explorer_enabled: !!res.data.file_explorer_enabled,
s3_endpoint: res.data.s3_endpoint || "",
s3_bucket: res.data.s3_bucket || "",
s3_region: res.data.s3_region || "",
s3_access_key: res.data.s3_access_key || "",
s3_secret_key: "",
s3_secret_key_set: !!res.data.s3_secret_key_set,
};
successMessage.value = "Feature flags updated.";
} catch (e) {
@@ -617,15 +720,235 @@ onMounted(async () => {
<style scoped>
.admin-page {
max-width: 1100px;
margin: 0 auto;
width: 100%;
max-width: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
.admin-topbar {
flex-wrap: wrap;
padding: 1rem;
border-bottom: 1px solid #dee2e6;
}
.admin-shell {
display: flex;
flex: 1;
min-height: 0;
gap: 0;
overflow: hidden;
}
.admin-sidebar {
width: 280px;
flex-shrink: 0;
background: #f8f9fa;
border-right: 1px solid #dee2e6;
}
.admin-sidebar-inner {
padding: 0.75rem;
}
.admin-nav .nav-link {
border-radius: 0.6rem;
color: #495057;
font-weight: 500;
}
.admin-nav .nav-link:hover {
background: #eef2f7;
color: #212529;
}
.admin-nav .nav-link.active {
background: #212529;
color: #fff;
}
.admin-content {
flex: 1;
min-width: 0;
min-height: 0;
overflow-y: auto;
padding: 1rem;
}
.admin-section {
border-radius: 12px;
}
.permissions-textarea {
font-family: "Courier New", monospace;
.users-list .list-group-item {
padding: 1rem;
}
.user-row {
display: flex;
gap: 1rem;
align-items: center;
justify-content: space-between;
}
.user-row-main {
flex: 1;
min-width: 0;
}
.user-row-actions {
flex-shrink: 0;
}
.user-actions-stack {
flex-wrap: wrap;
justify-content: flex-end;
}
.user-name-line {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.6rem;
}
.user-name {
font-size: 1.1rem;
}
.user-meta-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem 1.25rem;
}
.user-meta-label {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #6c757d;
margin-bottom: 0.1rem;
}
.user-meta-value {
color: #495057;
overflow-wrap: anywhere;
}
.user-meta-item-groups {
grid-column: span 1;
}
@media (max-width: 991.98px) {
.user-meta-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.user-meta-item-groups {
grid-column: 1 / -1;
}
}
@media (max-width: 767.98px) {
.admin-shell {
display: block;
min-height: auto;
}
.admin-topbar {
padding: 0.75rem;
}
.admin-content {
padding: 0.75rem;
}
.admin-sidebar-backdrop {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.45);
z-index: 1400;
}
.admin-sidebar {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: min(82vw, 320px);
z-index: 1410;
transform: translateX(-100%);
transition: transform 0.25s ease;
border-right: 1px solid #dee2e6;
}
.admin-sidebar-inner {
padding: 0.75rem;
}
.admin-sidebar.open {
transform: translateX(0);
}
.user-row {
flex-direction: column;
align-items: stretch;
}
.user-row-actions {
width: 100%;
}
.user-row-actions .btn {
width: 100%;
}
.user-actions-stack {
flex-direction: column;
}
.user-meta-grid {
grid-template-columns: 1fr;
gap: 0.65rem;
}
}
/* Dark mode overrides */
:root[data-bs-theme="dark"] .admin-topbar {
border-bottom-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .admin-sidebar {
background: #21252e;
border-right-color: #3a3f4b;
}
:root[data-bs-theme="dark"] .admin-nav .nav-link {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .admin-nav .nav-link:hover {
background: #2d3748;
color: #e2e8f0;
}
:root[data-bs-theme="dark"] .admin-nav .nav-link.active {
background: #e2e8f0;
color: #1a1d23;
}
:root[data-bs-theme="dark"] .user-meta-value {
color: #94a3b8;
}
:root[data-bs-theme="dark"] .admin-section {
background-color: #21252e;
}
</style>

View File

@@ -88,73 +88,33 @@ const startProviderLogin = (providerId) => {
window.location.href = `${apiClient.defaults.baseURL}/api/v1/auth/providers/${providerId}/start`;
};
const decodeBase64Url = (value) => {
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
const padding = normalized.length % 4;
const padded = padding === 0 ? normalized : `${normalized}${"=".repeat(4 - padding)}`;
return atob(padded);
};
const decodeBase64UrlUTF8 = (value) => {
const binary = decodeBase64Url(value);
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
return new TextDecoder().decode(bytes);
};
const readUserFromQuery = (params) => {
const plainUserJSON = params.get("user_json");
if (plainUserJSON) {
return JSON.parse(plainUserJSON);
}
const encodedUser = params.get("user");
if (encodedUser) {
return JSON.parse(decodeBase64UrlUTF8(encodedUser));
}
return null;
};
const completeOAuthRedirect = async () => {
const params = new URLSearchParams(window.location.search);
const status = params.get("status");
const accessToken = params.get("access_token") || params.get("accessToken") || params.get("token");
if (status === "oauth_error") {
error.value = params.get("message") || "Provider sign-in failed.";
return true;
}
// Accept callback payloads even when `status` is missing.
if (status !== "oauth_success" && !accessToken) {
if (status === "oauth_error") {
error.value = params.get("message") || "Provider sign-in failed.";
}
if (status !== "oauth_success") {
return false;
}
if (!accessToken) {
error.value = "Provider sign-in returned an incomplete session.";
return true;
}
try {
const user = readUserFromQuery(params);
if (!user) {
error.value = "Provider sign-in returned an incomplete session.";
return true;
}
authStore.setSession({ access_token: accessToken, user });
await router.replace("/");
await authStore.ensureInitialized();
} catch {
error.value = "Unable to restore the provider session.";
error.value = "Unable to restore provider session.";
return true;
}
if (authStore.isAuthenticated) {
window.location.replace("/");
await router.replace("/");
return true;
}
error.value = "Provider sign-in returned an incomplete session.";
return true;
};
@@ -163,6 +123,8 @@ onMounted(async () => {
registrationEnabled.value = !!flags.registration_enabled;
providerLoginEnabled.value = !!flags.provider_login_enabled;
await authStore.ensureInitialized();
if (authStore.isAuthenticated) {
await router.replace("/");
return;

View File

@@ -4,39 +4,6 @@ import { useSettingsStore } from "../stores/settingsStore";
import LoginPage from "../pages/Login.vue";
import RegisterPage from "../pages/Register.vue";
const decodeBase64UrlUTF8 = (value) => {
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
const padding = normalized.length % 4;
const padded = padding === 0 ? normalized : `${normalized}${"=".repeat(4 - padding)}`;
const binary = atob(padded);
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
return new TextDecoder().decode(bytes);
};
const restoreOAuthSessionFromQuery = (query, authStore) => {
// Merge router query with URLSearchParams for full coverage
const params = new URLSearchParams(window.location.search);
const accessToken = query.access_token || query.accessToken || query.token || params.get("access_token") || params.get("accessToken") || params.get("token");
if (!accessToken) {
return false;
}
try {
const plainUserJSON = query.user_json || params.get("user_json");
const encodedUser = query.user || params.get("user");
const user = plainUserJSON ? JSON.parse(plainUserJSON) : encodedUser ? JSON.parse(decodeBase64UrlUTF8(encodedUser)) : null;
if (!user) {
return false;
}
authStore.setSession({ access_token: accessToken, user });
return true;
} catch {
return false;
}
};
const routes = [
{
path: "/login",
@@ -54,6 +21,12 @@ const routes = [
component: () => import("../pages/Home.vue"),
meta: { requiresAuth: true },
},
{
path: "/search",
name: "Search",
component: () => import("../pages/Home.vue"),
meta: { requiresAuth: true },
},
{
path: "/admin",
name: "Admin",
@@ -81,25 +54,7 @@ router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore();
const settingsStore = useSettingsStore();
// Only attempt OAuth callback restoration if actual OAuth query params are present
const params = new URLSearchParams(window.location.search);
const hasOAuthParams = to.query.access_token || to.query.accessToken || to.query.token || params.get("access_token") || params.get("accessToken") || params.get("token");
if (to.path === "/login") {
if (hasOAuthParams) {
const restored = restoreOAuthSessionFromQuery(to.query, authStore);
if (restored) {
next({ path: "/", replace: true });
return;
}
}
// Allow login page to be viewed regardless of auth state if no OAuth callback
if (!hasOAuthParams) {
next();
return;
}
}
await authStore.ensureInitialized();
if (to.path === "/register") {
await settingsStore.loadFeatureFlags();

View File

@@ -3,23 +3,57 @@ import { useAuthStore } from "../stores/authStore";
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || "http://localhost:8080",
withCredentials: true,
});
apiClient.interceptors.request.use((config) => {
const authStore = useAuthStore();
if (authStore.accessToken) {
config.headers.Authorization = `Bearer ${authStore.accessToken}`;
}
return config;
});
let isRefreshing = false;
let refreshSubscribers = [];
function onRefreshed() {
refreshSubscribers.forEach((cb) => cb());
refreshSubscribers = [];
}
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
// Avoid retrying the refresh request itself
if (originalRequest.url?.includes("/auth/refresh") || originalRequest.url?.includes("/auth/login")) {
const authStore = useAuthStore();
authStore.logout();
authStore.clearSession();
return Promise.reject(error);
}
if (isRefreshing) {
// Queue the request until the ongoing refresh completes
return new Promise((resolve, reject) => {
refreshSubscribers.push(() => {
originalRequest._retry = true;
apiClient(originalRequest).then(resolve).catch(reject);
});
});
}
originalRequest._retry = true;
isRefreshing = true;
try {
await apiClient.post("/api/v1/auth/refresh");
onRefreshed();
return apiClient(originalRequest);
} catch {
refreshSubscribers = [];
const authStore = useAuthStore();
authStore.clearSession();
return Promise.reject(error);
} finally {
isRefreshing = false;
}
}
return Promise.reject(error);
},
);

View File

@@ -3,10 +3,11 @@ import { ref, computed } from "vue";
import apiClient from "../services/apiClient";
export const useAuthStore = defineStore("auth", () => {
const storedUser = localStorage.getItem("user");
const user = ref(storedUser ? JSON.parse(storedUser) : null);
const accessToken = ref(localStorage.getItem("accessToken"));
const isAuthenticated = computed(() => !!accessToken.value && !!user.value);
const user = ref(null);
const initialized = ref(false);
let initPromise = null;
const isAuthenticated = computed(() => !!user.value);
const isAdmin = computed(() => hasPermission("*") || hasPermission("admin.access"));
const normalizePermission = (permission) => (permission || "").trim().toLowerCase();
@@ -46,10 +47,36 @@ export const useAuthStore = defineStore("auth", () => {
};
const setSession = (responseData) => {
accessToken.value = responseData.access_token;
user.value = responseData.user;
localStorage.setItem("accessToken", accessToken.value);
localStorage.setItem("user", JSON.stringify(user.value));
user.value = responseData?.user || null;
initialized.value = true;
};
const clearSession = () => {
user.value = null;
initialized.value = true;
};
const loadSession = async () => {
try {
const response = await apiClient.get("/api/v1/auth/me");
user.value = response.data?.user || null;
} catch {
user.value = null;
} finally {
initialized.value = true;
}
};
const ensureInitialized = async () => {
if (initialized.value) {
return;
}
if (!initPromise) {
initPromise = loadSession().finally(() => {
initPromise = null;
});
}
await initPromise;
};
const register = async (email, username, password, firstName = "", lastName = "") => {
@@ -87,20 +114,20 @@ export const useAuthStore = defineStore("auth", () => {
};
const logout = () => {
accessToken.value = null;
user.value = null;
localStorage.removeItem("accessToken");
localStorage.removeItem("user");
apiClient.post("/api/v1/auth/logout").catch(() => {});
clearSession();
};
return {
user,
accessToken,
initialized,
isAuthenticated,
isAdmin,
hasPermission,
hasSpacePermission,
setSession,
clearSession,
ensureInitialized,
register,
login,
logout,

View File

@@ -6,6 +6,7 @@ const DEFAULT_FLAGS = {
registration_enabled: true,
provider_login_enabled: true,
public_sharing_enabled: true,
file_explorer_enabled: false,
};
export const useSettingsStore = defineStore("settings", () => {
@@ -15,6 +16,7 @@ export const useSettingsStore = defineStore("settings", () => {
const registrationEnabled = computed(() => !!featureFlags.value.registration_enabled);
const providerLoginEnabled = computed(() => !!featureFlags.value.provider_login_enabled);
const publicSharingEnabled = computed(() => !!featureFlags.value.public_sharing_enabled);
const fileExplorerEnabled = computed(() => !!featureFlags.value.file_explorer_enabled);
const loadFeatureFlags = async (force = false) => {
if (flagsLoaded.value && !force) {
@@ -42,6 +44,7 @@ export const useSettingsStore = defineStore("settings", () => {
registrationEnabled,
providerLoginEnabled,
publicSharingEnabled,
fileExplorerEnabled,
loadFeatureFlags,
};
});

View File

@@ -6,6 +6,7 @@ export const useSpaceStore = defineStore("space", () => {
const spaces = ref([]);
const currentSpace = ref(null);
const notes = ref([]);
const searchResults = ref([]);
const notesSkip = ref(0);
const notesLimit = ref(20);
const notesHasMore = ref(true);
@@ -188,20 +189,30 @@ export const useSpaceStore = defineStore("space", () => {
};
const searchNotes = async (query) => {
if (!currentSpace.value?.id) {
searchResults.value = [];
return [];
}
try {
const response = await apiClient.get(`/api/v1/spaces/${currentSpace.value.id}/notes/search`, { params: { q: query } });
notes.value = response.data || [];
notesHasMore.value = false;
notesSkip.value = notes.value.length;
searchResults.value = response.data || [];
return searchResults.value;
} catch (error) {
console.error("Error searching notes:", error);
searchResults.value = [];
return [];
}
};
const clearSearchResults = () => {
searchResults.value = [];
};
return {
spaces,
currentSpace,
notes,
searchResults,
notesHasMore,
notesLoading,
categories,
@@ -220,5 +231,6 @@ export const useSpaceStore = defineStore("space", () => {
updateNote,
deleteNote,
searchNotes,
clearSearchResults,
};
});

View File

@@ -0,0 +1,46 @@
import { marked } from "marked";
import { markedHighlight } from "marked-highlight";
import hljs from "highlight.js/lib/common";
marked.use(
markedHighlight({
langPrefix: "hljs language-",
highlight(code, lang) {
if (lang && hljs.getLanguage(lang)) {
return hljs.highlight(code, { language: lang }).value;
}
return hljs.highlightAuto(code).value;
},
}),
);
/**
* Preprocesses markdown content to support extended image size syntax:
*
* ![alt](url =WIDTHxHEIGHT)
* ![alt](url "title" =WIDTHxHEIGHT)
*
* WIDTH and HEIGHT are pixel values or percentages (e.g. 50%).
* Either can be omitted:
* =200x → width 200 only
* =x150 → height 150 only
*
* The syntax is transformed into a plain <img> tag before passing to marked
* because CommonMark terminates the link destination at whitespace, making it
* impossible for marked to see the size spec otherwise.
*/
export function preprocessMarkdown(content) {
if (!content) return content;
return content.replace(/!\[([^\]]*)\]\(([^\s)"]+)(?:\s+"([^"]*)")?\s+=(\d*%?)[xX](\d*%?)\)/gi, (_, alt, url, title, w, h) => {
const safeAlt = alt.replace(/"/g, "&quot;");
let attrs = `src="${url}" alt="${safeAlt}"`;
if (title) attrs += ` title="${title.replace(/"/g, "&quot;")}"`;
if (w) attrs += ` width="${w}"`;
if (h) attrs += ` height="${h}"`;
return `<img ${attrs}>`;
});
}
export function renderMarkdown(content) {
return marked.parse(preprocessMarkdown(content || ""), { gfm: true });
}

View File

@@ -1,10 +1,22 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { useAuthStore } from "../../src/stores/authStore";
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createPinia, setActivePinia } from "pinia";
vi.mock("../src/services/apiClient.js", () => ({
default: {
get: vi.fn(),
post: vi.fn(() => Promise.resolve({})),
},
}));
import apiClient from "../src/services/apiClient.js";
import { useAuthStore } from "../src/stores/authStore.js";
describe("Auth Store", () => {
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
});
it("should initialize with no user", () => {
@@ -13,27 +25,76 @@ describe("Auth Store", () => {
expect(store.user).toBeNull();
});
it("should store user data on login", () => {
it("should store user data with setSession", () => {
const store = useAuthStore();
// Mock user data
const mockUser = {
id: "123",
email: "test@example.com",
username: "testuser",
permissions: ["space.demo.note.create"],
};
// In a real test, you'd mock the API call
// For now, just test the store structure
expect(store.user).toBeNull();
store.setSession({ user: mockUser });
expect(store.isAuthenticated).toBe(true);
expect(store.user).toEqual(mockUser);
expect(store.hasPermission("space.demo.note.create")).toBe(true);
});
it("should clear user data on logout", () => {
it("should login and persist returned user", async () => {
const store = useAuthStore();
apiClient.post.mockResolvedValueOnce({
data: {
user: {
id: "123",
email: "test@example.com",
username: "testuser",
permissions: [],
},
},
});
const result = await store.login(" test@example.com ", "password123");
expect(apiClient.post).toHaveBeenCalledWith("/api/v1/auth/login", {
email: "test@example.com",
password: "password123",
});
expect(result.user.username).toBe("testuser");
expect(store.user?.username).toBe("testuser");
});
it("should clear user data on logout", async () => {
const store = useAuthStore();
store.setSession({
user: {
id: "123",
email: "test@example.com",
username: "testuser",
permissions: ["space.demo.settings.delete"],
},
});
store.logout();
expect(store.isAuthenticated).toBe(false);
expect(store.user).toBeNull();
expect(store.accessToken).toBeNull();
expect(apiClient.post).toHaveBeenCalledWith("/api/v1/auth/logout");
});
it("should evaluate space permissions using the space permission key", () => {
const store = useAuthStore();
store.setSession({
user: {
id: "123",
email: "test@example.com",
username: "testuser",
permissions: ["space.docs.settings.delete", "space.*.note.create"],
},
});
expect(store.hasSpacePermission({ permission_key: "docs" }, "settings.delete")).toBe(true);
expect(store.hasSpacePermission({ permission_key: "docs" }, "note.create")).toBe(true);
expect(store.hasSpacePermission({ permission_key: "docs" }, "note.delete")).toBe(false);
});
});