Laravel auth::attempt() not working - php

I'm newbie to Laravel and got stuck with login mechanism I'm using my custom login mechanism here (not using Laravel Authentication) and there I'm not able to login with authenticate credentials.
I want to login with credentials and after login the log should be maintain in login_master and redirected to home. but it is not maintaining plus if the credentials are wrong then it should redirect back to signin.blade.php but it's redirecting to home.
Here is the code
create_login_table.php (My Login Table Structure)
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLoginTable extends Migration
{
public function up()
{
Schema::create ('login_master',function($table)
{
$table->increments('login_id',true);
$table->integer('user_id')->unsigned();
$table->date('login_date');
$table->date('login_time');
});
// to create foreign key :)
Schema::table('login_master', function($table) {
$table->foreign('user_id')->references('user_id')->on('registration_master');
});
}
public function down()
{
Schema::dropIfExists('login_master');
}
}
LoginController (Controller for working with table)
namespace App\Http\Controllers;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Validator;
class LoginController extends Controller
{
public function loginform()
{
return view('signin');
}
public function authenticate(Request $request)
{
$userdata= Input::all();
$rules= array(
'email' => 'required|email',
'password' => 'required| min:6',
);
$validator = Validator::make($userdata,$rules);
if($validator->fails())
{
redirect('/signin')->withInput(Input::except('password'))->withErrors($validator);
}
else
{
$userdata= array(
'email' => Input::get('email'),
'password' => Input::get('pwd')
);
if(Auth::validate($userdata))
{
if(Auth::attempt($userdata))
{
$email= $userdata['email'];
$password= $userdata['password'];
$live_date=Carbon::now();
$log_date=$live_date->toDateString();
$log_time=$live_date->toTimeString();
$user_id= DB::select('select user_id from registration_master where email= ? and password = ?',[$email, $password]);
$record= DB::insert('insert into login_master
(user_id, login_date, login_time) values(?, ?, ?)',[$user_id, $log_date, $log_time]);
echo $email;
echo $password;
return Redirect::intended('/');
}
}
else
{
Session::flash('error', 'Something went wrong');
return Redirect::to('signin');
}
}
}
public function logout()
{
Auth::logout();
return Redirect::to('signin');
}
}
signin.blade.php (view for login)
<html>
<head>
<title>App Name - #yield('title')</title>
#include('library')
</head>
<body>
#include('header')
<div class="form-content">
<div class="headingstyle form-title">
<h1 class="heading1">Log in!</h1>
</div>
<form method="post" action="/home">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="formgroup">
<input class="input" type="text" name="uemail"required>
<label class="label">Email</label>
</div>
<div class="formgroup">
<input class="input" type="password" name="pwd"required>
<label class="label">Password</label>
</div>
<div class="formgroup bottomstyle">
<div id="check-awesome" class="form-group checkbox">
<input type="checkbox" id="RememberMeUser" mame="RememberMeUser">
<label for="RememberMeUser">
<span></span>
<span class="check"></span>
<span class="box"></span>
Remember Me
</label>
</div><!--Login-->
<input type="submit" value="Login"><br>
<a data-dismiss="modal" class="button cancelbtn">Cancel</a><br>
<span class="links"> <a class="bottomlink" href="#">Forgot Password?</a></span><br>
<span class="links">New User
<!--<a class="bottomlink" href="#" data-dismiss="modal" data-toggle="modal" data-target="#id02">Sign Up?</a> -->
{{ Html::linkAction('SignUpController#signupform','Sign Up', array(), array('class' => 'bottomlink')) }}
</span>
</div>
</form>
</div>
<div>
#include('footer')
</div>
</body>
</html>

You will need to configure app/auth.php or dotenv to use your own custom model with the Auth Guard helper in Laravel. There you can set the model and table you want to use.
Else you could implement your own Auth helper/facade to save logged_in_user_id in session. Your custom authentication will basically confirm the passed user credentials and store the logged_in_user_id in session. Your logout method will likewise clear this id from session when called.

Related

Laravel Error to inicialice ValidationFactory

I'm making my login system, through the LoginController controller, which in turn calls a request called loginRequest [I still have to update some names to Pascal]
My request only has two rules that username and password are required.
Then in a function getCredentials() I capture the username of this and validate that it is an email or not, this to give the user the option to log in both ways.
To identify if the user is actually an email, create a method 'isMail' in which I establish $factory with the content validated through an alias set to Validacion\Factory , ValidationFactory, but when executing the submit button it throws me the error :
Target [Illuminate\contracts\Validation\Factory] is not instantiable.
Could you help me?
template [login.blade.php]:
#extends('components\header')
<section class="vh-100">
<div class="container-fluid h-custom">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-4">
<img src="{{ URL::asset('img/logo.png') }}"
class="img-fluid" height="500">
</div>
<div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
<form action="{{route('samein.login')}}" method="POST">
#csrf
<!-- Email input -->
<div class="form-outline mb-4">
<input type="text" name="username" class="form-control form-control-lg"
placeholder="Usuario" />
<label class="form-label" for="form3Example3">Usuario</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="password" class="form-control form-control-lg"
placeholder="Contraseña" />
<label class="form-label" for="form3Example4">Contraseña</label>
</div>
<div class="text-rigth text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">Iniciar Sesión</button>
</div>
</form>
</div>
</div>
</div>
</section>
controller[LoginController.login]
<?php
namespace App\Http\Controllers;
use App\Http\Requests\loginrequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Queue\RedisQueue;
class LoginController extends Controller
{
public function index(){
return view('login');
}
public function login( loginrequest $request ){
$credentiales = $request->getCredentials();
if( Auth::validate($credentiales) ){
return redirect()->to('login')->withErrors('auth.failed');
}
$user = Auth::getProvider()->retrieveByCredentials($credentiales);
Auth::login($user);
return $this->authenticated($request,$user);
}
public function authenticated (Request $request,$user){
return redirect('accountModule.indexusers');
}
}
and my Request[loginrequst.php]
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\contracts\Validation\Factory as ValidationFactory;
class loginrequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
public function getCredentials(){
$username = $this->get('username');
if( $this->isMail($username) ){
return['email'=> $username,
'password' => $this->get('password')
];
}
return $this->only('username','password');
}
public function isMail($value){
$factory = $this->container->make(ValidationFactory::class);
return !$factory->make(['username'=>$value],['username'=>'email'])->fails();
}
}
I was reading your problem and I found interesting the way you plan to check if the email is there or not.
I know it doesn't answer your question but you could try the following:
In your Request:
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
In your controller:
public function login( loginrequest $request ){
$field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('username')]);
//validate credentials
if (!Auth::validate($request->only($field, 'password'))) {
return redirect()->to('login')->withErrors('auth.failed');
}
//create a session
$user = Auth::getProvider()->retrieveByCredentials($request->only($field, 'password'));
Auth::login($user);
return redirect()->to('/');
}
don't forget to configure your web.php file, so that the routes work for you. I hope I've helped.

Laravel 5.7 Custom Login Not Working - New Installation

I have a new installation of laravel 5.7
I have created the database and users table with dummy info manually and connected the database with the application.
Can anyone please point out why the following code isn't working.
login.blade.php
<div class="form box">
<h1 align="center">Login - MobileInfo</h1>
<br />
#if(isset(Auth::user()->username))
<script>window.location="main/success"</script>
#endif
#if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">x</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('login/checklogin') }}">
{{ csrf_field()}}
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" />
</div>
<div class="form-group">
<input type="submit" name="login" class="btn btn-primary" value="Login" />
</div>
</form>
</div>
</div>
Login Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class LoginController extends Controller
{
public function index()
{
return view ('login');
}
function checklogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
$user_data = array(
'username' => $request->get('username'),
'password' => $request->get('password')
);
if(Auth::attempt($user_data))
{
return redirect('login/success');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
function success()
{
return view('dashboard');
}
function logout()
{
Auth::logout();
return redirect('login');
}
}
web.php
Route::get('/', 'LoginController#index');
Route::post('login/checklogin', 'LoginController#checklogin');
Route::get('login/success', 'LoginController#success');
Route::get('login/logout', 'LoginController#logout');
The error I see after adding any of the correct combinations of username/password is the else block of Auth::attempt($user_data), that is "Wrong Login Details".
Laravel store passwords using its hashing algorithm and then validate/compare with same hashing algorithm.
The problem is, you stored literal passwords in database, that's why laravel is unable to validate those passwords. Laravel is expecting hashed password from database.
Literal password won't work. So ...
#1
Best solution is, make a signup form as well (using laravel Auth) and insert demo data through that signup form. Laravel will store passwords after hashing it, and eventually successfully validating those passwords.
#2
Another(complex/tedious) solution is, find out laravel's hashing algorithm and hash passwords with a separate php script. Then store hashed passwords in database directly. You don't need signup form in this case because you are doing it manually.
Update for solution # 2
Use below code to hash your literal passwords in laravel 5.x.
$hashedpassword = bcrypt('plaintextpassword');
By default, Laravel auth provide authentification with email, so to use another field to login, you may define it in LoginController.
public function username()
{
return 'username';
}
Documentation

can't get access to admin dasheboard

in my laravel project, I specified 2 guards, 1 for users and 1 for admins.
everything was working properly and today I find out that I couldn't log in to the admin page.
I don't know what happened! I did not change anything!!
when I try to log in as an admin, the login page gets reloads again!
btw, for the case of users, everything works fine!
this is the code
Adminlogincontroller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Admin;
class AdminLoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/admin';
public function __construct()
{
$this->middleware(array('guest:admin','guest:web'))->except('logout');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout(Request $request)
{
$this->guard('admin')->logout();
$request->session()->invalidate();
return redirect()->route('AdminLogin');
}
public function showLoginForm()
{
return view('Admin.admin-login');
}
protected function guard()
{
return Auth::guard('admin');
}
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
}
blade page
<form action="/admin/login" method="post">
{{csrf_field()}}
<div class="input-field col s12">
<i class="material-icons prefix">email
</i>
<input id="icon_prefix" name="email" type="text" class="validate">
<label for="icon_prefix" style="color:#fff;">E-Mail</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input id="icon_prefix" name="password" type="password"
class="validate">
<label for="icon_prefix" style="color:#fff;">Mot de passe</label>
</div>
<p>
<input type="checkbox" class="filled-in" id="filled-in-box" />
<label for="filled-in-box" >Se rappeler de moi?</label>
Mot de passe oublié
</p>
<div class="row">
<div class="col s12">
<input type="submit" class="btn hoverable purple white-text" style="margin-top:30px;" value="connexion">
</div></div>
</form>
routes:php
Route::post('/admin/login', 'Admin\AdminLoginController#login');
Route::get('/admin/logout', 'Admin\AdminLoginController#logout');
Route::get('/admin', 'Admin\AdminController#show')->name('dashboard')

I am working on authentication in laravel when i try to login it show error method not allowed http exception

I have followed a tutorial to add authentication to my application. I have a login route which has the method post and the form is also submitting as a post method. But whenever I click on the login button. Laravel throws an error of MethodNotAllowed. I assume that it is getting the method as a get request but the route is a post. Error is in thecompiled.php.
Route
Route::any('signup',['as' => 'signup' , 'uses' => 'Auth\AuthController#getRegister']);
Route::any('loginForm',['as' => 'loginForm' , 'uses' => 'Auth\AuthController#showLoginForm']);
Route::post('login',['as' => 'login' , 'uses' => 'Auth\AuthController#login']);
Route::any('postRegister',['as' => 'postRegister' , 'uses' =>'Auth\AuthController#postRegister']);
View
<form id="login" method="post" action="{{ route('login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input type="email" placeholder="User Email" id="email" name="email" class="form-control" value="{{old('email')}}"/>
</div>
<div class="form-group">
<input type="password" placeholder="Your Password" id="password" name="password" class="form-control" {{--value="{{old('email')}}"/--}}>
</div>
<div class="row">
<div class="mj_checkbox">
<input type="checkbox" value="1" id="check2" name="checkbox">
<label for="check2"></label>
</div>
<span> remember me</span>
</div>
</div>
<div class="form-group pull-right">
<span>forget password ?</span>
</div>
</div>
</div>
</div>
<input type="submit">
</div>
</form>
{authentication code is here}
<?php namespace App\Http\Controllers\Auth;
//use \App\Http\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use App\Http\Models\Company;
use Hash;
class AuthController extends Controller {
/**
* the model instance
public function __construct(Guard $auth, \App\User $user)
{
$this->user = $user;
$this->auth = $auth;
$this->middleware('guest', ['except' => ['getLogout']]);
}
public function getRegister()
{
return view('public-pages.Home.signup');
public function postRegister(Request $request)
{
$company = new Company;
$company-> companyName = $request -> companyName;
$company-> email = $request -> email;
$company-> password = Hash::make($request-> password);
$company-> address = $request -> address;
$company-> employeeName = $request -> employeeName;
$company-> phone_no = $request -> phone_no;
$company-> country = $request -> country;
$company-> city = $request -> city;
$company -> save();
return redirect('loginForm');
}
public function showLoginForm()
{
return view('public-pages.Home.login');
}
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect('Private-pages.Company.cmp-home');
} else {
return redirect('/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
public function getLogout()
{
$this->auth->logout();
return redirect('/');
}
}

Laravel : BadMethodCallException Method [store] does not exist

I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.

Categories