Compare commits

...

4 Commits

Author SHA1 Message Date
a2c35c5915 Merge remote web-upload history with local rewrite
# Conflicts:
#	README.md
#	bootstrap.sh
2026-08-04 11:28:41 +03:00
6dc35134fa latest 2026-08-04 11:26:25 +03:00
d0834df8df Force LF line endings for shell scripts 2026-08-03 15:58:36 +03:00
7c983a9d69 Add Laravel LXC bootstrap script, README, and Claude Code project prompt 2026-08-03 15:58:10 +03:00
171 changed files with 19241 additions and 49 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
docker/mosquitto/config/passwd
docker/mosquitto/credentials.env

View File

@ -1,23 +1,29 @@
# Laravel LXC Bootstrap # webappAIO LXC Bootstrap
Spin up a fully configured Laravel development container in one step: SSH, Apache/PHP/MariaDB or SQLite, Composer, a Laravel project, [code-server](https://code-server.dev), and [Claude Code](https://docs.claude.com/en/docs/claude-code) — all from a single command pasted into a fresh Proxmox LXC. Spin up a fully configured development container in one step: SSH, Apache/PHP/MariaDB or SQLite, a Laravel API backend (`backend/`) + React/Vite frontend (`frontend/`), a self-hosted Mosquitto MQTT broker (Docker), [code-server](https://code-server.dev), and [Claude Code](https://docs.claude.com/en/docs/claude-code) — all from a single command pasted into a fresh Proxmox LXC.
## Quick start ## Quick start
In an **empty, freshly created LXC**, logged in as root: In an **empty, freshly created LXC**, logged in as root:
```bash ```bash
curl -fsSL https://git.innovator.bh/ghassan/laravel-project/raw/branch/main/bootstrap.sh -o bootstrap.sh && bash bootstrap.sh curl -fsSL https://git.innovator.bh/ghassan/webappAIO/raw/branch/main/bootstrap.sh -o bootstrap.sh && bash bootstrap.sh
``` ```
You'll be prompted for: You'll be prompted for:
- Laravel project name - Project name
- Git repository to clone (leave blank to scaffold a brand-new Laravel project instead) - Git repository to clone (leave blank to scaffold a bare backend/frontend pair instead — see below)
- Database: `mysql` or `sqlite` - Database: `mysql` or `sqlite`
- MariaDB username/password/database (only if you chose `mysql`) - MariaDB username/password/database (only if you chose `mysql`)
- Seeded Super Admin email/username/password
When it finishes you'll have a running Laravel site, code-server, and Claude Code installed. When it finishes you'll have a running API, a Mosquitto broker, code-server, and Claude Code installed, plus a Super Admin account ready to log in with.
### Blank `GIT_REPO` vs. cloning this repo
- **Blank** scaffolds a fresh Laravel install in `backend/` and a fresh Vite React-TS app in `frontend/`, with the core packages already required (Sanctum, `spatie/laravel-permission`, `pragmarx/google2fa-laravel`, `php-mqtt/laravel-client`) — the foundation to build the rest of [`claude-project-prompt.md`](./claude-project-prompt.md)'s architecture on top of, not the finished app.
- **`GIT_REPO=https://git.innovator.bh/ghassan/webappAIO.git`** clones this repo, which already contains the full RBAC + 2FA + MQTT-realtime + Users-management implementation described in that prompt.
## Fully unattended install ## Fully unattended install
@ -27,6 +33,9 @@ Skip every prompt by exporting variables before running the script (useful for s
APP_NAME=myapp \ APP_NAME=myapp \
GIT_REPO="" \ GIT_REPO="" \
DB_TYPE=sqlite \ DB_TYPE=sqlite \
SUPER_ADMIN_EMAIL=admin@myapp.test \
SUPER_ADMIN_USERNAME=admin \
SUPER_ADMIN_PASSWORD='change-me' \
INSTALL_CODE_SERVER=yes \ INSTALL_CODE_SERVER=yes \
INSTALL_CLAUDE_CODE=yes \ INSTALL_CLAUDE_CODE=yes \
bash bootstrap.sh bash bootstrap.sh
@ -35,11 +44,14 @@ bash bootstrap.sh
| Variable | Description | Default | | Variable | Description | Default |
|---|---|---| |---|---|---|
| `APP_NAME` | Project directory name under `/var/www` | `laravel-app` | | `APP_NAME` | Project directory name under `/var/www` | `laravel-app` |
| `GIT_REPO` | Git URL to clone; blank creates a new Laravel project | *(blank)* | | `GIT_REPO` | Git URL to clone; blank scaffolds a bare backend/frontend pair | *(blank)* |
| `DB_TYPE` | `mysql` or `sqlite` | `sqlite` | | `DB_TYPE` | `mysql` or `sqlite` | `sqlite` |
| `DB_USER` | MariaDB username (`mysql` only) | `laravel_user` | | `DB_USER` | MariaDB username (`mysql` only) | `laravel_user` |
| `DB_PASS` | MariaDB password (`mysql` only) | random | | `DB_PASS` | MariaDB password (`mysql` only) | random |
| `DB_NAME` | MariaDB database name (`mysql` only) | `laravel_db` | | `DB_NAME` | MariaDB database name (`mysql` only) | `laravel_db` |
| `SUPER_ADMIN_EMAIL` | Seeded Super Admin email | `superadmin@example.com` |
| `SUPER_ADMIN_USERNAME` | Seeded Super Admin username | `superadmin` |
| `SUPER_ADMIN_PASSWORD` | Seeded Super Admin password | random |
| `INSTALL_CODE_SERVER` | Install code-server | `yes` | | `INSTALL_CODE_SERVER` | Install code-server | `yes` |
| `INSTALL_CLAUDE_CODE` | Install Node.js + Claude Code | `yes` | | `INSTALL_CLAUDE_CODE` | Install Node.js + Claude Code | `yes` |
| `FIX_SSHD` | Auto-relax sshd config (TurnKey TCP forwarding / Ubuntu root login) | `yes` | | `FIX_SSHD` | Auto-relax sshd config (TurnKey TCP forwarding / Ubuntu root login) | `yes` |
@ -48,15 +60,19 @@ bash bootstrap.sh
1. **Base system**`apt update/upgrade`, installs `sudo curl git wget unzip`. 1. **Base system**`apt update/upgrade`, installs `sudo curl git wget unzip`.
2. **SSH** — installs and enables `openssh-server`; on TurnKey Core containers enables `AllowTcpForwarding`, on other distros enables `PermitRootLogin yes` (needed for VS Code Remote-SSH / port tunneling). 2. **SSH** — installs and enables `openssh-server`; on TurnKey Core containers enables `AllowTcpForwarding`, on other distros enables `PermitRootLogin yes` (needed for VS Code Remote-SSH / port tunneling).
3. **Laravel stack** — Apache, PHP + required extensions, MariaDB or SQLite, Composer, clones or scaffolds the Laravel project, sets permissions, configures an Apache vhost, generates `.env`, runs `key:generate` and `migrate`. 3. **Docker + Mosquitto** — installs Docker Engine + Compose plugin, generates per-role Mosquitto broker credentials, brings up the `mosquitto` container (MQTT on 1883, WebSockets on 9001).
4. **code-server** — browser-based VS Code, so you can edit the app over SSH without a local editor. 4. **Laravel + React stack** — Apache, PHP + required extensions, MariaDB or SQLite, Composer, Node.js, clones or scaffolds `backend/` (Laravel) and `frontend/` (Vite React-TS), sets permissions, configures an Apache vhost pointing at `backend/public`, generates `.env` (DB, MQTT, Super Admin, Sanctum/CORS), runs `key:generate`, `migrate`, and `db:seed`.
5. **Claude Code** — installs Node.js LTS, then `npm install -g @anthropic-ai/claude-code`. 5. **Queue worker** — installs and starts a systemd unit (`<app-name>-queue`) running `php artisan queue:work`, required for MQTT events to actually publish.
6. Prints a summary with the app path, DB type, container IP, and next steps. 6. **code-server** — browser-based VS Code, so you can edit the app over SSH without a local editor.
7. **Claude Code**`npm install -g @anthropic-ai/claude-code`.
8. Prints a summary with the app path, DB type, container IP, Super Admin credentials, and next steps.
## After install ## After install
- **Edit the app:** `code-server /var/www/<app-name>` then open the tunneled port (8080) in your browser. - **Edit the app:** `code-server /var/www/<app-name>` then open the tunneled port (8080) in your browser.
- **Use Claude Code:** `cd /var/www/<app-name> && claude` - **Use Claude Code:** `cd /var/www/<app-name> && claude`
- **Run the frontend dev server:** `cd /var/www/<app-name>/frontend && npm run dev -- --host` then tunnel port 5173.
- **Log in:** the Super Admin credentials printed at the end of setup (also in `backend/.env` as `SUPER_ADMIN_*`).
## Manual SSH config notes (if you skip `FIX_SSHD`) ## Manual SSH config notes (if you skip `FIX_SSHD`)
@ -75,12 +91,3 @@ nano /etc/ssh/sshd_config
## Standard Claude Code project prompt ## Standard Claude Code project prompt
For a consistent architecture baseline (mobile-first React frontend, Laravel API backend, RBAC, MQTT real-time updates, SQLite↔PostgreSQL portability, security-first defaults), start every new Claude Code session in the project with [`claude-project-prompt.md`](./claude-project-prompt.md) as the system/instruction prompt. For a consistent architecture baseline (mobile-first React frontend, Laravel API backend, RBAC, MQTT real-time updates, SQLite↔PostgreSQL portability, security-first defaults), start every new Claude Code session in the project with [`claude-project-prompt.md`](./claude-project-prompt.md) as the system/instruction prompt.
## Legacy scripts
The original interactive, single-purpose scripts are still available if you don't want the full bootstrap:
- `install-laravel.sh` — Laravel + MySQL only, interactive prompts.
- `install-laravel-ad.sh` — Laravel + MySQL/SQLite choice, interactive prompts.
`bootstrap.sh` supersedes both and additionally installs SSH hardening, code-server, and Claude Code in one pass.

49
VERIFICATION.md Normal file
View File

@ -0,0 +1,49 @@
# 7-Point MCP Verification — Foundations + Users Management Module
Per `claude-project-prompt.md`'s `<mcp_rule>`, run after this implementation batch (plan: `imperative-toasting-tome.md`).
## 1. Architecture consistency
`backend/` is API-only (`routes/api.php`, versioned under `/v1`) — no server-rendered views for app data. `frontend/` is a Vite React SPA consuming it exclusively over `/api/v1/*` and `/sanctum/*`. Business logic lives in `app/Actions/*` (Login, VerifyTwoFactor, CreateUser, UpdateUser, DeleteUser, AssignRole), not in controllers. Controllers stay thin (validate via Form Requests → call an Action → fire an event → return a Resource).
## 2. Mobile-first compliance
`MobileShell` (`frontend/src/layouts/shell/MobileShell.tsx`) — top bar + bottom nav — and `DesktopShell` were built together in the same pass (task 7), not desktop-first with mobile bolted on. `AppShell` picks between them via `useIsMobile()` at a single decision point. Verified in-browser both directions: resizing/reloading at 375×812 renders `MobileShell`, at 1280×720 renders `DesktopShell`, with identical data and functionality (login, Users CRUD, dashboard widgets) in both.
## 3. Separate mobile/desktop view integrity
- `layouts/shell/{MobileShell,DesktopShell}.tsx` — distinct files, shared only via the `Outlet` contract.
- `features/users/{UsersListPage.tsx, UsersListPage.mobile.tsx}` — desktop uses a sortable/paginated `DataTable`; mobile uses a card list. Both share `useUsersRealtime()`, `usersApi.ts`, `UserFormModal`, `AssignRoleModal` — logic shared, markup separate, per the spec's explicit instruction.
- `UserFormModal` renders as a centered `Modal` on desktop and a bottom `Sheet` on mobile (same `UserFormFields` inside either).
## 4. Security compliance
- **CSRF**: Sanctum SPA cookie auth + `X-XSRF-TOKEN`; verified a stale token gets a 419, a fresh one succeeds.
- **Rate limiting**: login throttled 5/min/IP+identifier (verified: 6th attempt in a minute returns "Too many login attempts"); general API throttle 60/min (`RateLimiter::for('api', ...)`).
- **No user enumeration**: invalid login always returns the same generic message.
- **2FA**: TOTP (`pragmarx/google2fa`) + 10 single-use hashed recovery codes; verified full browser flow (enable → QR → confirm → recovery-code login) and that a used recovery code is consumed.
- **RBAC enforcement, 4 layers**: route middleware, `UserPolicy` (view/create/update/delete), API Resource `can_edit`/`can_delete` flags, frontend `usePermission()` nav/button gating. Verified a `user`-role account cannot see the Users nav item or any gated buttons; a `super-admin` can.
- **Self-delete guard**: `UserPolicy::delete` blocks it — **and this caught a real bug**: the `Gate::before` super-admin bypass initially overrode that guard, letting the Super Admin soft-delete their own account. Fixed by special-casing self-delete inside `Gate::before` itself (`app/Providers/AppServiceProvider.php`) so it applies even to the bypass; re-verified 403 after the fix, account restored.
- **Secure headers**: `SecurityHeaders` middleware (CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, HSTS-on-HTTPS) appended to the `api` middleware group; verified present on successful `/api/v1/*` responses.
- **CORS**: `supports_credentials: true`, `allowed_origins` restricted to `FRONTEND_URL` (no wildcard).
- **Audit logging**: covers login, logout, 2FA enable/verify/disable, and every Users CRUD + role-assign action — verified via the dashboard's Recent Activity feed and directly via `/api/v1/dashboard/activity`.
- **Secrets**: DB/MQTT/Super-Admin credentials all via `.env`, generated with `openssl rand`, never hardcoded; Mosquitto `passwd`/`credentials.env` git-ignored.
- **File-upload hardening**: `FileUploadValidator` scaffolded (mime-sniffing, size cap, randomized filenames) ahead of any actual upload feature.
## 5. RBAC/permissions compliance
Roles `super-admin`/`admin`/`manager`/`user` seeded with `{module}.{action}`-named permissions. Verified via tinker that the seeded Super Admin holds all 8 permissions and the `Gate::before` bypass grants even an undefined permission. Verified via the Users module UI that role reassignment (manager → admin) immediately changes the permission set returned by the API and reflected in the UI. MQTT topic ACLs add a fifth enforcement layer (role-scoped topics — see point 6).
## 6. Real-time/MQTT compliance
Topic taxonomy (`private/user/{id}/notifications`, `role/{role}/alerts`, `module/{module}/events`, `broadcast/system`) enforced via Mosquitto's `acl.conf`. Verified end-to-end:
- `mosquitto_pub`/`sub` round-trip on both 1883 (MQTT) and confirmed 9001 (WebSocket) is reachable and used by `mqtt.js` in the browser.
- ACL denial verified directly: a `role_user` credential subscribes successfully (SUBACK) but receives zero messages published to `module/users/events`, which it isn't authorized for.
- Full Users CRUD cycle (create/update/assign-role/delete) each published a distinct MQTT event, captured live via `mosquitto_sub`.
- Browser-side: creating/editing/deleting a user through the UI produced a live toast and an up-to-date list/dashboard with **zero manual refresh**, via `useUsersRealtime()`/`useMqttTopic` invalidating the relevant react-query cache.
- Reconnect/token-refresh logic (`mqttClient.ts`) re-fetches a new broker credential on `close` before mqtt.js's automatic reconnect retries.
- **Documented limitation, not silently dropped**: per-role static Mosquitto credentials give role-level topic isolation only, not per-user; true per-user isolation needs a JWT-validating auth plugin (e.g. `mosquitto-go-auth`), deferred as an explicit follow-up per the approved plan.
## 7. Database portability
All migrations use the Eloquent schema builder exclusively — no raw SQL anywhere. `users` adds a `public_id` UUID (used for route-model binding and all API-facing IDs, never the numeric PK), soft deletes, and a self-referential `created_by` FK. `audit_logs` is append-only (`UPDATED_AT = null`, no soft deletes) with a polymorphic `auditable` relation. `spatie/laravel-permission` and Sanctum's own migrations are vendor-maintained and already Postgres-portable. Verified `migrate:fresh` succeeds cleanly against SQLite; nothing in the schema (indexes, FKs, JSON casts) is SQLite-specific.
---
## Known follow-ups (flagged, not silently dropped)
- Per-user MQTT topic isolation (JWT-based Mosquitto ACLs) — deferred per plan.
- Production TLS/reverse-proxy for the API and MQTT WebSocket listener — out of scope for this LXC-dev-focused pass, required before any non-local exposure.
- Frontend bundle exceeds Vite's 500KB chunk-size warning threshold (mqtt.js + react-query + axios); worth code-splitting later, not a functional issue now.

18
backend/.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[compose.yaml]
indent_size = 4

87
backend/.env.example Normal file
View File

@ -0,0 +1,87 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
SUPER_ADMIN_EMAIL=superadmin@example.com
SUPER_ADMIN_USERNAME=superadmin
SUPER_ADMIN_PASSWORD=change-me
FRONTEND_URL=http://localhost:5173
SANCTUM_STATEFUL_DOMAINS=localhost:5173,localhost,127.0.0.1
MQTT_HOST=127.0.0.1
MQTT_PORT=1883
MQTT_WS_URL=ws://localhost:9001
MQTT_TLS=false
MQTT_PUBLISHER_USERNAME=laravel_publisher
MQTT_PUBLISHER_PASSWORD=change-me
MQTT_ROLE_ADMIN_USERNAME=role_admin
MQTT_ROLE_ADMIN_PASSWORD=change-me
MQTT_ROLE_MANAGER_USERNAME=role_manager
MQTT_ROLE_MANAGER_PASSWORD=change-me
MQTT_ROLE_USER_USERNAME=role_user
MQTT_ROLE_USER_PASSWORD=change-me
MQTT_AUTH_USERNAME=laravel_publisher
MQTT_AUTH_PASSWORD=change-me

11
backend/.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

59
backend/README.md Normal file
View File

@ -0,0 +1,59 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

View File

@ -0,0 +1,60 @@
<?php
namespace App\Actions\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginAction
{
/**
* @return array{status: 'authenticated', user: User}|array{status: 'requires_2fa', challenge_token: string}
*/
public function execute(Request $request, string $login, string $password): array
{
$throttleKey = 'login:'.$request->ip().':'.$login;
if (RateLimiter::tooManyAttempts($throttleKey, 5)) {
throw ValidationException::withMessages([
'login' => 'Too many login attempts. Please try again in a minute.',
]);
}
$user = User::where('email', $login)->orWhere('username', $login)->first();
if (! $user || ! Hash::check($password, $user->password)) {
RateLimiter::hit($throttleKey, 60);
// Generic message on purpose — never reveal whether the login
// identifier itself exists (no user enumeration).
throw ValidationException::withMessages([
'login' => 'These credentials do not match our records.',
]);
}
RateLimiter::clear($throttleKey);
if ($user->two_factor_enabled) {
$challengeToken = Str::random(40);
Cache::put("2fa_challenge:{$challengeToken}", [
'user_id' => $user->id,
'ip' => $request->ip(),
'attempts' => 0,
], now()->addMinutes(5));
return ['status' => 'requires_2fa', 'challenge_token' => $challengeToken];
}
Auth::login($user);
$request->session()->regenerate();
return ['status' => 'authenticated', 'user' => $user];
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace App\Actions\Auth;
use App\Models\User;
use App\Services\TwoFactorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;
class VerifyTwoFactorAction
{
public function __construct(private readonly TwoFactorService $twoFactor) {}
public function execute(Request $request, string $challengeToken, string $code): User
{
$cacheKey = "2fa_challenge:{$challengeToken}";
$challenge = Cache::get($cacheKey);
if (! $challenge || $challenge['ip'] !== $request->ip()) {
throw ValidationException::withMessages([
'challenge_token' => 'This challenge has expired. Please log in again.',
]);
}
if ($challenge['attempts'] >= 5) {
Cache::forget($cacheKey);
throw ValidationException::withMessages([
'code' => 'Too many failed attempts. Please log in again.',
]);
}
$user = User::findOrFail($challenge['user_id']);
$valid = $this->twoFactor->verifyCode($user->two_factor_secret, $code)
|| $this->twoFactor->redeemRecoveryCode($user, $code);
if (! $valid) {
$challenge['attempts']++;
Cache::put($cacheKey, $challenge, now()->addMinutes(5));
throw ValidationException::withMessages([
'code' => 'That code is invalid.',
]);
}
Cache::forget($cacheKey);
Auth::login($user);
$request->session()->regenerate();
return $user;
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace App\Actions\Users;
use App\Models\User;
class AssignRoleAction
{
public function execute(User $user, string $role): User
{
$user->syncRoles([$role]);
return $user;
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Actions\Users;
use App\Models\User;
class CreateUserAction
{
/**
* @param array{name: string, username: string, email: string, password: string, role: string} $data
*/
public function execute(array $data, User $actor): User
{
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => $data['password'],
'created_by' => $actor->id,
]);
// The DB default (false) applies, but isn't hydrated back onto this
// in-memory instance after insert — set it explicitly for the
// response/event payload built from this same object.
$user->two_factor_enabled = false;
$user->assignRole($data['role']);
return $user;
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Actions\Users;
use App\Models\User;
class DeleteUserAction
{
public function execute(User $user): void
{
$user->delete();
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Actions\Users;
use App\Models\User;
class UpdateUserAction
{
/**
* @param array{name?: string, username?: string, email?: string, password?: string} $data
*/
public function execute(User $user, array $data): User
{
$user->fill(array_filter($data, fn ($value) => $value !== null && $value !== ''));
$user->save();
return $user;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class RoleAssigned
{
use Dispatchable, SerializesModels;
public function __construct(public User $user, public User $actor, public string $role) {}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserCreated
{
use Dispatchable, SerializesModels;
public function __construct(public User $user, public User $actor) {}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserDeleted
{
use Dispatchable, SerializesModels;
public function __construct(public User $user, public User $actor) {}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Events;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserUpdated
{
use Dispatchable, SerializesModels;
public function __construct(public User $user, public User $actor) {}
}

View File

@ -0,0 +1,113 @@
<?php
namespace App\Http\Controllers\Api;
use App\Actions\Auth\LoginAction;
use App\Actions\Auth\VerifyTwoFactorAction;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\TwoFactorChallengeRequest;
use App\Http\Requests\Auth\TwoFactorConfirmRequest;
use App\Http\Requests\Auth\TwoFactorDisableRequest;
use App\Http\Resources\UserResource;
use App\Services\Audit\AuditLogger;
use App\Services\TwoFactorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
public function login(LoginRequest $request, LoginAction $action, AuditLogger $audit)
{
$result = $action->execute($request, $request->string('login')->toString(), $request->string('password')->toString());
if ($result['status'] === 'requires_2fa') {
return response()->json(['requires_2fa' => true, 'challenge_token' => $result['challenge_token']]);
}
$audit->log($result['user'], 'auth.login');
return UserResource::make($result['user']);
}
public function verifyTwoFactor(TwoFactorChallengeRequest $request, VerifyTwoFactorAction $action, AuditLogger $audit)
{
$user = $action->execute($request, $request->string('challenge_token')->toString(), $request->string('code')->toString());
$audit->log($user, 'auth.2fa_verified');
return UserResource::make($user);
}
public function logout(Request $request, AuditLogger $audit)
{
$audit->log($request->user(), 'auth.logout');
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return response()->noContent();
}
public function me(Request $request)
{
return UserResource::make($request->user());
}
public function enableTwoFactor(Request $request, TwoFactorService $twoFactor)
{
$user = $request->user();
$secret = $twoFactor->generateSecret();
// Stored but not yet "enabled" until confirmed with a valid code.
$user->forceFill(['two_factor_secret' => $secret])->save();
return response()->json([
'secret' => $secret,
'otpauth_url' => $twoFactor->otpAuthUrl($user, $secret),
]);
}
public function confirmTwoFactor(TwoFactorConfirmRequest $request, TwoFactorService $twoFactor, AuditLogger $audit)
{
$user = $request->user();
if (! $user->two_factor_secret || ! $twoFactor->verifyCode($user->two_factor_secret, $request->string('code')->toString())) {
throw ValidationException::withMessages(['code' => 'That code is invalid.']);
}
$user->forceFill([
'two_factor_enabled' => true,
'two_factor_confirmed_at' => now(),
])->save();
$recoveryCodes = $twoFactor->generateRecoveryCodes($user);
$audit->log($user, 'auth.2fa_enabled');
return response()->json(['recovery_codes' => $recoveryCodes]);
}
public function disableTwoFactor(TwoFactorDisableRequest $request, AuditLogger $audit)
{
$user = $request->user();
if (! Hash::check($request->string('password')->toString(), $user->password)) {
throw ValidationException::withMessages(['password' => 'That password is incorrect.']);
}
$user->twoFactorRecoveryCodes()->delete();
$user->forceFill([
'two_factor_enabled' => false,
'two_factor_secret' => null,
'two_factor_confirmed_at' => null,
])->save();
$audit->log($user, 'auth.2fa_disabled');
return response()->noContent();
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\AuditLogResource;
use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
class DashboardController extends Controller
{
public function stats(Request $request)
{
abort_unless($request->user()->can('dashboard.view'), 403);
$usersByRole = Role::where('name', '!=', 'super-admin')
->pluck('name')
->mapWithKeys(fn (string $role) => [$role => User::role($role)->count()]);
return response()->json([
'total_users' => User::count(),
'users_by_role' => (object) $usersByRole->all(),
]);
}
public function activity(Request $request)
{
abort_unless($request->user()->can('audit.view'), 403);
$logs = AuditLog::with('user')->latest()->limit(10)->get();
return AuditLogResource::collection($logs);
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class MqttController extends Controller
{
public function token(Request $request)
{
$user = $request->user();
$roleKey = match (true) {
$user->hasAnyRole(['super-admin', 'admin']) => 'admin',
$user->hasRole('manager') => 'manager',
default => 'user',
};
$credentials = config("mqtt.role_credentials.{$roleKey}");
return response()->json([
'ws_url' => config('mqtt.ws_url'),
'username' => $credentials['username'],
'password' => $credentials['password'],
]);
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\RoleResource;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
class RoleController extends Controller
{
public function index(Request $request)
{
abort_unless($request->user()->can('roles.view'), 403);
// Super Admin is intentionally excluded — it's granted only via
// seeding/tinker, never assignable through the Users module.
return RoleResource::collection(Role::where('name', '!=', 'super-admin')->orderBy('name')->get());
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers\Api;
use App\Actions\Users\AssignRoleAction;
use App\Actions\Users\CreateUserAction;
use App\Actions\Users\DeleteUserAction;
use App\Actions\Users\UpdateUserAction;
use App\Events\RoleAssigned;
use App\Events\UserCreated;
use App\Events\UserDeleted;
use App\Events\UserUpdated;
use App\Http\Controllers\Controller;
use App\Http\Requests\Users\AssignRoleRequest;
use App\Http\Requests\Users\StoreUserRequest;
use App\Http\Requests\Users\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Services\Audit\AuditLogger;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
$this->authorize('viewAny', User::class);
$query = User::query()->with('roles');
if ($search = $request->string('search')->toString()) {
$query->where(function ($q) use ($search) {
$q->where('name', 'like', "%{$search}%")
->orWhere('username', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
});
}
$sort = in_array($request->query('sort'), ['name', 'username', 'email', 'created_at'], true)
? $request->query('sort')
: 'created_at';
$direction = $request->query('direction') === 'asc' ? 'asc' : 'desc';
$users = $query->orderBy($sort, $direction)->paginate($request->integer('per_page', 15));
return UserResource::collection($users);
}
public function store(StoreUserRequest $request, CreateUserAction $action, AuditLogger $audit)
{
$user = $action->execute($request->validated(), $request->user());
event(new UserCreated($user, $request->user()));
$audit->log($request->user(), 'user.created', $user);
return UserResource::make($user)->response()->setStatusCode(201);
}
public function show(Request $request, User $user)
{
$this->authorize('view', $user);
return UserResource::make($user->load('roles'));
}
public function update(UpdateUserRequest $request, User $user, UpdateUserAction $action, AuditLogger $audit)
{
$user = $action->execute($user, $request->validated());
event(new UserUpdated($user, $request->user()));
$audit->log($request->user(), 'user.updated', $user);
return UserResource::make($user);
}
public function destroy(Request $request, User $user, DeleteUserAction $action, AuditLogger $audit)
{
$this->authorize('delete', $user);
$action->execute($user);
event(new UserDeleted($user, $request->user()));
$audit->log($request->user(), 'user.deleted', $user);
return response()->noContent();
}
public function assignRole(AssignRoleRequest $request, User $user, AssignRoleAction $action, AuditLogger $audit)
{
$role = $request->string('role')->toString();
$user = $action->execute($user, $role);
event(new RoleAssigned($user, $request->user(), $role));
$audit->log($request->user(), 'user.role_assigned', $user, ['role' => $role]);
return UserResource::make($user);
}
}

View File

@ -0,0 +1,10 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller
{
use AuthorizesRequests;
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class SecurityHeaders
{
/**
* Handle an incoming request.
*
* @param Closure(Request): (Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set(
'Content-Security-Policy',
"default-src 'none'; frame-ancestors 'none'"
);
if ($request->secure()) {
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
return $response;
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'login' => ['required', 'string'],
'password' => ['required', 'string'],
];
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Foundation\Http\FormRequest;
class TwoFactorChallengeRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'challenge_token' => ['required', 'string'],
'code' => ['required', 'string'],
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Foundation\Http\FormRequest;
class TwoFactorConfirmRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'code' => ['required', 'string'],
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Foundation\Http\FormRequest;
class TwoFactorDisableRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'password' => ['required', 'string'],
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
class AssignRoleRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('roles.assign');
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'role' => ['required', 'string', 'in:admin,manager,user'],
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
class StoreUserRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('users.create');
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users,username'],
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
'password' => ['required', 'string', Password::min(8)],
'role' => ['required', 'string', 'in:admin,manager,user'],
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
class UpdateUserRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('update', $this->route('user'));
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
$userId = $this->route('user')->id;
return [
'name' => ['sometimes', 'string', 'max:255'],
'username' => ['sometimes', 'string', 'max:255', Rule::unique('users', 'username')->ignore($userId)],
'email' => ['sometimes', 'email', 'max:255', Rule::unique('users', 'email')->ignore($userId)],
'password' => ['sometimes', 'nullable', 'string', Password::min(8)],
];
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class AuditLogResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'action' => $this->action,
'actor_name' => $this->user?->name ?? 'System',
'created_at' => $this->created_at,
];
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class RoleResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'name' => $this->name,
];
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->public_id,
'name' => $this->name,
'username' => $this->username,
'email' => $this->email,
'two_factor_enabled' => $this->two_factor_enabled,
'roles' => $this->getRoleNames(),
'permissions' => $this->getAllPermissions()->pluck('name'),
'created_at' => $this->created_at,
'can_edit' => $request->user()?->can('users.update') ?? false,
'can_delete' => $request->user()?->can('users.delete') && $request->user()->id !== $this->id,
];
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Listeners;
use App\Events\RoleAssigned;
use App\Events\UserCreated;
use App\Events\UserDeleted;
use App\Events\UserUpdated;
use App\Services\Mqtt\MqttPublisher;
use Illuminate\Contracts\Queue\ShouldQueue;
class PublishUserEventToMqtt implements ShouldQueue
{
public int $tries = 3;
public array $backoff = [5, 15, 30];
public function handle(UserCreated|UserUpdated|UserDeleted|RoleAssigned $event): void
{
// A plain payload, not UserResource — this broadcasts to every
// subscriber regardless of viewer, so per-viewer fields like
// can_edit/can_delete don't belong here.
$payload = [
'type' => class_basename($event),
'user' => [
'id' => $event->user->public_id,
'name' => $event->user->name,
'username' => $event->user->username,
'email' => $event->user->email,
'roles' => $event->user->getRoleNames(),
],
'actor_id' => $event->actor->public_id,
'ts' => now()->toIso8601String(),
];
MqttPublisher::publish('module/users/events', $payload);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class AuditLog extends Model
{
public const UPDATED_AT = null;
protected $fillable = [
'user_id',
'action',
'auditable_type',
'auditable_id',
'ip_address',
'user_agent',
'metadata',
];
protected function casts(): array
{
return [
'metadata' => 'array',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function auditable(): MorphTo
{
return $this->morphTo();
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class TwoFactorRecoveryCode extends Model
{
protected $fillable = [
'user_id',
'code_hash',
'used_at',
];
protected function casts(): array
{
return [
'used_at' => 'datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasApiTokens, HasFactory, HasRoles, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'username',
'email',
'password',
'created_by',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_secret',
];
public function twoFactorRecoveryCodes(): HasMany
{
return $this->hasMany(TwoFactorRecoveryCode::class);
}
/**
* Route-model binding (and URLs) use the UUID, never the numeric PK.
*/
public function getRouteKeyName(): string
{
return 'public_id';
}
protected static function booted(): void
{
static::creating(function (User $user) {
$user->public_id ??= (string) Str::uuid();
});
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'two_factor_enabled' => 'boolean',
'two_factor_secret' => 'encrypted',
'two_factor_confirmed_at' => 'datetime',
];
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Policies;
use App\Models\User;
class UserPolicy
{
public function viewAny(User $user): bool
{
return $user->can('users.view');
}
public function view(User $user, User $model): bool
{
return $user->can('users.view');
}
public function create(User $user): bool
{
return $user->can('users.create');
}
public function update(User $user, User $model): bool
{
return $user->can('users.update');
}
public function delete(User $user, User $model): bool
{
// Prevent self-delete even for roles that hold users.delete.
return $user->can('users.delete') && $user->id !== $model->id;
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Providers;
use App\Events\RoleAssigned;
use App\Events\UserCreated;
use App\Events\UserDeleted;
use App\Events\UserUpdated;
use App\Listeners\PublishUserEventToMqtt;
use App\Models\User;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
// Defense-in-depth: super-admin bypasses every permission/policy check,
// even if a permission is later removed or misconfigured — except
// self-delete, which must never be allowed for any role, so that
// check is enforced here too rather than left to fall through to
// a policy this bypass would otherwise short-circuit.
Gate::before(function (User $user, string $ability, array $arguments = []) {
if ($ability === 'delete' && ($arguments[0] ?? null) instanceof User && $arguments[0]->id === $user->id) {
return false;
}
return $user->hasRole('super-admin') ? true : null;
});
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
// Registered explicitly — auto-discovery doesn't reliably match a
// union-typed handle() parameter across multiple event classes.
Event::listen([UserCreated::class, UserUpdated::class, UserDeleted::class, RoleAssigned::class], PublishUserEventToMqtt::class);
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Services\Audit;
use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
class AuditLogger
{
public function log(User $actor, string $action, ?Model $auditable = null, array $metadata = []): AuditLog
{
return AuditLog::create([
'user_id' => $actor->id,
'action' => $action,
'auditable_type' => $auditable?->getMorphClass(),
'auditable_id' => $auditable?->getKey(),
'ip_address' => Request::ip(),
'user_agent' => Request::userAgent(),
'metadata' => $metadata,
]);
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Services;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
/**
* Scaffolded ahead of any actual upload feature (e.g. avatars) so hardening
* isn't an afterthought bolted on later. Not wired to a route yet.
*/
class FileUploadValidator
{
private const ALLOWED_MIME_TYPES = [
'image/jpeg',
'image/png',
'image/webp',
];
private const MAX_BYTES = 5 * 1024 * 1024; // 5MB
public function validate(UploadedFile $file): bool
{
if ($file->getSize() > self::MAX_BYTES) {
return false;
}
// Sniff actual content type rather than trusting the client-supplied
// extension or Content-Type header.
return in_array($file->getMimeType(), self::ALLOWED_MIME_TYPES, true);
}
/**
* A randomized filename that never trusts the client-supplied name.
*/
public function randomizedFilename(UploadedFile $file): string
{
return Str::uuid().'.'.$file->extension();
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Services\Mqtt;
use PhpMqtt\Client\Facades\MQTT;
use PhpMqtt\Client\MqttClient;
class MqttPublisher
{
public static function publish(string $topic, array $payload, int $qos = MqttClient::QOS_AT_LEAST_ONCE): void
{
MQTT::connection()->publish($topic, json_encode($payload), $qos);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Services;
use App\Models\TwoFactorRecoveryCode;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use PragmaRX\Google2FA\Google2FA;
class TwoFactorService
{
public function __construct(private readonly Google2FA $google2fa) {}
public function generateSecret(): string
{
return $this->google2fa->generateSecretKey();
}
public function otpAuthUrl(User $user, string $secret): string
{
return $this->google2fa->getQRCodeUrl(
config('app.name'),
$user->email,
$secret,
);
}
public function verifyCode(string $secret, string $code): bool
{
return $this->google2fa->verifyKey($secret, $code, window: 1);
}
/**
* @return list<string> the plaintext recovery codes (shown once, never stored plaintext)
*/
public function generateRecoveryCodes(User $user): array
{
$user->twoFactorRecoveryCodes()->delete();
$plaintextCodes = [];
foreach (range(1, 10) as $_) {
$code = Str::random(10);
$plaintextCodes[] = $code;
TwoFactorRecoveryCode::create([
'user_id' => $user->id,
'code_hash' => Hash::make($code),
]);
}
return $plaintextCodes;
}
public function redeemRecoveryCode(User $user, string $code): bool
{
$recoveryCode = $user->twoFactorRecoveryCodes()
->whereNull('used_at')
->get()
->first(fn (TwoFactorRecoveryCode $recoveryCode) => Hash::check($code, $recoveryCode->code_hash));
if (! $recoveryCode) {
return false;
}
$recoveryCode->update(['used_at' => now()]);
return true;
}
}

18
backend/artisan Normal file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

21
backend/bootstrap/app.php Normal file
View File

@ -0,0 +1,21 @@
<?php
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi();
$middleware->api(append: [SecurityHeaders::class]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();

2
backend/bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,7 @@
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
];

91
backend/composer.json Normal file
View File

@ -0,0 +1,91 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"bacon/bacon-qr-code": "^3.1",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.10.1",
"php-mqtt/laravel-client": "^1.8",
"pragmarx/google2fa-laravel": "^3.0",
"spatie/laravel-permission": "^6.25"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.50"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

9098
backend/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
backend/config/app.php Normal file
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

117
backend/config/auth.php Normal file
View File

@ -0,0 +1,117 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

117
backend/config/cache.php Normal file
View File

@ -0,0 +1,117 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];

34
backend/config/cors.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => explode(',', env('FRONTEND_URL', 'http://localhost:5173')),
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];

184
backend/config/database.php Normal file
View File

@ -0,0 +1,184 @@
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

View File

@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

View File

@ -0,0 +1,83 @@
<?php
return [
/*
* Enable / disable Google2FA.
*/
'enabled' => env('OTP_ENABLED', true),
/*
* Lifetime in minutes.
*
* In case you need your users to be asked for a new one time passwords from time to time.
*/
'lifetime' => env('OTP_LIFETIME', 0), // 0 = eternal
/*
* Renew lifetime at every new request.
*/
'keep_alive' => env('OTP_KEEP_ALIVE', true),
/*
* Auth container binding.
*/
'auth' => 'auth',
/*
* Guard.
*/
'guard' => '',
/*
* 2FA verified session var.
*/
'session_var' => 'google2fa',
/*
* One Time Password request input name.
*/
'otp_input' => 'one_time_password',
/*
* One Time Password Window.
*/
'window' => 1,
/*
* Forbid user to reuse One Time Passwords.
*/
'forbid_old_passwords' => false,
/*
* User's table column for google2fa secret.
*/
'otp_secret_column' => 'google2fa_secret',
/*
* One Time Password View.
*/
'view' => 'google2fa.index',
/*
* One Time Password error message.
*/
'error_messages' => [
'wrong_otp' => "The 'One Time Password' typed was wrong.",
'cannot_be_empty' => 'One Time Password cannot be empty.',
'unknown' => 'An unknown error has occurred. Please try again.',
],
/*
* Throw exceptions or just fire events?
*/
'throw_exceptions' => env('OTP_THROW_EXCEPTION', true),
/*
* Which image backend to use for generating QR codes?
*
* Supports imagemagick, svg and eps
*/
'qrcode_image_backend' => \PragmaRX\Google2FALaravel\Support\Constants::QRCODE_IMAGE_BACKEND_SVG,
];

132
backend/config/logging.php Normal file
View File

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
backend/config/mail.php Normal file
View File

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
],
];

View File

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\Repositories\MemoryRepository;
return [
/*
|--------------------------------------------------------------------------
| Default MQTT Connection
|--------------------------------------------------------------------------
|
| This setting defines the default MQTT connection returned when requesting
| a connection without name from the facade.
|
*/
'default_connection' => 'default',
/*
|--------------------------------------------------------------------------
| MQTT Connections
|--------------------------------------------------------------------------
|
| These are the MQTT connections used by the application. You can also open
| an individual connection from the application itself, but all connections
| defined here can be accessed via name conveniently.
|
*/
'connections' => [
'default' => [
// The host and port to which the client shall connect.
'host' => env('MQTT_HOST'),
'port' => env('MQTT_PORT', 1883),
// The MQTT protocol version used for the connection.
'protocol' => MqttClient::MQTT_3_1,
// A specific client id to be used for the connection. If omitted,
// a random client id will be generated for each new connection.
'client_id' => env('MQTT_CLIENT_ID'),
// Whether a clean session shall be used and requested by the client.
// A clean session will let the broker forget about subscriptions and
// queued messages when the client disconnects. Also, if available,
// data of a previous session will be deleted when connecting.
'use_clean_session' => env('MQTT_CLEAN_SESSION', true),
// Whether logging shall be enabled. The default logger will be used
// with the log level as configured.
'enable_logging' => env('MQTT_ENABLE_LOGGING', true),
// Which logging channel to use for logs produced by the MQTT client.
// If left empty, the default log channel or stack is being used.
'log_channel' => env('MQTT_LOG_CHANNEL', null),
// Defines which repository implementation shall be used. Currently,
// only a MemoryRepository is supported.
'repository' => MemoryRepository::class,
// Additional settings used for the connection to the broker.
// All of these settings are entirely optional and have sane defaults.
'connection_settings' => [
// The TLS settings used for the connection. Must match the specified port.
'tls' => [
'enabled' => env('MQTT_TLS_ENABLED', false),
'allow_self_signed_certificate' => env('MQTT_TLS_ALLOW_SELF_SIGNED_CERT', false),
'verify_peer' => env('MQTT_TLS_VERIFY_PEER', true),
'verify_peer_name' => env('MQTT_TLS_VERIFY_PEER_NAME', true),
'ca_file' => env('MQTT_TLS_CA_FILE'),
'ca_path' => env('MQTT_TLS_CA_PATH'),
'client_certificate_file' => env('MQTT_TLS_CLIENT_CERT_FILE'),
'client_certificate_key_file' => env('MQTT_TLS_CLIENT_CERT_KEY_FILE'),
'client_certificate_key_passphrase' => env('MQTT_TLS_CLIENT_CERT_KEY_PASSPHRASE'),
'alpn' => env('MQTT_TLS_ALPN'),
],
// Credentials used for authentication and authorization.
'auth' => [
'username' => env('MQTT_AUTH_USERNAME'),
'password' => env('MQTT_AUTH_PASSWORD'),
],
// Can be used to declare a last will during connection. The last will
// is published by the broker when the client disconnects abnormally
// (e.g. in case of a disconnect).
'last_will' => [
'topic' => env('MQTT_LAST_WILL_TOPIC'),
'message' => env('MQTT_LAST_WILL_MESSAGE'),
'quality_of_service' => env('MQTT_LAST_WILL_QUALITY_OF_SERVICE', 0),
'retain' => env('MQTT_LAST_WILL_RETAIN', false),
],
// The timeouts (in seconds) used for the connection. Some of these settings
// are only relevant when using the event loop of the MQTT client.
'connect_timeout' => env('MQTT_CONNECT_TIMEOUT', 60),
'socket_timeout' => env('MQTT_SOCKET_TIMEOUT', 5),
'resend_timeout' => env('MQTT_RESEND_TIMEOUT', 10),
// The interval (in seconds) in which the client will send a ping to the broker,
// if no other message has been sent.
'keep_alive_interval' => env('MQTT_KEEP_ALIVE_INTERVAL', 10),
// Additional settings for the optional auto-reconnect. The delay between reconnect attempts is in seconds.
'auto_reconnect' => [
'enabled' => env('MQTT_AUTO_RECONNECT_ENABLED', false),
'max_reconnect_attempts' => env('MQTT_AUTO_RECONNECT_MAX_RECONNECT_ATTEMPTS', 3),
'delay_between_reconnect_attempts' => env('MQTT_AUTO_RECONNECT_DELAY_BETWEEN_RECONNECT_ATTEMPTS', 0),
],
],
],
],
];

24
backend/config/mqtt.php Normal file
View File

@ -0,0 +1,24 @@
<?php
return [
// WebSocket URL the frontend's mqtt.js client connects to.
'ws_url' => env('MQTT_WS_URL', 'ws://localhost:9001'),
// Static per-role Mosquitto credentials (first-pass ACL model — see
// docker/mosquitto/acl.conf for the documented per-user-isolation
// limitation this implies).
'role_credentials' => [
'admin' => [
'username' => env('MQTT_ROLE_ADMIN_USERNAME'),
'password' => env('MQTT_ROLE_ADMIN_PASSWORD'),
],
'manager' => [
'username' => env('MQTT_ROLE_MANAGER_USERNAME'),
'password' => env('MQTT_ROLE_MANAGER_PASSWORD'),
],
'user' => [
'username' => env('MQTT_ROLE_USER_USERNAME'),
'password' => env('MQTT_ROLE_USER_PASSWORD'),
],
],
];

View File

@ -0,0 +1,206 @@
<?php
use Spatie\Permission\DefaultTeamResolver;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
return [
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => Role::class,
],
'table_names' => [
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'roles' => 'roles',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your permissions. We have chosen a basic
* default value but you may easily change it to any table you like.
*/
'permissions' => 'permissions',
/*
* When using the "HasPermissions" trait from this package, we need to know which
* table should be used to retrieve your models permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_permissions' => 'model_has_permissions',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your models roles. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'model_has_roles' => 'model_has_roles',
/*
* When using the "HasRoles" trait from this package, we need to know which
* table should be used to retrieve your roles permissions. We have chosen a
* basic default value but you may easily change it to any table you like.
*/
'role_has_permissions' => 'role_has_permissions',
],
'column_names' => [
/*
* Change this if you want to name the related pivots other than defaults
*/
'role_pivot_key' => null, // default 'role_id',
'permission_pivot_key' => null, // default 'permission_id',
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
/*
* Change this if you want to use the teams feature and your related model's
* foreign key is other than `team_id`.
*/
'team_foreign_key' => 'team_id',
],
/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false if you want to implement custom logic for checking permissions.
*/
'register_permission_check_method' => true,
/*
* When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered
* this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated
* NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it.
*/
'register_octane_reset_listener' => false,
/*
* Events will fire when a role or permission is assigned/unassigned:
* \Spatie\Permission\Events\RoleAttached
* \Spatie\Permission\Events\RoleDetached
* \Spatie\Permission\Events\PermissionAttached
* \Spatie\Permission\Events\PermissionDetached
*
* To enable, set to true, and then create listeners to watch these events.
*/
'events_enabled' => false,
/*
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/
'teams' => false,
/*
* The class to use to resolve the permissions team id
*/
'team_resolver' => DefaultTeamResolver::class,
/*
* Passport Client Credentials Grant
* When set to true the package will use Passports Client to check permissions
*/
'use_passport_client_credentials' => false,
/*
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_permission_in_exception' => false,
/*
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/
'display_role_in_exception' => false,
/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/
'enable_wildcard_permission' => false,
/*
* The class to use for interpreting wildcard permissions.
* If you need to modify delimiters, override the class and specify its name here.
*/
// 'wildcard_permission' => Spatie\Permission\WildcardPermission::class,
/* Cache-specific settings */
'cache' => [
/*
* By default all permissions are cached for 24 hours to speed up performance.
* When permissions or roles are updated the cache is flushed automatically.
*/
'expiration_time' => DateInterval::createFromDateString('24 hours'),
/*
* The cache key used to store all permissions.
*/
'key' => 'spatie.permission.cache',
/*
* You may optionally indicate a specific cache driver to use for permission and
* role caching using any of the `store` drivers listed in the cache.php config
* file. Using 'default' here means to use the `default` set in cache.php.
*/
'store' => 'default',
],
];

129
backend/config/queue.php Normal file
View File

@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

View File

@ -0,0 +1,87 @@
<?php
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => AuthenticateSession::class,
'encrypt_cookies' => EncryptCookies::class,
'validate_csrf_token' => ValidateCsrfToken::class,
],
];

View File

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
backend/config/session.php Normal file
View File

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

1
backend/database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,46 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'username' => fake()->unique()->userName(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,56 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->uuid('public_id')->unique();
$table->string('name');
$table->string('username')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('two_factor_enabled')->default(false);
$table->text('two_factor_secret')->nullable();
$table->timestamp('two_factor_confirmed_at')->nullable();
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@ -0,0 +1,134 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), Exception::class, 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // permission id
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
// $table->engine('InnoDB');
$table->bigIncrements('id'); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format)
$table->string('guard_name'); // For MyISAM use string('guard_name', 25);
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), Exception::class, 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
};

View File

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Append-only: no updated_at/soft deletes, audit records must be immutable.
Schema::create('audit_logs', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('action');
$table->nullableMorphs('auditable');
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->json('metadata')->nullable();
$table->timestamp('created_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('audit_logs');
}
};

View File

@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('two_factor_recovery_codes', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
$table->string('code_hash');
$table->timestamp('used_at')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('two_factor_recovery_codes');
}
};

View File

@ -0,0 +1,19 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
$this->call([
RolePermissionSeeder::class,
SuperAdminSeeder::class,
]);
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class RolePermissionSeeder extends Seeder
{
/**
* Permissions are named `{module}.{action}` so future modules just add
* their own rows here without any schema change.
*/
private const PERMISSIONS = [
'users.view', 'users.create', 'users.update', 'users.delete',
'roles.view', 'roles.assign',
'dashboard.view',
'audit.view',
];
private const ROLE_PERMISSIONS = [
// super-admin gets everything, plus a Gate::before bypass (see AuthServiceProvider)
'super-admin' => self::PERMISSIONS,
'admin' => [
'users.view', 'users.create', 'users.update', 'users.delete',
'roles.view', 'roles.assign',
'dashboard.view', 'audit.view',
],
'manager' => [
'users.view', 'users.update',
'dashboard.view',
],
'user' => [
'dashboard.view',
],
];
public function run(): void
{
// Sanctum SPA (cookie) requests authenticate via the 'web' session
// guard, so roles/permissions must be registered under 'web' to be
// visible to $user->can()/hasRole() during normal API requests.
foreach (self::PERMISSIONS as $permission) {
Permission::findOrCreate($permission, 'web');
}
foreach (self::ROLE_PERMISSIONS as $role => $permissions) {
Role::findOrCreate($role, 'web')->syncPermissions($permissions);
}
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
class SuperAdminSeeder extends Seeder
{
public function run(): void
{
$email = env('SUPER_ADMIN_EMAIL', 'superadmin@example.com');
$username = env('SUPER_ADMIN_USERNAME', 'superadmin');
$password = env('SUPER_ADMIN_PASSWORD', 'password');
$user = User::firstOrCreate(
['email' => $email],
[
'name' => 'Super Admin',
'username' => $username,
'password' => $password,
'email_verified_at' => now(),
]
);
if (! $user->hasRole('super-admin')) {
$user->assignRole('super-admin');
}
}
}

17
backend/package.json Normal file
View File

@ -0,0 +1,17 @@
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.7"
}
}

36
backend/phpunit.xml Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="DB_URL" value=""/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>

25
backend/public/.htaccess Normal file
View File

@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

View File

20
backend/public/index.php Normal file
View File

@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

View File

@ -0,0 +1,2 @@
User-agent: *
Disallow:

View File

@ -0,0 +1,11 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

View File

@ -0,0 +1 @@
import './bootstrap';

4
backend/resources/js/bootstrap.js vendored Normal file
View File

@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

File diff suppressed because one or more lines are too long

35
backend/routes/api.php Normal file
View File

@ -0,0 +1,35 @@
<?php
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\DashboardController;
use App\Http\Controllers\Api\MqttController;
use App\Http\Controllers\Api\RoleController;
use App\Http\Controllers\Api\UserController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1')->middleware('throttle:api')->group(function () {
Route::post('/auth/login', [AuthController::class, 'login']);
Route::post('/auth/2fa/verify', [AuthController::class, 'verifyTwoFactor']);
Route::middleware('auth:sanctum')->group(function () {
Route::post('/auth/logout', [AuthController::class, 'logout']);
Route::get('/auth/me', [AuthController::class, 'me']);
Route::post('/auth/2fa/enable', [AuthController::class, 'enableTwoFactor']);
Route::post('/auth/2fa/confirm', [AuthController::class, 'confirmTwoFactor']);
Route::post('/auth/2fa/disable', [AuthController::class, 'disableTwoFactor']);
Route::get('/mqtt/token', [MqttController::class, 'token']);
Route::get('/roles', [RoleController::class, 'index']);
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::get('/users/{user}', [UserController::class, 'show']);
Route::patch('/users/{user}', [UserController::class, 'update']);
Route::delete('/users/{user}', [UserController::class, 'destroy']);
Route::patch('/users/{user}/role', [UserController::class, 'assignRole']);
Route::get('/dashboard/stats', [DashboardController::class, 'stats']);
Route::get('/dashboard/activity', [DashboardController::class, 'activity']);
});
});

View File

@ -0,0 +1,8 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

7
backend/routes/web.php Normal file
View File

@ -0,0 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});

4
backend/storage/app/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
backend/storage/app/public/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

9
backend/storage/framework/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

View File

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

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