Compare commits
16
Commits
ae0cf61124
...
b88871879c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b88871879c | ||
|
|
562cea39de | ||
|
|
94f89be605 | ||
|
|
3579c9dfec | ||
|
|
3cc189c534 | ||
|
|
ec6734f491 | ||
|
|
b3c8d691b4 | ||
|
|
d98e08f144 | ||
|
|
f3cbbe901a | ||
|
|
d1fa68fe5b | ||
|
|
99c80b1b2f | ||
|
|
e252a95c08 | ||
|
|
5b27625ead | ||
|
|
12d715f97b | ||
|
|
d51ae26c70 | ||
|
|
e8df8cee94 |
No files matched your search
@@ -38,8 +38,8 @@ const routes = {
|
||||
},
|
||||
'session.destroy': {
|
||||
methods: ["POST"],
|
||||
pattern: '/logout',
|
||||
tokens: [{"old":"/logout","type":0,"val":"logout","end":""}],
|
||||
pattern: '/auth/logout',
|
||||
tokens: [{"old":"/auth/logout","type":0,"val":"auth","end":""},{"old":"/auth/logout","type":0,"val":"logout","end":""}],
|
||||
types: placeholder as Registry['session.destroy']['types'],
|
||||
},
|
||||
'computers.index': {
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ export interface Registry {
|
||||
}
|
||||
'session.destroy': {
|
||||
methods: ["POST"]
|
||||
pattern: '/logout'
|
||||
pattern: '/auth/logout'
|
||||
types: {
|
||||
body: {}
|
||||
paramsTuple: []
|
||||
|
||||
Vendored
+2
-1
@@ -9,7 +9,6 @@ type ExtractProps<T> = Omit<
|
||||
|
||||
declare module '@adonisjs/inertia/types' {
|
||||
export interface InertiaPages {
|
||||
'account/signup': ExtractProps<(typeof import('../../inertia/pages/account/signup.vue'))['default']>
|
||||
'auth/login': ExtractProps<(typeof import('../../inertia/pages/auth/login.vue'))['default']>
|
||||
'auth/signup': ExtractProps<(typeof import('../../inertia/pages/auth/signup.vue'))['default']>
|
||||
'components/create': ExtractProps<(typeof import('../../inertia/pages/components/create.vue'))['default']>
|
||||
@@ -33,7 +32,9 @@ declare module '@adonisjs/inertia/types' {
|
||||
'widgets/ComputerCard': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputerCard.vue'))['default']>
|
||||
'widgets/ComputerComponentsTable': ExtractProps<(typeof import('../../inertia/pages/widgets/ComputerComponentsTable.vue'))['default']>
|
||||
'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']>
|
||||
|
||||
@@ -39,8 +39,37 @@ jobs:
|
||||
IMAGE=192.168.1.39:3000/$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')
|
||||
docker build -t ${IMAGE}:latest -t ${IMAGE}:${{ github.sha }} .
|
||||
docker push ${IMAGE}:latest
|
||||
docker push ${{ github.sha }}
|
||||
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
|
||||
@@ -51,5 +80,6 @@ jobs:
|
||||
cd /volume1/docker/pc_builder &&
|
||||
echo '${{ secrets.NASPASS }}' | sudo -S /usr/bin/bash setup-db.sh &&
|
||||
echo '${{ secrets.NASPASS }}' | sudo -S /usr/bin/docker compose -f docker-compose.prod.yml pull &&
|
||||
echo '${{ secrets.NASPASS }}' | sudo -S /usr/bin/docker compose -f docker-compose.prod.yml up -d --remove-orphans
|
||||
echo '${{ secrets.NASPASS }}' | sudo -S /usr/bin/docker compose -f docker-compose.prod.yml up -d --remove-orphans &&
|
||||
echo '${{ secrets.NASPASS }}' | sudo -S /usr/bin/docker exec pc-builder node ace migration:run --force
|
||||
"
|
||||
@@ -9,6 +9,7 @@ dist
|
||||
# Secrets
|
||||
.env
|
||||
.env.local
|
||||
.env.production
|
||||
.env.production.local
|
||||
.env.development.local
|
||||
.env.test
|
||||
@@ -28,6 +29,7 @@ coverage
|
||||
.fleet
|
||||
.idea
|
||||
.vscode
|
||||
.serena
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
# 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).
|
||||
@@ -5,24 +5,39 @@ 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 })
|
||||
const components = await Component.query().preload('type').where('userId', user.id)
|
||||
return inertia.render('components/index', {
|
||||
components: asPageProp(components.map((c) => c.serialize())),
|
||||
})
|
||||
}
|
||||
|
||||
async create({ inertia }: HttpContext) {
|
||||
const types = await ComponentType.all()
|
||||
return inertia.render('components/create', { types })
|
||||
return inertia.render('components/create', {
|
||||
types: asPageProp(types.map((t) => t.serialize())),
|
||||
})
|
||||
}
|
||||
|
||||
async store({ request, response, auth }: HttpContext) {
|
||||
const data = request.all()
|
||||
const user = await auth.authenticate()
|
||||
const { quantity, ...componentData } = await storeComponentValidator.validate(data)
|
||||
const { quantity, ...componentData } = await request.validateUsing(storeComponentValidator)
|
||||
await ComponentType.findOrFail(componentData.typeId)
|
||||
for (let i = 0; i < quantity; i++) {
|
||||
await Component.create({
|
||||
@@ -42,7 +57,7 @@ export default class ComponentsController {
|
||||
.where('userId', user.id)
|
||||
.andWhere('id', componentId)
|
||||
.firstOrFail()
|
||||
return inertia.render('components/show', { component })
|
||||
return inertia.render('components/show', { component: asPageProp(component.serialize()) })
|
||||
}
|
||||
|
||||
async edit({ params, auth, inertia }: HttpContext) {
|
||||
@@ -54,13 +69,15 @@ export default class ComponentsController {
|
||||
.where('userId', user.id)
|
||||
.andWhere('id', componentId)
|
||||
.firstOrFail()
|
||||
return inertia.render('components/edit', { component, types })
|
||||
return inertia.render('components/edit', {
|
||||
component: asPageProp(component.serialize()),
|
||||
types: asPageProp(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)
|
||||
@@ -73,9 +90,13 @@ export default class ComponentsController {
|
||||
return response.redirect('/components')
|
||||
}
|
||||
|
||||
async destroy({ params, response }: HttpContext) {
|
||||
async destroy({ params, auth, response }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
const componentId = params.id
|
||||
const component = await Component.findOrFail(componentId)
|
||||
const component = await Component.query()
|
||||
.where('userId', user.id)
|
||||
.andWhere('id', componentId)
|
||||
.firstOrFail()
|
||||
await component.delete()
|
||||
return response.redirect('/components')
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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'
|
||||
@@ -8,6 +9,20 @@ 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()
|
||||
@@ -19,7 +34,9 @@ export default class ComputersController {
|
||||
picturesQuery.where('order', 1)
|
||||
})
|
||||
|
||||
return inertia.render('computers/index', { computers })
|
||||
return inertia.render('computers/index', {
|
||||
computers: asPageProp(computers.map((c) => c.serialize())),
|
||||
})
|
||||
}
|
||||
|
||||
async create({ auth, inertia }: HttpContext) {
|
||||
@@ -29,21 +46,24 @@ export default class ComputersController {
|
||||
.where('userId', user.id)
|
||||
.whereNull('computerId')
|
||||
.preload('type')
|
||||
return inertia.render('computers/create', { components, states })
|
||||
return inertia.render('computers/create', {
|
||||
components: asPageProp(components.map((c) => c.serialize())),
|
||||
states: asPageProp(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 storeComputerValidator.validate(data)
|
||||
const { pictures, componentsId, ...computerData } =
|
||||
await request.validateUsing(storeComputerValidator)
|
||||
await ComputerState.findOrFail(computerData.stateId)
|
||||
const computer = await Computer.create({
|
||||
...computerData,
|
||||
userId: user.id,
|
||||
})
|
||||
await handleComponents(componentsId as number[], computer)
|
||||
await handleComponents(componentsId as number[], computer, user.id)
|
||||
await handlePictures(pictures as Image[], request, computer)
|
||||
return response.redirect('computers/')
|
||||
return response.redirect('/computers')
|
||||
}
|
||||
|
||||
async show({ auth, inertia, params }: HttpContext) {
|
||||
@@ -60,7 +80,7 @@ export default class ComputersController {
|
||||
.where('user_id', user.id)
|
||||
.andWhere('id', computerId)
|
||||
.firstOrFail()
|
||||
return inertia.render('computers/show', { computer })
|
||||
return inertia.render('computers/show', { computer: asPageProp(computer.serialize()) })
|
||||
}
|
||||
|
||||
async edit({ params, inertia, auth }: HttpContext) {
|
||||
@@ -86,25 +106,43 @@ export default class ComputersController {
|
||||
'id',
|
||||
computer.components.map((c) => c.id)
|
||||
)
|
||||
return inertia.render('computers/edit', { computer, availableComponents, states })
|
||||
return inertia.render('computers/edit', {
|
||||
computer: asPageProp(computer.serialize()),
|
||||
availableComponents: asPageProp(availableComponents.map((c) => c.serialize())),
|
||||
states: asPageProp(states.map((s) => s.serialize())),
|
||||
})
|
||||
}
|
||||
|
||||
async update({ params, request, response }: HttpContext) {
|
||||
async update({ auth, params, request, response }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
const computerId = params.id
|
||||
const { pictures, componentsId, ...computerData } = await updateComputerValidator.validate(
|
||||
request.all()
|
||||
const { pictures, componentsId, ...computerData } = await request.validateUsing(
|
||||
updateComputerValidator
|
||||
)
|
||||
const computer = await Computer.findOrFail(computerId)
|
||||
const computer = await Computer.query()
|
||||
.where('user_id', user.id)
|
||||
.andWhere('id', computerId)
|
||||
.firstOrFail()
|
||||
computer.merge(computerData)
|
||||
await computer.save()
|
||||
await handleComponents(componentsId as number[], computer)
|
||||
await handleComponents(componentsId as number[], computer, user.id)
|
||||
await handlePictures(pictures as Image[], request, computer)
|
||||
return response.redirect(`${computer.id}`)
|
||||
return response.redirect(`/computers/${computer.id}`)
|
||||
}
|
||||
|
||||
async destroy({ params, response }: HttpContext) {
|
||||
async destroy({ auth, params, response }: HttpContext) {
|
||||
const user = await auth.authenticate()
|
||||
const computerId = params.id
|
||||
const computer = await Computer.findOrFail(computerId)
|
||||
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 })
|
||||
}
|
||||
await computer.delete()
|
||||
return response.redirect('/computers')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
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,6 +1,7 @@
|
||||
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'
|
||||
@@ -52,7 +53,10 @@ export default class Computer extends BaseModel {
|
||||
@computed()
|
||||
get cost(): number {
|
||||
if (!this.$preloaded.components) {
|
||||
console.warn('Components not preloaded, cost may be incorrect')
|
||||
logger.warn(
|
||||
{ computerId: this.id },
|
||||
'Computer.cost accessed without preloading "components"; returning 0'
|
||||
)
|
||||
return 0
|
||||
}
|
||||
return this.components.reduce((total, component) => total + Number(component.price), 0)
|
||||
|
||||
@@ -1,21 +1,53 @@
|
||||
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) {
|
||||
async function handleComponents(componentsId: number[], computer: Computer, userId: number) {
|
||||
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(
|
||||
componentsToAdd.map(async (id: number) => {
|
||||
const component = await Component.findOrFail(id)
|
||||
componentsToAddRecords.map(async (component) => {
|
||||
component.computerId = computer.id
|
||||
await component.save()
|
||||
})
|
||||
)
|
||||
await Promise.all(
|
||||
componentsToRemove.map(async (id: number) => {
|
||||
const component = await Component.findOrFail(id)
|
||||
const component = await Component.query()
|
||||
.where('userId', userId)
|
||||
.andWhere('id', id)
|
||||
.firstOrFail()
|
||||
component.computerId = null
|
||||
await component.save()
|
||||
})
|
||||
|
||||
@@ -19,7 +19,10 @@ async function handlePictures(
|
||||
await Promise.all(
|
||||
pictures.map(async (picture: Image, index: number) => {
|
||||
if ('id' in picture) {
|
||||
const existingPicture = await ComputerPicture.findOrFail(picture.id)
|
||||
const existingPicture = await ComputerPicture.query()
|
||||
.where('computerId', computer.id)
|
||||
.andWhere('id', picture.id)
|
||||
.firstOrFail()
|
||||
existingPicture.order = picture.order
|
||||
await existingPicture.save()
|
||||
} else {
|
||||
@@ -44,7 +47,10 @@ async function handlePictures(
|
||||
|
||||
await Promise.all(
|
||||
imagesToRemove.map(async (id: number) => {
|
||||
const picture = await ComputerPicture.findOrFail(id)
|
||||
const picture = await ComputerPicture.query()
|
||||
.where('computerId', computer.id)
|
||||
.andWhere('id', id)
|
||||
.firstOrFail()
|
||||
const filePath = `uploads/computer_${computer.id}/${picture.link.split('/').pop()}`
|
||||
if (existsSync(filePath)) {
|
||||
unlinkSync(filePath)
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
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),
|
||||
})
|
||||
)
|
||||
@@ -4,7 +4,7 @@ const email = () => vine.string().email().maxLength(254)
|
||||
const password = () => vine.string().minLength(8).maxLength(32)
|
||||
|
||||
export const signupValidator = vine.create({
|
||||
fullName: vine.string().nullable(),
|
||||
name: vine.string().nullable(),
|
||||
email: email().unique({ table: 'users', column: 'email' }),
|
||||
password: password().confirmed({
|
||||
confirmationField: 'passwordConfirmation',
|
||||
|
||||
+1
-2
@@ -1,4 +1,3 @@
|
||||
import app from '@adonisjs/core/services/app'
|
||||
import { defineConfig } from '@adonisjs/core/http'
|
||||
|
||||
/**
|
||||
@@ -66,7 +65,7 @@ export const http = defineConfig({
|
||||
/**
|
||||
* Send cookies only over HTTPS in production.
|
||||
*/
|
||||
secure: app.inProduction,
|
||||
secure: false,
|
||||
|
||||
/**
|
||||
* Cross-site policy for cookie sending.
|
||||
|
||||
+9
-2
@@ -9,12 +9,19 @@ const shieldConfig = defineConfig({
|
||||
/**
|
||||
* Enable the Content-Security-Policy header.
|
||||
*/
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
|
||||
/**
|
||||
* Per-resource CSP directives.
|
||||
*/
|
||||
directives: {},
|
||||
directives: {
|
||||
defaultSrc: [`'self'`, '@viteDevUrl'],
|
||||
connectSrc: [`'self'`, '@viteHmrUrl'],
|
||||
scriptSrc: [`'self'`, '@viteDevUrl'],
|
||||
styleSrc: [`'self'`, '@viteDevUrl', `'unsafe-inline'`],
|
||||
imgSrc: [`'self'`, 'data:'],
|
||||
fontSrc: [`'self'`, 'data:'],
|
||||
},
|
||||
|
||||
/**
|
||||
* Report violations without blocking resources.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { BaseSeeder } from '@adonisjs/lucid/seeders'
|
||||
import ComponentType from '#models/component_type'
|
||||
|
||||
export default class extends BaseSeeder {
|
||||
async run() {
|
||||
await ComponentType.createMany([
|
||||
{
|
||||
name: 'Processor',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Motherboard',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Graphic Card',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Memory',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'SSD',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'HDD',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Cooler',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Power Supply',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Case',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Fan',
|
||||
unique: false,
|
||||
},
|
||||
{
|
||||
name: 'WiFi-Card',
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'Other',
|
||||
unique: false,
|
||||
},
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { BaseSeeder } from '@adonisjs/lucid/seeders'
|
||||
import ComputerState from '#models/computer_state'
|
||||
|
||||
export default class extends BaseSeeder {
|
||||
async run() {
|
||||
await ComputerState.createMany([
|
||||
{
|
||||
name: 'ON_GOING',
|
||||
},
|
||||
{
|
||||
name: 'FINISHED',
|
||||
},
|
||||
{
|
||||
name: 'SOLD',
|
||||
},
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
MYSQL_CONTAINER=$(docker ps -q --filter ancestor=mysql:8 | head -1)
|
||||
if [ -z "$MYSQL_CONTAINER" ]; then
|
||||
echo "❌ MySQL container not found"
|
||||
exit 1
|
||||
fi
|
||||
echo "MySQL container: $MYSQL_CONTAINER"
|
||||
docker exec "$MYSQL_CONTAINER" mysql -u root -pnpm_root_password -e "
|
||||
CREATE DATABASE IF NOT EXISTS pc_builder;
|
||||
CREATE USER IF NOT EXISTS 'pcbuilder'@'%' IDENTIFIED BY 'pcbuilder_secure_pass';
|
||||
GRANT ALL PRIVILEGES ON pc_builder.* TO 'pcbuilder'@'%';
|
||||
FLUSH PRIVILEGES;
|
||||
"
|
||||
echo "✅ Database pc_builder created"
|
||||
@@ -10,6 +10,7 @@ services:
|
||||
- PORT=3333
|
||||
- HOST=0.0.0.0
|
||||
- NODE_ENV=production
|
||||
- LOG_LEVEL=info
|
||||
- APP_KEY=${APP_KEY}
|
||||
- APP_URL=${APP_URL}
|
||||
- SESSION_DRIVER=cookie
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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))
|
||||
})
|
||||
|
||||
+3
-222
@@ -2,18 +2,6 @@
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--gray-1: oklch(98.5% 0 0);
|
||||
--gray-2: oklch(97% 0 0);
|
||||
--gray-3: oklch(92.2% 0 0);
|
||||
--gray-4: oklch(87% 0 0);
|
||||
--gray-6: oklch(55.6% 0 0);
|
||||
--gray-7: oklch(43.9% 0 0);
|
||||
--gray-8: oklch(37.1% 0 0);
|
||||
--gray-10: oklch(26.9% 0 0);
|
||||
--gray-12: oklch(14.5% 0 0);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
@@ -23,218 +11,11 @@
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
font-family: system-ui, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
background: var(--gray-2);
|
||||
color: var(--gray-10);
|
||||
font-size: 16px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
[x-cloak] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
color: var(--gray-12);
|
||||
}
|
||||
|
||||
/* Header */
|
||||
header {
|
||||
max-width: 1440px;
|
||||
margin: auto;
|
||||
padding: 0 30px;
|
||||
}
|
||||
header > div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
height: 64px;
|
||||
}
|
||||
header nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 26px;
|
||||
}
|
||||
header nav a {
|
||||
font-weight: 500;
|
||||
color: var(--gray-8);
|
||||
}
|
||||
header nav a:hover,
|
||||
header nav a.current {
|
||||
color: var(--gray-12);
|
||||
}
|
||||
|
||||
/* Main */
|
||||
main {
|
||||
max-width: 1440px;
|
||||
margin: 0 30px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
min-height: calc(100vh - 65px);
|
||||
background: #fff;
|
||||
border: 1px solid var(--gray-3);
|
||||
}
|
||||
|
||||
.hero {
|
||||
padding: 100px 50px;
|
||||
max-width: 880px;
|
||||
}
|
||||
.hero h1 {
|
||||
margin-bottom: 15px;
|
||||
font-size: 52px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -1px;
|
||||
line-height: 1.05;
|
||||
}
|
||||
.hero p {
|
||||
font-size: 22px;
|
||||
color: var(--gray-7);
|
||||
}
|
||||
.hero .button {
|
||||
margin-top: 30px;
|
||||
.material-symbols-outlined {
|
||||
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24;
|
||||
display: inline-block;
|
||||
padding: 10px 16px;
|
||||
}
|
||||
|
||||
.cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
padding: 0 50px;
|
||||
border-top: 1px solid var(--gray-3);
|
||||
}
|
||||
.cards a {
|
||||
padding: 30px 40px;
|
||||
border-right: 1px solid var(--gray-3);
|
||||
}
|
||||
.cards a:first-child {
|
||||
border-left: 1px solid var(--gray-3);
|
||||
}
|
||||
.cards a:hover {
|
||||
background: var(--gray-1);
|
||||
}
|
||||
.cards h3 {
|
||||
margin-bottom: 10px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.4px;
|
||||
}
|
||||
.cards p {
|
||||
color: var(--gray-6);
|
||||
}
|
||||
|
||||
/* Form */
|
||||
.form-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
max-width: 400px;
|
||||
margin: auto;
|
||||
}
|
||||
.form-container h1 {
|
||||
font-size: 32px;
|
||||
letter-spacing: -0.5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.form-container p {
|
||||
font-size: 18px;
|
||||
margin-bottom: 48px;
|
||||
color: var(--gray-6);
|
||||
}
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
label {
|
||||
margin-bottom: 4px;
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
input,
|
||||
textarea,
|
||||
button {
|
||||
width: 100%;
|
||||
border-radius: 4px;
|
||||
font: inherit;
|
||||
}
|
||||
input {
|
||||
height: 40px;
|
||||
border: 1px solid var(--gray-4);
|
||||
padding: 0 16px;
|
||||
}
|
||||
input[data-invalid='true'],
|
||||
textarea[data-invalid='true'] {
|
||||
border-color: #fb2c36;
|
||||
}
|
||||
input[data-invalid='true'] + div,
|
||||
textarea[data-invalid='true'] + div {
|
||||
color: #fb2c36;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
button {
|
||||
background: var(--gray-12);
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 10px;
|
||||
font-weight: 500;
|
||||
}
|
||||
button:hover {
|
||||
background: var(--gray-10);
|
||||
}
|
||||
|
||||
/* Alerts */
|
||||
.alert {
|
||||
background: #fff;
|
||||
position: relative;
|
||||
padding: 12px 16px;
|
||||
font-size: 14px;
|
||||
min-width: 380px;
|
||||
font-weight: 500;
|
||||
border: 1px solid var(--gray-3);
|
||||
border-radius: 10px;
|
||||
animation: scale-up 0.2s cubic-bezier(0.39, 0.575, 0.565, 1) both;
|
||||
}
|
||||
.alert-destructive {
|
||||
color: #fb2c36;
|
||||
background: #fb2c361a;
|
||||
border-color: #fb2c36;
|
||||
}
|
||||
.alert-success {
|
||||
color: #00a63e;
|
||||
background: #00a63e1a;
|
||||
border-color: #00a63e;
|
||||
}
|
||||
.flash-container {
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@keyframes scale-up {
|
||||
from {
|
||||
transform: scale(0.7);
|
||||
}
|
||||
to {
|
||||
transform: scale(1);
|
||||
}
|
||||
vertical-align: middle;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Form, Link } from '@adonisjs/inertia/vue'
|
||||
import { useForm } from '@inertiajs/vue3'
|
||||
import EmptyLayout from '~/pages/layout/emptyLayout.vue'
|
||||
|
||||
defineOptions({ layout: EmptyLayout })
|
||||
|
||||
const form = useForm({
|
||||
fullName: '',
|
||||
email: '',
|
||||
password: '',
|
||||
passwordConfirmation: '',
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center justify-center min-h-screen px-4 py-8 bg-gradient-to-br from-gray-100 to-gray-200">
|
||||
<div class="w-full max-w-md p-6 sm:p-8 bg-white rounded-lg shadow-lg">
|
||||
<div class="flex flex-col items-center justify-center mb-8">
|
||||
<h1 class="text-2xl sm:text-3xl font-bold text-gray-800">Create Account</h1>
|
||||
<p class="text-sm text-gray-600 mt-2">Join PC Creator today</p>
|
||||
</div>
|
||||
|
||||
<Form route="account.signup" #default="{ processing, errors }">
|
||||
<div class="space-y-4 sm:space-y-6">
|
||||
<div>
|
||||
<label class="block">
|
||||
<span class="text-sm font-medium text-gray-700 mb-2 block">Full Name</span>
|
||||
<input
|
||||
v-model="form.fullName"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-600 focus:ring-2 focus:ring-indigo-500/40 transition text-base"
|
||||
name="fullName"
|
||||
type="text"
|
||||
placeholder="Enter your full name"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block">
|
||||
<span class="text-sm font-medium text-gray-700 mb-2 block">Email</span>
|
||||
<input
|
||||
v-model="form.email"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-600 focus:ring-2 focus:ring-indigo-500/40 transition text-base"
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="Enter your email"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block">
|
||||
<span class="text-sm font-medium text-gray-700 mb-2 block">Password</span>
|
||||
<input
|
||||
v-model="form.password"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-600 focus:ring-2 focus:ring-indigo-500/40 transition text-base"
|
||||
name="password"
|
||||
type="password"
|
||||
placeholder="Enter your password"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block">
|
||||
<span class="text-sm font-medium text-gray-700 mb-2 block">Confirm Password</span>
|
||||
<input
|
||||
v-model="form.passwordConfirmation"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-600 focus:ring-2 focus:ring-indigo-500/40 transition text-base"
|
||||
name="passwordConfirmation"
|
||||
type="password"
|
||||
placeholder="Confirm your password"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="processing"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 mt-6 sm:mt-8 text-base font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500/40 transition disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{{ processing ? 'Creating account...' : 'Sign Up' }}
|
||||
</button>
|
||||
|
||||
<div class="text-center mt-4">
|
||||
<p class="text-sm text-gray-600">
|
||||
Already have an account?
|
||||
<Link route="auth.show_login" class="text-indigo-600 hover:text-indigo-700 font-semibold">
|
||||
Login
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,39 +1,14 @@
|
||||
<script lang="ts" setup>
|
||||
import { Link, useForm } from '@inertiajs/vue3'
|
||||
import { computed } from 'vue'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { useForm } from '@inertiajs/vue3'
|
||||
import EmptyLayout from '~/pages/layout/emptyLayout.vue'
|
||||
|
||||
defineOptions({ layout: EmptyLayout })
|
||||
|
||||
const props = defineProps<{ errors?: any[] | any }>()
|
||||
|
||||
const vineErrors = computed(() => {
|
||||
if (Array.isArray(props.errors)) {
|
||||
return props.errors as any[]
|
||||
}
|
||||
return []
|
||||
})
|
||||
|
||||
const authError = computed(() => {
|
||||
if (!Array.isArray(props.errors) && props.errors) {
|
||||
return props.errors as any
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const form = useForm({
|
||||
email: '',
|
||||
password: '',
|
||||
})
|
||||
|
||||
function getErrorMessage(field: string): string | null {
|
||||
const error = vineErrors.value.find((error) => error.field === field)
|
||||
return error ? error.message : null
|
||||
}
|
||||
|
||||
console.log(authError)
|
||||
console.log(vineErrors)
|
||||
console.log(props)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -109,7 +84,7 @@ console.log(props)
|
||||
<Link
|
||||
as="button"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 mt-3 sm:mt-4 text-base font-semibold text-indigo-600 bg-gray-100 rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-indigo-500/40 transition"
|
||||
href="/account/signup"
|
||||
href="/auth/signup"
|
||||
type="button"
|
||||
>
|
||||
Create an account
|
||||
|
||||
@@ -6,7 +6,7 @@ import EmptyLayout from '~/pages/layout/emptyLayout.vue'
|
||||
defineOptions({ layout: EmptyLayout })
|
||||
|
||||
const form = useForm({
|
||||
fullName: '',
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
passwordConfirmation: '',
|
||||
@@ -21,15 +21,15 @@ const form = useForm({
|
||||
<p class="text-sm text-gray-600 mt-2">Join PC Creator today</p>
|
||||
</div>
|
||||
|
||||
<Form route="account.signup" #default="{ processing, errors }">
|
||||
<Form route="new_account.store" #default="{ processing }">
|
||||
<div class="space-y-4 sm:space-y-6">
|
||||
<div>
|
||||
<label class="block">
|
||||
<span class="text-sm font-medium text-gray-700 mb-2 block">Full Name</span>
|
||||
<input
|
||||
v-model="form.fullName"
|
||||
v-model="form.name"
|
||||
class="w-full px-3 sm:px-4 py-2 sm:py-3 border-2 border-gray-300 rounded-lg focus:border-indigo-600 focus:ring-2 focus:ring-indigo-500/40 transition text-base"
|
||||
name="fullName"
|
||||
name="name"
|
||||
type="text"
|
||||
placeholder="Enter your full name"
|
||||
/>
|
||||
@@ -86,7 +86,7 @@ const form = useForm({
|
||||
<div class="text-center mt-4">
|
||||
<p class="text-sm text-gray-600">
|
||||
Already have an account?
|
||||
<Link route="auth.show_login" class="text-indigo-600 hover:text-indigo-700 font-semibold">
|
||||
<Link route="session.create" class="text-indigo-600 hover:text-indigo-700 font-semibold">
|
||||
Login
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
@@ -1,30 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue'
|
||||
import { Link, useForm } from '@inertiajs/vue3'
|
||||
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'
|
||||
|
||||
const props = defineProps<{ types: any[]; errors?: any[] }>()
|
||||
const errors = computed(() => props.errors || [])
|
||||
defineProps<{ types: ComponentType[]; errors?: Record<string, string> }>()
|
||||
const form = reactive({
|
||||
name: '',
|
||||
price: 0,
|
||||
type_id: null,
|
||||
purchase_date: new Date().toISOString().split('T')[0],
|
||||
typeId: null,
|
||||
purchaseDate: new Date().toISOString().split('T')[0],
|
||||
quantity: 1,
|
||||
})
|
||||
|
||||
function getErrorMessage(field: string): string | null {
|
||||
const error = errors.value.find((error) => error.field === field)
|
||||
return error ? error.message : null
|
||||
}
|
||||
|
||||
function formatDateForMySQL(date: string) {
|
||||
const d = new Date(date)
|
||||
const year = d.getFullYear()
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
form.purchase_date = `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
function submitForm() {
|
||||
const inertiaForm = useForm(form)
|
||||
inertiaForm.post('/components')
|
||||
@@ -59,17 +48,11 @@ function submitForm() {
|
||||
|
||||
<div>
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="type">Type</label>
|
||||
<select
|
||||
name="type_id"
|
||||
v-model.number="form.type_id"
|
||||
id="type"
|
||||
class="w-full mt-2 border-gray-200 focus:border-indigo-600 focus:ring-indigo-500 px-3 py-2 focus:ring-1 border rounded text-gray-700 bg-white"
|
||||
>
|
||||
<option disabled :value="null">Choose a type</option>
|
||||
<option v-for="type in types" :key="type.id" :value="type.id">
|
||||
{{ type.name }}
|
||||
</option>
|
||||
</select>
|
||||
<CustomSelect
|
||||
v-model="form.typeId"
|
||||
:options="types"
|
||||
placeholder="Choose a type"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -77,8 +60,8 @@ function submitForm() {
|
||||
>Purchase Date</label
|
||||
>
|
||||
<input
|
||||
name="purchase_date"
|
||||
v-model="form.purchase_date"
|
||||
name="purchaseDate"
|
||||
v-model="form.purchaseDate"
|
||||
class="w-full mt-2 border-gray-200 focus:border-indigo-600 focus:ring focus:ring-indigo-500/40 border rounded text-gray-700 px-3 py-2"
|
||||
type="date"
|
||||
/>
|
||||
|
||||
@@ -1,37 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue'
|
||||
import { Link, usePage } from '@inertiajs/vue3'
|
||||
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: any
|
||||
types: any[]
|
||||
origin: string
|
||||
errors?: any[]
|
||||
component: Component
|
||||
types: ComponentType[]
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
const { component, types, origin } = props
|
||||
const errors = computed(() => props.errors || [])
|
||||
const { component, types } = props
|
||||
|
||||
const form = reactive({
|
||||
id: component.id,
|
||||
name: component.name,
|
||||
price: component.price,
|
||||
type_id: component.type.id,
|
||||
purchase_date: component.purchaseDate,
|
||||
origin: origin,
|
||||
typeId: component.type.id,
|
||||
purchaseDate: component.purchaseDate,
|
||||
})
|
||||
|
||||
function getErrorMessage(field: string): string | null {
|
||||
const error = errors.value.find((error) => error.field === field)
|
||||
return error ? error.message : null
|
||||
}
|
||||
|
||||
function formatDateForMySQL(date: string) {
|
||||
const d = new Date(date)
|
||||
const year = d.getFullYear()
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
form.purchase_date = `${year}-${month}-${day}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -61,16 +48,11 @@ function formatDateForMySQL(date: string) {
|
||||
|
||||
<div>
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="type">Type</label>
|
||||
<select
|
||||
v-model="form.type_id"
|
||||
id="type"
|
||||
class="w-full mt-2 border-gray-200 focus:border-indigo-600 focus:ring-indigo-500 px-3 py-2 focus:ring-1 border rounded text-gray-700 bg-white"
|
||||
>
|
||||
<option disabled :value="null">Choose a type</option>
|
||||
<option v-for="type in types" :key="type.id" :value="type.id">
|
||||
{{ type.name }}
|
||||
</option>
|
||||
</select>
|
||||
<CustomSelect
|
||||
v-model="form.typeId"
|
||||
:options="types"
|
||||
placeholder="Choose a type"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -78,8 +60,8 @@ function formatDateForMySQL(date: string) {
|
||||
>Purchase Date</label
|
||||
>
|
||||
<input
|
||||
name="purchase_date"
|
||||
v-model="form.purchase_date"
|
||||
name="purchaseDate"
|
||||
v-model="form.purchaseDate"
|
||||
class="w-full mt-2 border-gray-200 focus:border-indigo-600 focus:ring focus:ring-indigo-500/40 border rounded text-gray-700 px-3 py-2"
|
||||
type="date"
|
||||
/>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
|
||||
defineProps<{ components: any[] }>()
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import ComponentsViewer from '~/pages/widgets/ComponentsViewer.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h3 class="text-3xl font-semibold text-gray-700">Components</h3>
|
||||
<Link
|
||||
href="/components/create"
|
||||
@@ -17,27 +16,6 @@ defineProps<{ components: any[] }>()
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<template v-if="components.length > 0">
|
||||
<div
|
||||
v-for="component in components"
|
||||
:key="component.id"
|
||||
class="p-4 border rounded-lg shadow hover:shadow-lg transition"
|
||||
>
|
||||
<h4 class="font-semibold text-lg text-gray-800">{{ component.name }}</h4>
|
||||
<p class="text-gray-600">Type: {{ component.type?.name }}</p>
|
||||
<p class="text-indigo-600 font-semibold">Price: ${{ component.price }}</p>
|
||||
<Link
|
||||
:href="`/components/${component.id}`"
|
||||
class="mt-2 inline-block text-indigo-600 hover:text-indigo-700"
|
||||
>
|
||||
View Details
|
||||
</Link>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="text-gray-500">No components yet. Create one to get started!</p>
|
||||
</template>
|
||||
</div>
|
||||
<ComponentsViewer />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,53 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { Link, usePage } from '@inertiajs/vue3'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import type { Component } from '~/pages/types/UITypes'
|
||||
|
||||
const { props } = usePage<{ component: any }>()
|
||||
const { component } = props
|
||||
const originHeader = { 'X-Inertia-Origin': 'components' }
|
||||
const props = defineProps<{ component: Component }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="max-w-2xl mx-auto p-8 bg-white shadow-lg rounded-lg">
|
||||
<h1 class="text-2xl font-semibold mb-8 text-gray-800">Component Details</h1>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="name">Name</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700" id="name">
|
||||
{{ component.name }}
|
||||
<template v-if="props.component">
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2">Name</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700">
|
||||
{{ props.component.name }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="price">Price</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700" id="price">${{ component.price }}</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="type">Type</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700" id="type">
|
||||
{{ component.type.name }}
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2">Price</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700">${{ props.component.price }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="purchaseDate"
|
||||
>Purchase Date</label
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2">Type</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700">
|
||||
{{ props.component.type?.name ?? 'N/A' }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2">Purchase Date</label>
|
||||
<div class="px-3 py-2 border rounded text-gray-700">
|
||||
{{ props.component.purchaseDate }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
:href="`/components/${props.component.id}/edit`"
|
||||
type="button"
|
||||
as="button"
|
||||
class="w-full md:w-auto px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition text-center"
|
||||
>
|
||||
<div class="px-3 py-2 border rounded text-gray-700" id="purchaseDate">
|
||||
{{ component.purchaseDate }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
:href="`/components/${component.id}/edit`"
|
||||
type="button"
|
||||
as="button"
|
||||
class="w-full md:w-auto px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition text-center"
|
||||
:headers="originHeader"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
Edit
|
||||
</Link>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
@@ -1,14 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue'
|
||||
import { Link, usePage } from '@inertiajs/vue3'
|
||||
import { computed } from 'vue'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { useForm, usePage } from '@inertiajs/vue3'
|
||||
import type { Component, ComputerState } from '~/pages/types/UITypes'
|
||||
|
||||
const { props } = usePage<{
|
||||
components: any[]
|
||||
states: any[]
|
||||
errors: any[]
|
||||
components: Component[]
|
||||
states: ComputerState[]
|
||||
errors: Record<string, string>
|
||||
}>()
|
||||
const { components, states } = props
|
||||
const errors = computed(() => props.errors || [])
|
||||
|
||||
const componentTypeOrder = [
|
||||
'Processor',
|
||||
@@ -26,7 +27,7 @@ const componentTypeOrder = [
|
||||
]
|
||||
|
||||
const componentsByType = computed(() => {
|
||||
const groups = new Map<string, any[]>()
|
||||
const groups = new Map<string, Component[]>()
|
||||
components.forEach((component) => {
|
||||
if (!groups.has(component.type.name)) {
|
||||
groups.set(component.type.name, [])
|
||||
@@ -38,26 +39,35 @@ const componentsByType = computed(() => {
|
||||
.sort((a, b) => componentTypeOrder.indexOf(a.type) - componentTypeOrder.indexOf(b.type))
|
||||
})
|
||||
|
||||
const form = reactive({
|
||||
const form = useForm<{
|
||||
title: string
|
||||
sellPrice: number
|
||||
gpuScore: number
|
||||
cpuScore: number
|
||||
stateId: number
|
||||
globalScore: number
|
||||
componentsId: number[]
|
||||
pictures: Record<string, never>[]
|
||||
}>({
|
||||
title: '',
|
||||
sellPrice: 0,
|
||||
gpuScore: 0,
|
||||
cpuScore: 0,
|
||||
stateId: 1,
|
||||
globalScore: 0,
|
||||
componentsId: [] as number[],
|
||||
componentsId: [],
|
||||
pictures: [],
|
||||
})
|
||||
|
||||
function getErrorMessage(field: string): string | null {
|
||||
const error = errors.value.find((error) => error.field === field)
|
||||
return error ? error.message : null
|
||||
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">
|
||||
<form class="space-y-6" @submit.prevent="submitForm">
|
||||
<div class="mt-2">
|
||||
<label class="block text-gray-700 text-sm font-bold mb-2" for="title">Title</label>
|
||||
<input
|
||||
@@ -154,16 +164,21 @@ function getErrorMessage(field: string): string | null {
|
||||
</div>
|
||||
</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>
|
||||
<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>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue'
|
||||
import { Link, router, usePage } from '@inertiajs/vue3'
|
||||
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: any
|
||||
availableComponents: any[]
|
||||
states: any[]
|
||||
errors?: any[]
|
||||
computer: Computer
|
||||
availableComponents: Component[]
|
||||
states: ComputerState[]
|
||||
errors?: Record<string, string>
|
||||
}>()
|
||||
const { computer, availableComponents, states } = props
|
||||
const errors = computed(() => props.errors || [])
|
||||
const { computer, states } = props
|
||||
|
||||
const form = reactive({
|
||||
id: computer.id,
|
||||
@@ -19,21 +20,12 @@ const form = reactive({
|
||||
cpuScore: computer.cpuScore,
|
||||
globalScore: computer.globalScore,
|
||||
stateId: computer.state.id,
|
||||
componentsId: computer.components.map((c: any) => c.id),
|
||||
componentsId: computer.components.map((c) => c.id),
|
||||
})
|
||||
|
||||
function updateComponents(componentsId: number[]) {
|
||||
form.componentsId = componentsId
|
||||
}
|
||||
|
||||
function deleteComputer(id: number) {
|
||||
router.delete(`/computers/${id}`)
|
||||
}
|
||||
|
||||
function getErrorMessage(field: string): string | null {
|
||||
const error = errors.value.find((error) => error.field === field)
|
||||
return error ? error.message : null
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import type { Computer } from '~/pages/types/UITypes'
|
||||
|
||||
defineProps<{ computers: any[] }>()
|
||||
defineProps<{ computers: Computer[] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -13,7 +14,7 @@ defineProps<{ computers: any[] }>()
|
||||
href="/computers/create"
|
||||
type="button"
|
||||
as="button"
|
||||
class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition"
|
||||
class="inline-flex shrink-0 px-4 py-2 bg-indigo-600 text-white rounded hover:bg-blue-700 transition"
|
||||
>
|
||||
Add
|
||||
</Link>
|
||||
@@ -44,85 +45,3 @@ defineProps<{ computers: any[] }>()
|
||||
</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,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import type { Computer } from '~/pages/types/UITypes'
|
||||
|
||||
const { props } = defineProps<{ computer: any }>()
|
||||
const { computer } = defineProps<{ computer: Computer }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { Link, usePage } from '@inertiajs/vue3'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
|
||||
const page = usePage()
|
||||
|
||||
|
||||
@@ -4,14 +4,16 @@ import Header from './header.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-screen bg-gray-200 font-roboto">
|
||||
<Sidebar />
|
||||
<div class="flex h-screen bg-background font-body-md text-on-background overflow-hidden">
|
||||
<aside class="w-64 shrink-0">
|
||||
<Sidebar />
|
||||
</aside>
|
||||
|
||||
<div class="flex-1 flex flex-col overflow-hidden">
|
||||
<div class="flex-1 flex flex-col min-w-0">
|
||||
<Header />
|
||||
|
||||
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-200">
|
||||
<div class="container mx-auto px-6 py-8">
|
||||
<main class="flex-1 pt-16 min-h-screen border-0 overflow-auto">
|
||||
<div class="p-10 max-w-[1400px] mx-auto">
|
||||
<slot />
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { useSidebar } from '~/composables/useSidebar'
|
||||
import { Link, usePage } from '@inertiajs/vue3'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
import { userProfileIcon } from '~/assets/icons'
|
||||
import { useAdminMode } from '~/composables/isAdminMode'
|
||||
|
||||
const dropdownOpen = ref(false)
|
||||
const { isOpen } = useSidebar()
|
||||
const { isAdminActive } = useAdminMode()
|
||||
|
||||
function toggleActive() {
|
||||
isAdminActive.value = !isAdminActive.value
|
||||
}
|
||||
|
||||
const page = usePage()
|
||||
|
||||
@@ -22,78 +15,59 @@ const user = computed(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="flex items-center justify-between px-6 py-4 bg-white border-b-4 border-indigo-600">
|
||||
<div class="flex items-center">
|
||||
<button class="text-gray-500 focus:outline-none lg:hidden" @click="isOpen = true">
|
||||
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M4 6H20M4 12H20M4 18H11"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center">
|
||||
<div class="relative">
|
||||
<button
|
||||
class="relative z-10 block w-8 h-8 overflow-hidden rounded-full shadow focus:outline-none"
|
||||
@click="dropdownOpen = !dropdownOpen"
|
||||
>
|
||||
<img class="object-cover w-full h-full" :src="userProfileIcon" alt="Your avatar" />
|
||||
</button>
|
||||
<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"
|
||||
>
|
||||
<div class="flex items-center gap-6">
|
||||
<div
|
||||
class="relative flex items-center gap-3 cursor-pointer group"
|
||||
@click="dropdownOpen = !dropdownOpen"
|
||||
>
|
||||
<div class="text-right hidden sm:block">
|
||||
<p class="font-label-md text-label-md text-on-surface">{{ user.name }}</p>
|
||||
</div>
|
||||
<img
|
||||
class="w-10 h-10 rounded-full border-2 border-primary-container group-hover:border-primary transition-all object-cover"
|
||||
:src="userProfileIcon"
|
||||
alt="Avatar"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<transition
|
||||
enter-active-class="transition duration-150 ease-out transform"
|
||||
enter-from-class="scale-95 opacity-0"
|
||||
enter-to-class="scale-100 opacity-100"
|
||||
leave-active-class="transition duration-150 ease-in transform"
|
||||
leave-from-class="scale-100 opacity-100"
|
||||
leave-to-class="scale-95 opacity-0"
|
||||
>
|
||||
<div
|
||||
v-show="dropdownOpen"
|
||||
class="fixed inset-0 z-10 w-full h-full"
|
||||
@click="dropdownOpen = false"
|
||||
/>
|
||||
|
||||
<transition
|
||||
enter-active-class="transition duration-150 ease-out transform"
|
||||
enter-from-class="scale-95 opacity-0"
|
||||
enter-to-class="scale-100 opacity-100"
|
||||
leave-active-class="transition duration-150 ease-in transform"
|
||||
leave-from-class="scale-100 opacity-100"
|
||||
leave-to-class="scale-95 opacity-0"
|
||||
class="absolute top-14 right-0 z-50 min-w-48 max-w-72 bg-white rounded-lg shadow-xl border border-outline-variant overflow-hidden"
|
||||
>
|
||||
<div
|
||||
v-show="dropdownOpen"
|
||||
class="absolute right-0 z-20 w-48 py-2 mt-2 bg-white rounded-md shadow-xl"
|
||||
>
|
||||
<div class="flex items-center justify-between px-4 py-2 text-sm text-indigo-600">
|
||||
<strong>{{ user.name }}</strong>
|
||||
</div>
|
||||
<hr />
|
||||
|
||||
<div
|
||||
class="flex items-center justify-between px-4 py-2 text-sm text-gray-700 hover:bg-indigo-600 hover:text-white cursor-pointer"
|
||||
@click="toggleActive"
|
||||
>
|
||||
<span>{{ isAdminActive ? 'Admin' : 'Classic' }}</span>
|
||||
<button
|
||||
:class="{ 'bg-indigo-800': isAdminActive, 'bg-gray-200': !isAdminActive }"
|
||||
class="w-10 h-5 rounded-full focus:outline-none relative"
|
||||
>
|
||||
<span
|
||||
:class="{ 'translate-x-5': isAdminActive, 'translate-x-0': !isAdminActive }"
|
||||
class="block w-4 h-4 bg-white rounded-full shadow transform transition duration-300"
|
||||
></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="/auth/logout"
|
||||
class="block px-4 py-2 text-sm text-gray-700 hover:bg-indigo-600 hover:text-white"
|
||||
>
|
||||
Logout
|
||||
</Link>
|
||||
<div class="px-4 py-3 border-b border-outline-variant">
|
||||
<p class="font-label-md text-label-md text-on-surface truncate">{{ user.name }}</p>
|
||||
<p class="font-label-sm text-label-sm text-on-surface-variant truncate">
|
||||
{{ user.email }}
|
||||
</p>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="/auth/logout"
|
||||
method="post"
|
||||
class="flex items-center gap-3 px-4 py-2 text-body-sm font-body-sm text-on-surface hover:bg-surface-container-low transition-colors"
|
||||
>
|
||||
<span class="material-symbols-outlined text-[20px]">logout</span>
|
||||
Sign Out
|
||||
</Link>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-show="dropdownOpen"
|
||||
class="fixed inset-0 z-30"
|
||||
@click="dropdownOpen = false"
|
||||
/>
|
||||
</template>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref, useAttrs } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import { useSidebar } from '~/composables/useSidebar'
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
import { siteIcon } from '~/assets/icons'
|
||||
|
||||
const { isOpen } = useSidebar()
|
||||
@@ -9,12 +9,10 @@ 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>
|
||||
<div class="flex">
|
||||
<div class="flex h-full">
|
||||
<!-- Backdrop -->
|
||||
<div
|
||||
:class="isOpen ? 'block' : 'hidden'"
|
||||
@@ -25,7 +23,7 @@ console.log(route)
|
||||
|
||||
<div
|
||||
:class="isOpen ? 'translate-x-0 ease-out' : '-translate-x-full ease-in'"
|
||||
class="fixed inset-y-0 left-0 z-30 w-64 overflow-y-auto transition duration-300 transform bg-gray-900 lg:translate-x-0 lg:static lg:inset-0"
|
||||
class="fixed inset-y-0 left-0 z-30 w-64 overflow-y-auto transition duration-300 transform bg-gray-900 lg:h-full lg:translate-x-0 lg:static lg:inset-0"
|
||||
>
|
||||
<div class="flex items-center justify-center mt-8">
|
||||
<div class="flex items-center">
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { PageProps } from '@adonisjs/inertia/types'
|
||||
import { InertiaAppProps } from '@inertiajs/vue3/types/app'
|
||||
|
||||
interface ComponentType {
|
||||
export type ComponentType = {
|
||||
id: number
|
||||
name: string
|
||||
unique: boolean
|
||||
}
|
||||
|
||||
interface ComputerState {
|
||||
export type ComputerState = {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
@@ -29,23 +26,20 @@ export type Component = {
|
||||
id: number
|
||||
name: string
|
||||
price: string
|
||||
componentTypeId: number
|
||||
computerId: number | null
|
||||
userId: number
|
||||
componentStateId: number
|
||||
purchaseDate: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
type: ComponentType
|
||||
}
|
||||
|
||||
interface ServerImage {
|
||||
export interface ServerImage {
|
||||
id: number
|
||||
link: string
|
||||
order: number
|
||||
}
|
||||
|
||||
interface NewImage {
|
||||
export interface NewImage {
|
||||
file: File
|
||||
order: number
|
||||
}
|
||||
@@ -63,15 +57,4 @@ export type UIAuthError = {
|
||||
message: string
|
||||
}
|
||||
|
||||
interface SharedProps extends PageProps {
|
||||
auth: {
|
||||
user: {
|
||||
id: number
|
||||
name: string
|
||||
email: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type PageWithSharedProps = InertiaAppProps<SharedProps>
|
||||
export type Image = ServerImage | NewImage
|
||||
@@ -1,4 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
type UIAuthError = {
|
||||
status: number
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
defineProps<{
|
||||
authError?: UIAuthError
|
||||
}>()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, defineEmits, defineProps, onMounted, ref, watch } from 'vue'
|
||||
import { Component } from '~/pages/types/UITypes'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import type { Component } from '~/pages/types/UITypes'
|
||||
|
||||
interface ComponentsByType {
|
||||
type: 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,26 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import TableComponent from '~/pages/widgets/TableComponent.vue'
|
||||
import Component from '#models/component'
|
||||
import ComponentType from '#models/component_type'
|
||||
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'
|
||||
|
||||
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) => {
|
||||
@@ -31,152 +19,51 @@ const componentTypes = computed(() => {
|
||||
return Array.from(types.values())
|
||||
})
|
||||
|
||||
// D├®finir le type de l'objet filters
|
||||
interface Filters {
|
||||
showUsed: boolean
|
||||
showUnused: boolean
|
||||
types: { [key: number]: boolean }
|
||||
}
|
||||
const typeOptions = computed(() =>
|
||||
componentTypes.value.map((type) => ({ id: type.id, label: type.name }))
|
||||
)
|
||||
|
||||
const filters = reactive<Filters>({
|
||||
showUsed: false,
|
||||
showUnused: true,
|
||||
types: componentTypes.value.reduce(
|
||||
const usageFilters = ref<Record<string, boolean>>({
|
||||
unused: true,
|
||||
used: false,
|
||||
})
|
||||
|
||||
const typeFilters = ref<Record<number, boolean>>(
|
||||
componentTypes.value.reduce(
|
||||
(acc, type) => {
|
||||
acc[type.id] = true
|
||||
return acc
|
||||
},
|
||||
{} as { [key: number]: boolean }
|
||||
),
|
||||
})
|
||||
{} as Record<number, boolean>
|
||||
)
|
||||
)
|
||||
|
||||
const filteredComponents = computed(() => {
|
||||
return components.filter((component) => {
|
||||
const isUsed = filters.showUsed && component.computerId !== null
|
||||
const isUnused = filters.showUnused && component.computerId === null
|
||||
const isTypeSelected = filters.types[component.type.id]
|
||||
const isUsed = usageFilters.value.used && component.computerId !== null
|
||||
const isUnused = usageFilters.value.unused && component.computerId === null
|
||||
const isTypeSelected = typeFilters.value[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">
|
||||
<!-- 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>
|
||||
<FilterDropdown
|
||||
v-model="usageFilters"
|
||||
label="Usage"
|
||||
:options="[
|
||||
{ id: 'unused', label: 'Unused' },
|
||||
{ id: 'used', label: 'Used' },
|
||||
]"
|
||||
/>
|
||||
<FilterDropdown v-model="typeFilters" label="Types" :options="typeOptions" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tableau des composants filtr├®s -->
|
||||
<TableComponent :components="filteredComponents" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -14,8 +14,8 @@ import {
|
||||
ssd,
|
||||
wiFiCard,
|
||||
} from '~/assets/icons'
|
||||
import Component from '#models/component'
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
import type Component from '#models/component'
|
||||
import { Link } from '@adonisjs/inertia/vue'
|
||||
|
||||
const props = defineProps<{
|
||||
components: Component[]
|
||||
@@ -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,106 +3,45 @@ import { noImagePlaceholder } from '~/assets/images'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
import Computer from '#models/computer'
|
||||
import ComputerCard from '~/pages/widgets/ComputerCard.vue'
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import FilterDropdown from '~/pages/widgets/FilterDropdown.vue'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const { computers } = usePage<{ computers: Computer[] }>().props
|
||||
const stateDropdownOpen = ref(false)
|
||||
|
||||
function toggleDropdown() {
|
||||
stateDropdownOpen.value = !stateDropdownOpen.value
|
||||
}
|
||||
|
||||
const filters = reactive({
|
||||
const filters = ref<Record<string, boolean>>({
|
||||
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 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
|
||||
const key = stateToFilterKey[computer.state.name]
|
||||
return key ? filters.value[key] : false
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<!-- Dropdown pour les filtres -->
|
||||
<div class="relative">
|
||||
<h4 class="text-xl underline">Filters</h4>
|
||||
<div class="flex gap-2">
|
||||
<!-- 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>
|
||||
<FilterDropdown
|
||||
v-model="filters"
|
||||
label="Usage"
|
||||
:options="[
|
||||
{ id: 'onGoing', label: 'On Going' },
|
||||
{ id: 'finished', label: 'Finished' },
|
||||
{ id: 'sold', label: 'Sold' },
|
||||
]"
|
||||
/>
|
||||
</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
|
||||
@@ -119,5 +58,3 @@ const filteredComputers = computed(() => {
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
@@ -0,0 +1,72 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: number | null
|
||||
options: { id: number; name: string }[]
|
||||
placeholder?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: number | null]
|
||||
}>()
|
||||
|
||||
const isOpen = ref(false)
|
||||
const dropdownRef = ref<HTMLElement | null>(null)
|
||||
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (dropdownRef.value && !dropdownRef.value.contains(e.target as Node)) {
|
||||
isOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => document.addEventListener('mousedown', handleClickOutside))
|
||||
onBeforeUnmount(() => document.removeEventListener('mousedown', handleClickOutside))
|
||||
|
||||
const selectedLabel = computed(() => {
|
||||
const selected = props.options.find((o) => o.id === props.modelValue)
|
||||
return selected?.name ?? props.placeholder ?? 'Select...'
|
||||
})
|
||||
|
||||
function select(id: number | null) {
|
||||
emit('update:modelValue', id)
|
||||
isOpen.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="dropdownRef" class="relative w-full">
|
||||
<button
|
||||
type="button"
|
||||
class="w-full mt-2 border border-gray-200 focus:border-indigo-600 focus:ring-1 focus:ring-indigo-500 px-3 py-2 rounded text-gray-700 bg-white font-body-md text-left flex items-center justify-between"
|
||||
@click="isOpen = !isOpen"
|
||||
>
|
||||
<span>{{ selectedLabel }}</span>
|
||||
<svg class="w-4 h-4 text-gray-400 shrink-0" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<ul
|
||||
v-show="isOpen"
|
||||
class="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-auto"
|
||||
>
|
||||
<li
|
||||
class="px-3 py-2 font-body-md text-sm cursor-pointer hover:bg-indigo-50 hover:text-indigo-700 transition-colors"
|
||||
:class="{ 'text-gray-400': modelValue === null }"
|
||||
@click="select(null)"
|
||||
>
|
||||
{{ placeholder ?? 'Select...' }}
|
||||
</li>
|
||||
<li
|
||||
v-for="option in options"
|
||||
:key="option.id"
|
||||
class="px-3 py-2 font-body-md text-sm cursor-pointer hover:bg-indigo-50 hover:text-indigo-700 transition-colors"
|
||||
:class="{ 'bg-indigo-50 text-indigo-700 font-medium': option.id === modelValue }"
|
||||
@click="select(option.id)"
|
||||
>
|
||||
{{ option.name }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,6 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
import { defineEmits, defineProps } from 'vue'
|
||||
|
||||
defineProps<{ show: boolean }>()
|
||||
const emit = defineEmits(['confirm', 'cancel'])
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<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>
|
||||
@@ -84,8 +84,7 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { crossIcon } from '~/assets/icons'
|
||||
import { Navigation, Pagination } from 'vue3-carousel'
|
||||
import { NewImage, ServerImage } from '../../../app/types/UItypes'
|
||||
import { Image } from '~/pages/types/UITypes'
|
||||
import type { Image, NewImage, ServerImage } from '~/pages/types/UITypes'
|
||||
|
||||
const props = defineProps<{
|
||||
galleryId: string
|
||||
@@ -134,12 +133,12 @@ function addImage() {
|
||||
|
||||
function removeImage(image: Image) {
|
||||
if ('id' in image) {
|
||||
const index = serverImages.value.findIndex((img) => img.id === image.id)
|
||||
const index = serverImages.value.findIndex((img: ServerImage) => img.id === image.id)
|
||||
if (index !== -1) {
|
||||
serverImages.value.splice(index, 1)
|
||||
}
|
||||
} else {
|
||||
const index = newImages.value.findIndex((img) => img.file === image.file)
|
||||
const index = newImages.value.findIndex((img: NewImage) => img.file === image.file)
|
||||
if (index !== -1) {
|
||||
newImages.value.splice(index, 1)
|
||||
}
|
||||
@@ -166,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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from '~/assets/icons'
|
||||
import { router } from '@inertiajs/vue3'
|
||||
import { useAdminMode } from '~/composables/isAdminMode'
|
||||
import Component from '#models/component'
|
||||
import type Component from '#models/component'
|
||||
|
||||
const props = defineProps<{
|
||||
components: Component[]
|
||||
@@ -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
+379
-170
File diff suppressed because it is too large.
Load diff
+2
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "pc-builderV2",
|
||||
"name": "pc-builder",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -42,6 +42,7 @@
|
||||
"@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",
|
||||
|
||||
@@ -6,6 +6,17 @@
|
||||
<title inertia>
|
||||
AdonisJS
|
||||
</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@400;600;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet" />
|
||||
<style>
|
||||
.material-symbols-outlined {
|
||||
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24;
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
</style>
|
||||
|
||||
@vite(['inertia/app.ts'])
|
||||
@inertiaHead()
|
||||
|
||||
@@ -20,6 +20,7 @@ export default await Env.create(new URL('../', import.meta.url), {
|
||||
|
||||
// App
|
||||
APP_KEY: Env.schema.secret(),
|
||||
APP_URL: Env.schema.string(),
|
||||
|
||||
// Session
|
||||
SESSION_DRIVER: Env.schema.enum(['cookie', 'memory', 'database'] as const),
|
||||
|
||||
@@ -30,6 +30,7 @@ router
|
||||
.group(() => {
|
||||
router.post('logout', [controllers.Session, 'destroy'])
|
||||
})
|
||||
.prefix('/auth')
|
||||
.use(middleware.auth())
|
||||
|
||||
router
|
||||
|
||||
+60
-1
@@ -6,7 +6,66 @@ export default {
|
||||
'./inertia/**/*.vue',
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
extend: {
|
||||
colors: {
|
||||
'primary': '#3525cd',
|
||||
'on-primary': '#ffffff',
|
||||
'primary-container': '#4f46e5',
|
||||
'on-primary-container': '#dad7ff',
|
||||
'secondary': '#565e74',
|
||||
'on-secondary': '#ffffff',
|
||||
'secondary-container': '#dae2fd',
|
||||
'on-secondary-container': '#5c647a',
|
||||
'tertiary': '#46494b',
|
||||
'on-tertiary': '#ffffff',
|
||||
'error': '#ba1a1a',
|
||||
'on-error': '#ffffff',
|
||||
'error-container': '#ffdad6',
|
||||
'on-error-container': '#93000a',
|
||||
'background': '#f8f9ff',
|
||||
'on-background': '#0b1c30',
|
||||
'surface': '#f8f9ff',
|
||||
'on-surface': '#0b1c30',
|
||||
'surface-variant': '#d3e4fe',
|
||||
'on-surface-variant': '#464555',
|
||||
'surface-dim': '#cbdbf5',
|
||||
'surface-bright': '#f8f9ff',
|
||||
'surface-container-lowest': '#ffffff',
|
||||
'surface-container-low': '#eff4ff',
|
||||
'surface-container': '#e5eeff',
|
||||
'surface-container-high': '#dce9ff',
|
||||
'surface-container-highest': '#d3e4fe',
|
||||
'inverse-surface': '#213145',
|
||||
'inverse-on-surface': '#eaf1ff',
|
||||
'inverse-primary': '#c3c0ff',
|
||||
'outline': '#777587',
|
||||
'outline-variant': '#c7c4d8',
|
||||
'surface-tint': '#4d44e3',
|
||||
},
|
||||
fontFamily: {
|
||||
'headline-lg': ['Hanken Grotesk'],
|
||||
'headline-md': ['Hanken Grotesk'],
|
||||
'headline-xl': ['Hanken Grotesk'],
|
||||
'body-lg': ['Inter'],
|
||||
'body-md': ['Inter'],
|
||||
'body-sm': ['Inter'],
|
||||
'label-md': ['JetBrains Mono'],
|
||||
'label-sm': ['JetBrains Mono'],
|
||||
},
|
||||
fontSize: {
|
||||
'headline-lg': ['28px', { lineHeight: '36px', letterSpacing: '-0.01em', fontWeight: '600' }],
|
||||
'headline-md': ['20px', { lineHeight: '28px', fontWeight: '600' }],
|
||||
'headline-xl': ['36px', { lineHeight: '44px', letterSpacing: '-0.02em', fontWeight: '700' }],
|
||||
'body-lg': ['18px', { lineHeight: '28px', fontWeight: '400' }],
|
||||
'body-md': ['16px', { lineHeight: '24px', fontWeight: '400' }],
|
||||
'body-sm': ['14px', { lineHeight: '20px', fontWeight: '400' }],
|
||||
'label-md': ['14px', { lineHeight: '20px', letterSpacing: '0.02em', fontWeight: '500' }],
|
||||
'label-sm': ['12px', { lineHeight: '16px', letterSpacing: '0.05em', fontWeight: '500' }],
|
||||
},
|
||||
spacing: {
|
||||
'sidebar-width': '280px',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
} satisfies Config
|
||||
+17
-2
@@ -1,9 +1,13 @@
|
||||
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
|
||||
@@ -13,7 +17,15 @@ import testUtils from '@adonisjs/core/services/test_utils'
|
||||
* Configure Japa plugins in the plugins array.
|
||||
* Learn more - https://japa.dev/docs/runner-config#plugins-optional
|
||||
*/
|
||||
export const plugins: Config['plugins'] = [assert(), pluginAdonisJS(app), dbAssertions(app)]
|
||||
export const plugins: Config['plugins'] = [
|
||||
assert(),
|
||||
apiClient(),
|
||||
sessionApiClient(app),
|
||||
authApiClient(app),
|
||||
shieldApiClient(),
|
||||
pluginAdonisJS(app),
|
||||
dbAssertions(app),
|
||||
]
|
||||
|
||||
/**
|
||||
* Configure lifecycle function to run before and after all the
|
||||
@@ -33,6 +45,9 @@ export const runnerHooks: Required<Pick<Config, 'setup' | 'teardown'>> = {
|
||||
*/
|
||||
export const configureSuite: Config['configureSuite'] = (suite) => {
|
||||
if (['browser', 'functional', 'e2e'].includes(suite.name)) {
|
||||
return suite.setup(() => testUtils.httpServer().start())
|
||||
suite.setup(() => testUtils.httpServer().start())
|
||||
suite.onGroup((group) => {
|
||||
group.each.setup(() => testUtils.db().withGlobalTransaction())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,198 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
Whitespace-only changes.
Reference in new issue
Block a user