I have two roles in my app admin and users. Both roles are using a middleware called auth. Now in the application, when i login as a admin, i am not able to route to user page (that is perfect).
But when i login as user, i am able to route to admin page but my auth must prevent the user from accessing the admin page. Currently, that is my issue... What am i not doing right?
Below is my code
AuthMiddleWare
if (Auth::check())
{
if(Auth::user()->roles->pluck('name')->first() == "admin")
{
// return $next($request);
return Redirect::to('/admin/dashboard');
}
else if(Auth::user()->roles->pluck('name')->first() == "user")
{
return Redirect::to('/user/dashboard/');
}
else{
return Redirect::to('login');
}
}
Route
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => ['auth']), function () {
Route::get('dashboard','Controller#show');
}
Route::group(array('prefix' => 'user', 'namespace' => 'User', 'middleware' => ['auth']), function () {
Route::get('dashboard','Controller#show');
}
Try the following code:
if (Auth::check())
{
if(in_aaray('admin', Auth::user()->roles->pluck('name')->all()))
{
// return $next($request);
return redirect('/admin/dashboard');
}
else if(in_array('user', Auth::user()->roles->pluck('name')->all()))
{
return redirect('/user/dashboard/');
}
else{
return redirect('login');
}
}else{
return redirect('login');
}
you need to make custom auth in laravel and make different table for admin and user
Related
Im making a api with laravel 9 about a fitness app. This app will have 2 roles Admin and Normal user. What im struggling with is making an Authentication system for the users, so that an Admin can have access to certain routes that a normal user wont. To do that i created a middleware called AdminMiddleware
{
if(Auth::check()){
//if admin role = 1
$user = Auth::guard('api')->user();
if(Auth::user()->role == 1){
return $next($request);
}
else{
return redirect('/login')->with('message', 'Access Denied');
}
}
else{
return redirect('/login')->with('message', 'Log In to gain access');
}
return $next($request);
}
This checks whether the user is an admin or not.
This is the routes where the middleware is used
Route::middleware(['auth', 'isAdmin'])->get('/admin', function () {
Route::post('/addProducts', [ProductController::class, 'store']);
Route::delete('/deleteProducts/{id}', [ProductController::class, 'destroy']);
Route::post('/addRecipe', [RecipeController::class, 'store']);
Route::put('/updateRecipe/{id}', [RecipeController::class, 'update'], function (Request $id) {
return 'Recipe '.$id;
});
Route::delete('/deleteRecipe/{id}', [RecipeController::class, 'destroy']);
Route::post('/addEvent', [SpecialEventsController::class, 'store']);
Route::get('event/{id}', [SpecialEventsController::class, 'show'], function (Request $id) {
return 'Events '.$id;
});
Route::put('/updateEvent/{id}', [SpecialEventsController::class, 'update'], function (Request $id) {
return 'Recipe '.$id;
});
Route::delete('/deleteEvent/{id}', [SpecialEventsController::class, 'destroy']);
});
And this is the Login Controller, where im having my problems:
public function login(Request $request)
{
//(Auth::guard('api')->attempt(['email' => $request->email, 'password' => $request->password]))
if(Auth::guard('api')(['email' => $request->email, 'password' => $request->password])){
$user = Auth::guard('api')->user();
if($user){
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
$success['role'] = $user->role;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
}
This code is returning
Error: Object of type Laravel\Passport\Guards\TokenGuard is not callable in file C:\xampp\htdocs\Ritwell-App - Copy (2)\app\Http\Controllers\API\RegisterController.php on line 52
The part
Auth::guard('api')(['email' => $request->email, 'password' => $request->password])){
was originally
if(Auth::attempt
but that code gave me an exception
BadMethodCallException: Method Laravel\Passport\Guards\TokenGuard::attempt does not exist. in file C:\xampp\htdocs\Ritwell-App - Copy (2)\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php on line 113
I tried using resources online to help with answers but this is what i could come up with so far and it isnt working.
Can someone tell me what am i doing wrong and what is missing in my code?
I am stuck with users profile feature, I want only authenticated users to access their own profile only.
User with id: 1 can only access route /applicants/profile/1, otherwise return 404 Not found?
class ApplicantProfileController extends Controller
{
public function show(Applicant $applicant)
{
return view('applicant.show', compact('applicant'));
}
}
route::group(['prefix' => 'applicants', 'middleware' => 'auth:applicant'], function() {
Route::get('/profile/{applicant}', 'Profiles\ApplicantProfileController#show');
});
You can chech whether the logged user and the parameter user are the same by using the Illuminate/Support/Facades/Auth facade like this:
public function show(Applicant $applicant)
{
if (Auth::id() == $applicant->id) {
return view('applicant.show', compact('applicant'));
}
return abort(404);
}
I have this in my database
|username|password|type|
------------------------
|foo |12345 |1 |
|asd |adsdsd |0 |
Here 1 means that the user is an admin, 0 a normal user.
How can I redirect the admin to the admin page and the normal user to normal user page??
if($attempt)
{
$id = User::find($attempt);
$user = $id->type;
if($user === 0)
{
return Redirect::action('LoginUsersController#profile');
}
else
{
return Redirect::to('adminpage');
}
}
I created this in my UsersController page I don’t know if this is the proper way to do this, and my code is not working.
Are you using normal Laravel Authentication?
You will get Object Auth::user(), this will return current user Object.
It should look like this.
Controller (SessionsController#store)
public function store() {
$input = Input::all();
$attempt = Auth::attempt([
'username' => $input['username'],
'password' => $input['password']
]);
if($attempt) {
if(Auth::user()->type == 1) {
return Redirect::admin(); // If admin, redirect to admin
} else {
return Redirect::profile(); // Else, redirect to user profile
}
}
}
Route
Route::resource('sessions', 'SessionsController', ['only' => ['create','store','destroy']]);
Route::get('admin', 'AdminController#dashboard')->before('adminAuth');
Route::get('profile/{id}', 'UsersController#showProfile')->before('auth');
First of all you have to add a new field in your users table to check against, for example 'rank'. If rank for a user is '1' so he is an Admin,
else he is a normal user.
Then define all required routes in your routes file like this:
Route::get('login', 'adminController#login');
Route::post('login', 'adminController#checkuser');
Route::group(array('before' => 'auth'), function() {
Route::resource('admin', 'adminController');
Route::resource('normaluser', 'normaluserController');
} );
Then in your controller you have to define all actions:
public function login()
{
return View::make('loginview');
}
public function checkuser()
{
if (Auth::attempt(array('username'=>Input::get('username'), 'password'=>Input::get('password'))))
{
$user_data = Auth::getUser();
if ($user_data->rank == 1) //if true, so this user is an admin
{return Redirect::to('admin');} //go to adminController index action
else //if not, so he is a normal user
{return Redirect::to('normaluser');} // go to normaluserController index action
}
else
{
//return 'wrong user name or password';
Session::flash('mismatch', "Username and Password mismatch");
return Redirect::to('login'); // go again to login form to relogin
}
}
if any thing is not clear, don't hesitate to ask.
in the if statement use:
if($attempt)
{
$id = User::find($attempt);
$user = $id->type;
if($user === 0)
{
return Redirect::action('LoginUsersController#profile');
header('Location: http://www.example.com/userpahe.php');
}
else
{
return Redirect::to('adminpage');
header('Location: http://www.example.com/admin-page.php');
}
}
I'm trying to make some custom filters for my Laravel application.
In filter.php I have
Route::filter('admin', function()
{
if (Auth::guest() AND ! Auth::user()->isAdmin()) {
return 'Not Authorized';
}
});
User.php model
public function isAdmin()
{
if($this->role==1) return true;
else return false;
}
And finally in the Route:
//SECTIONS ONLY FOR ADMIN
Route::group(array('prefix' => 'admins', 'before' => array('admin')), function(){
Route::get('/frontoffice', 'FrontofficeController#index');
Route::get('/frontoffice/about', 'FrontofficeController#about');
Route::get('/frontoffice/research', 'FrontofficeController#research');
});
I'm logged in as an Admin in my application, but still I'm getting NotFoundHttpException when I try to access the above URLs in the route.
Any idea why?
I do not want to show login page after login in laravel 4. If a logged in user want to visit login page it should redirect to homepage('/'). I am using Sentry for authentication.
filter.php
Route::filter(
'auth', function () {
if (!Sentry::check()) {
return Redirect::to('login');
}
}
routes.php
Route::get('login', array('as' => 'login', function() {
return View::make('login');
}))->before('guest');
Route::post('login', 'AuthController#postLogin');
AuthController.php
function postLogin() {
try {
// Set login credentials
$credentials = array(
'email' => Input::get('email'), 'password' => Input::get('password')
);
// Try to authenticate the user
$user = Sentry::authenticate($credentials, false);
if ($user) {
return Redirect::to('/');
}
} catch (Cartalyst\Sentry\Users\LoginRequiredException $e) {
return Redirect::to('login')->withErrors('Login field is required');
}
}
After successful login if, if login page is requested it still shows the login page
If you're using Laravel's default guest filter, it will not work, because the default guest filter does not check if your Sentry user is logged in.
Try this instead:
Route::filter(
'filter', function () {
if (Sentry::check()) {
return Redirect::to('/');
}
}
In your routes.php, the filter is already being applied to the login route, so things should work this way.