Files
unified-restaurant-original/backend/app/Models/Usuario.php

68 lines
1.9 KiB
PHP

<?php
namespace App\Models;
use App\Services\Auth0Service;
use App\Traits\UuidPrimaryKey;
use App\Exceptions\ModelNotFoundException;
use App\Exceptions\HasNoPermissionsOnRestaurantException;
use App\Exceptions\CantManageRestaurantsException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Log;
class Usuario extends Model {
use UuidPrimaryKey, SoftDeletes;
protected $table = 'usuarios';
protected $fillable = ['id', 'auth0_id', 'nombre'];
protected $appends = ['roles'];
/**
* Busca un usuario o envia una excepcion si no se encuentra
*/
public static function findOrFail($id) {
if (str_starts_with($id, 'auth0')) $usuario = Usuario::where('auth0_id', urldecode($id));
else $usuario = Usuario::where('id', $id);
if(!$usuario) throw new ModelNotFoundException("usuario", $id);
return $usuario->first();
}
public function isGlobalAdmin() {
return in_array('global_admin', $this->roles);
}
public function isAdmin() {
return in_array('admin', $this->roles);
}
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'] : [];
}
}