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

@@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Restaurante;
use App\Models\Usuario; use App\Models\Usuario;
use App\Services\Auth0Service; use App\Services\Auth0Service;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -54,25 +55,24 @@ class UsuariosController extends Controller {
'restaurant' => 'required|exists:restaurantes,id', 'restaurant' => 'required|exists:restaurantes,id',
]); ]);
$restaurant = $request->input('restaurant'); /** @var Usuario $logged_user */
$logged_user = $request->user;
// solo un global admin puede crear usuarios en cualquier restaurant $restaurant = Restaurante::find($request->input('restaurant'));
if (!in_array('global_admin', $request->user->roles)) {
// si el usuario no es administrador no puede crear usuarios if (!$logged_user->canManageUsers()) {
if (!in_array('admin', $request->user->roles)) {
return response()->json([ return response()->json([
'error' => 'not_allowed', 'error' => 'not_allowed',
'message' => 'El usuario no puede tiene permisos para crear usuarios' 'message' => 'El usuario no tiene permisos para crear usuarios'
], 403); ], 403);
} }
// los administradores solo pueden crear usuarios en su propio restaurant
if (!$request->user->restaurantes->contains($restaurant)) { if (!$logged_user->hasPermissionsOnRestaurant($restaurant)) {
return response()->json([ return response()->json([
'error' => 'not_allowed', 'error' => 'not_allowed',
'message' => 'El usuario no puede crear un usuario en un restaurant al que no pertenece' 'message' => 'El usuario no puede crear un usuario en un restaurant al que no pertenece'
], 403); ], 403);
} }
}
$auth0 = app(Auth0Service::class); $auth0 = app(Auth0Service::class);
$auth0User = $auth0->createUser( $auth0User = $auth0->createUser(
@@ -92,13 +92,11 @@ class UsuariosController extends Controller {
], $auth0User['statusCode']); ], $auth0User['statusCode']);
} }
$usuario = new Usuario(); $usuario = $restaurant->usuarios()->create([
$usuario->id = Uuid::uuid4(); 'id' => Uuid::uuid4(),
$usuario->auth0_id = $auth0User['identities'][0]['provider'] . '|' . $auth0User['identities'][0]['user_id']; 'auth0_id' => $auth0User['identities'][0]['provider'] . '|' . $auth0User['identities'][0]['user_id'],
$usuario->nombre = $request->input('nombre'); 'nombre' => $request->input('nombre')
$usuario->save(); ]);
$usuario->restaurantes()->attach($restaurant);
return response()->json(["usuario" => $usuario]); return response()->json(["usuario" => $usuario]);
} }
@@ -120,6 +118,8 @@ class UsuariosController extends Controller {
'roles.*' => ['sometimes', Rule::in(['admin', 'mesero', 'recaudador', 'productor'])], 'roles.*' => ['sometimes', Rule::in(['admin', 'mesero', 'recaudador', 'productor'])],
]); ]);
/** @var Usuario $logged_user */
$logged_user = $request->user;
$usuario = Usuario::findByIdOrAuth0Id($id); $usuario = Usuario::findByIdOrAuth0Id($id);
if (!$usuario) { if (!$usuario) {
@@ -129,27 +129,23 @@ class UsuariosController extends Controller {
], 404); ], 404);
} }
// solo un global admin puede modificar usuarios en cualquier restaurant if (!$logged_user->canManageUsers()) {
if (!in_array('global_admin', $request->user->roles)) {
// si el usuario no es administrador no puede modificar usuarios
if (!in_array('admin', $request->user->roles)) {
return response()->json([ return response()->json([
'error' => 'not_allowed', 'error' => 'not_allowed',
'message' => 'El usuario no puede tiene permisos para modificar usuarios' 'message' => 'El usuario no tiene permisos para modificar usuarios'
], 403); ], 403);
} }
// los administradores solo pueden modificar usuarios en sus propio restaurantes
if ($request->user->restaurantes->intersect($usuario->restaurantes)->count() == 0) { if (!$logged_user->hasPermissionsOverUser($usuario)) {
return response()->json([ return response()->json([
'error' => 'not_allowed', 'error' => 'not_allowed',
'message' => 'El usuario no puede modificar un usuario en un restaurant al que no pertenece' 'message' => 'El usuario no tiene permisos para modificar a este usuario'
], 403); ], 403);
} }
}
$metadata = []; $metadata = [];
if ($request->input('roles')) if ($request->input('roles')) $metadata['roles'] = $request->input('roles');
$metadata['roles'] = $request->input('roles');
$auth0 = app(Auth0Service::class); $auth0 = app(Auth0Service::class);
$auth0User = $auth0->updateUser( $auth0User = $auth0->updateUser(
@@ -167,8 +163,7 @@ class UsuariosController extends Controller {
], $auth0User['statusCode']); ], $auth0User['statusCode']);
} }
if ($request->input('nombre')) if ($request->input('nombre')) $usuario->nombre = $request->input('nombre');
$usuario->nombre = $request->input('nombre');
$usuario->save(); $usuario->save();
return response()->json(["usuario" => $usuario]); return response()->json(["usuario" => $usuario]);

View File

@@ -6,6 +6,7 @@ use App\Services\Auth0Service;
use App\Traits\UuidPrimaryKey; use App\Traits\UuidPrimaryKey;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use phpDocumentor\Reflection\Types\Boolean;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
/** /**
@@ -14,9 +15,12 @@ use Ramsey\Uuid\Uuid;
* @property $id * @property $id
* @property $auth0_id * @property $auth0_id
* @property $nombre * @property $nombre
* @property $roles
* @property $restaurantes
* *
* @method static find($id) * @method static find($id)
* @method static where(string $string, $sub) * @method static where(string $string, $sub)
* @method static create(array $array)
* *
* @package App\Models * @package App\Models
* *
@@ -25,8 +29,14 @@ class Usuario extends Model {
use UuidPrimaryKey, SoftDeletes; use UuidPrimaryKey, SoftDeletes;
protected $table = 'usuarios'; protected $table = 'usuarios';
protected $fillable = ['id', 'auth0_id', 'nombre'];
protected $appends = ['roles']; 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) { public static function findByIdOrAuth0Id($id) {
if (str_starts_with($id, 'auth0')) { if (str_starts_with($id, 'auth0')) {
return Usuario::where('auth0_id', urldecode($id))->first(); 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() { public function restaurantes() {
return $this->belongsToMany(Restaurante::class, 'usuarios_restaurantes', 'usuario_id', 'restaurante_id'); return $this->belongsToMany(Restaurante::class, 'usuarios_restaurantes', 'usuario_id', 'restaurante_id');
} }