only fist two line execute in this code last two role not check how can solve this problem
$input = $request->all();
$this->validate($request,[
'email'=>'required|email',
'password'=>'required'
]);
if(auth()->attempt(['email'=>$input["email"], 'password'=>$input['password']]))
{
if(auth()->user()->role == 'accountadmin')
{
return redirect()->route('accountadmins');
}
else if(auth()->user()->role == 'maintainadmin')
{
return redirect()->route('maintainadmins');
}
if(auth()->user()->role == 'superadmin')
{
return redirect()->route('superadmins');
}
if(auth()->user()->role == 'subscriber')
{
return redirect()->route('subscriberss');
}
else
{
return redirect()->route('home');
}
}
else
{
return redirect()
->route("login")
->with("error",'Incorrect email or password');
}
if(auth()->user()->role == 'superadmin')
{
return redirect()->route('superadmins');
}
if(auth()->user()->role == 'subscriber')
{
return redirect()->route('subscriberss');
}
without checking this role go next step. i have four login role using auth . but when i execute the only first two role check after that go next step . i try to else if else if but same problem
You could use a switch control structure here. Like this:
switch (auth()->user()->role) {
case 'accountadmin' : return redirect()->route('accountadmins');
case 'maintainadmin' : return redirect()->route('maintainadmins');
case 'superadmin' : return redirect()->route('superadmins');
case 'subscriber' : return redirect()->route('subscribers');
default : return redirect()->route('home');
}
Although its much better to use middlewares or route -> permission binding, but to simply answer your question you can do the following:
$routes = [
'accountadmins' => 'accountadmin',
'maintainadmins' => 'maintainadmin',
'superadmins' => 'superadmin',
'subscribers' => 'subscriber'
];
Using array_search:
if (false !== $route = array_search(auth()->user()->role, $routes)) {
return redirect()->route($route);
} else {
return redirect()->route('home');
}
Personally I recommend to use a permission package such as spatie/laravel-permission it is very well maintained and documented:
https://spatie.be/docs/laravel-permission/v5/basic-usage/middleware#package-middleware
https://github.com/spatie/laravel-permission
Related
I have created a route to pass dynamic parameters to controller but when i serve url it shows me for not found here is my route and controller I create
Routes
Route::get('/admin/managers/{method}/{id}',
[
SetupController::class, 'managers'
]
);
Controller
public function managers($method, $id) {
if($method == 'create') {
return view('admin.pages.create-manager');
} elseif($method == 'create') {
echo $id;
return view('admin.pages.create-manager');
} else {
return view('admin.pages.managers');
}
}
When i serve url localhost/public/managers it shows me 404 not found but when i serve localhost/public/managers/create/1 the page is loading then can anyone hep me out why exactly is it happening
as we discussed in the comments what you need is to make your parameters optional like below
change your route like this
Route::get('/admin/managers/{method?}/{id?}', [SetupController::class, 'managers']);
and your controller like this
public function managers($method=null, $id=null) {
if ($method == 'create') {
return view('admin.pages.create-manager');
} elseif ($method == 'edit') { // change here
echo $id;
return view('admin.pages.create-manager');
} else {
return view('admin.pages.managers');
}
}
and also don't forget to run at the end
php artisan optimize
The issue is that in your code, the second if condition is checking for the same value 'create', this resulting in a 404 error for the URL "localhost/public/managers".
To resolve this issue, change the second if condition to check for another value. For example, if you want to show the page with the id, use the following code:
public function managers($method, $id) {
if ($method == 'create') {
return view('admin.pages.create-manager');
} elseif ($method == 'show') {//or anything else
echo $id;
return view('admin.pages.create-manager');
} else {
return view('admin.pages.managers');
}
}
I'm a beginner web developer
I'm trying to write a condition that will be fulfilled depending on what data the user will send
Condition if fulfilled by one hundred percent
But the condition else produces an error with the following text
Trying to get property 'unique_id' of non-object
If someone have info how to solv this problem I will be grateful
This is my code from controller
public function checkRestorePassword(Request $request)
{
$result['success'] = false;
$rules = [
'unique_id' => 'required',
];
$validation = Validator::make($request->all(), $rules);
if (empty($validation))
{
$result['error'] = "Enter the code that was sent to you by mail.";
return response()->json($result, 422);
}
$user = User::where('unique_id', $request->uniqueId)->first();
if ($user->unique_id === $request->uniqueId)
{
$result['success'] = 'Access to your personal account successfully restored. Please change your password.';
return response()->json($result, 200);
}
else
{
$result['success'] = false;
return response()->json($result, 422);
}
}
I think it's because $user is returning null.
so do this
if (!is_null($user) && $user->unique_id === $request->uniqueId)
I am using Sentinel by Cartalyst in my Laravel 5.4 project. However I am tying to check the value of a database field of the 'users' table after the user provides his/her credentials for logging in.
if(Sentinel::authenticate($credentials, $rememberMe)) {
$slug = Sentinel::getUser()->roles()->first()->slug;
if($slug == 'A') {
Session::flash('welcome_message' , 'A');
return response()->json(['redirect' => '/A/dashboard']);
} elseif($slug == 'B') {
Session::flash('welcome_message' , 'B');
return response()->json(['redirect' => '/B/dashboard']);
}
} else {
return response()->json(['error' => 'Wrong credentials entered'], 500);
}
// if(Sentinel::getUser()->status == 'Active') -- if this is true we log in
The problem I cant find a way to implement this..though it checks the field but if it returns false then also the user gets logged in
Try following :
if($user = Sentinel::authenticate($credentials, $rememberMe) && $user->status == 'Active') {
$slug = Sentinel::getUser()->roles()->first()->slug;
if($slug == 'A') {
Session::flash('welcome_message' , 'A');
return response()->json(['redirect' => '/A/dashboard']);
} elseif($slug == 'B') {
Session::flash('welcome_message' , 'B');
return response()->json(['redirect' => '/B/dashboard']);
}
} else {
return response()->json(['error' => 'Wrong credentials entered'], 500);
}
I am using multiauth with two tables admin_profile and company in Laravel 4.2.
public function Login()
{
$LoginData = Input::except(array('_token'));
//return $LoginData;
if (Input::get('username')=='' || Input::get('password')=='')
{
if(!$LoginData['CompanyURL']=='')
return Redirect::to('')->withInput()->with('Message', 'Enter Username and Password');
else
return Redirect::to('company/'.$LoginData['CompanyURL'])->withInput()->with('Message', 'Enter Username and Password');
}
//Admin User
if($LoginData['CompanyURL']=='')
{
if (Auth::admin()->attempt(array_filter($LoginData)))
{
$UserDetails = User::where('username', Input::get('username'))->first();
if(count($UserDetails)>0)
return Redirect::intended('home');
}
else
return Redirect::to('')->withInput()->with('Message', 'UserName or Password Invalid');
}
else
{
if (Auth::user()->attempt($LoginData))
{
//return $LoginData;
$CompanyModel = User::where('username', Input::get('username'))->first();
return Redirect::intended('company/'.$LoginData['CompanyURL'].'/home');
}
return Redirect::to('company/'.$LoginData['CompanyURL'])->withInput()->with('Message', 'UserName or Password Invalid');
}
}
But i cannot check whether any user of type admin or company is logged in to open the pages like home page which needs user authentication
How to change this
Route::group(array('before' => 'auth'), function()
{
Some routes....
}
You have to change your filters please check example for how to fix it https://gist.github.com/ollieread/8303638
In addition that , if you want to use only one auth filter for common pages there is your solution,
Route::filter('auth', function()
{
$guest = true;
if (Auth::student()->guest() && Auth::teacher()->guest() && Auth::parent()->guest()){
$guest = false;
}
if(!$guest){
return Redirect::to('login');
}
});
I also suggest you to define different type of filters these are very useful for who has permission for routes,
Route::filter('student', function()
{
if (!Auth::student()->check() ) // Checks the current user
{
return Redirect::to('login');
}
});
Route::filter('teacher', function()
{
if (! Auth::teacher()->check() ) // Checks the current user
{
return Redirect::to('login');
}
});
I'm trying to make authentication with Laravel and MongoDB.
The problem is in my controller. This code does not make authentication :
if(!Input::exists('username') or !Input::exists('password')) {
App::abort(403, 'Forbidden request');
}
$credentials = array(
'username' => Input::get('username', null),
'password' => Input::get('password', null),
);
if(Auth::validate($credentials)) {
return 'Success';
} else {
return 'Failed';
}
But this one just works fine:
if(!Input::exists('username') or !Input::exists('password')) {
App::abort(403, 'Forbidden request');
}
$credentials = array(
'username' => Input::get('username', null),
'password' => Input::get('password', null),
);
$users = User::all();
$found = false;
foreach($users as $user) {
if($user->username == $credentials['username']
and Hash::check($credentials['password'], $user->password)) {
$found = true;
break;
}
}
if($found) {
return 'Success';
} else {
return 'Failed';
}
Both controllers are given the same username and password. First one always prints Failed, but second one gives true results.
The problem is you are using Auth::validate which only checks if the credentials are correct, but does not log the user in. You need to use Auth::attempt for a complete login. See the docs here http://laravel.com/docs/security#authenticating-users .
OK, Always remember that your model has to implement UserInterface.