enter image description here
Login is failed, the credencials email and password, is correct, but laravel dont acces to dashboard
The password reset is worng to, the email is correct and i try chance of credentials on myphpadmin but dont entry.
this is my code
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
If you're mass assignment while attempting authentication make sure the form requested keys must same as Model's $fillable keys.
then try this:
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$credentials = $request->validated();
if (Auth::attempt($credentials)) {
return redirect()->intended(RouteServiceProvider::HOME);
}
return back()->with('message', 'The given credentials are not matched');
}
if you're working with multi guards, try this:
public function store(LoginRequest $request)
{
$credentials = $request->validated();
if (Auth::guard('web')->attempt($credentials)) {
return redirect()->intended(RouteServiceProvider::HOME);
}
return back()->with('message', 'The given credentials are not matched');
}
I have tested this example code from your and my implementation
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\User;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Session::flush();
Auth::logout();
return redirect('/');
}
/**
* Registration page.
*
*/
public function registration()
{
return view('auth.registration');
}
/**
* Store new user request handler
*
*/
public function storeUser(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("dashboard")->withSuccess('have signed-in');
}
/**
* Store new user
*
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Dashboard for user
*
*/
public function dash()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('are not allowed to access');
}
}
Please check from your project and check flash messages if password was wrong check password hashing correctly
Related
I am try to integrate Google login with my application. Its working fine but it send your user back to login screen after google authentication. But when I click on the google login again it behaves like the user is already logged in. I dont want want the user to fall back to login when we comeback from google. Following are my files for controller and routes.
LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
/*
* Remove the socialite session variable if exists
*/
\Session::forget(config('access.socialite_session_name'));
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => __('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
*
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$errors = [];
if (config('auth.users.confirm_email') && !$user->confirmed) {
$errors = [$this->username() => __('auth.notconfirmed', ['url' => route('confirm.send', [$user->email])])];
}
if (!$user->active) {
$errors = [$this->username() => __('auth.active')];
}
if ($errors) {
auth()->logout(); //logout
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
return redirect()->intended($this->redirectPath());
}
}
SocialLoginController
namespace App\Http\Controllers\Auth;
use App\Models\Auth\User\User;
use App\Services\RoleService;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Socialite;
class SocialLoginController extends LoginController
{
use AuthenticatesUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/admin';
public function redirect($provider)
{
return Socialite::driver($provider)->stateless()->redirect();
}
public function googleCallback($provider)
{
$userSocial = Socialite::driver($provider)->stateless()->user();
$user = User::where(['email' => $userSocial->getEmail()])->first();
if($user){
Auth::login($user,true);
return redirect('admin/partners');
} else {
$user = User::create([
'name' => $userSocial->getEmail(),
'email' => $userSocial->getEmail(),
]);
$user->roles()->attach([RoleService::ROLE_AUTHENTICATED]);
return redirect('/admin');
}
}
}
routes/auth.php
Route::group(['namespace' => 'Auth', 'middleware' => ['force.ssl']], function () {
// Authentication Routes...
Route::get('login', 'LoginController#showLoginForm')->name('login');
Route::post('login', 'LoginController#login');
Route::get('logout', 'LoginController#logout')->name('logout');
// Social Authentication Routes...
Route::post('login', 'SocialController#login');
Route::get('login/{provider}', 'SocialLoginController#redirect');
Route::get('login/{provider}/callback', 'SocialLoginController#googleCallback');
});
Middleware/RedirectIfAuthenicated.php
class RedirectIfAuthenticated
{
/**
* 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)->check()) {
return redirect('/admin');
}
return $next($request);
}
}
return Socialite::driver($provider)->with(["prompt" => "select_account"])->redirect();
this is worked for me
I am trying to change hashing in the laravel.
So I made custom SHA256 with salt in the RegisterController.
Register completed but how to change in the login?
protected function create(array $data)
{
$salt = Str::random(8);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => '$SHA$' . $salt . '$' . hash('sha256', hash('sha256', $data['password']) . $salt),
]);
}
This is code of LoginController. $this->guard()->attempt($this->credentials($request)) this goes to something and hash then get token.
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Exceptions\VerifyEmailException;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
$token = $this->guard()->attempt($this->credentials($request));
if (! $token) {
return false;
}
$user = $this->guard()->user();
if ($user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail()) {
return false;
}
$this->guard()->setToken($token);
return true;
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*/
protected function sendLoginResponse(Request $request)
{
$this->clearLoginAttempts($request);
$user = $this->guard()->user();
$token = (string) $this->guard()->getToken();
$expiration = $this->guard()->getPayload()->get('exp');
return response()->json([
'token' => $token,
'token_type' => 'bearer',
'expires_in' => $expiration - time(),
]);
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$user = $this->guard()->user();
if ($user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail()) {
throw VerifyEmailException::forUser($user);
}
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
}
}
Here is (what I believe is) the correct way to add hashing functions:
Step 1: Create your hasher by implementing the Hasher contract:
namespace App;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
class Sha256Hasher implements HasherContract {
public function make($value, array $options = []) {
$salt = Str::random(8);
return '$SHA$' . $salt . '$' . hash('sha256', hash('sha256', $data['password']) . $salt),
}
public function info($value) {
// Implement something that works like https://www.php.net/manual/en/function.password-get-info.php
}
public function check($value, $hashedValue, array $options = [])) {
// Verify the hash here e.g.
return $this->make($value, $options) === $hashedValue;
// But more secure than this
}
public function needsRehash($hashedValue, array $options = []) {
return <a boolean whether the passwords needs rehashing>;
}
}
You can then extend the hashers with this hasher. In a service provider add:
Hash::extend('sha256', function () {
return new Sha256Hasher();
});
Then (finally) change your default hashing driver in your config/hashing.php:
'driver' => 'sha256',
This should switch your hashing to use your new driver and should not need any changes to views or models.
First, create this function where you can reuse it:
protected function hash($string){
return hash('sha256', $string . config('app.encryption_key'));
}
On user creation you have to call the function to hash the password:
protected function create(array $data){
return User::create([
'name' => $data['name'],
'password' => $this->hash($data['password'])
]);
}
On login, you would have to call hash function on password again:
protected function login(Request $request){
$user = User::where([
'email' => $request->request('email'),
'password' => $this->hash($request->input('password'))
])->first();
Auth::login($user);
$token = $user->createToken('MyApp')->accessToken;
return response()->json(compact('token', 'user'));
}
I think that is the best approach to consider.
I have a payment card. there is a link at the bottom of it that derives guest users to the login page. I want users redirect to the card payment route again after login. can you please help me how can I do that?
by the way I am new in laravel.
thanks for your time guys :X
here is loginController.php :
<?php
namespace App\Http\Controllers\Auth;
use App\Events\LoginLogged;
use App\Rules\Recaptcha;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('throttle:3,1')->only('login');
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
//'g-recaptcha-response' => ['required', new Recaptcha]
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return array_merge(($request->only($this->username(), 'password')), ['usr_is_admin' => 1]);
}
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'usr_name';
}
protected function authenticated(Request $request, $user)
{
event(new LoginLogged($request, $user));
}
}
here is redirectIfAuthenticated.php middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* 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)->check()) {
return redirect()->route('dashboard');
}
return $next($request);
}
}
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available. For example :
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
I want user to register and also buy a package. To do that I took input for registration details and package details. Now when I'm processing order to save package details in session and register, I get this error : Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\View\View given, called in C:\xampp\htdocs\rename\app\Traits\OrderRegister.php on line 63 and defined. I'm using an trait to register user and return back to function when registration is complete.
OrderController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Package;
use App\ListingType;
use Illuminate\Support\Facades\Auth;
use App\Order;
use Carbon\Carbon;
use App\Traits\OrderRegister;
class OrderController extends Controller
{
use OrderRegister;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index($type)
{
$listingtype = ListingType::where('type', '=', $type)->first();
if ($listingtype) {
$packages = $listingtype->packages()->get();
return view('packages.index', compact('packages'));
}
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
$package = Package::where('id', '=', $id)->first();
if (Auth::check()) {
return view('order.create_loggedin', compact('package'));
}
else {
return view('order.create_register', compact('package'));
}
}
/**
* Process a new order request. Store order values in session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function process(Request $request)
{
$order = ['package_id' => $request->package_id, 'order_qty' => $request->no_of_listing];
session(['order' => $order]);
if (Auth::guest()) {
return $this->register($request); // need to check session for orders available in OrderRegister trait.
}
return $this->store($request);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if($request->session()->has('order')) {
$package = Package::where('id', '=', $request->package_id )->first();
if($request->user() == Auth::user()) {
for( $n=1;$n<=$request->no_of_listing;$n++) {
$order = new Order;
$order->package_id = $request->package_id;
$order->user_id = Auth::user()->id;
$order->expire_at = Carbon::now()->modify('+'.$package->duration_in_months.' months');
$order->save();
}
return redirect('/');
}
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
trait : OrderRegister.php
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
trait OrderRegister
{
use RedirectsUsers;
/**
* 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',
'username' => 'required|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)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new UserProfile);
return $user;
}
/**
* Execute the job.
*
* #return void
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
return $this->store($request);
}
/**
* Get the guard to be used during registration.
*
* #return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
}
I could not find any solution for this error so created my own thread for the first time please someone help.
It throws an error because you are trying to login a vue.
in your OrderController.php you are using create method which return a view.
this method will override the create method on your trait.
So you have something like this :
Auth::guard($this->getGuard())->login(/* A view */);
you can at least rename the method on the trait from create to createUser for example.
then you call it from the guard like this :
Auth::guard($this->getGuard())->login($this->createUser($request->all()));
I am created a Laravel 5.2 application; I need to limit failure login attempts.I am created a AuthController with following code; But not working logging attempt lock.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Auth;
use URL;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
protected $maxLoginAttempts=5;
protected $lockoutTime=300;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
$this->loginPath = URL::route('login');
$this->redirectTo = URL::route('dashboard'); //url after login
$this->redirectAfterLogout = URL::route('home');
}
public function index()
{
return 'Login Page';
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'username' => 'required', 'password' => 'required',
]);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return redirect()->intended($this->redirectPath());
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath)
->withInput($request->only('username', 'remember'))
->withErrors([
'username' => $this->getFailedLoginMessage(),
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only('username', 'password');
}
/**
* 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'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
}
}
After many failure login their is no error message displayed. I am added some line to display error in login.blade.php file
Assuming you have implemented the make:auth artisan command of laravel.
Inside of the loginController, change the properties:
protected $maxLoginAttempts=5; to protected $maxAttempts = 5;
and
protected $lockoutTime=300; to protected $decayMinutes = 5; //in minutes
you need to use ThrottlesLogins trait in your controller
....
use AuthenticatesAndRegistersUsers, ThrottlesLogins ;
...
take a look here https://github.com/GrahamCampbell/Laravel-Throttle
and here https://mattstauffer.co/blog/login-throttling-in-laravel-5.1
Second link is for L5.1, but I think shouldnt be different for L5.2
Hope it helps!
Have a nice day.
Just overriding the following 2 functions maxAttempts and decayMinutes will be good to go. This 2 functions belong to Illuminate\Foundation\Auth\ThrottlesLogins.php file. I have tested on Laravel 5.6 version and working fine.
public function maxAttempts()
{
//Lock on 4th Failed Login Attempt
return 3;
}
public function decayMinutes()
{
//Lock for 2 minutes
return 2;
}