Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae0cf61124 | ||
|
|
c4cad4f875 | ||
|
|
15d3a13d0a | ||
|
|
75bf7c205a | ||
|
|
3721b98420 | ||
|
|
c6d43040c5 | ||
|
|
66a97be5c6 | ||
|
|
184de52ad2 | ||
|
|
0d422cfed5 | ||
|
|
c822872184 |
No files matched your search
Vendored
-1
@@ -34,7 +34,6 @@ declare module '@adonisjs/inertia/types' {
|
||||
'widgets/ComputersViewer': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputersViewer.vue'))['default']>
|
||||
'widgets/CustomSelect': ExtractProps<(typeof import('../../inertia/pages/widgets/CustomSelect.vue'))['default']>
|
||||
'widgets/DeleteConfirmationModal': ExtractProps<(typeof import('../../inertia/pages/widgets/DeleteConfirmationModal.vue'))['default']>
|
||||
'widgets/FilterDropdown': ExtractProps<(typeof import('../../inertia/pages/widgets/FilterDropdown.vue'))['default']>
|
||||
'widgets/SimpleGallery': ExtractProps<(typeof import('../../inertia/pages/widgets/SimpleGallery.vue'))['default']>
|
||||
'widgets/TableComponent': ExtractProps<(typeof import('../../inertia/pages/widgets/TableComponent.vue'))['default']>
|
||||
'widgets/ValidationError': ExtractProps<(typeof import('../../inertia/pages/widgets/ValidationError.vue'))['default']>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
APP_KEY=Z_CbQqpIxo4bGJ0WpqZkB3HoaLXvHf0J
|
||||
APP_URL=http://192.168.1.39:3333
|
||||
DB_PASSWORD=pcbuilder_secure_pass
|
||||
DB_DATABASE=pc_builder
|
||||
DB_USER=pcbuilder
|
||||
@@ -41,35 +41,6 @@ jobs:
|
||||
docker push ${IMAGE}:latest
|
||||
docker push ${IMAGE}:${{ github.sha }}
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# ⚠️ SECURITY REVIEW NOTES (see pc_builder remediation plan, item 1.4)
|
||||
# ---------------------------------------------------------------------
|
||||
# This deploy step has two known issues that were flagged during a
|
||||
# security review but intentionally NOT auto-fixed here (no access to
|
||||
# reconfigure the NAS SSH/sudo setup from this environment):
|
||||
#
|
||||
# 1. `.env.production` was removed from git tracking (it contained
|
||||
# plaintext APP_KEY/DB_PASSWORD and should never have been
|
||||
# committed). The `cat .env.production` line below now reads a
|
||||
# file that will NOT exist in a fresh `git clone` of this repo,
|
||||
# since this job clones the repo from scratch at the top of the
|
||||
# `docker` job. This step WILL fail until the deployment secrets
|
||||
# are migrated to Gitea Actions secrets and the `.env` file is
|
||||
# generated at deploy time instead of committed, e.g.:
|
||||
# printf 'APP_KEY=%s\nDB_PASSWORD=%s\n...' \
|
||||
# "${{ secrets.APP_KEY }}" "${{ secrets.DB_PASSWORD }}" | \
|
||||
# sshpass ... "cat > /volume1/docker/pc_builder/.env"
|
||||
# Until that migration happens, whoever runs this pipeline must
|
||||
# place a non-committed `.env.production` file back in the
|
||||
# repository checkout (or update this script) for deploys to work.
|
||||
#
|
||||
# 2. The NAS password (`secrets.NASPASS`) is passed on the command
|
||||
# line via `sshpass -p` and `sudo -S`, which can leak through
|
||||
# process listings and CI logs. Recommended remediation: switch to
|
||||
# a dedicated SSH key stored as a Gitea secret, and configure a
|
||||
# scoped passwordless `sudo` (NOPASSWD) on the NAS limited to the
|
||||
# exact commands below (setup-db.sh, docker compose, docker exec),
|
||||
# rather than transiting the interactive user's password.
|
||||
- name: Deploy on NAS
|
||||
run: |
|
||||
apk add --no-cache openssh-client sshpass
|
||||
|
||||
@@ -9,7 +9,6 @@ dist
|
||||
# Secrets
|
||||
.env
|
||||
.env.local
|
||||
.env.production
|
||||
.env.production.local
|
||||
.env.development.local
|
||||
.env.test
|
||||
@@ -29,7 +28,6 @@ coverage
|
||||
.fleet
|
||||
.idea
|
||||
.vscode
|
||||
.serena
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
# Plan de remédiation — PC Builder
|
||||
|
||||
Basé sur la revue de code du 2026-07-23. Objectif : corriger les failles de
|
||||
sécurité critiques avant toute mise en production, puis assainir la base du
|
||||
code (majeur), puis traiter les points mineurs/qualité.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — CRITIQUE (bloquant avant prod)
|
||||
|
||||
### 1.1 IDOR sur `update`/`destroy` (Computers & Components)
|
||||
|
||||
**Problème** : `computers_controller.ts` (`update` L92-103, `destroy` L105-110)
|
||||
et `components_controller.ts` (`destroy` L77-82) chargent la ressource via
|
||||
`findOrFail(id)` sans filtrer par `userId`. `destroy` des deux controllers
|
||||
n'authentifie même pas l'utilisateur (`auth.authenticate()` absent). N'importe
|
||||
quel utilisateur connecté peut modifier/supprimer les PC ou composants d'un
|
||||
autre utilisateur.
|
||||
|
||||
**Remédiation** :
|
||||
- `computers_controller.ts#update` : ajouter `auth.authenticate()`, remplacer
|
||||
`Computer.findOrFail(computerId)` par
|
||||
`Computer.query().where('user_id', user.id).andWhere('id', computerId).firstOrFail()`
|
||||
(même pattern que `show`/`edit`).
|
||||
- `computers_controller.ts#destroy` : ajouter `auth.authenticate()`, même
|
||||
pattern de query scopée par `user_id`.
|
||||
- `components_controller.ts#destroy` : ajouter `auth.authenticate()`, remplacer
|
||||
`Component.findOrFail(componentId)` par une query scopée
|
||||
`where('userId', user.id).andWhere('id', componentId).firstOrFail()`.
|
||||
- Vérifier les routes (`start/routes.ts`) : `middleware.auth()` est déjà
|
||||
appliqué sur les groupes `/computers` et `/components`, donc l'utilisateur
|
||||
est authentifiable dans le contexte — juste manquant l'appel explicite +
|
||||
le filtre.
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `app/controllers/computers_controller.ts`
|
||||
- `app/controllers/components_controller.ts`
|
||||
|
||||
### 1.2 IDOR transitif via `handleComponents` / `handlePictures`
|
||||
|
||||
**Problème** : même après la 1.1, `component_service.ts#handleComponents`
|
||||
(L11, L18) et `picture_service.ts#handlePictures` (L22, L47) font
|
||||
`findOrFail(id)` sans vérifier que le composant/l'image appartient à
|
||||
l'utilisateur courant. Un attaquant authentifié peut poster un `componentsId`
|
||||
contenant l'ID d'un composant appartenant à un autre utilisateur pour
|
||||
se l'approprier (`component.computerId = computer.id`).
|
||||
|
||||
**Remédiation** :
|
||||
- `handleComponents(componentsId, computer, userId)` : ajouter le paramètre
|
||||
`userId`, et scoper les requêtes `Component.query().where('userId', userId).andWhere('id', id).firstOrFail()`
|
||||
au lieu de `Component.findOrFail(id)`. Si un ID demandé n'appartient pas à
|
||||
l'utilisateur, lever une erreur explicite (404 ou 403) plutôt que d'échouer
|
||||
silencieusement.
|
||||
- `handlePictures` : scoper `ComputerPicture.findOrFail(picture.id)` par
|
||||
`computerId` du computer courant (`.where('computerId', computer.id)`), pour
|
||||
empêcher de manipuler des images d'un autre computer/utilisateur.
|
||||
- Mettre à jour les appels dans `computers_controller.ts#store` et `#update`
|
||||
pour passer `user.id`.
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `app/services/component_service.ts`
|
||||
- `app/services/picture_service.ts`
|
||||
- `app/controllers/computers_controller.ts` (appels à `handleComponents`)
|
||||
|
||||
### 1.3 Secrets commités : `.env.production`
|
||||
|
||||
**Problème** : `.env.production` est suivi par git et contient `APP_KEY`,
|
||||
`DB_PASSWORD`, `DB_USER`, `DB_DATABASE` en clair (commit `c822872`). Le CI
|
||||
(`.gitea/workflows/build.yml`) le lit et le déploie tel quel sur le NAS.
|
||||
|
||||
**Remédiation** (à faire avec le user — actions sensibles) :
|
||||
1. **Révoquer/régénérer immédiatement** les secrets réels côté NAS :
|
||||
nouveau `APP_KEY` (`node ace generate:key`), nouveau mot de passe MySQL,
|
||||
éventuellement recréer l'utilisateur DB.
|
||||
2. Ajouter `.env.production` au `.gitignore` (garder uniquement
|
||||
`.env.production.example` comme gabarit, déjà présent et sans valeurs
|
||||
réelles).
|
||||
3. Retirer le fichier du suivi git : `git rm --cached .env.production`.
|
||||
4. Purger l'historique git du secret (`git filter-repo` ou BFG Repo-Cleaner)
|
||||
— **à valider avec l'utilisateur** car cela réécrit l'historique partagé
|
||||
(impact sur les autres clones/branches).
|
||||
5. Migrer la distribution des secrets de prod vers les **Secrets Gitea Actions**
|
||||
(comme `secrets.NASPASS`) plutôt qu'un fichier committé : injecter les
|
||||
variables via `${{ secrets.APP_KEY }}`, `${{ secrets.DB_PASSWORD }}`, etc.,
|
||||
et générer `.env` à la volée dans le job de déploiement.
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `.gitignore`
|
||||
- `.gitea/workflows/build.yml`
|
||||
- `.env.production` (suppression du suivi)
|
||||
- Historique git (opération destructive, confirmation utilisateur requise)
|
||||
|
||||
### 1.4 Secrets en ligne de commande dans le pipeline CI (NASPASS)
|
||||
|
||||
**Problème** : `.gitea/workflows/build.yml` L46-56 utilise `sshpass -p` et
|
||||
`sudo -S` avec le secret NAS directement en argument de commande shell —
|
||||
risque d'exposition dans les logs/process list.
|
||||
|
||||
**Remédiation** :
|
||||
- Remplacer l'authentification par mot de passe par une **clé SSH dédiée**
|
||||
stockée en secret Gitea (`secrets.NAS_SSH_KEY`), utilisée via
|
||||
`ssh -i <(echo "$NAS_SSH_KEY")` ou `webfactory/ssh-agent`-like action.
|
||||
- Configurer un accès `sudo` sans mot de passe restreint aux commandes
|
||||
nécessaires (`visudo` avec `NOPASSWD` limité aux scripts `setup-db.sh`,
|
||||
`docker compose`, `docker exec`) plutôt que de faire transiter le mot de
|
||||
passe utilisateur via `sudo -S`.
|
||||
- À défaut de refonte complète immédiate, au minimum masquer la commande
|
||||
(`set +x` explicite, éviter `-x` en debug) et documenter le risque résiduel.
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `.gitea/workflows/build.yml`
|
||||
- Configuration NAS (hors dépôt — à faire manuellement)
|
||||
|
||||
### 1.5 Pas de contrainte d'unicité applicative pour les composants "uniques"
|
||||
|
||||
**Problème** : `ComponentType.unique` (ex: un seul CPU par PC) n'est vérifié
|
||||
nulle part côté serveur. Un POST direct sur `/computers` ou `/computers/:id`
|
||||
avec plusieurs composants du même type "unique" dans `componentsId` est accepté.
|
||||
|
||||
**Remédiation** :
|
||||
- Dans `handleComponents`, après résolution des composants à ajouter, grouper
|
||||
par `typeId` (en préchargeant `type.unique`) et rejeter (erreur 422/exception
|
||||
métier) si plus d'un composant du même type "unique" seraient attachés au
|
||||
computer simultanément.
|
||||
- Ajouter un test automatisé couvrant ce cas (voir Phase 4).
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `app/services/component_service.ts`
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — MAJEUR (avant la prochaine itération fonctionnelle)
|
||||
|
||||
### 2.1 Redirections relatives fragiles
|
||||
|
||||
**Problème** : `computers_controller.ts#store` (L46) fait
|
||||
`response.redirect('computers/')` et `#update` (L102) fait
|
||||
`response.redirect(`${computer.id}`)` — chemins relatifs incohérents avec
|
||||
le reste du code (`/components`, `/auth/login`, etc.).
|
||||
|
||||
**Remédiation** : remplacer par des chemins absolus explicites :
|
||||
- `store` → `response.redirect('/computers')`
|
||||
- `update` → `response.redirect(`/computers/${computer.id}`)`
|
||||
|
||||
### 2.2 Incohérence `request.all()` vs `request.validateUsing()`
|
||||
|
||||
**Problème** : `components_controller.ts` et `computers_controller.ts`
|
||||
utilisent `request.all()` + `xxxValidator.validate(data)` au lieu du helper
|
||||
standard `request.validateUsing(validator)` utilisé par
|
||||
`session_controller.ts`/`new_account_controller.ts`. Risque d'incohérence
|
||||
sur le flash des erreurs de validation Inertia (`inputErrorsBag`).
|
||||
|
||||
**Remédiation** : uniformiser tous les controllers sur
|
||||
`await request.validateUsing(xxxValidator)`, supprimer les appels manuels à
|
||||
`.validate()` sur `request.all()`.
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `app/controllers/computers_controller.ts` (store, update)
|
||||
- `app/controllers/components_controller.ts` (store, update)
|
||||
|
||||
### 2.3 Validateurs d'inscription dupliqués et incohérents
|
||||
|
||||
**Problème** : `app/validators/Auth/register.ts` (`registerValidator`) n'est
|
||||
utilisé nulle part (code mort) ; `new_account_controller.ts` utilise
|
||||
`signupValidator` de `app/validators/user.ts`. Les deux ont des règles
|
||||
différentes sur `name` (obligatoire minLength 3 vs nullable sans contrainte).
|
||||
|
||||
**Remédiation** :
|
||||
- Supprimer `app/validators/Auth/register.ts` (code mort), ou le fusionner
|
||||
si une seconde route d'inscription est prévue.
|
||||
- Décider de la règle métier définitive sur `name` (obligatoire ou non) dans
|
||||
`signupValidator` et l'appliquer.
|
||||
|
||||
### 2.4 Formulaire `computers/create.vue` ne se soumet pas via Enter / pas d'état de chargement
|
||||
|
||||
**Problème** : le bouton "Create" est un `<Link method="post">` externe au
|
||||
`<form>` (pas de `@submit.prevent`), contrairement à `components/create.vue`
|
||||
qui utilise `useForm` + `@submit.prevent` correctement.
|
||||
|
||||
**Remédiation** : refactorer `computers/create.vue` pour utiliser
|
||||
`useForm()` d'Inertia avec `@submit.prevent="form.post('/computers')"`,
|
||||
afficher `form.processing` sur le bouton (état de chargement), harmoniser
|
||||
avec le pattern de `components/create.vue`.
|
||||
|
||||
### 2.5 `origin` fantôme dans `components/edit.vue`
|
||||
|
||||
**Problème** : la page lit `props.origin` et le renvoie dans le payload,
|
||||
mais `components_controller.ts#edit` ne le partage jamais dans
|
||||
`inertia.render(...)`.
|
||||
|
||||
**Remédiation** : soit supprimer complètement `origin` du formulaire et du
|
||||
type de props si la fonctionnalité est abandonnée, soit l'implémenter
|
||||
proprement si un besoin réel existe (ex: retour à la page d'origine après
|
||||
modification). À trancher avec l'utilisateur — proposition : suppression
|
||||
(simplification), sauf avis contraire.
|
||||
|
||||
### 2.6 Suppression d'un `Computer` : cascade destructive sur les composants + fichiers orphelins
|
||||
|
||||
**Problème** : `destroy` d'un `Computer` supprime en cascade DB ses
|
||||
`Component` liés au lieu de les détacher (`computerId = null`), ce qui fait
|
||||
perdre définitivement les composants de l'utilisateur. De plus, les fichiers
|
||||
images physiques (`uploads/computer_X/...`) ne sont jamais nettoyés lors
|
||||
d'un `destroy` de computer (seulement lors d'un retrait explicite via update).
|
||||
|
||||
**Remédiation** :
|
||||
- Dans `computers_controller.ts#destroy`, avant `computer.delete()` :
|
||||
détacher les composants (`UPDATE components SET computer_id = NULL WHERE computer_id = ?`)
|
||||
et supprimer physiquement le dossier `uploads/computer_${id}` (+ les lignes
|
||||
`computer_pictures`, qui elles peuvent rester en cascade DB puisque les
|
||||
fichiers sont supprimés en même temps).
|
||||
- Vérifier/adapter la contrainte `onDelete('CASCADE')` sur `components.computer_id`
|
||||
dans la migration si on souhaite un `SET NULL` réellement porté par la DB
|
||||
plutôt qu'un traitement applicatif (nécessiterait une migration corrective).
|
||||
|
||||
**Fichiers impactés** :
|
||||
- `app/controllers/computers_controller.ts`
|
||||
- Éventuellement une nouvelle migration si `onDelete` doit changer.
|
||||
|
||||
### 2.7 Duplication `ComponentsViewer.vue` / `ComputersViewer.vue`
|
||||
|
||||
**Remédiation** : extraire un composant générique `FilterDropdown.vue`
|
||||
(props : liste d'options `{id, label}`, `v-model` sur l'état de filtre,
|
||||
slot ou prop pour le libellé du bouton) réutilisé dans les deux vues, pour
|
||||
éliminer la duplication du markup dropdown + logique `toggleDropdown`.
|
||||
|
||||
### 2.8 Composants "widgets" orphelins et fonctionnalité galerie incomplète
|
||||
|
||||
**Problème** : `ComponentEditor.vue`, `ComputerComponentsTable.vue`,
|
||||
`SimpleGallery.vue`, `AuthErrorAlert.vue` ne sont référencés par aucune page
|
||||
active. La gestion de galerie photo (`SimpleGallery.vue` + `picture_service.ts`)
|
||||
n'est appelée par aucun formulaire actuel (`computers/create.vue`/`edit.vue`
|
||||
n'ont pas de champ pictures).
|
||||
|
||||
**Remédiation** — décision à prendre avec l'utilisateur :
|
||||
- **Option A (simplification)** : supprimer ces composants orphelins et le
|
||||
code backend de gestion d'images s'ils ne sont plus dans la roadmap.
|
||||
- **Option B (finaliser la fonctionnalité)** : intégrer `SimpleGallery.vue`
|
||||
dans `computers/create.vue`/`edit.vue` pour rendre l'upload d'images
|
||||
réellement fonctionnel, et réintégrer `ComponentEditor.vue` (gestion
|
||||
propre des composants uniques via select) à la place des checkboxes brutes
|
||||
actuelles — ce qui réglerait aussi une partie du problème 1.5 côté UX.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — MINEUR (qualité, hygiène)
|
||||
|
||||
### 3.1 Sécurité de configuration
|
||||
- `config/session.ts` L45 : remplacer `secure: false` par `secure: app.inProduction`.
|
||||
- `config/shield.ts` L12 : activer une CSP de base (`csp.enabled: true`)
|
||||
avec des directives minimales (`default-src 'self'`, autoriser les sources
|
||||
Vite en dev).
|
||||
|
||||
### 3.2 Typage frontend
|
||||
- Remplacer les `any` dans `computers/*.vue` et `components/*.vue` par les
|
||||
types réels (`Computer`, `Component`, `ComputerState`, `ComponentType`
|
||||
importés depuis `#models/*` comme le fait déjà `ComponentsViewer.vue`).
|
||||
- Corriger/aligner `inertia/pages/types/UITypes.ts` avec le schéma backend
|
||||
réel (`typeId` au lieu de `componentTypeId`, retirer `componentStateId`
|
||||
inexistant) ou supprimer ce fichier si les vrais modèles Lucid suffisent.
|
||||
|
||||
### 3.3 Encodage UTF-8 cassé (mojibake)
|
||||
- Corriger l'encodage dans `ComponentsViewer.vue`, `ComponentEditor.vue`,
|
||||
`ComputerComponentsTable.vue`, `TableComponent.vue` (caractères `├®`, `Ôé¼`
|
||||
etc. à réécrire en UTF-8 propre : é, à, ô, €).
|
||||
|
||||
### 3.4 Accessibilité
|
||||
- Corriger les doublons d'`id` HTML dans `ComputersViewer.vue` (L82/94,
|
||||
deux fois `id="used"`).
|
||||
- Ajouter `aria-expanded`/`aria-haspopup` sur les boutons de dropdown filtres.
|
||||
- Remplacer `CustomSelect.vue` par un `<select>` natif stylé, ou ajouter les
|
||||
rôles ARIA manquants (`role="listbox"`, navigation clavier).
|
||||
|
||||
### 3.5 Nettoyage divers
|
||||
- Remplacer `console.warn` dans `computer.ts#cost` par un logger applicatif
|
||||
ou un comportement documenté.
|
||||
- Déplacer/supprimer `MIGRATION_PAGES_SUMMARY.md`, `MIGRATION_COMPLETE.md`,
|
||||
`MIGRATION_CHECKLIST.md` (artefacts temporaires) vers `docs/` ou les
|
||||
supprimer une fois la migration validée.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Tests de non-régression
|
||||
|
||||
Pour valider les correctifs de sécurité (Phase 1), ajouter des tests
|
||||
fonctionnels Japa :
|
||||
- Un utilisateur A ne peut pas `PUT`/`DELETE` un computer/component
|
||||
appartenant à l'utilisateur B (attend 404/403).
|
||||
- Un utilisateur ne peut pas attacher via `componentsId` un composant
|
||||
appartenant à un autre utilisateur.
|
||||
- Impossible d'attacher deux composants du même type "unique" à un même
|
||||
computer.
|
||||
- Après suppression d'un computer, ses composants redeviennent disponibles
|
||||
(`computerId = null`) au lieu d'être supprimés.
|
||||
|
||||
**Fichiers** : `tests/functional/computers.spec.ts`,
|
||||
`tests/functional/components.spec.ts` (à créer si absents).
|
||||
|
||||
---
|
||||
|
||||
## Ordre d'exécution proposé
|
||||
|
||||
1. **Phase 1** entièrement (sécurité bloquante), avec confirmation
|
||||
utilisateur explicite avant toute réécriture d'historique git (1.3) ou
|
||||
changement de config NAS (1.4).
|
||||
2. **Phase 4** (tests) en parallèle de la Phase 1 pour prouver les correctifs.
|
||||
3. **Phase 2** (majeur), avec un point de décision utilisateur sur 2.5 et 2.8
|
||||
(garder/supprimer/finaliser des fonctionnalités).
|
||||
4. **Phase 3** (mineur) en dernier, en petits commits séparés par thème
|
||||
(config sécurité / typage / encodage / accessibilité / nettoyage fichiers).
|
||||
|
||||
## Points nécessitant une décision explicite de l'utilisateur avant exécution
|
||||
|
||||
- **1.3** : confirmer la réécriture de l'historique git pour purger le secret,
|
||||
et confirmer que les secrets réels (APP_KEY, DB_PASSWORD) seront bien
|
||||
régénérés côté NAS avant/juste après.
|
||||
- **1.4** : confirmer l'accès pour reconfigurer l'authentification SSH/sudo
|
||||
sur le NAS (hors du dépôt, nécessite un accès serveur).
|
||||
- **2.5** : garder, implémenter ou supprimer le champ `origin`.
|
||||
- **2.8** : supprimer les composants orphelins (Option A) ou finaliser la
|
||||
fonctionnalité galerie/éditeur de composants uniques (Option B).
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -5,39 +5,22 @@ import { updateComponentValidator } from '#validators/Components/update'
|
||||
import Component from '#models/component'
|
||||
import ComponentType from '#models/component_type'
|
||||
|
||||
/**
|
||||
* Lucid's `serialize()` returns a loosely typed `ModelObject`
|
||||
* (`{ [key: string]: any }`). It is not structurally assignable to the
|
||||
* concrete prop shapes declared by the Vue pages (see
|
||||
* `inertia/pages/types/UITypes.ts`), which live in a separate TypeScript
|
||||
* project (the `inertia/**` tree is excluded from the backend tsconfig).
|
||||
* Since the controller fully controls which columns/relations are
|
||||
* preloaded and serialized, this cast documents that the runtime shape
|
||||
* matches what the page expects at this boundary.
|
||||
*/
|
||||
function asPageProp<T>(value: unknown): T {
|
||||
return value as T
|
||||
}
|
||||
|
||||
export default class ComponentsController {
|
||||
async index({ inertia, auth }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
const components = await Component.query().preload('type').where('userId', user.id)
|
||||
return inertia.render('components/index', {
|
||||
components: asPageProp(components.map((c) => c.serialize())),
|
||||
})
|
||||
return inertia.render('components/index', { components: components.map((c) => c.serialize()) })
|
||||
}
|
||||
|
||||
async create({ inertia }: HttpContext) {
|
||||
const types = await ComponentType.all()
|
||||
return inertia.render('components/create', {
|
||||
types: asPageProp(types.map((t) => t.serialize())),
|
||||
})
|
||||
return inertia.render('components/create', { types: types.map((t) => t.serialize()) })
|
||||
}
|
||||
|
||||
async store({ request, response, auth }: HttpContext) {
|
||||
const data = request.all()
|
||||
const user = await auth.authenticate()
|
||||
const { quantity, ...componentData } = await request.validateUsing(storeComponentValidator)
|
||||
const { quantity, ...componentData } = await storeComponentValidator.validate(data)
|
||||
await ComponentType.findOrFail(componentData.typeId)
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
await Component.create({
|
||||
@@ -57,7 +40,7 @@ export default class ComponentsController {
|
||||
.where('userId', user.id)
|
||||
.andWhere('id', componentId)
|
||||
.firstOrFail()
|
||||
return inertia.render('components/show', { component: asPageProp(component.serialize()) })
|
||||
return inertia.render('components/show', { component: component.serialize() })
|
||||
}
|
||||
|
||||
async edit({ params, auth, inertia }: HttpContext) {
|
||||
@@ -70,14 +53,15 @@ export default class ComponentsController {
|
||||
.andWhere('id', componentId)
|
||||
.firstOrFail()
|
||||
return inertia.render('components/edit', {
|
||||
component: asPageProp(component.serialize()),
|
||||
types: asPageProp(types.map((t) => t.serialize())),
|
||||
component: component.serialize(),
|
||||
types: types.map((t) => t.serialize()),
|
||||
})
|
||||
}
|
||||
|
||||
async update({ params, auth, request, response }: HttpContext) {
|
||||
const data = request.all()
|
||||
const componentData = await updateComponentValidator.validate(data)
|
||||
const user = await auth.authenticate()
|
||||
const componentData = await request.validateUsing(updateComponentValidator)
|
||||
const component = await Component.query()
|
||||
.where('userId', user.id)
|
||||
.andWhere('id', params.id)
|
||||
@@ -90,13 +74,9 @@ export default class ComponentsController {
|
||||
return response.redirect('/components')
|
||||
}
|
||||
|
||||
async destroy({ params, auth, response }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
async destroy({ params, response }: HttpContext) {
|
||||
const componentId = params.id
|
||||
const component = await Component.query()
|
||||
.where('userId', user.id)
|
||||
.andWhere('id', componentId)
|
||||
.firstOrFail()
|
||||
const component = await Component.findOrFail(componentId)
|
||||
await component.delete()
|
||||
return response.redirect('/components')
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { HttpContext } from '@adonisjs/core/http'
|
||||
import { existsSync, rmSync } from 'node:fs'
|
||||
import Computer from '#models/computer'
|
||||
import ComputerState from '#models/computer_state'
|
||||
import Component from '#models/component'
|
||||
@@ -9,20 +8,6 @@ import { handlePictures } from '#services/picture_service'
|
||||
import type { Image } from '#types/UItypes'
|
||||
import { updateComputerValidator } from '#validators/Computers/update'
|
||||
|
||||
/**
|
||||
* Lucid's `serialize()` returns a loosely typed `ModelObject`
|
||||
* (`{ [key: string]: any }`). It is not structurally assignable to the
|
||||
* concrete prop shapes declared by the Vue pages (see
|
||||
* `inertia/pages/types/UITypes.ts`), which live in a separate TypeScript
|
||||
* project (the `inertia/**` tree is excluded from the backend tsconfig).
|
||||
* Since the controller fully controls which columns/relations are
|
||||
* preloaded and serialized, this cast documents that the runtime shape
|
||||
* matches what the page expects at this boundary.
|
||||
*/
|
||||
function asPageProp<T>(value: unknown): T {
|
||||
return value as T
|
||||
}
|
||||
|
||||
export default class ComputersController {
|
||||
async index({ auth, inertia }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
@@ -34,9 +19,7 @@ export default class ComputersController {
|
||||
picturesQuery.where('order', 1)
|
||||
})
|
||||
|
||||
return inertia.render('computers/index', {
|
||||
computers: asPageProp(computers.map((c) => c.serialize())),
|
||||
})
|
||||
return inertia.render('computers/index', { computers: computers.map((c) => c.serialize()) })
|
||||
}
|
||||
|
||||
async create({ auth, inertia }: HttpContext) {
|
||||
@@ -46,24 +29,21 @@ export default class ComputersController {
|
||||
.where('userId', user.id)
|
||||
.whereNull('computerId')
|
||||
.preload('type')
|
||||
return inertia.render('computers/create', {
|
||||
components: asPageProp(components.map((c) => c.serialize())),
|
||||
states: asPageProp(states.map((s) => s.serialize())),
|
||||
})
|
||||
return inertia.render('computers/create', { components: components.map((c) => c.serialize()), states: states.map((s) => s.serialize()) })
|
||||
}
|
||||
|
||||
async store({ auth, request, response }: HttpContext) {
|
||||
const data = request.all()
|
||||
const user = await auth.authenticate()
|
||||
const { pictures, componentsId, ...computerData } =
|
||||
await request.validateUsing(storeComputerValidator)
|
||||
const { pictures, componentsId, ...computerData } = await storeComputerValidator.validate(data)
|
||||
await ComputerState.findOrFail(computerData.stateId)
|
||||
const computer = await Computer.create({
|
||||
...computerData,
|
||||
userId: user.id,
|
||||
})
|
||||
await handleComponents(componentsId as number[], computer, user.id)
|
||||
await handleComponents(componentsId as number[], computer)
|
||||
await handlePictures(pictures as Image[], request, computer)
|
||||
return response.redirect('/computers')
|
||||
return response.redirect('computers/')
|
||||
}
|
||||
|
||||
async show({ auth, inertia, params }: HttpContext) {
|
||||
@@ -80,7 +60,7 @@ export default class ComputersController {
|
||||
.where('user_id', user.id)
|
||||
.andWhere('id', computerId)
|
||||
.firstOrFail()
|
||||
return inertia.render('computers/show', { computer: asPageProp(computer.serialize()) })
|
||||
return inertia.render('computers/show', { computer: computer.serialize() })
|
||||
}
|
||||
|
||||
async edit({ params, inertia, auth }: HttpContext) {
|
||||
@@ -106,43 +86,25 @@ export default class ComputersController {
|
||||
'id',
|
||||
computer.components.map((c) => c.id)
|
||||
)
|
||||
return inertia.render('computers/edit', {
|
||||
computer: asPageProp(computer.serialize()),
|
||||
availableComponents: asPageProp(availableComponents.map((c) => c.serialize())),
|
||||
states: asPageProp(states.map((s) => s.serialize())),
|
||||
})
|
||||
return inertia.render('computers/edit', { computer: computer.serialize(), availableComponents: availableComponents.map((c) => c.serialize()), states: states.map((s) => s.serialize()) })
|
||||
}
|
||||
|
||||
async update({ auth, params, request, response }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
async update({ params, request, response }: HttpContext) {
|
||||
const computerId = params.id
|
||||
const { pictures, componentsId, ...computerData } = await request.validateUsing(
|
||||
updateComputerValidator
|
||||
const { pictures, componentsId, ...computerData } = await updateComputerValidator.validate(
|
||||
request.all()
|
||||
)
|
||||
const computer = await Computer.query()
|
||||
.where('user_id', user.id)
|
||||
.andWhere('id', computerId)
|
||||
.firstOrFail()
|
||||
const computer = await Computer.findOrFail(computerId)
|
||||
computer.merge(computerData)
|
||||
await computer.save()
|
||||
await handleComponents(componentsId as number[], computer, user.id)
|
||||
await handleComponents(componentsId as number[], computer)
|
||||
await handlePictures(pictures as Image[], request, computer)
|
||||
return response.redirect(`/computers/${computer.id}`)
|
||||
return response.redirect(`${computer.id}`)
|
||||
}
|
||||
|
||||
async destroy({ auth, params, response }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
async destroy({ params, response }: HttpContext) {
|
||||
const computerId = params.id
|
||||
const computer = await Computer.query()
|
||||
.where('user_id', user.id)
|
||||
.andWhere('id', computerId)
|
||||
.firstOrFail()
|
||||
|
||||
const uploadsDir = `uploads/computer_${computer.id}`
|
||||
await computer.related('components').query().update({ computerId: null })
|
||||
if (existsSync(uploadsDir)) {
|
||||
rmSync(uploadsDir, { recursive: true, force: true })
|
||||
}
|
||||
const computer = await Computer.findOrFail(computerId)
|
||||
await computer.delete()
|
||||
return response.redirect('/computers')
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Exception } from '@adonisjs/core/exceptions'
|
||||
import type { HttpContext } from '@adonisjs/core/http'
|
||||
|
||||
/**
|
||||
* Thrown when a component selection is invalid, either because:
|
||||
* - the referenced component does not belong to the current user, or
|
||||
* - more than one component of the same "unique" type is being attached
|
||||
* to the same computer at once.
|
||||
*/
|
||||
export default class InvalidComponentSelectionException extends Exception {
|
||||
static status = 422
|
||||
static code = 'E_INVALID_COMPONENT_SELECTION'
|
||||
|
||||
handle(error: this, { response }: HttpContext) {
|
||||
return response.status(error.status).send({ errors: [{ message: error.message }] })
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { DateTime } from 'luxon'
|
||||
import { BaseModel, belongsTo, column, computed, hasMany } from '@adonisjs/lucid/orm'
|
||||
import type { BelongsTo, HasMany } from '@adonisjs/lucid/types/relations'
|
||||
import logger from '@adonisjs/core/services/logger'
|
||||
import ComputerState from '#models/computer_state'
|
||||
import ComputerPicture from '#models/computer_picture'
|
||||
import Component from '#models/component'
|
||||
@@ -53,10 +52,7 @@ export default class Computer extends BaseModel {
|
||||
@computed()
|
||||
get cost(): number {
|
||||
if (!this.$preloaded.components) {
|
||||
logger.warn(
|
||||
{ computerId: this.id },
|
||||
'Computer.cost accessed without preloading "components"; returning 0'
|
||||
)
|
||||
console.warn('Components not preloaded, cost may be incorrect')
|
||||
return 0
|
||||
}
|
||||
return this.components.reduce((total, component) => total + Number(component.price), 0)
|
||||
|
||||
@@ -1,53 +1,21 @@
|
||||
import Component from '#models/component'
|
||||
import Computer from '#models/computer'
|
||||
import InvalidComponentSelectionException from '#exceptions/invalid_component_selection_exception'
|
||||
|
||||
async function handleComponents(componentsId: number[], computer: Computer, userId: number) {
|
||||
async function handleComponents(componentsId: number[], computer: Computer) {
|
||||
const currentComponents = await computer.related('components').query()
|
||||
const currentComponentsIds = currentComponents.map((component) => component.id)
|
||||
const componentsToAdd = componentsId.filter((id) => !currentComponentsIds.includes(id))
|
||||
const componentsToRemove = currentComponentsIds.filter((id) => !componentsId.includes(id))
|
||||
|
||||
const componentsToAddRecords = await Promise.all(
|
||||
componentsToAdd.map((id: number) =>
|
||||
Component.query().where('userId', userId).andWhere('id', id).preload('type').firstOrFail()
|
||||
)
|
||||
)
|
||||
|
||||
// Ensure at most one component of each "unique" type ends up attached to
|
||||
// the computer once the additions/removals are applied.
|
||||
const remainingComponentIds = currentComponentsIds.filter(
|
||||
(id) => !componentsToRemove.includes(id)
|
||||
)
|
||||
const remainingComponents = remainingComponentIds.length
|
||||
? await Component.query().whereIn('id', remainingComponentIds).preload('type')
|
||||
: []
|
||||
const finalComponents = [...remainingComponents, ...componentsToAddRecords]
|
||||
|
||||
const uniqueTypeCounts = new Map<number, number>()
|
||||
for (const component of finalComponents) {
|
||||
if (!component.type.unique) continue
|
||||
const count = (uniqueTypeCounts.get(component.type.id) ?? 0) + 1
|
||||
uniqueTypeCounts.set(component.type.id, count)
|
||||
if (count > 1) {
|
||||
throw new InvalidComponentSelectionException(
|
||||
`Only one component of type "${component.type.name}" can be attached to a computer at a time.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
componentsToAddRecords.map(async (component) => {
|
||||
componentsToAdd.map(async (id: number) => {
|
||||
const component = await Component.findOrFail(id)
|
||||
component.computerId = computer.id
|
||||
await component.save()
|
||||
})
|
||||
)
|
||||
await Promise.all(
|
||||
componentsToRemove.map(async (id: number) => {
|
||||
const component = await Component.query()
|
||||
.where('userId', userId)
|
||||
.andWhere('id', id)
|
||||
.firstOrFail()
|
||||
const component = await Component.findOrFail(id)
|
||||
component.computerId = null
|
||||
await component.save()
|
||||
})
|
||||
|
||||
@@ -19,10 +19,7 @@ async function handlePictures(
|
||||
await Promise.all(
|
||||
pictures.map(async (picture: Image, index: number) => {
|
||||
if ('id' in picture) {
|
||||
const existingPicture = await ComputerPicture.query()
|
||||
.where('computerId', computer.id)
|
||||
.andWhere('id', picture.id)
|
||||
.firstOrFail()
|
||||
const existingPicture = await ComputerPicture.findOrFail(picture.id)
|
||||
existingPicture.order = picture.order
|
||||
await existingPicture.save()
|
||||
} else {
|
||||
@@ -47,10 +44,7 @@ async function handlePictures(
|
||||
|
||||
await Promise.all(
|
||||
imagesToRemove.map(async (id: number) => {
|
||||
const picture = await ComputerPicture.query()
|
||||
.where('computerId', computer.id)
|
||||
.andWhere('id', id)
|
||||
.firstOrFail()
|
||||
const picture = await ComputerPicture.findOrFail(id)
|
||||
const filePath = `uploads/computer_${computer.id}/${picture.link.split('/').pop()}`
|
||||
if (existsSync(filePath)) {
|
||||
unlinkSync(filePath)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import vine from '@vinejs/vine'
|
||||
|
||||
export const registerValidator = vine.compile(
|
||||
vine.object({
|
||||
name: vine.string().minLength(3).maxLength(64),
|
||||
email: vine
|
||||
.string()
|
||||
.email()
|
||||
.unique(async (query, field) => {
|
||||
const user = await query.from('users').where('email', field).first()
|
||||
return !user
|
||||
}),
|
||||
password: vine.string().minLength(8).maxLength(32),
|
||||
})
|
||||
)
|
||||
+1
-2
@@ -1,5 +1,4 @@
|
||||
import env from '#start/env'
|
||||
import app from '@adonisjs/core/services/app'
|
||||
import { defineConfig, stores } from '@adonisjs/session'
|
||||
|
||||
const sessionConfig = defineConfig({
|
||||
@@ -43,7 +42,7 @@ const sessionConfig = defineConfig({
|
||||
/**
|
||||
* Send cookies only over HTTPS in production.
|
||||
*/
|
||||
secure: app.inProduction,
|
||||
secure: false,
|
||||
|
||||
/**
|
||||
* Cross-site policy for cookie sending.
|
||||
|
||||
+2
-9
@@ -9,19 +9,12 @@ const shieldConfig = defineConfig({
|
||||
/**
|
||||
* Enable the Content-Security-Policy header.
|
||||
*/
|
||||
enabled: true,
|
||||
enabled: false,
|
||||
|
||||
/**
|
||||
* Per-resource CSP directives.
|
||||
*/
|
||||
directives: {
|
||||
defaultSrc: [`'self'`, '@viteDevUrl'],
|
||||
connectSrc: [`'self'`, '@viteHmrUrl'],
|
||||
scriptSrc: [`'self'`, '@viteDevUrl'],
|
||||
styleSrc: [`'self'`, '@viteDevUrl', `'unsafe-inline'`],
|
||||
imgSrc: [`'self'`, 'data:'],
|
||||
fontSrc: [`'self'`, 'data:'],
|
||||
},
|
||||
directives: {},
|
||||
|
||||
/**
|
||||
* Report violations without blocking resources.
|
||||
|
||||
@@ -7,6 +7,134 @@
|
||||
import { BaseModel, column } from '@adonisjs/lucid/orm'
|
||||
import { DateTime } from 'luxon'
|
||||
|
||||
export class AccessListSchema extends BaseModel {
|
||||
static $columns = ['createdOn', 'id', 'isDeleted', 'meta', 'modifiedOn', 'name', 'ownerUserId', 'passAuth', 'satisfyAny'] as const
|
||||
$columns = AccessListSchema.$columns
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare name: string
|
||||
@column()
|
||||
declare ownerUserId: number
|
||||
@column()
|
||||
declare passAuth: number
|
||||
@column()
|
||||
declare satisfyAny: number
|
||||
}
|
||||
|
||||
export class AccessListAuthSchema extends BaseModel {
|
||||
static $columns = ['accessListId', 'createdOn', 'id', 'meta', 'modifiedOn', 'password', 'username'] as const
|
||||
$columns = AccessListAuthSchema.$columns
|
||||
@column()
|
||||
declare accessListId: number
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column({ serializeAs: null })
|
||||
declare password: string
|
||||
@column()
|
||||
declare username: string
|
||||
}
|
||||
|
||||
export class AccessListClientSchema extends BaseModel {
|
||||
static $columns = ['accessListId', 'address', 'createdOn', 'directive', 'id', 'meta', 'modifiedOn'] as const
|
||||
$columns = AccessListClientSchema.$columns
|
||||
@column()
|
||||
declare accessListId: number
|
||||
@column()
|
||||
declare address: string
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare directive: string
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
}
|
||||
|
||||
export class AuditLogSchema extends BaseModel {
|
||||
static $columns = ['action', 'createdOn', 'id', 'meta', 'modifiedOn', 'objectId', 'objectType', 'userId'] as const
|
||||
$columns = AuditLogSchema.$columns
|
||||
@column()
|
||||
declare action: string
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare objectId: number
|
||||
@column()
|
||||
declare objectType: string
|
||||
@column()
|
||||
declare userId: number
|
||||
}
|
||||
|
||||
export class AuthSchema extends BaseModel {
|
||||
static $columns = ['createdOn', 'id', 'isDeleted', 'meta', 'modifiedOn', 'secret', 'type', 'userId'] as const
|
||||
$columns = AuthSchema.$columns
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare secret: string
|
||||
@column()
|
||||
declare type: string
|
||||
@column()
|
||||
declare userId: number
|
||||
}
|
||||
|
||||
export class CertificateSchema extends BaseModel {
|
||||
static $columns = ['createdOn', 'domainNames', 'expiresOn', 'id', 'isDeleted', 'meta', 'modifiedOn', 'niceName', 'ownerUserId', 'provider'] as const
|
||||
$columns = CertificateSchema.$columns
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare domainNames: any
|
||||
@column.dateTime()
|
||||
declare expiresOn: DateTime
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare niceName: string
|
||||
@column()
|
||||
declare ownerUserId: number
|
||||
@column()
|
||||
declare provider: string
|
||||
}
|
||||
|
||||
export class ComponentTypeSchema extends BaseModel {
|
||||
static $columns = ['id', 'name', 'unique'] as const
|
||||
$columns = ComponentTypeSchema.$columns
|
||||
@@ -92,6 +220,253 @@ export class ComputerSchema extends BaseModel {
|
||||
declare userId: number | null
|
||||
}
|
||||
|
||||
export class DeadHostSchema extends BaseModel {
|
||||
static $columns = ['advancedConfig', 'certificateId', 'createdOn', 'domainNames', 'enabled', 'hstsEnabled', 'hstsSubdomains', 'http2Support', 'id', 'isDeleted', 'meta', 'modifiedOn', 'ownerUserId', 'sslForced'] as const
|
||||
$columns = DeadHostSchema.$columns
|
||||
@column()
|
||||
declare advancedConfig: string
|
||||
@column()
|
||||
declare certificateId: number
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare domainNames: any
|
||||
@column()
|
||||
declare enabled: number
|
||||
@column()
|
||||
declare hstsEnabled: number
|
||||
@column()
|
||||
declare hstsSubdomains: number
|
||||
@column()
|
||||
declare http2Support: number
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare ownerUserId: number
|
||||
@column()
|
||||
declare sslForced: number
|
||||
}
|
||||
|
||||
export class MigrationSchema extends BaseModel {
|
||||
static $columns = ['batch', 'id', 'migrationTime', 'name'] as const
|
||||
$columns = MigrationSchema.$columns
|
||||
@column()
|
||||
declare batch: number | null
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column.dateTime()
|
||||
declare migrationTime: DateTime | null
|
||||
@column()
|
||||
declare name: string | null
|
||||
}
|
||||
|
||||
export class MigrationsLockSchema extends BaseModel {
|
||||
static $columns = ['index', 'isLocked'] as const
|
||||
$columns = MigrationsLockSchema.$columns
|
||||
@column({ isPrimary: true })
|
||||
declare index: number
|
||||
@column()
|
||||
declare isLocked: number | null
|
||||
}
|
||||
|
||||
export class ProxyHostSchema extends BaseModel {
|
||||
static $columns = ['accessListId', 'advancedConfig', 'allowWebsocketUpgrade', 'blockExploits', 'cachingEnabled', 'certificateId', 'createdOn', 'domainNames', 'enabled', 'forwardHost', 'forwardPort', 'forwardScheme', 'hstsEnabled', 'hstsSubdomains', 'http2Support', 'id', 'isDeleted', 'locations', 'meta', 'modifiedOn', 'ownerUserId', 'sslForced', 'trustForwardedProto'] as const
|
||||
$columns = ProxyHostSchema.$columns
|
||||
@column()
|
||||
declare accessListId: number
|
||||
@column()
|
||||
declare advancedConfig: string
|
||||
@column()
|
||||
declare allowWebsocketUpgrade: number
|
||||
@column()
|
||||
declare blockExploits: number
|
||||
@column()
|
||||
declare cachingEnabled: number
|
||||
@column()
|
||||
declare certificateId: number
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare domainNames: any
|
||||
@column()
|
||||
declare enabled: number
|
||||
@column()
|
||||
declare forwardHost: string
|
||||
@column()
|
||||
declare forwardPort: number
|
||||
@column()
|
||||
declare forwardScheme: string
|
||||
@column()
|
||||
declare hstsEnabled: number
|
||||
@column()
|
||||
declare hstsSubdomains: number
|
||||
@column()
|
||||
declare http2Support: number
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare locations: any | null
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare ownerUserId: number
|
||||
@column()
|
||||
declare sslForced: number
|
||||
@column()
|
||||
declare trustForwardedProto: boolean
|
||||
}
|
||||
|
||||
export class RedirectionHostSchema extends BaseModel {
|
||||
static $columns = ['advancedConfig', 'blockExploits', 'certificateId', 'createdOn', 'domainNames', 'enabled', 'forwardDomainName', 'forwardHttpCode', 'forwardScheme', 'hstsEnabled', 'hstsSubdomains', 'http2Support', 'id', 'isDeleted', 'meta', 'modifiedOn', 'ownerUserId', 'preservePath', 'sslForced'] as const
|
||||
$columns = RedirectionHostSchema.$columns
|
||||
@column()
|
||||
declare advancedConfig: string
|
||||
@column()
|
||||
declare blockExploits: number
|
||||
@column()
|
||||
declare certificateId: number
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare domainNames: any
|
||||
@column()
|
||||
declare enabled: number
|
||||
@column()
|
||||
declare forwardDomainName: string
|
||||
@column()
|
||||
declare forwardHttpCode: number
|
||||
@column()
|
||||
declare forwardScheme: string
|
||||
@column()
|
||||
declare hstsEnabled: number
|
||||
@column()
|
||||
declare hstsSubdomains: number
|
||||
@column()
|
||||
declare http2Support: number
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare ownerUserId: number
|
||||
@column()
|
||||
declare preservePath: number
|
||||
@column()
|
||||
declare sslForced: number
|
||||
}
|
||||
|
||||
export class SettingSchema extends BaseModel {
|
||||
static $columns = ['description', 'id', 'meta', 'name', 'value'] as const
|
||||
$columns = SettingSchema.$columns
|
||||
@column()
|
||||
declare description: string
|
||||
@column({ isPrimary: true })
|
||||
declare id: string
|
||||
@column()
|
||||
declare meta: any
|
||||
@column()
|
||||
declare name: string
|
||||
@column()
|
||||
declare value: string
|
||||
}
|
||||
|
||||
export class StreamSchema extends BaseModel {
|
||||
static $columns = ['certificateId', 'createdOn', 'enabled', 'forwardingHost', 'forwardingPort', 'id', 'incomingPort', 'isDeleted', 'meta', 'modifiedOn', 'ownerUserId', 'tcpForwarding', 'udpForwarding'] as const
|
||||
$columns = StreamSchema.$columns
|
||||
@column()
|
||||
declare certificateId: number
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare enabled: number
|
||||
@column()
|
||||
declare forwardingHost: string
|
||||
@column()
|
||||
declare forwardingPort: number
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare incomingPort: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare meta: any
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare ownerUserId: number
|
||||
@column()
|
||||
declare tcpForwarding: number
|
||||
@column()
|
||||
declare udpForwarding: number
|
||||
}
|
||||
|
||||
export class NpmUserSchema extends BaseModel {
|
||||
static $columns = ['avatar', 'createdOn', 'email', 'id', 'isDeleted', 'isDisabled', 'modifiedOn', 'name', 'nickname', 'roles'] as const
|
||||
$columns = NpmUserSchema.$columns
|
||||
@column()
|
||||
declare avatar: string
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare email: string
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column()
|
||||
declare isDeleted: number
|
||||
@column()
|
||||
declare isDisabled: number
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare name: string
|
||||
@column()
|
||||
declare nickname: string
|
||||
@column()
|
||||
declare roles: any
|
||||
}
|
||||
|
||||
export class UserPermissionSchema extends BaseModel {
|
||||
static $columns = ['accessLists', 'certificates', 'createdOn', 'deadHosts', 'id', 'modifiedOn', 'proxyHosts', 'redirectionHosts', 'streams', 'userId', 'visibility'] as const
|
||||
$columns = UserPermissionSchema.$columns
|
||||
@column()
|
||||
declare accessLists: string
|
||||
@column()
|
||||
declare certificates: string
|
||||
@column.dateTime()
|
||||
declare createdOn: DateTime
|
||||
@column()
|
||||
declare deadHosts: string
|
||||
@column({ isPrimary: true })
|
||||
declare id: number
|
||||
@column.dateTime()
|
||||
declare modifiedOn: DateTime
|
||||
@column()
|
||||
declare proxyHosts: string
|
||||
@column()
|
||||
declare redirectionHosts: string
|
||||
@column()
|
||||
declare streams: string
|
||||
@column()
|
||||
declare userId: number
|
||||
@column()
|
||||
declare visibility: string
|
||||
}
|
||||
|
||||
export class UserSchema extends BaseModel {
|
||||
static $columns = ['createdAt', 'email', 'id', 'name', 'password', 'updatedAt'] as const
|
||||
$columns = UserSchema.$columns
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
// Créer une référence pour isAdminActive
|
||||
// Cr├®er une r├®f├®rence pour isAdminActive
|
||||
const isAdminActive = ref(JSON.parse(localStorage.getItem('isAdminActive') || 'false'))
|
||||
|
||||
// Surveiller les changements de isAdminActive et mettre à jour localStorage
|
||||
// Surveiller les changements de isAdminActive et mettre à jour localStorage
|
||||
watch(isAdminActive, (newValue) => {
|
||||
localStorage.setItem('isAdminActive', JSON.stringify(newValue))
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createApp, DirectiveBinding, h, ObjectDirective } from 'vue'
|
||||
import DeleteConfirmationModal from '~/pages/widgets/DeleteConfirmationModal.vue'
|
||||
|
||||
// Interface pour étendre HTMLElement avec _handleClick
|
||||
// Interface pour ├®tendre HTMLElement avec _handleClick
|
||||
interface HTMLElementWithHandleClick extends HTMLElement {
|
||||
_handleClick?: (event: Event) => void
|
||||
}
|
||||
@@ -9,8 +9,8 @@ interface HTMLElementWithHandleClick extends HTMLElement {
|
||||
const deleteConfirmDirective: ObjectDirective<HTMLElementWithHandleClick> = {
|
||||
mounted(el: HTMLElementWithHandleClick, binding: DirectiveBinding) {
|
||||
const handleClick = (event: Event) => {
|
||||
event.stopPropagation() // Empêcher la propagation de l'événement
|
||||
event.preventDefault() // Empêcher l'action par défaut
|
||||
event.stopPropagation() // Emp├¬cher la propagation de l'├®v├®nement
|
||||
event.preventDefault() // Emp├¬cher l'action par d├®faut
|
||||
|
||||
const modalApp = createApp({
|
||||
data() {
|
||||
@@ -20,7 +20,7 @@ const deleteConfirmDirective: ObjectDirective<HTMLElementWithHandleClick> = {
|
||||
confirm() {
|
||||
this.show = false
|
||||
document.body.removeChild(modalContainer)
|
||||
binding.value() // Exécuter la fonction de suppression
|
||||
binding.value() // Ex├®cuter la fonction de suppression
|
||||
},
|
||||
cancel() {
|
||||
this.show = false
|
||||
@@ -42,7 +42,7 @@ const deleteConfirmDirective: ObjectDirective<HTMLElementWithHandleClick> = {
|
||||
}
|
||||
|
||||
el.addEventListener('click', handleClick)
|
||||
el._handleClick = handleClick // Stocker la référence pour la suppression ultérieure
|
||||
el._handleClick = handleClick // Stocker la r├®f├®rence pour la suppression ult├®rieure
|
||||
},
|
||||
unmounted(el: HTMLElementWithHandleClick) {
|
||||
if (el._handleClick) {
|
||||
|
||||
@@ -6,7 +6,7 @@ const formatPrice = (value: string): string => {
|
||||
return Number.isNaN(numberValue) ? '' : numberValue.toFixed(2).replace('.', ',')
|
||||
}
|
||||
|
||||
// Interface pour étendre HTMLInputElement avec _handleBlur
|
||||
// Interface pour ├®tendre HTMLInputElement avec _handleBlur
|
||||
interface HTMLInputElementWithHandleBlur extends HTMLInputElement {
|
||||
_handleBlur?: () => void
|
||||
}
|
||||
@@ -15,10 +15,10 @@ const priceDirective: ObjectDirective<HTMLInputElementWithHandleBlur> = {
|
||||
mounted(el: HTMLInputElementWithHandleBlur) {
|
||||
const handleBlur = () => {
|
||||
el.value = formatPrice(el.value)
|
||||
el.dispatchEvent(new Event('input')) // Pour mettre à jour le v-model
|
||||
el.dispatchEvent(new Event('input')) // Pour mettre à jour le v-model
|
||||
}
|
||||
el.addEventListener('blur', handleBlur)
|
||||
el._handleBlur = handleBlur // Stocker la référence pour la suppression ultérieure
|
||||
el._handleBlur = handleBlur // Stocker la r├®f├®rence pour la suppression ult├®rieure
|
||||
},
|
||||
unmounted(el: HTMLInputElementWithHandleBlur) {
|
||||
if (el._handleBlur) {
|
||||
|
||||
@@ -33,7 +33,7 @@ const validationErrorDirective: ObjectDirective<HTMLElement, string | null> = {
|
||||
const vnode = createVNode(ValidationError, { message: errorMessage })
|
||||
render(vnode, container)
|
||||
|
||||
// Force reflow pour déclencher la transition
|
||||
// Force reflow pour d├®clencher la transition
|
||||
void container.offsetWidth
|
||||
container.classList.remove('w-0', 'opacity-0')
|
||||
container.classList.add('w-full', 'opacity-100')
|
||||
@@ -77,7 +77,7 @@ const validationErrorDirective: ObjectDirective<HTMLElement, string | null> = {
|
||||
const vnode = createVNode(ValidationError, { message: errorMessage })
|
||||
render(vnode, newContainer)
|
||||
|
||||
// Force reflow pour déclencher la transition
|
||||
// Force reflow pour d├®clencher la transition
|
||||
void newContainer.offsetWidth
|
||||
newContainer.classList.remove('w-0', 'opacity-0')
|
||||
newContainer.classList.add('w-100', 'opacity-100')
|
||||
@@ -92,7 +92,7 @@ const validationErrorDirective: ObjectDirective<HTMLElement, string | null> = {
|
||||
container.classList.remove('transition-all', 'duration-2500', 'ease-in-out') // Supprimez les classes de transition pour la disparition
|
||||
container.classList.add('w-0', 'opacity-0')
|
||||
|
||||
// Supprimez le conteneur immédiatement sans délai
|
||||
// Supprimez le conteneur imm├®diatement sans d├®lai
|
||||
render(null, container)
|
||||
container.remove()
|
||||
;(el as any)._validationErrorContainer = null
|
||||
|
||||
@@ -3,9 +3,8 @@ import { reactive } from 'vue'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { useForm } from '@inertiajs/vue3'
|
||||
import CustomSelect from '~/pages/widgets/CustomSelect.vue'
|
||||
import type { ComponentType } from '~/pages/types/UITypes'
|
||||
|
||||
defineProps<{ types: ComponentType[]; errors?: Record<string, string> }>()
|
||||
defineProps<{ types: any[]; errors?: Record<string, string> }>()
|
||||
const form = reactive({
|
||||
name: '',
|
||||
price: 0,
|
||||
|
||||
@@ -3,14 +3,14 @@ import { reactive } from 'vue'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
import CustomSelect from '~/pages/widgets/CustomSelect.vue'
|
||||
import type { Component, ComponentType } from '~/pages/types/UITypes'
|
||||
|
||||
const { props } = usePage<{
|
||||
component: Component
|
||||
types: ComponentType[]
|
||||
component: any
|
||||
types: any[]
|
||||
origin: string
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
const { component, types } = props
|
||||
const { component, types, origin } = props
|
||||
|
||||
const form = reactive({
|
||||
id: component.id,
|
||||
@@ -18,6 +18,7 @@ const form = reactive({
|
||||
price: component.price,
|
||||
typeId: component.type.id,
|
||||
purchaseDate: component.purchaseDate,
|
||||
origin: origin,
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import type { Component } from '~/pages/types/UITypes'
|
||||
|
||||
const props = defineProps<{ component: Component }>()
|
||||
const props = defineProps<{ component: any }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { computed, reactive } from 'vue'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { useForm, usePage } from '@inertiajs/vue3'
|
||||
import type { Component, ComputerState } from '~/pages/types/UITypes'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
|
||||
const { props } = usePage<{
|
||||
components: Component[]
|
||||
states: ComputerState[]
|
||||
components: any[]
|
||||
states: any[]
|
||||
errors: Record<string, string>
|
||||
}>()
|
||||
const { components, states } = props
|
||||
@@ -27,7 +26,7 @@ const componentTypeOrder = [
|
||||
]
|
||||
|
||||
const componentsByType = computed(() => {
|
||||
const groups = new Map<string, Component[]>()
|
||||
const groups = new Map<string, any[]>()
|
||||
components.forEach((component) => {
|
||||
if (!groups.has(component.type.name)) {
|
||||
groups.set(component.type.name, [])
|
||||
@@ -39,35 +38,21 @@ const componentsByType = computed(() => {
|
||||
.sort((a, b) => componentTypeOrder.indexOf(a.type) - componentTypeOrder.indexOf(b.type))
|
||||
})
|
||||
|
||||
const form = useForm<{
|
||||
title: string
|
||||
sellPrice: number
|
||||
gpuScore: number
|
||||
cpuScore: number
|
||||
stateId: number
|
||||
globalScore: number
|
||||
componentsId: number[]
|
||||
pictures: Record<string, never>[]
|
||||
}>({
|
||||
const form = reactive({
|
||||
title: '',
|
||||
sellPrice: 0,
|
||||
gpuScore: 0,
|
||||
cpuScore: 0,
|
||||
stateId: 1,
|
||||
globalScore: 0,
|
||||
componentsId: [],
|
||||
pictures: [],
|
||||
componentsId: [] as number[],
|
||||
})
|
||||
|
||||
function submitForm() {
|
||||
form.post('/computers')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="max-w-4xl mx-auto p-8 bg-white shadow-lg rounded-lg">
|
||||
<h1 class="text-2xl font-semibold mb-8 text-gray-800">Create New Computer</h1>
|
||||
<form class="space-y-6" @submit.prevent="submitForm">
|
||||
<form class="space-y-6">
|
||||
<div class="mt-2">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="title">Title</label>
|
||||
<input
|
||||
@@ -164,21 +149,16 @@ function submitForm() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-4">
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="form.processing"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700 transition disabled:opacity-50"
|
||||
>
|
||||
{{ form.processing ? 'Creating…' : 'Create' }}
|
||||
</button>
|
||||
<Link
|
||||
href="/computers"
|
||||
class="px-4 py-2 bg-gray-300 text-gray-800 rounded hover:bg-gray-400 transition"
|
||||
>
|
||||
Cancel
|
||||
</Link>
|
||||
</div>
|
||||
<Link
|
||||
href="/computers"
|
||||
type="button"
|
||||
as="button"
|
||||
method="post"
|
||||
:data="form"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition"
|
||||
>
|
||||
Create
|
||||
</Link>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -2,12 +2,11 @@
|
||||
import { reactive } from 'vue'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { router, usePage } from '@inertiajs/vue3'
|
||||
import type { Component, Computer, ComputerState } from '~/pages/types/UITypes'
|
||||
|
||||
const { props } = usePage<{
|
||||
computer: Computer
|
||||
availableComponents: Component[]
|
||||
states: ComputerState[]
|
||||
computer: any
|
||||
availableComponents: any[]
|
||||
states: any[]
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
const { computer, states } = props
|
||||
@@ -20,7 +19,7 @@ const form = reactive({
|
||||
cpuScore: computer.cpuScore,
|
||||
globalScore: computer.globalScore,
|
||||
stateId: computer.state.id,
|
||||
componentsId: computer.components.map((c) => c.id),
|
||||
componentsId: computer.components.map((c: any) => c.id),
|
||||
})
|
||||
|
||||
function deleteComputer(id: number) {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import type { Computer } from '~/pages/types/UITypes'
|
||||
|
||||
defineProps<{ computers: Computer[] }>()
|
||||
defineProps<{ computers: any[] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -45,3 +44,85 @@ defineProps<{ computers: Computer[] }>()
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.computers-container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.computers-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.computer-card {
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 0.5rem;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.card-image {
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
background-color: #f3f4f6;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.card-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.no-image {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.card-content {
|
||||
padding: 1rem;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.card-content h3 {
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
.card-content p {
|
||||
color: #6b7280;
|
||||
margin: 0 0 1rem 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.card-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 4rem 2rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import type { Computer } from '~/pages/types/UITypes'
|
||||
|
||||
const { computer } = defineProps<{ computer: Computer }>()
|
||||
const { computer } = defineProps<{ computer: any }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -16,9 +16,33 @@ const user = computed(() => {
|
||||
|
||||
<template>
|
||||
<header
|
||||
class="flex justify-end items-center px-10 h-16 bg-white ml-64 w-[calc(100%-16rem)] fixed top-0 right-0 z-40 border-b border-outline-variant shadow-sm"
|
||||
class="flex justify-between items-center px-10 h-16 bg-white ml-64 w-[calc(100%-16rem)] fixed top-0 right-0 z-40 border-b border-outline-variant shadow-sm"
|
||||
>
|
||||
<div
|
||||
class="flex items-center gap-4 bg-surface-container-low px-4 py-2 rounded-lg border border-outline-variant w-96 focus-within:ring-2 focus-within:ring-primary transition-all"
|
||||
>
|
||||
<span class="material-symbols-outlined text-on-surface-variant">search</span>
|
||||
<input
|
||||
class="bg-transparent border-none focus:ring-0 focus:outline-none text-body-sm font-body-sm w-full p-0"
|
||||
placeholder="Search builds..."
|
||||
type="text"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-6">
|
||||
<button
|
||||
class="text-on-surface-variant hover:bg-surface-container-low p-2 rounded-full transition-all"
|
||||
>
|
||||
<span class="material-symbols-outlined">notifications</span>
|
||||
</button>
|
||||
<button
|
||||
class="text-on-surface-variant hover:bg-surface-container-low p-2 rounded-full transition-all"
|
||||
>
|
||||
<span class="material-symbols-outlined">settings</span>
|
||||
</button>
|
||||
|
||||
<div class="h-8 w-px bg-outline-variant mx-2"></div>
|
||||
|
||||
<div
|
||||
class="relative flex items-center gap-3 cursor-pointer group"
|
||||
@click="dropdownOpen = !dropdownOpen"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref } from 'vue'
|
||||
import { ref, useAttrs } from 'vue'
|
||||
import { useSidebar } from '~/composables/useSidebar'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { siteIcon } from '~/assets/icons'
|
||||
@@ -9,6 +9,8 @@ const activeClass = ref('bg-gray-600/25 text-gray-100 border-gray-100')
|
||||
const inactiveClass = ref(
|
||||
'border-gray-900 text-gray-500 hover:bg-gray-600/25 hover:text-gray-100'
|
||||
)
|
||||
const route = useAttrs()
|
||||
console.log(route)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
export type ComponentType = {
|
||||
interface ComponentType {
|
||||
id: number
|
||||
name: string
|
||||
unique: boolean
|
||||
}
|
||||
|
||||
export type ComputerState = {
|
||||
interface ComputerState {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
@@ -26,7 +26,10 @@ export type Component = {
|
||||
id: number
|
||||
name: string
|
||||
price: string
|
||||
componentTypeId: number
|
||||
computerId: number | null
|
||||
userId: number
|
||||
componentStateId: number
|
||||
purchaseDate: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
|
||||
@@ -30,7 +30,7 @@ const componentTypeOrder = [
|
||||
'Other',
|
||||
]
|
||||
|
||||
// Fusionner les composants disponibles et initialement sélectionnés
|
||||
// Fusionner les composants disponibles et initialement s├®lectionn├®s
|
||||
const allComponents = computed(() => {
|
||||
const mergedComponents = [...props.availableComponents]
|
||||
if (props.initialSelectedComponents) {
|
||||
@@ -134,7 +134,7 @@ function updateComponents(event: Event, type: string) {
|
||||
</select>
|
||||
</div>
|
||||
<div v-else>
|
||||
<!-- Utilisation de cases à cocher pour les composants non uniques avec grille responsive -->
|
||||
<!-- Utilisation de cases à cocher pour les composants non uniques avec grille responsive -->
|
||||
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
<div v-for="component in components" :key="component.id" class="flex items-center mt-1">
|
||||
<input
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import TableComponent from '~/pages/widgets/TableComponent.vue'
|
||||
import FilterDropdown from '~/pages/widgets/FilterDropdown.vue'
|
||||
import type Component from '#models/component'
|
||||
import type ComponentType from '#models/component_type'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
@@ -9,6 +8,19 @@ import { usePage } from '@inertiajs/vue3'
|
||||
const { props } = usePage<{ components: Component[] }>()
|
||||
const { components } = props
|
||||
|
||||
const usageDropdownOpen = ref(false)
|
||||
const typeDropdownOpen = ref(false)
|
||||
|
||||
function toggleDropdown(dropdown: any) {
|
||||
if (dropdown === 'usage') {
|
||||
usageDropdownOpen.value = !usageDropdownOpen.value
|
||||
typeDropdownOpen.value = false
|
||||
} else if (dropdown === 'type') {
|
||||
typeDropdownOpen.value = !typeDropdownOpen.value
|
||||
usageDropdownOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const componentTypes = computed(() => {
|
||||
const types = new Map<number, ComponentType>()
|
||||
components.forEach((component) => {
|
||||
@@ -19,51 +31,152 @@ const componentTypes = computed(() => {
|
||||
return Array.from(types.values())
|
||||
})
|
||||
|
||||
const typeOptions = computed(() =>
|
||||
componentTypes.value.map((type) => ({ id: type.id, label: type.name }))
|
||||
)
|
||||
// D├®finir le type de l'objet filters
|
||||
interface Filters {
|
||||
showUsed: boolean
|
||||
showUnused: boolean
|
||||
types: { [key: number]: boolean }
|
||||
}
|
||||
|
||||
const usageFilters = ref<Record<string, boolean>>({
|
||||
unused: true,
|
||||
used: false,
|
||||
})
|
||||
|
||||
const typeFilters = ref<Record<number, boolean>>(
|
||||
componentTypes.value.reduce(
|
||||
const filters = reactive<Filters>({
|
||||
showUsed: false,
|
||||
showUnused: true,
|
||||
types: componentTypes.value.reduce(
|
||||
(acc, type) => {
|
||||
acc[type.id] = true
|
||||
return acc
|
||||
},
|
||||
{} as Record<number, boolean>
|
||||
)
|
||||
)
|
||||
{} as { [key: number]: boolean }
|
||||
),
|
||||
})
|
||||
|
||||
const filteredComponents = computed(() => {
|
||||
return components.filter((component) => {
|
||||
const isUsed = usageFilters.value.used && component.computerId !== null
|
||||
const isUnused = usageFilters.value.unused && component.computerId === null
|
||||
const isTypeSelected = typeFilters.value[component.type.id]
|
||||
const isUsed = filters.showUsed && component.computerId !== null
|
||||
const isUnused = filters.showUnused && component.computerId === null
|
||||
const isTypeSelected = filters.types[component.type.id]
|
||||
return (isUsed || isUnused) && isTypeSelected
|
||||
})
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<div>
|
||||
<!-- Dropdown pour les filtres -->
|
||||
<div class="relative">
|
||||
<h4 class="text-xl underline">Filters</h4>
|
||||
<div class="flex gap-2">
|
||||
<FilterDropdown
|
||||
v-model="usageFilters"
|
||||
label="Usage"
|
||||
:options="[
|
||||
{ id: 'unused', label: 'Unused' },
|
||||
{ id: 'used', label: 'Used' },
|
||||
]"
|
||||
/>
|
||||
<FilterDropdown v-model="typeFilters" label="Types" :options="typeOptions" />
|
||||
<!-- Usage Dropdown -->
|
||||
<div id="usage-selector" class="relative" style="width: fit-content">
|
||||
<button
|
||||
@click="toggleDropdown('usage')"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition text-center inline-flex items-center"
|
||||
type="button"
|
||||
>
|
||||
Usage
|
||||
<svg
|
||||
class="w-4 h-4 ml-2"
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Dropdown menu -->
|
||||
<div
|
||||
v-show="usageDropdownOpen"
|
||||
class="absolute right-0 z-20 py-2 mt-2 bg-white rounded-md shadow-xl"
|
||||
>
|
||||
<ul class="space-y-2 text-sm px-4 py-2">
|
||||
<li class="flex items-center">
|
||||
<input
|
||||
id="unused"
|
||||
type="checkbox"
|
||||
v-model="filters.showUnused"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label
|
||||
for="unused"
|
||||
class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
Unused
|
||||
</label>
|
||||
</li>
|
||||
<li class="flex items-center">
|
||||
<input
|
||||
id="used"
|
||||
type="checkbox"
|
||||
v-model="filters.showUsed"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label for="used" class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
Used
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Type Dropdown -->
|
||||
<div id="type-selector" class="relative" style="width: fit-content">
|
||||
<button
|
||||
@click="toggleDropdown('type')"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition text-center inline-flex items-center"
|
||||
type="button"
|
||||
>
|
||||
Types
|
||||
<svg
|
||||
class="w-4 h-4 ml-2"
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Dropdown menu -->
|
||||
<div
|
||||
v-show="typeDropdownOpen"
|
||||
class="absolute right-0 z-20 py-2 mt-2 bg-white rounded-md shadow-xl"
|
||||
>
|
||||
<ul class="space-y-2 text-sm px-4 py-2">
|
||||
<li class="flex items-center" v-for="type in componentTypes" :key="type.id">
|
||||
<input
|
||||
:id="`type-${type.id}`"
|
||||
type="checkbox"
|
||||
v-model="filters.types[type.id]"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label
|
||||
:for="`type-${type.id}`"
|
||||
class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
{{ type.name }}
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tableau des composants filtr├®s -->
|
||||
<TableComponent :components="filteredComponents" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -46,7 +46,7 @@ const componentTypeOrder = [
|
||||
'Other',
|
||||
]
|
||||
|
||||
// Trier les composants selon l'ordre spécifié
|
||||
// Trier les composants selon l'ordre sp├®cifi├®
|
||||
const sortedComponents = computed(() => {
|
||||
return components.slice().sort((a, b) => {
|
||||
return componentTypeOrder.indexOf(a.type.name) - componentTypeOrder.indexOf(b.type.name)
|
||||
@@ -67,7 +67,7 @@ function getIconPath(typeName: string): string {
|
||||
'WiFi-Card': wiFiCard,
|
||||
'Case': pcCase,
|
||||
}
|
||||
return typeToIconMap[typeName] || defaultIcon // Utilisez une icône par défaut si nécessaire
|
||||
return typeToIconMap[typeName] || defaultIcon // Utilisez une ic├┤ne par d├®faut si n├®cessaire
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -106,7 +106,7 @@ function getIconPath(typeName: string): string {
|
||||
</td>
|
||||
|
||||
<td v-if="isAdminActive" class="px-4 py-2 border-b border-gray-400 text-right">
|
||||
€{{ component.price }}
|
||||
Ôé¼{{ component.price }}
|
||||
</td>
|
||||
<td class="px-4 py-2 border-b border-gray-400 flex justify-center items-center">
|
||||
<Link
|
||||
@@ -125,7 +125,7 @@ function getIconPath(typeName: string): string {
|
||||
<tr class="bg-gray-800 text-white">
|
||||
<td class="px-4 py-2 border-b border-gray-400 whitespace-nowrap" colspan="3">Total</td>
|
||||
<td class="px-4 py-2 border-b border-gray-400 whitespace-nowrap text-right">
|
||||
€{{ cost.toFixed(2) }}
|
||||
Ôé¼{{ cost.toFixed(2) }}
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
|
||||
@@ -3,45 +3,106 @@ import { noImagePlaceholder } from '~/assets/images'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
import Computer from '#models/computer'
|
||||
import ComputerCard from '~/pages/widgets/ComputerCard.vue'
|
||||
import FilterDropdown from '~/pages/widgets/FilterDropdown.vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
|
||||
const { computers } = usePage<{ computers: Computer[] }>().props
|
||||
const stateDropdownOpen = ref(false)
|
||||
|
||||
const filters = ref<Record<string, boolean>>({
|
||||
function toggleDropdown() {
|
||||
stateDropdownOpen.value = !stateDropdownOpen.value
|
||||
}
|
||||
|
||||
const filters = reactive({
|
||||
onGoing: true,
|
||||
finished: true,
|
||||
sold: false,
|
||||
})
|
||||
|
||||
const stateToFilterKey: Record<string, string> = {
|
||||
ON_GOING: 'onGoing',
|
||||
FINISHED: 'finished',
|
||||
SOLD: 'sold',
|
||||
}
|
||||
|
||||
const filteredComputers = computed(() => {
|
||||
return computers.filter((computer) => {
|
||||
const key = stateToFilterKey[computer.state.name]
|
||||
return key ? filters.value[key] : false
|
||||
const isOnGoing = filters.onGoing && computer.state.name == 'ON_GOING'
|
||||
const isFinished = filters.finished && computer.state.name == 'FINISHED'
|
||||
const isSold = filters.sold && computer.state.name == 'SOLD'
|
||||
return isOnGoing || isFinished || isSold
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<!-- Dropdown pour les filtres -->
|
||||
<div class="relative">
|
||||
<h4 class="text-xl underline">Filters</h4>
|
||||
<div class="flex gap-2">
|
||||
<FilterDropdown
|
||||
v-model="filters"
|
||||
label="Usage"
|
||||
:options="[
|
||||
{ id: 'onGoing', label: 'On Going' },
|
||||
{ id: 'finished', label: 'Finished' },
|
||||
{ id: 'sold', label: 'Sold' },
|
||||
]"
|
||||
/>
|
||||
<!-- Usage Dropdown -->
|
||||
<div id="usage-selector" class="relative" style="width: fit-content">
|
||||
<button
|
||||
@click="toggleDropdown()"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition text-center inline-flex items-center"
|
||||
type="button"
|
||||
>
|
||||
Usage
|
||||
<svg
|
||||
class="w-4 h-4 ml-2"
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Dropdown menu -->
|
||||
<div
|
||||
v-show="stateDropdownOpen"
|
||||
class="absolute right-0 z-20 py-2 mt-2 bg-white rounded-md shadow-xl"
|
||||
>
|
||||
<ul class="space-y-2 text-sm px-4 py-2">
|
||||
<li class="flex items-center">
|
||||
<input
|
||||
id="unused"
|
||||
type="checkbox"
|
||||
v-model="filters.onGoing"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label
|
||||
for="unused"
|
||||
class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
On Going
|
||||
</label>
|
||||
</li>
|
||||
<li class="flex items-center">
|
||||
<input
|
||||
id="used"
|
||||
type="checkbox"
|
||||
v-model="filters.finished"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label for="used" class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
Finished
|
||||
</label>
|
||||
</li>
|
||||
<li class="flex items-center">
|
||||
<input
|
||||
id="used"
|
||||
type="checkbox"
|
||||
v-model="filters.sold"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label for="used" class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100">
|
||||
Sold
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 mb-3 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
<ComputerCard
|
||||
@@ -58,3 +119,5 @@ const filteredComputers = computed(() => {
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
@@ -1,72 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
interface FilterOption {
|
||||
id: string | number
|
||||
label: string
|
||||
}
|
||||
|
||||
defineProps<{
|
||||
label: string
|
||||
options: FilterOption[]
|
||||
}>()
|
||||
|
||||
const modelValue = defineModel<Record<string | number, boolean>>({ required: true })
|
||||
|
||||
const isOpen = ref(false)
|
||||
|
||||
function toggle() {
|
||||
isOpen.value = !isOpen.value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative" style="width: fit-content">
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition text-center inline-flex items-center"
|
||||
:aria-expanded="isOpen"
|
||||
aria-haspopup="true"
|
||||
@click="toggle"
|
||||
>
|
||||
{{ label }}
|
||||
<svg
|
||||
class="w-4 h-4 ml-2"
|
||||
aria-hidden="true"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M19 9l-7 7-7-7"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div
|
||||
v-show="isOpen"
|
||||
class="absolute right-0 z-20 py-2 mt-2 bg-white rounded-md shadow-xl"
|
||||
>
|
||||
<ul class="space-y-2 text-sm px-4 py-2">
|
||||
<li v-for="option in options" :key="option.id" class="flex items-center">
|
||||
<input
|
||||
:id="`filter-${label}-${option.id}`"
|
||||
v-model="modelValue[option.id]"
|
||||
type="checkbox"
|
||||
class="w-4 h-4 bg-gray-100 border-gray-300 rounded text-primary-600 focus:ring-primary-500 dark:focus:ring-primary-600 dark:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
|
||||
/>
|
||||
<label
|
||||
:for="`filter-${label}-${option.id}`"
|
||||
class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-100"
|
||||
>
|
||||
{{ option.label }}
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -165,7 +165,7 @@ function handleDragEnter(index: number) {
|
||||
const sourceArray =
|
||||
dragIndex.value < serverImages.value.length ? serverImages.value : newImages.value
|
||||
const draggedItem = sourceArray.splice(dragIndex.value, 1)[0]
|
||||
sourceArray.splice(index, 0, draggedItem as any) // Utilisation de 'as any' pour résoudre le problème de typage
|
||||
sourceArray.splice(index, 0, draggedItem as any) // Utilisation de 'as any' pour r├®soudre le probl├¿me de typage
|
||||
dragIndex.value = index
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ function getIconPath(typeName: string): string {
|
||||
'WiFi-Card': wiFiCard,
|
||||
'Case': pcCase,
|
||||
}
|
||||
return typeToIconMap[typeName] || defaultIcon // Utilisez une icône par défaut si nécessaire
|
||||
return typeToIconMap[typeName] || defaultIcon // Utilisez une ic├┤ne par d├®faut si n├®cessaire
|
||||
}
|
||||
|
||||
function goToDetail(id: number) {
|
||||
@@ -105,7 +105,7 @@ function deleteComponent(id: number) {
|
||||
{{ component.name }}
|
||||
</td>
|
||||
<td v-if="isAdminActive" class="px-6 py-4 border-b border-gray-200 whitespace-nowrap">
|
||||
€{{ component.price }}
|
||||
Ôé¼{{ component.price }}
|
||||
</td>
|
||||
<td class="px-6 py-4 border-b border-gray-200 whitespace-nowrap">
|
||||
{{ component.purchaseDate }}
|
||||
|
||||
Generated
+168
-377
File diff suppressed because it is too large.
Load diff
@@ -42,7 +42,6 @@
|
||||
"@adonisjs/eslint-config": "^3.1.0",
|
||||
"@adonisjs/prettier-config": "^1.5.0",
|
||||
"@adonisjs/tsconfig": "^2.0.0",
|
||||
"@japa/api-client": "^3.2.1",
|
||||
"@japa/assert": "^4.2.0",
|
||||
"@japa/browser-client": "^2.3.0",
|
||||
"@japa/plugin-adonisjs": "^5.2.0",
|
||||
|
||||
+2
-17
@@ -1,13 +1,9 @@
|
||||
import { assert } from '@japa/assert'
|
||||
import { apiClient } from '@japa/api-client'
|
||||
import app from '@adonisjs/core/services/app'
|
||||
import type { Config } from '@japa/runner/types'
|
||||
import { pluginAdonisJS } from '@japa/plugin-adonisjs'
|
||||
import { dbAssertions } from '@adonisjs/lucid/plugins/db'
|
||||
import testUtils from '@adonisjs/core/services/test_utils'
|
||||
import { authApiClient } from '@adonisjs/auth/plugins/api_client'
|
||||
import { sessionApiClient } from '@adonisjs/session/plugins/api_client'
|
||||
import { shieldApiClient } from '@adonisjs/shield/plugins/api_client'
|
||||
|
||||
/**
|
||||
* This file is imported by the "bin/test.ts" entrypoint file
|
||||
@@ -17,15 +13,7 @@ import { shieldApiClient } from '@adonisjs/shield/plugins/api_client'
|
||||
* Configure Japa plugins in the plugins array.
|
||||
* Learn more - https://japa.dev/docs/runner-config#plugins-optional
|
||||
*/
|
||||
export const plugins: Config['plugins'] = [
|
||||
assert(),
|
||||
apiClient(),
|
||||
sessionApiClient(app),
|
||||
authApiClient(app),
|
||||
shieldApiClient(),
|
||||
pluginAdonisJS(app),
|
||||
dbAssertions(app),
|
||||
]
|
||||
export const plugins: Config['plugins'] = [assert(), pluginAdonisJS(app), dbAssertions(app)]
|
||||
|
||||
/**
|
||||
* Configure lifecycle function to run before and after all the
|
||||
@@ -45,9 +33,6 @@ export const runnerHooks: Required<Pick<Config, 'setup' | 'teardown'>> = {
|
||||
*/
|
||||
export const configureSuite: Config['configureSuite'] = (suite) => {
|
||||
if (['browser', 'functional', 'e2e'].includes(suite.name)) {
|
||||
suite.setup(() => testUtils.httpServer().start())
|
||||
suite.onGroup((group) => {
|
||||
group.each.setup(() => testUtils.db().withGlobalTransaction())
|
||||
})
|
||||
return suite.setup(() => testUtils.httpServer().start())
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { test } from '@japa/runner'
|
||||
import { DateTime } from 'luxon'
|
||||
import User from '#models/user'
|
||||
import Component from '#models/component'
|
||||
import ComponentType from '#models/component_type'
|
||||
|
||||
async function createUser(email: string) {
|
||||
return User.create({
|
||||
name: 'Test User',
|
||||
email,
|
||||
password: 'secret@123A',
|
||||
})
|
||||
}
|
||||
|
||||
async function createType(name: string, unique = true) {
|
||||
return ComponentType.firstOrCreate({ name }, { name, unique })
|
||||
}
|
||||
|
||||
async function createComponent(userId: number, typeId: number) {
|
||||
return Component.create({
|
||||
name: 'Test Component',
|
||||
price: 20,
|
||||
typeId,
|
||||
userId,
|
||||
computerId: null,
|
||||
purchaseDate: DateTime.now(),
|
||||
})
|
||||
}
|
||||
|
||||
test.group('Components authorization (IDOR)', () => {
|
||||
test('owner can update their own component', async ({ client, assert }) => {
|
||||
const owner = await createUser('owner-comp-update@example.com')
|
||||
const type = await createType('RAM-comp-1')
|
||||
const component = await createComponent(owner.id, type.id)
|
||||
|
||||
const response = await client
|
||||
.put(`/components/${component.id}`)
|
||||
.loginAs(owner)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
.json({
|
||||
name: 'Updated name',
|
||||
price: 30,
|
||||
typeId: type.id,
|
||||
purchaseDate: DateTime.now().toFormat('yyyy-MM-dd'),
|
||||
})
|
||||
|
||||
response.assertStatus(302)
|
||||
await component.refresh()
|
||||
assert.equal(component.name, 'Updated name')
|
||||
})
|
||||
|
||||
test('a user cannot update another user component', async ({ client, assert }) => {
|
||||
const owner = await createUser('owner-comp-a@example.com')
|
||||
const attacker = await createUser('attacker-comp-a@example.com')
|
||||
const type = await createType('RAM-comp-2')
|
||||
const component = await createComponent(owner.id, type.id)
|
||||
|
||||
const response = await client
|
||||
.put(`/components/${component.id}`)
|
||||
.loginAs(attacker)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
.json({
|
||||
name: 'Hacked name',
|
||||
price: 1,
|
||||
typeId: type.id,
|
||||
purchaseDate: DateTime.now().toFormat('yyyy-MM-dd'),
|
||||
})
|
||||
|
||||
response.assertStatus(404)
|
||||
await component.refresh()
|
||||
assert.notEqual(component.name, 'Hacked name')
|
||||
})
|
||||
|
||||
test('a user cannot delete another user component', async ({ client, assert }) => {
|
||||
const owner = await createUser('owner-comp-b@example.com')
|
||||
const attacker = await createUser('attacker-comp-b@example.com')
|
||||
const type = await createType('RAM-comp-3')
|
||||
const component = await createComponent(owner.id, type.id)
|
||||
|
||||
const response = await client
|
||||
.delete(`/components/${component.id}`)
|
||||
.loginAs(attacker)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
|
||||
response.assertStatus(404)
|
||||
const stillExists = await Component.find(component.id)
|
||||
assert.isNotNull(stillExists)
|
||||
})
|
||||
|
||||
test('an unauthenticated request cannot delete a component', async ({ client, assert }) => {
|
||||
const owner = await createUser('owner-comp-c@example.com')
|
||||
const type = await createType('RAM-comp-4')
|
||||
const component = await createComponent(owner.id, type.id)
|
||||
|
||||
const response = await client.delete(`/components/${component.id}`)
|
||||
|
||||
response.assertRedirectsTo('/auth/login')
|
||||
const stillExists = await Component.find(component.id)
|
||||
assert.isNotNull(stillExists)
|
||||
})
|
||||
})
|
||||
@@ -1,198 +0,0 @@
|
||||
import { test } from '@japa/runner'
|
||||
import { DateTime } from 'luxon'
|
||||
import User from '#models/user'
|
||||
import Computer from '#models/computer'
|
||||
import ComputerState from '#models/computer_state'
|
||||
import Component from '#models/component'
|
||||
import ComponentType from '#models/component_type'
|
||||
|
||||
async function createUser(email: string) {
|
||||
return User.create({
|
||||
name: 'Test User',
|
||||
email,
|
||||
password: 'secret@123A',
|
||||
})
|
||||
}
|
||||
|
||||
async function createState(name = 'ON_GOING') {
|
||||
return ComputerState.firstOrCreate({ name }, { name })
|
||||
}
|
||||
|
||||
async function createType(name: string, unique = true) {
|
||||
return ComponentType.firstOrCreate({ name }, { name, unique })
|
||||
}
|
||||
|
||||
async function createComponent(userId: number, typeId: number, computerId: number | null = null) {
|
||||
return Component.create({
|
||||
name: 'Test Component',
|
||||
price: 42.5,
|
||||
typeId,
|
||||
userId,
|
||||
computerId,
|
||||
purchaseDate: DateTime.now(),
|
||||
})
|
||||
}
|
||||
|
||||
async function createComputer(userId: number, stateId: number) {
|
||||
return Computer.create({
|
||||
title: 'My PC',
|
||||
sellPrice: 100,
|
||||
gpuScore: 1,
|
||||
cpuScore: 1,
|
||||
globalScore: 1,
|
||||
stateId,
|
||||
userId,
|
||||
})
|
||||
}
|
||||
|
||||
test.group('Computers authorization (IDOR)', () => {
|
||||
test('owner can update their own computer', async ({ client, assert }) => {
|
||||
const owner = await createUser('owner-update@example.com')
|
||||
const state = await createState()
|
||||
const computer = await createComputer(owner.id, state.id)
|
||||
|
||||
const response = await client
|
||||
.put(`/computers/${computer.id}`)
|
||||
.loginAs(owner)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
.json({
|
||||
title: 'Updated title',
|
||||
sellPrice: 150,
|
||||
gpuScore: 2,
|
||||
cpuScore: 2,
|
||||
globalScore: 2,
|
||||
stateId: state.id,
|
||||
componentsId: [],
|
||||
pictures: [],
|
||||
})
|
||||
|
||||
response.assertStatus(302)
|
||||
await computer.refresh()
|
||||
assert.equal(computer.title, 'Updated title')
|
||||
})
|
||||
|
||||
test('a user cannot update another user computer', async ({ client }) => {
|
||||
const owner = await createUser('owner-a@example.com')
|
||||
const attacker = await createUser('attacker-a@example.com')
|
||||
const state = await createState()
|
||||
const computer = await createComputer(owner.id, state.id)
|
||||
|
||||
const response = await client
|
||||
.put(`/computers/${computer.id}`)
|
||||
.loginAs(attacker)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
.json({
|
||||
title: 'Hacked title',
|
||||
sellPrice: 1,
|
||||
gpuScore: 1,
|
||||
cpuScore: 1,
|
||||
globalScore: 1,
|
||||
stateId: state.id,
|
||||
componentsId: [],
|
||||
pictures: [],
|
||||
})
|
||||
|
||||
response.assertStatus(404)
|
||||
})
|
||||
|
||||
test('a user cannot delete another user computer', async ({ client, assert }) => {
|
||||
const owner = await createUser('owner-b@example.com')
|
||||
const attacker = await createUser('attacker-b@example.com')
|
||||
const state = await createState()
|
||||
const computer = await createComputer(owner.id, state.id)
|
||||
|
||||
const response = await client
|
||||
.delete(`/computers/${computer.id}`)
|
||||
.loginAs(attacker)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
|
||||
response.assertStatus(404)
|
||||
const stillExists = await Computer.find(computer.id)
|
||||
assert.isNotNull(stillExists)
|
||||
})
|
||||
|
||||
test('a user cannot attach another user component via componentsId', async ({
|
||||
client,
|
||||
assert,
|
||||
}) => {
|
||||
const owner = await createUser('owner-c@example.com')
|
||||
const attacker = await createUser('attacker-c@example.com')
|
||||
const state = await createState()
|
||||
const type = await createType('Processor-IDOR', true)
|
||||
const victimComponent = await createComponent(owner.id, type.id)
|
||||
const attackerComputer = await createComputer(attacker.id, state.id)
|
||||
|
||||
const response = await client
|
||||
.put(`/computers/${attackerComputer.id}`)
|
||||
.loginAs(attacker)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
.json({
|
||||
title: attackerComputer.title,
|
||||
sellPrice: attackerComputer.sellPrice,
|
||||
gpuScore: 0,
|
||||
cpuScore: 0,
|
||||
globalScore: 0,
|
||||
stateId: state.id,
|
||||
componentsId: [victimComponent.id],
|
||||
pictures: [],
|
||||
})
|
||||
|
||||
// handleComponents scopes the lookup to the current user, so the
|
||||
// victim's component cannot be found/attached -> 404.
|
||||
response.assertStatus(404)
|
||||
await victimComponent.refresh()
|
||||
assert.isNull(victimComponent.computerId)
|
||||
})
|
||||
|
||||
test('cannot attach two components of the same unique type to a computer', async ({ client }) => {
|
||||
const owner = await createUser('owner-d@example.com')
|
||||
const state = await createState()
|
||||
const type = await createType('Motherboard-IDOR', true)
|
||||
const componentA = await createComponent(owner.id, type.id)
|
||||
const componentB = await createComponent(owner.id, type.id)
|
||||
const computer = await createComputer(owner.id, state.id)
|
||||
|
||||
const response = await client
|
||||
.put(`/computers/${computer.id}`)
|
||||
.loginAs(owner)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
.json({
|
||||
title: computer.title,
|
||||
sellPrice: computer.sellPrice,
|
||||
gpuScore: 0,
|
||||
cpuScore: 0,
|
||||
globalScore: 0,
|
||||
stateId: state.id,
|
||||
componentsId: [componentA.id, componentB.id],
|
||||
pictures: [],
|
||||
})
|
||||
|
||||
response.assertStatus(422)
|
||||
})
|
||||
|
||||
test('deleting a computer detaches its components instead of destroying them', async ({
|
||||
client,
|
||||
assert,
|
||||
}) => {
|
||||
const owner = await createUser('owner-e@example.com')
|
||||
const state = await createState()
|
||||
const type = await createType('Fan-IDOR', false)
|
||||
const computer = await createComputer(owner.id, state.id)
|
||||
const component = await createComponent(owner.id, type.id, computer.id)
|
||||
|
||||
const response = await client
|
||||
.delete(`/computers/${computer.id}`)
|
||||
.loginAs(owner)
|
||||
.withCsrfToken()
|
||||
.redirects(0)
|
||||
|
||||
response.assertStatus(302)
|
||||
await component.refresh()
|
||||
assert.isNull(component.computerId)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user