1
votes

I tried to use auth::attempt() for my login page. But auth::attempt() always returns false. I tried all the other ways available in older stackoverflow posts but still couldn't find the correct solution. I am new to laravel and want to know how can I check if 'email' and 'password' matches with any record in my users table without using laravel auth?

users.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class users extends Authenticatable 
{
    use Notifiable;
    protected $fillable = ['name', 'username', 'password', 'email',];

}

login.blade.php

<!DOCTYPE html>
<html>
    <head>
    <title>SUST ONLINE EXAM - Student Login</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style type="text/css">
      .box{
      width:600px;
      margin:0 auto;
      border:1px solid #ccc;
    }
    </style>
    </head>
    <body>
    <br />
    <div class="container box">
    <h3 align="center">STUDENT LOGIN!</h3><br />

    @if(isset(Auth::user()->email))
      <script>window.location="/student";</script>
    @endif

    @if ($message = Session::get('error'))
    <div class="alert alert-danger alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <strong>{{ $message }}</strong>
    </div>
    @endif

   @if (count($errors) > 0)
    <div class="alert alert-danger">
     <ul>
     @foreach($errors->all() as $error)
      <li>{{ $error }}</li>
     @endforeach
     </ul>
    </div>
   @endif

   <form method="post" action="{{ url('/student') }}">
    {{ csrf_field() }}
    <div class="form-group">
     <label>Enter Email</label>
     <input type="email" name="email" class="form-control" />
    </div>
    <div class="form-group">
     <label>Enter Password</label>
     <input type="password" name="password" id="p1" class="form-control" />
    </div>
    <div class="form-group">
     <input type="submit" name="login" class="btn btn-primary" value="Login" />
    </div>
   </form>
  </div>

<!--
 @foreach($data as $value)
  <table>
  <tr>
    <td> {{ $value->email }} </td>
    <td> {{ $value->password }} </td>
  </tr>
</table>
  @endforeach
-->

 </body>
</html>

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('index');
});

Route::get('/welcome', function () {
    return view('index');
});

Route::get('/register', function () {
    return view('registration');
});

Route::get('/student', function () {
    return view('studentRegistration');
});

Route::get('/create-exam', function () {
    return view('createExam');
});

Route::get('/login', function () {
    return view('login');
});


Route::get('/login', 'Controller@getdata');


Route::post('/student', 'Controller@checklogin');


//Route::get('/logout', 'LoginController1@logout');
//Route::get('/student', 'LoginController1@successlogin');


Route::post('/insert', 'Controller@insert');

//Auth::routes();

//Route::get('/home', 'HomeController@index')->name('home');

Controller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use DB;
use Auth;
use Validator;
use Hash;
use App\users;
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    function insert(Request $req)
    {
        $this->validate($req, [
            'name' => 'required',
            'username' => 'required',
            'password' => 'required',
            'email' => 'required'
        ]);
        $Name = $req->input('name');
        $Username = $req->input('username');
        $Password = $req->input('password');
        $Password = Hash::make('password');
        $Email = $req->input('email');

        DB::table("users")->insert(["name"=>$Name,"username"=>$Username,"password"=>$Password,"email"=>$Email]
        );

    //  DB::table('users')->insert($data);
        echo "user inserted";
    }

    function checklogin(Request $request)
    {
        $this->validate($request, [
            'email'   => 'required|email',
            'password'  => 'required|min:3'
        ]);


        $auth = array(
            'email'=>$request->get('email'),
            'password'=> $request->get('password'));

        //dd($auth);
        if(Auth::attempt($auth))
        {
        // return back()->with('error', 'RIGhT Login Details');   
             return redirect('student');
        }
        else
        {
            return back()->with('error', 'Wrong Login Details');
        }

    }

    function successlogin()
    {
        return view('studentRegistration');
    }

    function logout()
    {
        Auth::logout();
        return redirect('index');
    }

   public function getdata()
    {
        $data['data']=DB::table('users')->get();
        return view('login',$data);
    }


}

I expected that auth::attempt() would return true when i entered email and password saved in my mysql correctly.I am new to laravel, I need to know is there any other way to verify email and password without auth::attempt()? I am fed up with this auth::attempt() thing! In short lines: 1) Password is hashed. 2) Auth::attempt() returns false always 3) I used mysql db, changed users.php model according to laravel User.php.

1

1 Answers

0
votes

Basically This is the common option that, you check email and password. Like,

if((email_from_input == email_from_database) && (password_from_input == password_from_database)) {
     // Credential match. now you can do any action.
}

In any framework or, for our security issue, we don't insert password directly as plain text. We use some encryption algorithm. For your case you used hashing algorithm by $Password = Hash::make('password');

After that, you can not check plain text of password with database. So, the above function for your case will be,

if((email_from_input == email_from_database) && (Hash::make('password_from_input') == password_from_database)) {
     // Credential match. now you can do any action.
}

But remember, there have some basic to intermediate security in laravel Auth::attemp() So, My suggestion will be, find out why this always return false. And it true/false as you desires.

Try attemptLogin Instead of attempt . This also can solve your problem.

Never forget to add use AuthenticatesUsers; inside class and Illuminate\Foundation\Auth\AuthenticatesUsers; on top. then try.