I am new in Laravel so I would need help with my solution of AuthServiceProvider class.
How should I write role control if user can have more than one role?
I have this:
$gate->define( 'admin', function ( $user )
{
return $user->roles()
->where( 'name', 'admin' )
->orWhere( 'name', 'super_admin' )
->first();
} );
or wold be better to write
$gate->define( 'admin', function ( $user )
{
foreach( $user->roles as $role )
{
if( $role->name == 'admin' || $role->name == 'super_admin' ) return true
}
return false;
} );
Or is there a better way? Is that query from first example executed once or every time i need to check users role?
Thx.
You can use ready-made packages for role and different types of permission. Here is some packages that I have used.
https://github.com/romanbican/roles
https://github.com/Zizaco/entrust
Related
I want to do login system using Eloquent ORM in laravel 8.
$data = User::where('email',$email)->where('password',$password)->get();
How can i check $data have value ?
if($data hasValue)
{
dd('login');
}
If you are looking to authenticate users manually, you can do something like this:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
This is straight from the Laravel docs BTW: https://laravel.com/docs/authentication#authenticating-users
I'm pretty sure your passwords aren't stored in plain text.
Try this:
use Illuminate\Support\Facades\Hash; // place this at the very top
$user = User::where('email', '=', $email)->first();
if( $user && Hash::check($password, $user->password) ) {
dd( 'login' );
}
I have this policy: (extract of GroupPolicy.php)
public function create(User $user)
{
return (
$user->role_id === 'SUPERADMIN'
||
$user->role_id === 'ADMIN'
);
}
I would like to add some other conditions in this policy by injecting another object coming from my controller. If I have understood, this method 'create' accepts only the connected user.
Is it possible, and how, to add other parameters for this policy?
You can pass as many arguments as you want to the policy method, they have to be in an array though:
Your Controller:
public function create()
{
$var1 = new \stdClass();
$var2 = 123;
$this->authorize('create', [User::class, $var1, $var2]);
}
Your Policy:
public function create(User $user, $var1, $var2)
{
return (
$user->role_id === 'SUPERADMIN'
||
$user->role_id === 'ADMIN'
);
}
I have this method in my DocumentsController and am trying to implement some simple permissions system, in that a user that is not an admin must have been assigned a branch and a department before adding, editing or deleting a Document.
Here is the code for the method
/**
* Check the credentials of the user that is not an admin
* to add, modify a document
*/
private function checkCredentials() {
$user = auth()->user();
// dd((!is_admin() && !$user->branch_id && !$user->department_id));
if (!is_admin() && !$user->branch_id && !$user->department_id) {
// dd(redirect()->route('documents'));
return redirect()->route('documents')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
}
And here is how am calling it in one of my controller methods that mapped to the route Route::get('/documents/add', ['as' => 'documents.add', 'uses' => 'DocumentsController#create',]);
public function create()
{
$this->checkCredentials();
...
return view('main/documents/create', $data);
}
Problem is the redirection is not working as it continues to display the form, even when the user has not yet been assigned a branch or department, that is when both the branch_id and department_id are both equal to null.
What could be the reason for this? Thank you.
You are not returning the redirect from the controller, try this:
/**
* Check the credentials of the user that is not an admin
* to add, modify a document
*/
private function checkCredentials() {
$user = auth()->user();
// dd((!is_admin() && !$user->branch_id && !$user->department_id));
if (!is_admin() && !$user->branch_id && !$user->department_id) {
// dd(redirect()->route('documents'));
return false;
}
}
public function create()
{
if(!$this->checkCredentials()) {
return redirect()->route('documents')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
...
return view('main/documents/create', $data);
}
I think you use authorization (gate/policy). https://laravel.com/docs/5.8/authorization
Your code need to be
<?php
private function checkCredentials() {
$user = auth()->user();
if (!is_admin() && !$user->branch_id && !$user->department_id) {
return redirect()->route('documents.add')->with([
'class' => 'alert-danger',
'message' => 'Ask your administrator to assign you a branch and department first',
]);
}
}
public function create()
{
$this->checkCredentials();
//...
return view('main/documents/create', compact('data'));
}
I am having issues with using multiple route filters in Laravel 4.2 while using the pattern role:permission. I've attached my code below.
This doesn't work at all. When I change roles, it always give one 403 unauthorized. I want both moderator and administrator to access this route.
Perhaps there's a way to tell Laravel, "if the logged in user is either an administrator OR a moderator, then let them access this route".
Route::get('engage', [
'as' => 'engage_path',
'before' => 'role:administrator',
'before' => 'role:moderator',
'uses' => 'ManagementController#showEngagement'
]);
This is my role filter.
Route::filter('role', function($route, $request, $role)
{
if (Auth::guest() or ! Auth::user()->hasRole($role))
{
return Response::make('Unauthorized', 403);
}
});
I suggest you use some kind of delimiter, like a ; to pass in multiple roles.
'before' => 'role:administrator;moderator'
And change the filter:
Route::filter('role', function($route, $request, $value)
{
if(Auth::check()){
$user = Auth::user();
$roles = explode(';', $value);
foreach($roles as $role){
if($user->hasRole($role)){
return;
}
}
}
return Response::make('Unauthorized', 403);
});
i'm using laravel with oracle database. Now, i'm making login sections. When i was input correct username and password, result is okay. But i was input incorrect username or password, following exception occured:
Illuminate \ Database \ QueryException
oci_error() expects parameter 1 to be resource, object given (SQL: select * from test_laravel_auth where username = tugsuu and password = testsss)
My controller code:
$user = DB::table('test_laravel_auth')->where('username', '=', $input['login_username'])
->where('password', '=', $input['login_password'])
->get();
return count($user);
if($user != null){
return "SUCCESS :D";
}
return "failed";
I assume you were using [jfelder/Laravel-OracleDB] package. It is a known issue as stated on site and a fixed was already added. Try updating your packages by running composer update.
Another option is to use yajra/laravel-oci8 package to connect to Oracle.
try this
$user = DB::table('test_laravel_auth')->where('username', '=', Input::get('username'))
->where('password', '=', Input::get('password'))
->get();
if(Auth::attempt($user))
{
//here success
}
else
{
return Redirect::to('login')->with('login_errors','Invalid Login Credentials.');
}
I suggest you use first instead of get(), this will retrieve the first record (only one should be found). You could also try with firstOrFail() and create an error handler if it "fails". If it fails = login incorrect.
$user = DB::table('test_laravel_auth')->where('username', '=', Input::get('login_username'))->where('password', '=', Input::get('login_password'))->first();
if (!is_null($user))
{
Auth::login($user);
}
else
{
//failed
}
Im also using Oracle database in Laravel and this solution works for me:
if ( Auth::attempt( array( 'user_name' => Input::get( 'username' ), 'password' => Input::get( 'password' ) ) ) )
{
return Redirect::intended( 'dashboard' );
}
else
{
return Redirect::to( 'login' )->withInput( Input::except( 'password' ) );
}
My code is just same on the Laravel documentation. It doesn't require you to use queries for authentication, all you need to use is the authentication class that comes with Laravel.
What driver/package you are using? Im using the yajra/laravel-oci8 package to make Oracle work with Laravel.
You may read more about laravel-oci8 package documentation on its page: https://github.com/yajra/laravel-oci8