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
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 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.
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']])
i have a column called active_user to show when a user is online(1). When i log a user in i set the active_user column to 1 but when i log the user out and check active_user it still shows online(1). what i want is that when i click the logout button the aactive_user column will change to offline(0) and also update it to the database. my login is below.
public function postSignIn(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
$user=User::whereRaw('email=?',[Input::get('email')])->first();
//this is where i set the active_user to 1
$user->active_user=1;
$user->save();
if($user!=null){
switch($user->role_id){
case 1:
if($user->status==0){
session()->flash('flash_message_error', ' Your Account has been deactivated. Contact the administrator');
return Redirect::to('admin/login');
}
return redirect()->route("index");
break;
then below is my logout function
public function LogOut($id) {
$user = User::find($id);
$user->active_user=1;
$user->save();
Auth::logout();
return redirect('admin/login');
}
in the logout function i want to change the active_user back to offline(0) but i keep getting an error "Missing argument 1 for App\Http\Controllers\AdminController::LogOut()"
Your route logout is now expecting an id attribute passed to it. This seems wrong to me as it is the authenticated user that you want to apply this logic to, having to pass their id to logout is unnecessary. For example if your logged in user has an id of 1, to logout with your code they would need to go to a url such as:
http://myapp.app/logout/1
Instead, use the Auth implementation to modify the user.
// Remove requirement for ID as a parameter
public function LogOut() {
$user = Auth::user();
$user->active_user=1;
$user->save();
Auth::logout();
return redirect('admin/login');
}
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.