I make many projects with Laravel 5.6 with the same login setup (Use Auth facade), but with one shared hosting the users can't log in. When you enter the correctly mail and password, only reload de login page WITHOUT ANY ERRORS, when in my controller all the views return errors or a message.
This is the code of my login (Works in all servers except in this):
public function login(Request $request) {
$rules = array(
'email' => 'required|email|min:3|max:88',
'password' => 'required|min:3|max:88',
);
$messages = [
'required' => 'El :attribute es requerido',
'email' => 'Tiene que ingresar un mail válido',
'min' => 'Longitud del campo :attribute no válido',
'max' => 'Longitud del campo :attribute no válido',
];
$validator = Validator::make($request->all(), $rules, $messages);
if($validator->fails()) {
return redirect()->intended('admin')->withErrors($validator);
} else {
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
return redirect()->intended('admin');
} else {
return redirect()->intended('admin')->withErrors(['loginFail' => 'Usuario/Contraseña incorrectos']);
}
}
}
If I enter a wrong email or password in any server, this return me to the login view with the errors, but in these the errors don't appear and I can't login with the correct email and password.
I call to the hosting and say me that is nothing wrong, how can i solve it?
Related
In my project I am trying to validate that registration information and authenticate myself when I register. But what is happening is that when you register, you send me to the Login page, this happens because when I click on the register button, you send me to a route protected by the Middleware "Auth". That is, you are not authenticating in the same registration action.
protected function create(RequestFormRegister $data)
{
$userCount = User::where(['email'=> $data['email']])->count();
if($userCount>0){
return redirect()->back()->with('error', '¡El correo ya existe!');
}else{
$user = User::create([
'nombres' => $data['nombres'],
'apellidos' => $data['apellidos'],
'ni' => $data['ni'],
'role_id' => 2,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'password_confirmation' => Hash::make($data['password_confirmation']),
'remember_token'=> str_random(15),
]);
}
}
With the previous function the system records the data in BD. But then I have to go to the login. (Thing I don't want)
If I use the function that laravel brings by default
protected function create(array $data)
{
User::create([
'nombres' => $data['nombres'],
'apellidos' => $data['apellidos'],
'ni' => $data['ni'],
'role_id' => 2,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'password_confirmation' => Hash::make($data['password_confirmation']),
'remember_token'=> str_random(15),
]);
}
I get the following error
enter image description here
What would be the solution for this case. I am using Laravel 5.8 and AdminLte as a template
You can manually login the newly created user and redirect it to homepage.
protected function create(RequestFormRegister $data)
{
$userCount = User::where(['email'=> $data['email']])->count();
if($userCount>0){
return redirect()->back()->with('error', '¡El correo ya existe!');
}else{
$user = User::create([
...
]);
// Manually logging user
Auth::login($user);
return redirect()->route('homepage');
}
}
https://laravel.com/docs/master/authentication#other-authentication-methods
I'm creating a login function in Laravel 5.4 and I want to show error message in the view when the password is incorrect. Also I have a custom message for account approval so it makes things a bit difficult for me. Meanwhile I put those messages together but is not very user-friendly. How can I separate them?
This is my controller:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
As result i want to replace Wrong password or this account not approved yet with two separate messages:
If password is wrong to show: Password is wrong
If account not approved show: This account not approved yet
You can pass custom error messages for each validation rule, you can do this:
public function login(Request $request)
{
//Error messages
$messages = [
"email.required" => "Email is required",
"email.email" => "Email is not valid",
"email.exists" => "Email doesn't exists",
"password.required" => "Password is required",
"password.min" => "Password must be at least 6 characters"
];
// validate the form data
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
], $messages);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
} else {
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors([
'approve' => 'Wrong password or this account not approved yet.',
]);
}
}
Before this, you have to include Validator class:
use Illuminate\Support\Facades\Validator;
Without writing a new custom login method we can easily handle a custom wrong password message with the Auth default login process.
Open LoginController from the location: app/Http/Controllers/Auth/
Include the Request class if not exit on top of the controller
use Illuminate\Http\Request;
Finally add below line of codes at the very bottom of your LoginController to process the response error with custom message
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
// Load user from database
$user = \App\User::where($this->username(), $request->{$this->username()})->first();
if ($user && !\Hash::check($request->password, $user->password)) {
$errors = ['password' => 'Wrong password'];
}
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
You can use like this:
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
Controller:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required|min:6'
]);
// attempt to log
if (Auth::attempt(['approve' => '1', 'email' => $request->email, 'password' => $request->password ], $request->remember)) {
// if successful -> redirect forward
return redirect()->intended(route('user.overview'));
}
// if unsuccessful -> redirect back
return Redirect::back()
->withInput()
->withErrors(
[
'password' => 'Wrong Password',
],
[
'approve' => 'Account not approved',
],
);
}
i am creating a web project and i want to get login with facebook but i have this annoying error please help me!
this is my routes
Route::get('auth/facebook','AuthController#redirectToProvider');
Route::get('auth/facebook/callback','AuthController#handleProviderCallback');
this is my controller
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();}
public function handleProviderCallback(){
$user = Socialite::driver('facebook')->user();
$data = ['name'=>$user->name, 'email'=>$user->email, 'password'=>$user->token];
$userDB = User::where('email', $user->email)->first();
if(!is_null($userDB)){
Auth::login($userDB);
}
else{
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => $data['token'],
]);
Auth::login($userDB);}return redirect('/');
}
and thi is th service.php
'facebook' =>
[
'client_id' => '1005472786205748',
'client_secret' => '75d15a7e24c7d61ddecd25a490baeaaf',
'redirect' => 'http://localhost/PFE/public/auth/facebook',
],
when i click on the boutton of login with facebook it redirect me to facebook.com i enter my adress mail and password but it tell me this :La page www.facebook.com ne fonctionne pas
www.facebook.com vous a redirigé à de trop nombreuses reprises.
Change your 'redirect' field value to your callback route.
'redirect' => 'http://localhost/PFE/public/auth/facebook/callback',
This way, you handle the response instead of redirecting to the same route.
I get the wrong error messages. My purpose is following :
1. checking username / pw combination, and if it doesn't match, "wrong username/pw combination" error through validator.
2. captcha (mews) is troubling me. Even user enters true captcha chars (no case-sensitive by config) I get the error message.
Here is my validator :
FYI: i have a table "user" instead of users, and i can use it nicely in other controllers.
protected function loginValidator()
{
$message = array(
'exists:user,username' => 'Wrong username/pass combination',
'exists' => 'Wrong :attribute.',
'required' => ':attribute cannot be empty',
'captcha' => 'Wrong captcha'
);
return Validator::make(Input::all(),[
'usernameInput' => 'required|exists:user,username',
'passwordInput' => 'required',
'captchaInput' => 'captcha|required'
], $message);
}
Even if username/pass combination is true, i get wrong captcha message.
Thanks in advance.
protected function loginValidator()
{
$validator = Validator::make(
array(
'name' => 'Dayle',
'password' => 'lamepassword',
'email' => 'email#example.com'
),
array(
'name' => 'required',
'password' => 'required|min:8',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
$data['messages'] = $validator->messages()->all();
}
else
{
//complete validation
}
return View::make('home.login', $data);
}
I'm sorry if this is a duplicate (i searched everywhere for a possible solution) but i just have to know how to use a jquery code after submitting a form in Laravel.
FYI: I am using Laravel and i use a Redirect::back() when form credentials are correct.
Here's my Controller code used when submitting form:
public function store()
{
$user = array(
'voornaam' => Input::get('voornaam'),
'achternaam' => Input::get('achternaam'),
'email' => Input::get('email'),
'telefoonnummer' => Input::get('telefoonnummer'),
'bedrijfsnaam' => Input::get('bedrijfsnaam'),
'adres' => Input::get('adres'),
'opmerking' => Input::get('opmerking'),
'titel' => Input::get('paginanaam'),
'datum' => Input::get('dedatum'),
'personen' => Input::get('personen'),
);
$data = $user;
$rules = array(
'voornaam' => 'required',
'achternaam' => 'required',
'email' => 'required',
'adres' => 'required',
'bedrijfsnaam' => 'required',
'datum' => 'required',
);
$messages = array(
'voornaam.required' => 'Vul a.u.b. uw voornaam in.',
'achternaam.required' => 'Vul a.u.b. uw achternaam in.',
'email.required' => 'Vul a.u.b. uw emailadres in.',
'adres.required' => 'Vul a.u.b. uw factuuradres in.',
'bedrijfsnaam.required' => 'Vul a.u.b. uw bedrijfsnaam in.',
'datum.required' => 'Selecteer a.u.b. een datum.',
);
if(Input::get('spamcheck'))
{
return 'Stop spamming please.';
}
$validation = Validator::make($data, $rules, $messages);
if ( $validation->fails() )
{
return Redirect::back()->withErrors($validation)->withInput();
} else {
if(Input::get('kopie') === 'ja') {
Mail::send();
} else {
Mail::sendothermail();
}
return Redirect::back();
}
}
I deleted some unneccesary code from this controller (fyi) so you won't get distracted from my problem. When a user submits the form and it has errors, the errors are displayed at the top of the page. But, i would like to make something like: when a user submits the form, and credentials are ok, it reloads the page and should scroll to the form and hides the form and displays a success message instead of the form.
IF this is a duplicate for a similair problem, please let me know.
Upon successful validation return to your view with session flash data to perform if success load js
Controller
return Redirect::back()->with('success');
View - demo
#if(Session::get('success'))
<script>
$('html, body').animate({
scrollTop: $("#form").offset().top
}, 2000);
window.setTimeout(function(){
$('#form').hide().next('#success').show();
}, 1500);
</script>
#endif
Give the element that contains either the form+error or the succes message a 'name' attribute, say 'form'. Then, don't use Redirect:back(), but instead Redirect to the page with #form behind it, for example 'index.php#form'.
JavaScript would offer some more options.