How to give access to views to specific user in laravel? - laravel

I have a Category Controller which checks if user is logged in
class CategoryController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
...
My category routes are :
//Category Controller
Route::get('admin/category/{category}/edit', ['uses'=>'categoryController#edit','as'=>'admin.category.edit']);
Route::put('admin/category/{category}', ['uses'=>'categoryController#update','as'=>'admin.category.update']);
Route::get('admin/category/{category}', ['uses'=>'categoryController#show','as'=>'admin.category.show']);
Route::delete('admin/category/{category}', ['uses'=>'categoryController#destroy','as'=>'admin.category.destroy']);
Route::get('admin/category/create', ['uses'=>'categoryController#create','as'=>'admin.category.create']);
Route::get('admin/category', ['uses'=>'categoryController#index','as'=>'admin.category.index']);
Route::post('admin/category', ['uses'=>'categoryController#store','as'=>'admin.category.store']);
Is there a way to give access to these views to only specific user?
For example if user email is admin123#gmail.com then he is allowed to go to those view.
I know I can check like this
if(Auth::user()->email == 'admin123#gmail.com')
{
dd('admin Logged in');
}
But this is possible if i go to individual view and put all my content in the if statement.
Is there way to handle this in controller.
Thanks.

You can use the middlewares for these kinds of work.
From the docs
Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

You should restrict users by route groups. Use middleware for that.
However, if you have complicated logic, sometimes you may want to check if user is admin in controller, model and other classes. In this case you can create global helper isAdmin() and use it for simple checks. Examples:
if (isAdmin()) {
// Do something
}
{{ isAdmin() ? 'active' : '' }}

A better way to define user role is like 0 for admin, 1 for user, 2 for member.
Then you can check the user role like:
if(Auth::check())
{
if(Auth::User()->user_type == 0)
{
return view('admin_dashboard');
}
else if(Auth::User()->user_type == 1)
{
return view('user_dashboard');
}
else if(Auth::User()->user_type == 2)
{
return view('member_dashboard');
}
}

Related

How to restrict users to use application

I am using laravel framework to develop api’s ,it’s an existing application .there is a requirement if more than 5users registered from 6th user onwards i have to restrict them to use application until they approved by manager or they paid for registration fee then only the user will allow to use the application.
Can anyone give me the idea how to acheive this scenario or suggest me any package in laravel
Solution:
You can add 'status' field in your table. Now when your api is registering a user, you can check the No. of users in the database. If more than or equals to 5, you can set the status to 0. Now show the manager list of user with status 0 and when the status changes you can use the application.
Make sure to add condition where status = 1 when user is getting logged in.
I hope it helps!
Well, you can just put a isApproved column to indicate if the user is already approved or just like the email_verified_at that accepts timestamp as a value then create a middleware where you can check if the user is approved or not. then add a method to the user model to check if the user is approve :
User model
class User extends Authenticatable
{
public function isApproved()
{
// check if the account_approved_at column is not null.
return ! is_null($this->account_approved_at);
}
}
Middleware
class EnsureUserIsApproved
{
public function handle(Request $request, Closure $next)
{
if(! $request->user()->isApproved()) {
// can also use abort(403) instead of redirect
return redirect('route-where-you-want-the-user-to-redirect')
}
return $next($request);
}
}
You can check this for more information about middleware

having anonymous user on laravel

I'm using Laravel 5.8. And I have created a custom Guard that is using jwt. That I use as a middleware for authenticating users.
I have some routes that need to have different responses based on being an authenticated user or an unauthenticated user. what do you suggest me to do? what is the best practices to implement this?
I can define a custom guard which its check function always returns true.and returning an integer like -1 for unauthenticated user while the user is not authenticated.but it does not sound a clean way of implementing this.
Depending on how you want to set this up, you can just use the Auth facade helpers in your controller method to see whether a user is authenticated or not:
// SomeController.php
public function index(Request $request)
{
if(Auth::guest()) {
return response()->json('i am a guest');
} else {
return response()->json('im not a guest');
}
}
or use any of the related methods:
// Inverse of `Auth::guest()`
$isLoggedIn = Auth::check();
$loggedInUser = Auth::user();
https://laravel.com/api/5.8/Illuminate/Auth/GuardHelpers.html

How can I add ask username and password feature to only one of my laravel routes?

I have created a few forms in laravel. I want to restrict access to one of them only to a specific user.
I want to create a user and password myself.
This is my routes excerpt. This is the route I want to protect from access
Route::get('/tabledata_id_title', 'KedivimController#appearanceiddata');
This is my controller excerpt:
public function appearanceiddata()
{
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
This is a short fix for your problem.
public function appearanceiddata()
{
if (!Auth::guard('web')->check()) //check if someone is logged in
{
//redirect to login page.
}
else {
/*Check if the logged in user is your desired user.
Maybe try matching the logged in id with your desired id.
If you find that a user is logged in but they are not your desired user
then you may redirect them in some other place or show them a message. */
}
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
However, this practice is ok if you have one or two restricted field. But if you have more than that then you should read about middleware.

Controller constructor to check Auth middleware for two different guards

I have a dashboard view that shows certain contain depending on which user is viewing, whether it be an admin or just a regular user.
I can get my admins onto that page, but regular users aren't able to currently because of my middleware guard.
class DashboardController extends Controller {
public function __construct()
{
$this->middleware('auth:admin');
}
public function index()
{
return view('dashboard.index');
}
}
The following code checks on each DashboardController call for auth:admins, but I want regular users to access this too, is there a way to check the auth middleware twice like so?
$this->middleware(['auth:admin','auth']);
So ideally it will check if you're an admin or just a regular auth user.
Also on my view page, when accessing properties of an admin I'm using:
{{ Auth::user()->admin_username }}
Is this normal? I have an admin Model but I'm still accessing it via Auth::user() which feels strange to me, shouldn't it be Auth::admin()->admin_username
Accessing a particular page for users with differing roles is more suited for laravels gates and policy authorization mechanisms.
https://laravel.com/docs/5.5/authorization#writing-gates
These allow you to write fine tuned rules for each use case you have. Simple gates can be defined as closures within your application AuthServiceProvider. For example:
public function boot()
{
$this->registerPolicies();
Gate::define('access-dashboard', function ($user, $post) {
return auth()->check() && (auth()->user()->hasRole('admin') || auth()->user()->hasRole('regular'));
});
}
Then you can use the gate facade wherever necessary, for instance a controller method or constructor.
if (Gate::allows('access-dashboard', $model)) {
// The current user can access dashboard, load their data
}
Alternatively use the can or cant helpers on the user model directly.
if (auth()->user()->can('access-dashboard')) {
//
}
Of course, you can achieve similar via middleware, the advantage of using the above is you can authorize actions at specific points in your code as well as reusability.
As for for last question, as you have it written is correct.
{{ Auth::user()->admin_username }}
Auth::user() or auth()->user() simply returns the currently authenticated user, regardless of their role.
Policies will never work without auth middleware

Redirect authenticated users according to their role

I need to redirect users based on ther role in application. In MySQL, I've added "isAdmin" column in Users table to check whether user is admin or not. Only solution I've come up with is to render html on the same blade according to user's type.
For example.
#if(Auth::user()->isAdmin == 1)
<p>Hello, Admin</p>
//other html for admin
#else
//other html for users
Is there a better way to do this in terms of more beautiful and efficient code because this looks messy?
I'm using this package (https://github.com/acacha/adminlte-laravel) which uses Laravel's default authentication system.
I want to redirect users during their login process to two different blades, lets say homeUsers.blade.php and admin.blade.php.
Logic is here: The best way is to create two tables one users and another roles, and put role_id in users table as foreign key.Then create a relation that a role belongsTo a user.
However in your case if you have two views and you want to show one for admin and other for other users follow the below method.
Create two views which you want to use in your case 1) admin 2) homeUsers
#if(Auth::user()->isAdmin == 1)
#include('admin') //admin.blade.php
#else
#include('homeUsers') //homeUsers.blade.php
I'm not sure what version of Laravel you're using, but this seems like it should be in your Middleware.
Check out RedirectIfAuthenticated.php in Middleware. Then, you could do the following.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::user()->role == 'Admin')
{
return redirect('/admin');
}
else
{
return redirect('/home')
}
}
return $next($request);
}

Resources