ldc-nature-eleveurs/app/Models/User.php

92 lines
2.8 KiB
PHP
Raw Permalink Normal View History

2022-08-09 12:29:21 +00:00
<?php
namespace App\Models;
2024-01-31 16:42:01 +01:00
use App\Enums\Users\RoleEnum;
use App\Traits\Models\ActivityLog;
use Illuminate\Auth\Access\AuthorizationException;
2022-08-09 12:29:21 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
2024-01-31 16:42:01 +01:00
/**
* @property string $first_name Firstname.
* @property string $last_name Lastname.
* @property string $email Email.
* @property \App\Enums\Users\RoleEnum $role Role.
* @property bool $published Published status.
2024-01-31 16:42:01 +01:00
* @property \Illuminate\Support\Carbon $published_at Publication status update date.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*/
2022-08-09 12:29:21 +00:00
class User extends Authenticatable
{
2024-01-31 16:42:01 +01:00
use ActivityLog;
2022-08-09 12:29:21 +00:00
use HasFactory;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
2022-08-09 12:29:21 +00:00
*/
protected $fillable = [
2024-01-31 16:42:01 +01:00
'first_name',
'last_name',
2022-08-09 12:29:21 +00:00
'email',
2024-01-31 16:42:01 +01:00
'role',
'published',
'published_at',
2022-08-09 12:29:21 +00:00
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
2024-01-31 16:42:01 +01:00
'role' => RoleEnum::class,
'published' => 'boolean',
'published_at' => 'datetime',
2022-08-09 12:29:21 +00:00
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
2024-01-31 16:42:01 +01:00
protected static function booted(): void
2022-08-09 12:29:21 +00:00
{
2024-01-31 16:42:01 +01:00
static::creating(function (self $model) {
// * Prevent user elevation privileges
throw_if(
auth('backend')->user() and auth('backend')->user()->role->value() > $model->role->value(),
AuthorizationException::class
);
2022-08-09 12:29:21 +00:00
});
2024-01-31 16:42:01 +01:00
static::updating(function (self $model) {
if (optional(auth('backend')->user())->getKey() === $model->getKey()) {
\validator(
['published' => $model->published],
['published' => 'required|boolean|accepted'],
['published.accepted' => trans('crud.messages.user_unpublished')],
)->validate();
2022-08-09 12:29:21 +00:00
}
2024-01-31 16:42:01 +01:00
// * Prevent user elevation privileges
throw_if(
auth('backend')->user() and auth('backend')->user()->role->value() > $model->role->value(),
AuthorizationException::class
);
2022-08-09 12:29:21 +00:00
});
}
}