I want to manually login a user in laravel 8. The problem is that authentication succeeds, but the authenticated user is not stored in the session(or the session is not updated). I use the method given in de docs.
My loginController has two methods: 1) showing the login form and 2) performing the login
<?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function login(){
return view('auth/login');
}
public function validateLogin(LoginRequest $request){
if (Auth::attempt(['email'=>$request->email, 'password'=>$request->password])) {
$request->session()->regenerate();
return redirect()->to('/');
}
return back()->withErrors(['credentials' => 'Deze gegevens zijn niet bekend!']);
}
}
The controller redirects indeed to / , so the user is authenticated but after the redirect the autenticated users is unavailable, so somehow it is not stored in the session.
Does anyone know how to solve this?
I removed the id from the User model as I wanted to use the e-mailadress as the primary key. This violated the Authenticable trait so the session was not updated.
The usermodel needed the following function to replace the id with the email:
public function getKeyName(){
return 'email';
}
The same can be accomplished with:
protected $primaryKey = 'email';
public $incrementing = false;
Related
I used laravel like 4 years ago. Had to work on a project on laravel and tried using my own authentication methods but mybad forgot there was already inbuilt better security authentication. I understand if my question seem to be basic.
As you can see the commented line "$userID = Auth::user()->userID;" the auth() is null therefore, userID cannot get its id from null. I am unable to get user session data in any other controllers as well.
Any kind of help or suggestions is appreciated.
P.S. i have used the default login and registration inbuilt function only required function like login is override code. I am using laravel v 4.2.3. I tried passing the userid as url parameter but then discarded it as inbuilt session data makes it more secure and easier
the login function of my controller looks like this
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function login(Request $request){
$user = new User(); //my model User
$result=$user->login($request); //result has the id of the user
if ($result) {
//$userID = Auth::user()->userID;
return redirect()->route('homepage');
}else{
return redirect()->route('login');
}
}
}
model for user login()
//Auth user then let them login
public function login($request){
$email = $request->input('email');
$password = $request->input('password');
$result=DB::table('users')
->where('email', $email)
->where('password', $password)
->get();
return $result;
}
My Routes.. its default route of "Auth::routes();"
Route::get('/homepage/{userID?}', function($userID = null){
return view('index', ['userID' => $userID]);
})->name('homepage');
Route::get('/evaluate/{userID?}', function ($userID = null) {
return view('evaluate', ['userID' => $userID]);
})->name('evaluate');
I installed a fresh new laravel and tried my code again and somehow it worked. Must have made some errors when trying to override the codes. Thank you
We have decided to use Laravel for a project as a test run for future frameworks and are really enjoying it. There is one issue we are having though.
We use the trait Illuminate\Foundation\Auth\AuthenticatesUsers which handles user authentication. It works well. However, we have a column in the database called userstatus which could be a 0 or a 1.
How do we inject this where clause into the Illuminate\Foundation\Auth\AuthenticatesUsers trait?
I was thinking maybe something here (in my LoginController):
public function authenticated($request , $user){
//if $user->userstatus != 1 logout and redirect to start page
}
But I dont know how to logout (im looking into that now) .
your logic is right, you should redefine login and authenticated methods within LoginController.
your methods should be like below:
this method should be within your LoginController.php:
class LoginController extends Controller
{
use AuthenticatesUsers {
login as public loginParent;
}
protected function login(Request $request){
$default = '/';
$user = User::where('email', $request->get('email'))->NotActive->first();
if($user){
return redirect()->intended($default);
}
return $this->loginParent($request);
}
protected function authenticated(Request $request, $user)
{
if($user->not_active) {
$this->logout($request);
}
}
}
then we should create ScopeNotActive method within User.php Model as Local Scope:
//User.php
public function ScopeNotActive($query){
return $query->where('userStatus', '!=', 1);
}
and a Mutator to check if the user is not active:
// User.php
public function getNotActiveAttribute(){
return $this->userStatus != 1;
}
i need a two way Login. First check database one if user exists and if not check database two.
So i build a custom Login Controller:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Redirect;
use App\Http\Controllers\Controller;
class CustomLoginController extends Controller
{
public function login(Request $request)
{
if($request->email) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('/');
} else {
DB::setDefaultConnection('otherdb');
if (Auth::attempt($credentials)) {
// The Login credentials will be found and user will be logged in
but after Redirect to home user isn't logged in anymore.
return redirect()->intended('/');
} else {
return redirect()->to('/login')
->withInput($request->only($credentials['email'], 'remember'))
->withErrors([
'email' => Lang::get('auth.failed'),
]);
}
}
} else {
return view('auth.login');
}
}
}
After i changed the database Connection with "DB::setDefaultConnection('otherdb');", the second login works but after Redirect to any page user isn't logged in anymore.
What am I doing wrong?
Any ideas?
Laravel trying to find a user in DB in every request. So after redirect there in no user in your default database. DB connection doesn't stored in session.
I think you need to create a custom auth guard with another user model like
class OtherUser extends Eloquent
{
protected $connection = 'otherdb';
}
and work with it.
On my application, i'm using the login from the Steam API.
When the user authenticate on steam, the app create a new user if he doesn't exists on the database, else he bring the user data.
In this process, even if i create or just select the user info, i get an array from the user, and i do the Auth::login($user, true); .
On this function it works, if i debug the Auth::user() he returns correctly.
On the view i can use the Auth::guest() too and it works.
But if i go to another page, that only logged users can join, Auth::guest() returns true, Auth::check() returns false, Auth::user() returns NULL... (on the controller).
How can i access the auth methods on the new controller?
Controller that fails with auth:
<?php
namespace App\Http\Controllers\Profile;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Auth;
class ProfileController extends Controller
{
public function __construct()
{
if(Auth::guest()) {
return redirect()->route('home');
}
}
public function index()
{
// die(var_dump(Auth::user()->id));
return view('pages/profile/profile');
}
}
Due to Laravel's architecture, Auth::user() will always return null if called directly from a controller's construct.
Instead you should reference the 'auth' middleware like the following:
class ProfileController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
...
I wanted to give option to create users for Admin without using Registration form.
Do I need to change existing methods and forms ? How do I store password with encryption same as in default registration option. what is the best way to do it?
UserController class is already created using
php artisan make:controller PhotoController
class UserController extends Controller {
public function create()
{
$users = User::get();
return view('user.index', compact('users'));
}
public function store()
{
$input = Request::all();
........
}
}