Movidas validaciones de usuario al modelo de usuario

This commit is contained in:
2021-04-30 02:51:08 -04:00
parent 2510261b63
commit d3c7c81661
2 changed files with 78 additions and 44 deletions

View File

@@ -6,6 +6,7 @@ use App\Services\Auth0Service;
use App\Traits\UuidPrimaryKey;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use phpDocumentor\Reflection\Types\Boolean;
use Ramsey\Uuid\Uuid;
/**
@@ -14,9 +15,12 @@ use Ramsey\Uuid\Uuid;
* @property $id
* @property $auth0_id
* @property $nombre
* @property $roles
* @property $restaurantes
*
* @method static find($id)
* @method static where(string $string, $sub)
* @method static create(array $array)
*
* @package App\Models
*
@@ -25,8 +29,14 @@ class Usuario extends Model {
use UuidPrimaryKey, SoftDeletes;
protected $table = 'usuarios';
protected $fillable = ['id', 'auth0_id', 'nombre'];
protected $appends = ['roles'];
/**
* Busca un usuario según su id o auth_0 id, dependiendo del formato entregado en $id
* @param $id
* @return Usuario
*/
public static function findByIdOrAuth0Id($id) {
if (str_starts_with($id, 'auth0')) {
return Usuario::where('auth0_id', urldecode($id))->first();
@@ -35,6 +45,35 @@ class Usuario extends Model {
}
}
/**
* Valida que el usuario tiene permisos sobre otro usuario
* @param $user
* @return bool
*/
public function hasPermissionsOverUser($user) {
if (in_array('global_admin', $this->roles)) return true;
if (!in_array('admin', $this->roles)) return false;
if ($this->restaurantes->intersect($user->restaurantes)->count() > 0) return true;
return false;
}
/**
* Valida que el usuario tiene permisos en un restaurant
* @param $restaurant
* @return bool
*/
public function hasPermissionsOnRestaurant($restaurant) {
if (in_array('global_admin', $this->roles)) return true;
if ($this->restaurantes->contains($restaurant)) return true;
return false;
}
public function canManageUsers() {
if (in_array('global_admin', $this->roles)) return true;
if (in_array('admin', $this->roles)) return true;
return false;
}
public function restaurantes() {
return $this->belongsToMany(Restaurante::class, 'usuarios_restaurantes', 'usuario_id', 'restaurante_id');
}