Pulling my hair out over what seems a simple task. I use the username instead of email in my AuthController using the following code:
/**
* Set the login system to use username instead of email address
* #var string
*/
protected $username = 'username';
This has worked fine for a long time (when I wasn't planning on users activating their accounts). However, now I need users to activate their accounts, I know I need to do additional checks on login before they can see their dashboard.
I have modified the postLogin() method below, to what I thought would be correct:
public function postLogin(Request $request)
{
$this->validate($request, [
'username' => 'required', 'password' => 'required',
]);
$credentials = $request->only('username', 'password');
$credentials = array_add($credentials, 'confirmed', '1');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('username', 'remember'))
->withErrors([
'username' => $this->getFailedLoginMessage(),
]);
}
But all I get is the following error:
Undefined property: App\Http\Controllers\Auth\AuthController::$auth
What is it that i'm doing wrong?
Andy
Just one glitch that I see there.
if ($this->auth->attempt($credentials, $request->has('remember')))
should be
if (Auth::attempt($credentials, $request->has('remember')))
In Laravel 5.1, the $auth attribute does not exist in the AuthController class constructor, as explained in the 5.1 upgrade guide. So you're referencing a property which does not exist.
Related
Im new at Laravel, i made a login page for my backend application(its working fine) and then i did the JWT documentation to install and begin to use(https://jwt-auth.readthedocs.io/en/develop/).
In my Controllers i used after:
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
Now everytime i try to enter my same login i cant.
How can i enter my login now with JWT?
If you're using Laravel 8, the newly recommended route is to use Laravel's Sanctum feature:
https://laravel.com/docs/8.x/sanctum
For this, if you want stateful logins, you simply post to any controller that then makes an Auth::attempt call like this:
class AuthController extends Controller
{
/**
* Store a newly created resource in storage.
*
* #param Request $request
* #throws ValidationException
*/
public function store(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (!Auth::attempt($credentials, true)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
}
}
I recently set up my login system successfully on React using this package:
https://github.com/koole/react-sanctum
For Stateless, you can follow the documentation here:
https://laravel.com/docs/8.x/sanctum#api-token-authentication
Hi I'm trying to work with encryption of emails in user table and change auth process's "email" with encryption but not working for me keep returning my email does not match records.
My RegisterController is:
User::create([
'name' => $data['name'],
'email' => sha1(sha1($data['email'])),
'password' => Hash::make($data['password']),
'referred_by' => $referred_by
]);
And I'm trying to do manual auth with laravel as of here: https://laravel.com/docs/6.x/authentication#authenticating-users
my LoginController:
public function authenticate(Request $request)
{
$credentials = $request->only(sha1(sha1('email')), 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
Note: I know sha1 is not good but i think double of sha1 for emails will be pretty hard to crack tho.
also i can't exactly find where auth is taking place (because i started learning laravel like 3 weeks ago) where i can switch user input of email field into sha1 x2 so then it can compare with users table emails.
Thanks
Found the answer here: https://laracasts.com/discuss/channels/laravel/encrypt-email-field-in-users-table
Changing function login of AuthenticatesUsers by:
public function login(Request $request)
{
if (Auth::attempt(['email' => sha1(sha1($request->email)), 'password' => $request->password])) {
return redirect()->intended();
} else {
return $this->sendFailedLoginResponse($request);
}
}
thanks to saaz.
My auth function is always returning false in my UserController function, here is my controller function.
public function postSignin(Request $request)
{
$userdata = array(
'email' => $request->input('email'),
'password' => $request->input('password')
);
if (Auth::attempt($userdata))
{
return redirect()->route('user.profile');
}
else
{
return redirect()->back();
}
}
and here is my route code
Route::post('/signin', [
'uses' => 'UserController#postSignin' , 'as' => 'user.signin'
]);
When I enter the credentials, the if part of auth is not working and I am redirected to my page as instructed by the else condition...
You may be saving your users passwords as plain text into the database, because when using the Auth::attempt() function laravel automatically hashes the password to compare. Make sure when inserting you properly hash the password with the bcrypt() helper function. The only other possibility I can think of is if your sure your putting in the right password or username?
Example of bcrypt when creating a new user:
User::create([
"username" => $username,
"password" => bcrypt($password);
]);
Hope this helps!
There are several similar questions but all of them seem incomplete as they are referring to not existing functions.
I am referring to:
Check for active user state with laravel
Login only if user is active using Laravel
extend laravel 5 built-in authentication to login only "if user == active"
In all of them there are presented solutions mostly to alter functions from AuthController, however those functions are not there.
I am using latest version of Laravel (5.2) so my default mentioned file looks like: https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/AuthController.php
Now, how do I implement this functionality? I have tried copying public function postLogin() (as suggested in those other mentioned posts) into that AuthController file. Nothing changed.
I am clearly missing something here.
Please someone help!
Edit:
The function that I have added is:
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath()) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'You must be active to login.'
]);
}
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
Most functionality in AuthController is added using traits. Note this line in the beginning of the class:
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
If you look at AuthenticatesAndRegistersUsers you can see that it does have a postLogin method.
As of why implementing this method doesn't work: I think you are missing the $request parameter in the method signature.
Add a larger code snippet to your question if this isn't the case.
EDIT: for future debugging: php artisan route:list gives you a list of which routes call which methods. This can give you a hint to which method to override.
So, for everyone facing the same problem on Laravel 5.2 with Authentication provided by php artisan make:auth.
First important thing is to understand that Route::auth(); points to login function and not postLogin(Thank you #lagbox!)
Then you will have to update AuthController:
Add on top of the file:
use Auth;
use Illuminate\Http\Request;
Add somewhere after use AuthenticatesAndRegistersUsers, ThrottlesLogins; :
/**
* Where to redirect users if login is unsuccessufull.
*
* #var string
*/
protected $loginPath = '/login';`
And the updated login function:
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'You must be active to login.'
]);
}
}
return redirect($this->loginPath)
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
Then login.blade.php should be updated to show the new error #if ($errors->has('active'))
Thank you guys for help!
I'm new to Laravel 5, I use its built in login stuff and yes I can login with email and password, everything works perfectly. Now, I created a new column named username and filled it with my desired username in the `users table (the table containing the login stuff). How can I login with either email or username and password?
I found this from AuthenticatesAndRegistersUsers.php:
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
Any suggestion, recommendations, clues, ideas, help to tweak the above code so that I could login with either username or email and password?
The documentation states that it is possible to use a custom column. So if you want to authenticate with a username you could use the following:
this->auth->attempt(['username' => 'the_username', 'password' => 'the_password',
$request->has('remember'));
That would require you to do a second call to Auth::attempt if the first one fails.
You could also take the approach that was answered to a similar question (Credit to Raphael for his excellent solution:
$usernameinput = $request->input('email');
$field = filter_var($usernameinput, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
if (Auth::attempt(array($field => $usernameinput, 'password' => $password),
$request->has('remember'))) {
// ...
}