103 lines
2.8 KiB
PHP
103 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
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;
|
|
|
|
/**
|
|
* Class Usuario
|
|
*
|
|
* @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
|
|
*
|
|
*/
|
|
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();
|
|
} else {
|
|
return Usuario::where('id', $id)->first();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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');
|
|
}
|
|
|
|
public function administrador() {
|
|
return $this->hasOne(Administrador::class);
|
|
}
|
|
|
|
public function recaudador() {
|
|
return $this->hasOne(Recaudador::class);
|
|
}
|
|
|
|
public function mesero() {
|
|
return $this->hasOne(Mesero::class);
|
|
}
|
|
|
|
public function productor() {
|
|
return $this->hasOne(Productor::class);
|
|
}
|
|
|
|
public function getRolesAttribute() {
|
|
$auth0Service = app(Auth0Service::class);
|
|
$auth0User = $auth0Service->getUser($this->auth0_id);
|
|
return $this->attributes['roles'] = array_key_exists('app_metadata', $auth0User) ? $auth0User['app_metadata']['roles'] : [];
|
|
}
|
|
}
|