0

I am new to laravel. i have seen some related posts but i could not find right answer. I made an auth using php artisan make:auth, i have a directory publicPages. I have changed the auth.login view to my custom publicPages.login and publicPages.register. Registration process works fine, inserts the data into users table. but it does not login the user. When i go to login view and enter credentials. It neither give any error nor log the user in. just redirects it to back.

Here are routes:

Route::auth();
Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController'
]);

Route::group(array('namespace' => 'UserControllers'), function()
{
    Route::group(['middleware' => ['web']], function() {
        Route::group(['middleware' => 'auth'], function () {
        Route::get('community', 'UserController@showCommunity');
        Route::post('communities', 'UserController@addCommunity');
        Route::get('edit/{id}', ['as' => 'edit', 'uses' => 'UserController@editCommunity']);
        Route::get('delete/{id}', 'UserController@deleteCommunity');
        Route::post('update/{id}', ['as' => 'update', 'uses' => 'UserController@updateCommunity']);
        Route::get('create', 'IdeaController@displayPost');
        Route::post('idea', 'IdeaController@storePost');
        Route::get('users', 'UserController@showUserListing');
        Route::get('deleteUser/{id}', 'UserController@deleteUser');
        Route::get('delete/idea/{id}', 'IdeaController@deleteIdea');
        Route::get('approve/{id}', 'IdeaController@approveIdea');
    });
    });

Controller:

class UserController extends Controller {

    //constructor
    public function __construct() {
        $this->middleware('auth');
    }

I know when i would use $this->middleware('auth'); it would redirect to login page for every UserController function. which is working fine.

View:

 <form id="login-form" class="clearfix" action="{{url('/login')}}" method="post">
 <input type="hidden" name="_token" value="{{ csrf_token() }}">
 <p class="rs pb30">Please Provide your Credentials to Verify Your Identity</p>
 <div class="form form-post-comment">
 <div class="fa-align-center">
 <label for="login_email">
 <input id="login_email" type="email" name="email" class="txt fill-width txt-name{{ $errors->has('email') ? ' has-error' : '' }}" placeholder="Enter Your Email" required="required"/>
 </label>
 @if ($errors->has('email'))
   <span class="help-block">
   <strong>{{ $errors->first('email') }}</strong>
   </span>
 @endif
 <br><br>
 <label for="password">
 <input id="password" type="password" name="login_password" class="txt fill-width txt-email" placeholder="Enter Your Password" required="required"/>
 </label> <br><br>
 <label for="links">
 <a href="/changepassword" class="txt-emphasis">Forgotten Password?</a>
 <p>Don't have an account? <a href="/register" class="txt-emphasis">Register Here</a> </p>
 </label>
 </div>

 <div class="clear"></div>
 <p >
 <span id="response"></span>
 {{--<input type="submit" class="btn btn-submit-comment" value="Login">--}}
 <button class="btn btn-submit-comment" form="login-form">Login</button>
 </p>
 </div>

Here is AuthenticatesUsers file:

<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
//use App\Http\Requests\UserRequest;

trait AuthenticatesUsers
{
    use RedirectsUsers;

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return $this->showLoginForm();
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        $view = property_exists($this, 'loginView')
                    ? $this->loginView : 'auth.authenticate';

        if (view()->exists($view)) {
            return view($view);
        }

        return view('publicPages.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postLogin(Request $request)
    {
        return $this->login($request);
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);

        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if ($throttles && ! $lockedOut) {
            $this->incrementLoginAttempts($request);
        }

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $throttles
     * @return \Illuminate\Http\Response
     */
    protected function handleUserWasAuthenticated(Request $request, $throttles)
    {
        if ($throttles) {
            $this->clearLoginAttempts($request);
        }

        if (method_exists($this, 'authenticated')) {
            return $this->authenticated($request, Auth::guard($this->getGuard())->user());
        }

        return redirect()->intended($this->redirectPath());
    }

    /**
     * Get the failed login response instance.
     *
     * @param \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        return redirect()->back()
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }

    /**
     * Get the failed login message.
     *
     * @return string
     */
    protected function getFailedLoginMessage()
    {
        return Lang::has('auth.failed')
                ? Lang::get('auth.failed')
                : 'These credentials do not match our records.';
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function getCredentials(Request $request)
    {
        return $request->only($this->loginUsername(), 'password');
    }

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogout()
    {
        return $this->logout();
    }

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function logout()
    {
        Auth::guard($this->getGuard())->logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

    /**
     * Get the guest middleware for the application.
     */
    public function guestMiddleware()
    {
        $guard = $this->getGuard();

        return $guard ? 'guest:'.$guard : 'guest';
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function loginUsername()
    {
        return property_exists($this, 'username') ? $this->username : 'email';
    }

    /**
     * Determine if the class is using the ThrottlesLogins trait.
     *
     * @return bool
     */
    protected function isUsingThrottlesLoginsTrait()
    {
        return in_array(
            ThrottlesLogins::class, class_uses_recursive(static::class)
        );
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return string|null
     */
    protected function getGuard()
    {
        return property_exists($this, 'guard') ? $this->guard : null;
    }
}

is There anything i need to change in postLoginForm() ? Thanks

update 2: I have changed postLoginForm() function's code to

 if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        } else {
 echo 'not logged in';
}

now finally it prints not logged in but even i use true credentials it says not logged in,

Qasim Ali
  • 587
  • 2
  • 11
  • 28

2 Answers2

0

Try to remove web middleware from routes.php, because it applies automatically since 5.2.27 and if you apply it manually it can cause errors similar to yours.

Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • thanks for your reply, I have also tried that. At first i did not have it in `routes.php`. @Alexey Mezenin – Qasim Ali May 05 '16 at 07:12
  • Have you updated the view paths in `showLoginForm` function ? – Vikas May 05 '16 at 07:31
  • this is showLoginForm `public function showLoginForm() { $view = property_exists($this, 'loginView') ? $this->loginView : 'auth.authenticate'; if (view()->exists($view)) { return view($view); } return view('auth.login'); }` Do i have to change `return view('auth.login')` to `return view('publicPages.login)'` ? – Qasim Ali May 05 '16 at 07:42
  • I have also changed the view of `showLoginform()` still no success @Vikas – Qasim Ali May 05 '16 at 10:29
0

According to your routes file, your login route is /auth/login not /login. So I suggest you to change the action in your view file as:

action="{{url('/auth/login')}}"

EDIT

Since Route::auth(); is already added at the top of your routes file, you do not need following in your routes file:

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController'
]);

Please remove that and revert the url in login form.

Vikas
  • 993
  • 1
  • 10
  • 16
  • I have also changed it. but nothing worked. `login` view neither gives any authentication error on wrong input nor it log in the user. – Qasim Ali May 05 '16 at 07:25
  • when i removed suggested part of code. it is throwing a `NotFoundHttpException` @Vikas – Qasim Ali May 05 '16 at 12:05
  • Have you also reverted back the action in form ? – Vikas May 05 '16 at 12:07
  • yes i reverted it back to `\login` But login is still now working it looks like it only refreshes the page – Qasim Ali May 05 '16 at 12:11
  • It is strange if `login` is not working `register` should also not work. But registration is working properly – Qasim Ali May 05 '16 at 12:15
  • can you try printing the data in `login` function inside `AuthenticatesUsers.php` file to verify if the request is reaching there or not ? – Vikas May 05 '16 at 12:18
  • I commented out`postLoginForm()` this line `return $this->login($request);` and wrote `echo "hello"` inside it. It worked and printed hello @Vikas – Qasim Ali May 05 '16 at 12:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/111143/discussion-between-qasim-ali-and-vikas). – Qasim Ali May 05 '16 at 15:40