2
votes

I have a question about the built in user authentication functionality in laravel. I got the authentication part to work but it doesn't seem like a user is stored in the session.
Admin Controler Code:

<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator, Input, Redirect; 
use DB;
use Session;

class AdminController extends Controller
{
    public function index(Request $request)
    {
        if(isset($_POST['submit'])){
                    $v = Validator::make($request->all(), [
                    'email' => 'required',
                    'password' => 'required',
                    ],
                    [
                        'required' => 'This field is required.'
                    ]);

                    if ($v->fails())
                    {
                        $messages = $v->messages();
                        return redirect()->back()->withErrors($v)->withInput();
                    }
                   else
                   {

                        $email = $request->input('email');
                        $pass = $request->input('password');
                        $whereData = [
                                ['email',$email],
                                ['password',md5($pass)]
                            ];

                       $res = DB::table('tbl_admin_users')->where($whereData)->get();
                        if(!empty($res)){
                            $userid=$res[0]->id;
                            $fname=$res[0]->fname;
                            Session::put('userid', $userid);
                            Session::put('fname', $fname);
                            return Redirect('admin/dashboard-listing');
                    }
                        else
                        {
                            Session::flash('message', 'Email/Password is invalid!'); 
                            Session::flash('alert-class', 'alert-danger');
                            return Redirect('admin/login');
                        }
                    }
          }
          else{
            return view('admin.admin-login');
          }  


    }


 public function logout()
 {
    Session::flush();
    return Redirect('admin/login');
 }


}

Middleware Authentication.php code:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        return $next($request);
    }
}

AuthController I have:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

Route after correct details and login page route:

Route::get('/admin/dashboard-listing',array('uses'=>'Admin\AdminDashboardController@index'));

After logout redirect route:

Route::get('/admin/login',array('uses'=>'Admin\AdminController@index'));

My question is that how can i use middleware in this code. because after logout i can easily access the url .back button is also worrking i want laravel user authentication through middleware ..

1
Post up all of your Routes file. - Option
already posted the after login and logout route no other route m using instead of this... - Apoorva
No i dont have actually i am newbie in laravel thats why i need to knw all abt this... - Apoorva
what if you want to load to the url after logout, what happen that you access the url with back button now?? - Sohel0415
currenty using logout function m getting redirect to login page but in that case session destroy but back button browser take me to the login state - Apoorva

1 Answers

0
votes

You need to manually login user with auth()->login():

$res = DB::table('tbl_admin_users')->where($whereData)->first();
if(!empty($res)) {
    $userid = $res[0]->id;
    $fname = $res[0]->fname;
    Session::put('userid', $userid);
    Session::put('fname', $fname);
    auth()->login($res);
    return Redirect('admin/dashboard-listing');
}

Alternatively, you can use the auth()->loginById($res->id) method.