I have a login page which shows flash notifications on errors.
following are errors on which it shows flash notification:
1.when the user has not confirmed his/her email id.
2.when user enters wrong login credentials.
it was working fine few days ago but now it shows error
undefined index password
my logic:
public function postSignIn(Request $request)
{
$this->validate($request,[
'loginEmail'=> 'required' ,
'loginPassword' => 'required'
]);
$remember = $request->input('remember_me');
$user=User::where('email', $request['loginEmail'])->first();
if(Auth::attempt(['email'=>$request['loginEmail'], 'password' => $request['loginPassword'],'confirmed'=>1],$remember))
{
//return redirect()->route('myplace');
return redirect()->route('myplace',['username' => $user->username]) ;
}
if(Auth::attempt(['confirmed'=>0]))
{
\Session::flash('message','Please verify your email!');
\Session::flash('alert-class', 'alert-warning');
return redirect()->back();
}
if(!Auth::attempt(['email'=>$request['loginEmail'], 'password' => $request['loginPassword']]))
{
\Session::flash('message','Login credentials are wrong!');
\Session::flash('alert-class', 'alert-warning');
return redirect()->back();
}
}
The problem is here:
if(Auth::attempt(['confirmed'=>0]))
You can't use attempt() without passing password. So try to use same code you use later in the code:
Auth::attempt(['email'=>$request['loginEmail'], 'password' => $request['loginPassword']])
Related
After login in to the website it is redirecting to the correct page according to inspect "network". However it's getting logged out and reloads the login page.
I am using Laravel 5.1 and here is the code of AuthController.php.
Can you find out what is wrong with this? It should redirect to "admin_message" and it is in the New Routegroup.
/**
* View login page
*/
protected function index(){
if(\Auth::check()){
return \Redirect::route('admin_messages');
}else{
return view('auth/login');
}
}
/**
* View login page
*/
protected function verifylogin(){
$input = Input::all();
$rules = array(
'email' => 'required|email|max:255',
'password' => 'required|min:6'
);
$validator = \Validator::make(Input::all(), $rules);
if($validator->fails()){
return \Redirect::route('login_index')
->withInput()
->withErrors($validator);
}else{
if (\Auth::attempt(array('email' => $input['email'], 'password' => $input['password']))){
$user = User::find(\Auth::id());
\Auth::setUser($user);
$user->login_count = $user->login_count +1;
$user->save();
return \Redirect::route('admin_messages');
}
return \Redirect::route('login_index')
->with('error_message', 'Invalid email/password. Please try again.')
->withInput();
}
}
Auth::setUser() doesn't touch your session. so It redirects to log in view. You want to instead be calling Auth::login($user)
I want the user to only post a comment when logged in. Otherwise a massege appears 'You must be logged in to post a comment'. If I logged in it works if not it doesnt just redirect back!
I solved it. The problem was that the PostCommentsController was in the admin middleware where you have to logged in to see If you are an admin. And if you not logged in redirect to index.
the Controller:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$data = [
'post_id' => $request->post_id,
'author' => $user->name,
'email' => $user->email,
'body' => $request->body
];
Comment::create($data);
$request->session()->flash('comment_success','Your comment have been submited and is waiting moderation');
return redirect()->back();
} else {
$request->session()->flash('login','You must be logged in to post a comment');
return redirect('/login')->back();
}
}
public function store(Request $request)
{
if (!Auth::check()) {
$request->session()->flash('login', 'You must be logged in to post a comment');
return redirect()->back();
}
$user = Auth::user();
$data = [
'post_id' => $request->post_id,
'author' => $user->name,
'email' => $user->email,
'body' => $request->body
];
if (Comment::create($data)) {
$request->session()->flash('comment_success', 'Your comment have been submitted and is waiting moderation');
return redirect()->back();
}
$request->session()->flash('comment_error', 'Your comment does not submited. Try again!!');
return redirect()->back();
}
In your else statement, just use this code return redirect('/login'); using back() function will redirect user back.
Laravel has the built in Auth system, if you use that you can use constructors like the example from my project.
public function __construct()
{
$this->middleware('auth');
}
This just says that the user cannot access any of the methods in this class without being logged in. If they are not logged in it will redirect them back to the login page. You can also have, in your views, #auth and #guest. I use this to show info on private information e.g. private servers can only be seen by the logged in user.
If you have any other questions I may be able to answer, let me know, I would love to help!
https://laravel.com/docs/5.6/authentication
I am using laravel multi-auth. I have a table column called status. At the time of login in, I want compare user whether it is active or in active. If active only login and if not give a message 'inactive account, please contacct to administrator'.
Here is my login controller.
<?php
namespace Modules\University\Http\Controllers;
class LoginController extends Controller
{
protected $redirectTo = '/university';
public function __construct()
{
$this->middleware('guest:university', ['except' => ['universityLogout']]);
}
public function showLoginForm()
{
return view('university::login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
//attempt to log the user in
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
/****Here I want check whether university status is active or not and give message if not else login*****/
return redirect()->intended(route('university.dashboard'));
}
Session::flash('failed', 'Login credential incorrect!');
return redirect()
->back()
->withInput($request->only('email', 'remember'));
}
public function universityLogout(Request $request)
{
Auth::guard('university')->logout();
return redirect(route('university.login'));
}
}
Thanks in advance.
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
if( Auth::guard('university')->user()->status == 'inactive')
{
return redirect()->route('university.dashboard-inactive');
}
return redirect()->intended(route('university.dashboard'));
}
If you want to check before login is attempted you may just query the DB by the email address to check its status and then procceed with login attempt if the status is active. If you want to login anyhow regardless of the status and redirect only if inactive, something like above would work.
In my laravel app, at the start I had decided to create my own custom login controller, rather than use the base one.
public function postSignin(Request $request, AppMailer $mailer) {
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('info', 'Could not sign you in with those details.');
}
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'verified' => 0]))
{
$mailer->sendEmailConfirmationTo(Auth::user());
Auth::logout();
return redirect()->back()->with('info', 'Email verification required.');
}
Auth::user()->last_login = new DateTime();
Auth::user()->save();
return redirect()->back()->with('info', 'You are now signed in.');
}
And now I want to edit this so that users can also login with their usernames and not just their emails, using the same field. However, the attempt method is confusing. It seems to expect an email even after I switch the values around.
The Auth documentation isn't very helpful in this case either. It asks me to add this:
public function username()
{
return 'username';
}
in the login controller, but obviously this is for a default setup.
You can use the 'FILTER_VALIDATE_EMAIL' checker.
$username = $request->get('username');
$password = $request->get('password');
$remember_me = $request->get('remember_me','1');
$field = filter_var($username,FILTER_VALIDATE_EMAIL)? 'email': 'username';
if(Auth::attempt([$field => $username,'password' => $password],$remember_me)){
//Auth successful here
}
Meaning FILTER_VALIDATE_EMAIL do check the string whether it is in email format or not.
I hope this sample code helps you.
-ken
I already looking for related issue with this but didn't solved yet.
link 1, link 2, link 3
Auth::attempt() is success
try to register session after Auth::attempt() is success
remember_token field on users table is always null
This is my code:
AuthController:
protected function login(Request $request){
$result = [];
$rules = ['email' => 'required|email', 'password' => 'required|alphaNum|min:3'];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()) {
$result['message'] = 'Login Failed';
}else{
$userdata = ['email' => $request->email, 'password' => $request->password];
if (Auth::attempt($userdata, $request->has('auth_remember'))) {
// dd(Auth::user()); << THIS DATA IS EXIST
// $request->session()->push('user.id', Auth::user()->id);
// $request->session()->push('user.name', Auth::user()->name);
// $request->session()->push('user.email', Auth::user()->email);
// dd($request->session()->all()); << THIS DATA IS EXIST
$result['message'] = 'Login successfull. Redirecting ...';
}else{
$result['message'] = 'User not found';
}
}
echo json_encode($result);
}
I have a middleware Auth when I go to http://.../dashboard, but...
Auth::check() return false
$request->session()->has('user') return false
Auth Middleware:
public function handle($request, Closure $next){
if($this->auth->viaRemember()) return $next($request);
if($this->auth->guest()){
if($request->ajax()){
return response('Unauthorized.', 401);
}else{
return redirect()->guest('login');
}
}
return $next($request);
}
storage/framework/session already set to 777
file session are generated
app timezone already match with server settings and database settings
Any help would be appreciated.
Why are you adding logged user data manually to the session, You can user use Auth::user() to get user data anytime after attempt
Delete this lines:
$request->session()->push('user.id', Auth::user()->id);
$request->session()->push('user.name', Auth::user()->name);
$request->session()->push('user.email', Auth::user()->email);
and verify with dd($request) the auth_remember
I think I resolve this issue.
Laravel authentication are not working when using Ajax. Just follow the documentation from http://laravel.com/docs/5.1/authentication and all should be worked!
But it's strange! Authentication with ajax are worked well in my localhost but no when I upload it to server.