Custom login property Laravel 8 - laravel

I have this custom function for atempting to login in Laravel 8
protected function attemptLogin(Request $request)
{
$credentials = $this->credentials($request);
$credentials['estado']=1;
return $this->guard()->attempt(
$credentials, $request->filled('remember')
);
}
How I can make to accept the login atempt when $credentials['estado'] also has 2 as value.
Don't know how to make it accept multiple values.
I managed to make the custom function accept the value of 1 but dunno how to make it accept multiple $credentials['estado'] values.

You don't need to change anything in attemptLogin() method, instead you can customize the crededentials() method in LoginController like this:
// login, if user have like a following described data in array
protected function credentials(Request $request)
{
$username = $this->username();
return [
$username => $request->get($username),
'password' => $request->get('password'),
'estado' => [ 1, 2 ], // OR condition
];
}
Answer for comments:
Honestly in my experience I didn't have that case, but if you want to redirect to the another view on failed login (for specific field 'estado'), you can customize the "sendFailedLoginResponse" method, and add some additional if-condition for checking the 'estado'.
As the "sendFailedLoginResponse" method will be called only for getting failed login response instance, then you can check: is that fail comes from 'estado' field actually. Something like this:
protected function sendFailedLoginResponse(Request $request)
{
// custom case, when login failed and estado is 2
if ($request->get('estado') == 2) {
return view('some.specific.view');
}
// laravel by default implementation
else {
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
}
Remember, in this case (when we're redirecting the user to some page) we actually not redirecting as for always, but instead we're just returning a view. We do that because I think you don't want to let the users to open that specific view page anytime their want, as you need to let them see that page only for specific case. But when you'll do the actual redirect, then you will let the users to visit that page with some static URL.
Of course, you can do some additional stuff (add something in DB or the Session, and check is the request comes actually from 'estado' fails, but not from any user), but this could be a headeche for you, and in my opinion that will not be a real laravel-specific code.
Anyway, this is the strategy. I don't think, that this is mandatory, but this can be do your work easy and secure.
Note: I've got this deafault implementations from "AuthenticatesUsers" trait (use use Illuminate\Foundation\Auth\AuthenticatesUsers;). In any time you can get some available methods from there and override them in your LoginController, as the LoginController used that as a trait.

Related

Unwanted validation rule being applied on password reset

I'm trying to use the password reset ability of Laravel's authentication. After running make:auth command, inside my ResetPasswordController, I have overridden rules function of Illuminate\Foundation\Auth\ResetsPasswords trait as the following:
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:4',
];
}
So, I am trying to change the minimum length value to 4. But when I try to reset my password, a rule of minimum of 8 characters is still being applied instead of 4.
Here is the reset function of laravel in the same file:
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
And the $response being returned is Illuminate\Support\Facades\Password::INVALID_PASSWORD. I don't understand where this rule is coming from.
Actually the validation behavior is like this: When I enter less than 4 characters, my own rule is applied (correctly). However, entering 4 to less than 8 characters is also an error by some other rule.
The reason that you're getting the error back is because the PasswordBroker expects a password with a minimum length of 8 characters so even though your form validation is passing, the validation in the PasswordBroker isn't.
One way to get around this would be to override the broker() method in your ResetPasswordController and pass your own validator to it:
public function broker()
{
$broker = Password::broker();
$broker->validator(function ($credentials) {
return $credentials['password'] === $credentials['password_confirmation'];
});
return $broker;
}
The above is essentially the same as what's going on in the PasswordBroker itself, just without the string length check as well.
Don't forget to import the Password facade into your controller:
use Illuminate\Support\Facades\Password;
This isn't essential, but for good measure I would then suggest updating the password error message in your resources/lang/en/passwords.php file as well.

What is the correct order of form validation and retrieving input values?

I wonder if I should do form validation before retrieving input values or vice versa.
I usually do validation first as I see no benefit in trying to access input values that might not be valid. However, a coworker looked at my code recently and found it strange. Is there any correct order for these steps?
public function createGroups(Request $request)
{
$this->validate($request, [
'courses' => 'required_without:sections',
'sections' => 'required_without:courses',
'group_set_name' => 'required',
'group_number' => 'required|integer|min:1'
]);
$courses = $request->input('courses');
$sections = $request->input('sections');
$group_set_name = $request->input('group_set_name');
$group_number = $request->input('group_number');
Positioning the validation for your controller logic at the beginning of a method is probably the way to go here, as you have required parameters defined. If you receive data that does not fully satisfy the requirements, you produce a validation error back to the user. This follows the productive "Fail Fast" line of thinking: https://en.wikipedia.org/wiki/Fail-fast
It's also important that you're not using any data that hasn't passed your stringent requirements from validation. Data that fails validation should no longer be trusted. Unless there's some other reason you need to be, say, logging any incoming data from the frontend, the order here looks good to me.
I totally agree with #1000Nettles response, to elaborate a little bit more on his/her answer (who should be the accepted one): There isn't any need to continue with your business logic when the data doens't comply with your specifications. Let's say you expected a string of a N characters long, because you defined your database with that limitation (in order to optimize the db desing), will you try to persist it even when it'll throw an exception? Not really.
Besides, Laravel has a particular way to extract validation classes: Form Request. This are injected in controllers. When a call reach the controller it means that already passed the validation, if not, an 422error be returned.
Create a custom request and keep the mess out of your controller, it doesn't even hit your controller function if validation failed and can just grab the data in your controller if validation passed.
php artisan make:request GroupRequest
In app/Http/Requests/GroupRequest.php:
public function authorize()
{
// return true;
return request()->user()-isAdmin; // <-- example, but true if anyone can use this form
}
public function rules()
{
return [
'courses' => ['required_without:sections'],
'sections' => ['required_without:courses'],
'group_set_name' => ['required'],
'group_number' => ['required', 'integer', 'min:1'],
];
}
The best part is you can even manipulate the data in here (GroupRequest.php) after it has been validated:
public function validated()
{
$validated = $this->getValidatorInstance()->validate();
// EXAMPLE: hash password here then just use new hashed password in controller
$validated['password'] = Hash::make($validated['password']);
return $validated;
}
In your controller:
public function createUser(UserRequest $request) // <- in your case 'GroupRequest'
{
$validated = $request->validated(); // <-- already passed validation
$new_user = User::create($validated); // <-- password already hashed in $validated
return view('dashboard.users.show')->with(compact('user'));
}
In your case, if you use my GroupRequest block above, you can return to view in 1 line of code:
public function createGroups(GroupRequest $request)
{
return view('example.groups.show')->with($request->validated()); // <-- already an array
}
In you blade view file, you can then use your variables like {{ $group_set_name }} and {{ $group_number }}

What is the difference between "login" and "attempt" method in Auth

I'm learning Laravel 5.4 and customizing and making my original Auth functionalities.
The below is my "authenticate" method.
public function authenticate(Request $request)
{
$remember_me = (Input::has('remember')) ? true : false;
Auth::guard('web');
$this->validateLogin($request);
$credentials = array(
'username' => trim($request->input('username')),
'password' => trim($request->input('password'))
);
if(Auth::attempt($credentials, $remember_me)){
$user = Auth::guard('web')->user();
Auth::guard('web')->login($user, $remember_me);
return redirect()->route('mypage');
}
return redirect()->back();
}
I have a question about the part of $remember_me argument about both attempt and login methods noted above.
What is the difference between them?
When I saw the documentation, it said similar to, if you want to make "remember me" token, you can set the second boolean argument about both of them.
attempt($credentials, $remember_me) will attempt to log the user in if the login credentials are correct. If they are not, then the user is not logged in. This method returns a boolean so you can check success.
login($user_id, $remember_me) will log the user in, without checking any credentials.
The remember me specifys if the user login should persist across browser sessions without needing to re-auth.
In your example I see your calling login(...) within your attempt(...). This shouldn't be needed. You can remove the login(...) line.
Example:
if(Auth::attempt($credentials, $remember_me)){
return redirect()->route('mypage');
}

laravel 5 double validation and request

I did this validation and works:
public function salvar(CreateEquipamento $Vequip, CreateLocalizacao $VLocal)
{
$this->equipamento->create($Vequip->all());
$equipamento = $this->equipamento->create($input);
return redirect()->route('equipamento.index');
}
what I want is to also do something like get the last created equipment ID and include in the array to validate and create for Local validation (CreateLocalizacao $VLocal) because i've two tables, one for the equipment and another one who stores all the places where my equipment was in.
$input['equipamento_id'] = $equipamento->id;
$this->localizacao->create($VLocal->all());
How could I do something like this?? thx in advance !
I do a "workarround" solution ;)
$localizacao = [
'equipamento_id' => $id,
'centrocusto_id' => $input['centrocusto_id'],
'projeto' => $input['projeto'],
'data_movimentacao' => $input['data_movimentacao']
];
$this->localizacao->create($VLocal->all($localizacao));
I dont know if this is the best way to do it but works, but if somebody has the right way to do post please!
Are you using Laravel 5?
If yes, use form Requests, they make everything easier. If you need to validate two things from one form, you just put two requests in the controller method. I use this when I register an user for an ecommerce page. I need to validate the user data and the address data, like this:
public function store(UserRegisterRequest $user_request, AddressCreateRequest $add_request)
{
//if this is being executed, the input passed the validation tests...
$user = User::create(
//... some user input...
));
Address::create(array_merge(
$add_request->all(),
['user_id' => $user->id]
));
}}
Create the request using artisan: php artisan make:request SomethingRequest, it generates an empty request (note the authorize function always returns false, change this to true or code that verifies that the user is authorized to make that request).
Here's an example of a Request:
class AddressCreateRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [
"fullname" => "required",
//other rules
];
}
}
More on that on the docs:
http://laravel.com/docs/5.0/validation#form-request-validation

Before method with multiple role restrictions

Im curious to know if it is possible to prevent users who don't have a role of owner or administrator from accessing certain controllers in a laravel application?
Yes you can. You can do this with a route filter.
routes.php
Route::group(['prefix' => 'admin', 'before' => 'auth.admin'), function()
{
// Your routes
}
]);
and in filters.php
Route::filter('auth.admin', function()
{
// logic to set $isAdmin to true or false
if(!$isAdmin)
{
return Redirect::to('login')->with('flash_message', 'Please Login with your admin credentials');
}
});
Route filters have already been proposed but since your filter should be Controller specific you might want to try controller filters.
First off, lets add this your controller(s)
public function __construct()
{
$this->beforeFilter(function()
{
// check permissions
});
}
This function gets called before a controller action is executed.
In there it depends on you what you want to do. I'm just guessing now, because I don't know your exact architecture but I suppose you want to do something like this:
$user = Auth::user();
$role = $user->role->identifier;
if($role !== 'admin' && $role !== 'other-role-that-has-access'){
App::abort(401); // Throw an unauthorized error
}
Instead of throwing an error you could also make a redirect, render a view or do basically whatever you want. Just do something that stops further execution so your controller action doesn't get called.
Edit
Instead of using Closure function, you can use predefined filters (from the routes.php or filters.php)
$this->beforeFilter('filter-name', array('only' => array('fooAction', 'barAction')));
For more information, check out the documentation

Resources