Compare commits

...

6 Commits

Author SHA1 Message Date
93d1340c1c Merge branch 'develop' into fix/-style-global
# Conflicts:
#	.idea/workspace.xml
#	frontend/layouts/default.vue
2026-02-09 16:09:19 +01:00
e06636bc15 fix : style global de l'app 2026-02-09 16:08:29 +01:00
gitea-actions
d3dfde7060 chore: bump version to v0.0.36
All checks were successful
Auto Tag Develop / tag (push) Successful in 4s
Build Release Artefact / build (push) Successful in 1m13s
2026-02-09 15:04:23 +00:00
90c2cfc665 [#317] Création d'une page d'administration : modification/création d'un transporteur (!18)
All checks were successful
Auto Tag Develop / tag (push) Successful in 5s
| Numéro du ticket | Titre du ticket |
|------------------|-----------------|
|           #317       |      Création d'une page d'administration : modification/création d'un transporteur           |

## Description de la PR

## Modification du .env

## Check list

- [x] Pas de régression
- [ ] TU/TI/TF rédigée
- [x] TU/TI/TF OK
- [x] CHANGELOG modifié

Reviewed-on: #18
Reviewed-by: Autin <tristan@yuno.malio.fr>
Co-authored-by: sroy <sebastien@yuno.malio.fr>
Co-committed-by: sroy <sebastien@yuno.malio.fr>
2026-02-09 15:04:16 +00:00
gitea-actions
9fc3e2f9bc chore: bump version to v0.0.35
All checks were successful
Auto Tag Develop / tag (push) Successful in 4s
Build Release Artefact / build (push) Successful in 1m13s
2026-02-09 14:58:25 +00:00
329bb4cee5 [#315] Création d'une page d'administration : modification/création d'un utilisateur (!17)
All checks were successful
Auto Tag Develop / tag (push) Successful in 5s
| Numéro du ticket | Titre du ticket |
|------------------|-----------------|
|         315         |       Création d'une page d'administration : modification/création d'un utilisateur          |

## Description de la PR

## Modification du .env

## Check list

- [x] Pas de régression
- [ ] TU/TI/TF rédigée
- [x] TU/TI/TF OK
- [x] CHANGELOG modifié

Reviewed-on: #17
Reviewed-by: Autin <tristan@yuno.malio.fr>
Co-authored-by: kevin <kevin@yuno.malio.fr>
Co-committed-by: kevin <kevin@yuno.malio.fr>
2026-02-09 14:58:20 +00:00
26 changed files with 587 additions and 96 deletions

4
.idea/dataSources.xml generated
View File

@@ -5,7 +5,7 @@
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://localhost:5432/ferme</jdbc-url>
<jdbc-url>jdbc:postgresql://localhost:5433/ferme</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="Ferme recette" uuid="ae622167-c834-4e7b-87a5-c1721036f5dc">
@@ -16,4 +16,4 @@
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>
</project>

10
.idea/data_source_mapping.xml generated Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourcePerFileMappings">
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/f407a514-c6b4-4b26-9555-445a85892502/console.sql" value="f407a514-c6b4-4b26-9555-445a85892502" />
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/f407a514-c6b4-4b26-9555-445a85892502/console_1.sql" value="f407a514-c6b4-4b26-9555-445a85892502" />
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/f407a514-c6b4-4b26-9555-445a85892502/console_2.sql" value="f407a514-c6b4-4b26-9555-445a85892502" />
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/f407a514-c6b4-4b26-9555-445a85892502/console_3.sql" value="f407a514-c6b4-4b26-9555-445a85892502" />
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/f407a514-c6b4-4b26-9555-445a85892502/console_4.sql" value="f407a514-c6b4-4b26-9555-445a85892502" />
</component>
</project>

2
.idea/workspace.xml generated
View File

@@ -778,4 +778,4 @@
<option value=".github/prompts" />
</promptFileLocations>
</component>
</project>
</project>

View File

@@ -31,6 +31,8 @@ Ajouter dans le fichier .env du frontend
* [#268] Lister les réceptions terminées
* [#316] Admin liste des transporteurs
* [#312] Creation administration listing fournisseurs
* [#315] Creation page admin utilisateur
* [#317] Admin modification creation transporteur
### Changed

View File

@@ -1,2 +1,2 @@
parameters:
app.version: '0.0.34'
app.version: '0.0.36'

View File

@@ -0,0 +1,123 @@
<template>
<form @submit.prevent="validate">
<div
class="flex items-center justify-between gap-10">
<h1 class="text-3xl font-bold uppercase">
{{ userId ? "Modifications de l'utilisateur" : "Ajout d'un utilisateur" }}
</h1>
<button
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit"
>
{{ userId ? 'Sauvegarder' : 'Ajouter' }}
</button>
</div>
<div class="grid gap-y-16 gap-x-40 mb-16">
<UiTextInput
id="user-name"
v-model="form.username"
label="Nom de l'utilisateur"
/>
<UiSelect
id="user-role"
v-model="form.role"
label="Rôle de l'utilisateur"
:options="ROLE"
/>
<UiTextInput
id="user-password"
v-model="form.password"
label="Mot de passe"
type="password"
/>
</div>
</form>
</template>
<script setup lang="ts">
import {computed, reactive, ref, watch} from 'vue'
import {ROLE} from '~/utils/constants'
import {createUser, updateUser, getUser} from '~/services/auth'
import type {UserData, UserFormData} from '~/services/dto/user-data'
const route = useRoute()
const router = useRouter()
const userId = computed(() => resolveUserId(route.params.id))
const isLoading = ref(false)
const isHydrating = ref(false)
const resolveUserId = (param: unknown) => {
const idStr = Array.isArray(param) ? param[0] : param
if (!idStr) {
return null
}
const id = Number(idStr)
return Number.isFinite(id) ? id : null
}
const form = reactive<UserFormData>({
username: '',
password: '',
role: ''
})
const hydrateFromUser = (user: UserData | null) => {
if (!user) {
return
}
isHydrating.value = true
form.username = user.username ?? ''
const roles = user.roles ?? []
const hasAdmin = roles.includes("ROLE_ADMIN")
form.role = hasAdmin ? "ROLE_ADMIN" : "ROLE_USER"
form.password = ''
isHydrating.value = false
}
watch(
() => userId.value,
async (id) => {
if (id === null) {
return
}
isLoading.value = true
try {
const user = await getUser(id)
hydrateFromUser(user)
} finally {
isLoading.value = false
}
},
{immediate: true}
)
async function validate() {
const normalizedUsername = form.username.trim()
const normalizedRole = form.role.trim()
const normalizedPassword = form.password.trim()
const basePayload = {
username: normalizedUsername,
roles: normalizedRole ? [normalizedRole] : undefined,
password: normalizedPassword || undefined
}
if (userId.value) {
await updateUser(userId.value, basePayload)
await router.push(`/admin/user/list/`)
return
}
const created = await createUser(basePayload)
if (created) {
await router.push(`/admin/user/list/`)
}
}
</script>

View File

@@ -46,7 +46,11 @@
"list": "Impossible de récupérer la liste des races de bovins."
},
"carrier": {
"list": "Impossible de récupérer la liste des transporteurs."
"list": "Impossible de récupérer la liste des transporteurs.",
"fetch": "Impossible de récupérer les données du transporteur",
"update": "Impossible de mettre à jour le transporteur",
"create": "Impossible de créer le transporteur"
},
"driver": {
"list": "Impossible de récupérer la liste des chauffeurs."
@@ -57,7 +61,9 @@
"auth": {
"login": "Identifiants invalides.",
"users": "Impossible de récupérer les utilisateurs.",
"logout": "Impossible de se déconnecter."
"logout": "Impossible de se déconnecter.",
"update": "Impossible de mettre à jour l'utilisateur.",
"create": "Impossible de créer l'utilisateur."
}
},
"success": {
@@ -65,8 +71,14 @@
"update": "Réception mise à jour avec succès."
},
"auth": {
"update": "Utilisateur mis à jour avec succès.",
"create": "Utilisateur créé avec succès.",
"login": "Connexion réussie.",
"logout": "Déconnexion réussie."
},
"carrier": {
"update": "Transporteur mis à jour",
"create": "Transporteur créé"
}
}
}

View File

@@ -33,9 +33,13 @@
<NuxtLink to="/admin/carrier/carrier-list">
Transporteur
</NuxtLink>
<NuxtLink to="/admin/user/list">
Utilisateurs
</NuxtLink>
</div>
<div class="p-4">
<p class="font-bold text-white text-left">v{{ version }}</p>
<button
@click="handleLogout"
class="w-full bg-red-600 hover:bg-red-700 py-2 rounded font-bold"
@@ -56,7 +60,10 @@
<script setup lang="ts">
import {useAuthStore} from '~/stores/auth'
const auth = useAuthStore()
const { version } = useAppVersion()
const handleLogout = async () => {
try {
await auth.logout()

View File

@@ -1,5 +1,5 @@
<template>
<div class="min-h-screen bg-white text-neutral-900">
<div class="min-h-screen bg-white text-neutral-900 flex flex-col">
<header class="w-full border-b border-neutral-200 bg-primary-500">
<div class="flex w-full items-center justify-center px-6 py-4">
<button
@@ -20,10 +20,11 @@
Accueil
</a>
</NuxtLink>
<NuxtLink to="/admin/dashboard" custom v-slot="{ href, navigate, isActive }">
<NuxtLink to="/admin/dashboard" custom v-slot="{ href, navigate, isExactActive }">
<a
:href="href"
@click="navigate"
:class="isExactActive ? 'opacity-100' : 'opacity-50'"
>
Admin
</a>
@@ -97,7 +98,7 @@
</aside>
</transition>
</header>
<main class="mx-auto w-full max-w-[1280px] pb-0">
<main class="mx-auto w-full max-w-[1280px] flex-1 pb-0">
<slot/>
</main>
<footer class="w-full mt-8 bg-primary-500 p-6">
@@ -107,27 +108,27 @@
</template>
<script setup lang="ts">
import { useAuthStore } from '~/stores/auth'
import {useAuthStore} from '~/stores/auth'
const route = useRoute()
const auth = useAuthStore()
const isMenuOpen = ref(false)
const { version } = useAppVersion()
const {version} = useAppVersion()
const closeMenu = () => {
isMenuOpen.value = false
isMenuOpen.value = false
}
const toggleMenu = () => {
isMenuOpen.value = !isMenuOpen.value
isMenuOpen.value = !isMenuOpen.value
}
const handleLogout = async () => {
try {
await auth.logout()
} finally {
closeMenu()
await navigateTo('/login')
}
try {
await auth.logout()
} finally {
closeMenu()
await navigateTo('/login')
}
}
</script>

View File

@@ -0,0 +1,101 @@
<template>
<form @submit.prevent="validate">
<div class="flex items-center justify-between ">
<h1 class="text-3xl font-bold uppercase">
{{ route.params.id ? 'Modifier transporteur' : 'Ajout transporteur' }}
</h1>
<button
type="submit"
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
>Enregistrer
</button>
</div>
<div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 mb-16">
<UiTextInput
label = "nom du fournisseur"
id="carrier-name"
v-model="form.name"
/>
<UiTextInput
label = "code fournisseur"
id="code-id"
v-model="form.code"
/>
</div>
</form>
</template>
<script setup lang="ts">
import {createCarrier, getCarrier, updateCarrier} from "~/services/carrier";
import type {CarrierData, CarrierFormData} from "~/services/dto/carrier-data";
const router = useRouter()
const route = useRoute()
const idCarrier = Number(route.params.id)
const isLoading = ref(false)
const isHydrating = ref(false)
const form = reactive<CarrierFormData>({
code:'',
name:''
})
definePageMeta({
layout: 'admin'
})
const hydrateFromUser = (carrier: CarrierData | null) => {
if (!carrier) {
return
}
isHydrating.value = true
form.name = carrier.name ?? ''
form.code = carrier.code ?? ''
isHydrating.value = false
}
watch(
() => idCarrier,
async (id) => {
if (id === null) {
return
}
isLoading.value = true
try {
const user = await getCarrier(id)
hydrateFromUser(user)
} finally {
isLoading.value = false
}
},
{immediate: true}
)
async function validate() {
const normalizedCarrierCode = form.code.trim()
const normalizedCarrierName = form.name.trim()
const basePayload = {
name: normalizedCarrierName,
code: normalizedCarrierCode
}
if(idCarrier){
await updateCarrier(idCarrier, basePayload)
navigate()
return
}
await createCarrier(basePayload)
navigate()
}
function navigate(){
router.push("/admin/carrier/carrier-list")
}
</script>

View File

@@ -2,11 +2,11 @@
<div class="flex items-center justify-between ">
<h1 class="text-3xl font-bold uppercase">listes des transporteurs</h1>
<button
@Click="goToCarrier()"
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] "
<NuxtLink
to="/admin/carrier"
class="flex items-center justify-center text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
>Ajouter
</button>
</NuxtLink>
</div>
<div class="mt-6 border border-slate-200 mb-16 ">
@@ -37,8 +37,8 @@ import {getCarrierList} from "~/services/carrier";
const carrierList = ref<CarrierData[]>()
const router = useRouter()
const goToCarrier = (id: number|null = null) => {
id !== null ? router.push(`/admin/carrier/${id}`) : router.push(`/admin/carrier`)
const goToCarrier = (id: number) => {
router.push(`/admin/carrier/${id}`)
}
definePageMeta({

View File

@@ -1,13 +1,9 @@
<template>
<AdminUserForm/>
</template>
<script setup lang="ts">
definePageMeta({
layout: 'admin'
})
</script>
<template>
<h1>test</h1>
</template>
<style scoped>
</style>

View File

@@ -0,0 +1,8 @@
<template>
<UserForm/>
</template>
<script setup lang="ts">
definePageMeta({
layout: 'admin'
})
</script>

View File

@@ -0,0 +1,57 @@
<template>
<div class="flex items-center justify-between">
<h1 class="text-3xl font-bold uppercase">Liste des utilisateurs</h1>
<NuxtLink
class="flex items-center justify-center text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
@click="router.push('/admin/user/')"
>
Ajouter
</NuxtLink>
</div>
<div>
<div class="mt-6 border border-slate-200 mb-16 ">
<div class="grid grid-cols-3 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
<div>Username</div>
<div>Role</div>
</div>
<div
v-for="user in userList"
:key="user.id"
class="grid grid-cols-3 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t items-center"
role="button"
tabindex="0"
@click="goToUser(user.id)"
>
<div>
{{ user.username }}
</div>
<div>
{{ user.roles?.join(', ') || ' ---' }}
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
definePageMeta({
layout: 'admin'
})
import type {UserData} from "~/services/dto/user-data";
import {getAdminUsers, getUsers} from "~/services/auth";
const userList = ref<UserData[]>([])
const router = useRouter()
const goToUser = (id: number) => {
router.push(`/admin/user/${id}`)
}
onMounted(async () => {
userList.value = await getAdminUsers()
})
</script>

View File

@@ -1,6 +1,6 @@
<template>
<div>
<div class="flex justify-between h-[52px] mb-[80px]">
<div class="flex justify-between h-[52px] mb-[80px] mt-16">
<div class="flex flex-1 mr-16">
<UiStepper
:labels="RECEPTION_STEP_LABELS"

View File

@@ -1,5 +1,5 @@
<template>
<div class="flex items-center justify-start gap-10">
<div class="flex items-center justify-start gap-10 mt-16 cursor-pointer">
<Icon @click="router.push('/')" name="gg:arrow-left-o" style="color: black" size="44" />
<h1 class="text-3xl font-bold uppercase">listes des réceptions finie</h1>
</div>

View File

@@ -1,5 +1,5 @@
<template>
<div class="flex items-center justify-between ">
<div class="flex items-center justify-between mt-16 cursor-pointer">
<div class="flex items-center gap-10">
<Icon @click="router.push('/')" name="gg:arrow-left-o" style="color: black" size="44" />
<h1 class="text-3xl font-bold uppercase">listes des réceptions en attente</h1>

View File

@@ -1,5 +1,6 @@
import { useApi } from '~/composables/useApi'
import type { UserData } from '~/services/dto/user-data'
import type {UserPayload} from "~/services/dto/user-data";
export async function getUsers() {
const api = useApi()
@@ -12,7 +13,40 @@ export async function getUsers() {
return data['hydra:member'] ?? []
}
export async function getAdminUsers() {
const api = useApi()
const data = await api.get<UserData[] | { 'hydra:member': UserData[] }>('admin/users', {}, {
toastErrorKey: 'errors.auth.users'
})
if (Array.isArray(data)) {
return data
}
return data['hydra:member'] ?? []
}
export async function getUser(id: number) {
const api = useApi()
return api.get<UserData>(`users/${id}`, {}, {
toastErrorKey: 'errors.auth.user'
})
}
export async function createUser(payload: UserPayload = {}) {
const api = useApi()
return api.post<UserData>('users', payload, {
toastErrorKey: 'errors.auth.create',
toastSuccessKey : 'success.auth.create'
})
}
export async function updateUser(id : number, playload: UserPayload = {}){
const api = useApi()
return api.patch<UserData>(`users/${id}`, playload, {
toastErrorKey: 'errors.auth.update',
toastSuccessKey: 'success.auth.update'
})
}
export async function getCurrentUser() {
const api = useApi()
return api.get<UserData>('me', {}, {

View File

@@ -1,5 +1,5 @@
import { useApi } from '~/composables/useApi'
import type { CarrierData } from '~/services/dto/carrier-data'
import type {CarrierData, CarrierPayload} from "~/services/dto/carrier-data";
export type CarrierListResponse =
| CarrierData[]
@@ -21,3 +21,26 @@ export async function getCarrierList(): Promise<CarrierData[]> {
return []
}
export async function getCarrier(id: number) {
const api = useApi()
return api.get<CarrierData>(`carriers/${id}`, {}, {
toastErrorKey: 'errors.carrier.fetch'
})
}
export async function updateCarrier(id: number, payload: CarrierPayload) {
const api = useApi()
return api.patch<CarrierData>(`carriers/${id}`, payload, {
toastErrorKey: 'errors.carrier.update',
toastSuccessKey: 'success.carrier.update'
})
}
export async function createCarrier(payload: CarrierPayload = {}) {
const api = useApi()
return api.post<CarrierData>('carriers', payload, {
toastErrorKey: 'errors.carrier.create',
toastSuccessKey: 'success.carrier.update'
})
}

View File

@@ -3,3 +3,13 @@ export interface CarrierData {
name: string
code: string
}
export interface CarrierFormData {
name: string
code: string
}
export type CarrierPayload = {
name?: string | null
code?: string
}

View File

@@ -1,4 +1,17 @@
export interface UserData {
id: number
username: string
roles: string[]
}
export type UserPayload = {
username?: string
password?: string
roles?: string[]
}
export type UserFormData = {
username: string
password: string
role: string
}

View File

@@ -1,63 +1,80 @@
import { defineStore } from 'pinia'
import type { UserData } from '~/services/dto/user-data'
import { getCurrentUser, login, logout } from '~/services/auth'
import {defineStore} from 'pinia'
import type {UserData} from '~/services/dto/user-data'
import {getCurrentUser, createUser, login, logout} from '~/services/auth'
import type {UserPayload} from "~/services/dto/user-data";
import {ROLE} from '~/utils/constants'
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null as UserData | null,
isLoading: false,
checked: false
}),
getters: {
isAuthenticated: (state) => Boolean(state.user)
},
actions: {
clearSession() {
this.user = null
this.checked = true
this.isLoading = false
state: () => ({
user: null as UserData | null,
isLoading: false,
checked: false
}),
getters: {
isAuthenticated: (state) => Boolean(state.user),
isAdmin: (state) => Boolean(state.user?.roles?.includes(ROLE[0].value))
},
async ensureSession() {
if (this.checked) {
return this.user
}
actions: {
clearSession() {
this.user = null
this.checked = true
this.isLoading = false
},
async ensureSession() {
if (this.checked) {
return this.user
}
this.checked = true
this.checked = true
try {
const me = await getCurrentUser()
this.user = me
return me
} catch {
this.user = null
return null
}
},
async login(username: string, password: string) {
this.isLoading = true
try {
const me = await getCurrentUser()
this.user = me
return me
} catch {
this.user = null
return null
}
},
async login(username: string, password: string) {
this.isLoading = true
try {
await login(username, password)
const me = await getCurrentUser()
this.user = me
this.checked = true
return me
} finally {
this.isLoading = false
}
},
async logout() {
this.isLoading = true
try {
await login(username, password)
const me = await getCurrentUser()
this.user = me
this.checked = true
return me
} finally {
this.isLoading = false
}
},
async createUser(payload: UserPayload = {}) {
this.isLoading = true
const result = await createUser(payload).finally(() => {
this.isLoading = false
})
return result
},
async updateUser(id: number, payload: UserPayload) {
this.isLoading = true
const result = await createUser(payload).finally(() => {
this.isLoading = false
})
return result
},
async logout() {
this.isLoading = true
try {
await logout()
} catch {
// Ignore logout errors so we can still clear local auth state.
} finally {
this.user = null
this.checked = true
this.isLoading = false
}
try {
await logout()
} catch {
// Ignore logout errors so we can still clear local auth state.
} finally {
this.user = null
this.checked = true
this.isLoading = false
}
},
}
}
})

View File

@@ -8,6 +8,10 @@ export const MERCHANDISE_TYPE_CODES = {
AUTRES: 'AUTRES'
} as const
export const ROLE = [
{ label: 'Administrateur', value: 'ROLE_ADMIN' },
{ label: 'Utilisateur', value: 'ROLE_USER' }
]
export const SUPLLIER_CODE = {
LIOT: 'LIOT'
}

View File

@@ -7,6 +7,8 @@ namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
@@ -21,6 +23,15 @@ use Symfony\Component\Serializer\Attribute\Groups;
new GetCollection(
normalizationContext: ['groups' => ['carrier:read']],
),
new Post(
normalizationContext: ['groups' => ['carrier:read']],
denormalizationContext: ['groups' => ['carrier:write']],
),
new Patch(
requirements: ['id' => '\d+'],
normalizationContext: ['groups' => ['carrier:read']],
denormalizationContext: ['groups' => ['carrier:write']],
),
],
security: "is_granted('ROLE_USER')",
)]
@@ -33,11 +44,11 @@ class Carrier
private ?int $id = null;
#[ORM\Column(length: 180)]
#[Groups(['carrier:read', 'driver:read', 'vehicle:read', 'reception:read'])]
#[Groups(['carrier:read', 'carrier:write', 'driver:read', 'vehicle:read', 'reception:read'])]
private string $name = '';
#[ORM\Column(length: 30, nullable: true)]
#[Groups(['carrier:read', 'driver:read', 'vehicle:read', 'reception:read'])]
#[Groups(['carrier:read', 'carrier:write', 'driver:read', 'vehicle:read', 'reception:read'])]
private ?string $code = null;
public function getId(): ?int

View File

@@ -7,7 +7,10 @@ namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use App\State\MeProvider;
use App\State\UserPasswordProcessor;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
@@ -28,10 +31,27 @@ use Symfony\Component\Serializer\Attribute\Groups;
normalizationContext: ['groups' => ['user:read']],
security: "is_granted('ROLE_USER')"
),
new GetCollection(
new Post(
normalizationContext: ['groups' => ['user:read']],
denormalizationContext: ['groups' => ['user:write']],
security: "is_granted('ROLE_ADMIN')",
processor: UserPasswordProcessor::class
),
new Patch(
normalizationContext: ['groups' => ['user:read']],
denormalizationContext: ['groups' => ['user:write']],
security: "is_granted('ROLE_ADMIN')",
processor: UserPasswordProcessor::class
),
new GetCollection(
normalizationContext: ['groups' => ['user-login:read']],
security: "is_granted('PUBLIC_ACCESS')"
),
new GetCollection(
uriTemplate: '/admin/users',
normalizationContext: ['groups' => ['user:read']],
security: "is_granted('ROLE_ADMIN')"
),
],
normalizationContext: ['groups' => ['user:read']],
paginationEnabled: false
@@ -41,17 +61,19 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
#[Groups(['user:read', 'reception:read'])]
#[Groups(['user:read', 'user-login:read', 'reception:read'])]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
#[Groups(['user:read', 'reception:read'])]
#[Groups(['user:read', 'user:write', 'user-login:read', 'reception:read'])]
private string $username = '';
#[ORM\Column(type: 'json')]
#[Groups(['user:write', 'user:read'])]
private array $roles = [];
#[ORM\Column]
#[Groups(['user:write'])]
private string $password = '';
public function getId(): ?int

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\User;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
final class UserPasswordProcessor implements ProcessorInterface
{
public function __construct(
private readonly UserPasswordHasherInterface $hasher,
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
private readonly ProcessorInterface $persistProcessor
) {}
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
if ($data instanceof User) {
$plain = $data->getPassword();
if ('' !== $plain) {
$data->setPassword($this->hasher->hashPassword(
$data,
$plain
));
}
}
return $this->persistProcessor->process(
$data,
$operation,
$uriVariables,
$context
);
}
}