Ir para conteúdo
Fórum Script Brasil
  • 0

Controlando o acesso a funções


Frank K Hosaka

Pergunta

Eu tenho uma função chamada pagar, mas eu gostaria que só o usuário com o id=1 tivesse acesso a essa função.

Hoje eu encontrei uma solução, não sei se é correto, mas ele funcionou para mim.

No PHP eu coloquei a seguinte instrução:

if($_SESSION['id']!==1){header('location:menu.php');}

No Laravel, eu usei essa instrução:

if(auth::id()!==1){return redirect('menu');}

 

Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

  • 0

O Lary do Laracasts respondeu:

Yes, there are several elegant solutions to control user access in Laravel. One of the most common ways is to use middleware. Middleware is a way to filter HTTP requests entering your application. You can create a middleware that checks if the user is authorized to access a particular route or function. Here's an example:

Create a middleware using the following command:

php artisan make:middleware CheckUserRole

Open the app/Http/Middleware/CheckUserRole.php file and add the following code:

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckUserRole {
    public function handle($request, Closure $next, $role){
		if (!Auth::check()) {return redirect('/login');}
        $user = Auth::user();
        if ($user->role != $role) {
            return redirect('/menu');}
        return $next($request);}
}

Register the middleware in the app/Http/Kernel.php file:

protected $routeMiddleware = [
    // ...
    'role' => \App\Http\Middleware\CheckUserRole::class,
];

Use the middleware in your routes:

Route::get('/admin', function () {
    // Only users with the 'admin' role can access this route
})->middleware('role:admin');

In this example, the middleware checks if the user is authenticated and has the required role to access the route. If the user is not authenticated, they are redirected to the login page. If the user is authenticated but does not have the required role, they are redirected to the menu page.

This is just one example of how you can control user access in Laravel. There are many other ways to achieve this, depending on your specific requirements.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...