PHPUnit Laravel Hash not available - php

I have a Unit test in Laravel for testing an API call that looks like this, however I am getting the following runtime error when running it:
RuntimeException: A facade root has not been set.
I'm creating a user in the setup method, with the intent to delete it again in the tearDown() method, then run my auth test.
Firstly, is there a better way of doing what I want? For example Mocking a user without touching the database? And secondly, how do I set a 'facade root' or what does that error mean exactly? I've tried not bothering to hash that particular field for the purposes of creating a Dummy user, but the error then seems to move to the model, where (again) the Hash facade class is used.
Is there any additional steps to setup the environment so these facades can be used in testing?
Thanks in advance.
use Illuminate\Support\Facades\Hash;
/*
* Make sure the structure of the API call is sound.
*/
public function testAuthenticateFailed()
{
$this->json('POST', $this->endpoint,
[ 'email' => 'test#test.com',
'password' => 'password',
])
->seeJsonStructure([
'token'
]);
}
//create a user if they don't already exist.
public function setup()
{
$user = User::create([
'company_id' => 9999,
'name'=>'testUser',
'email' => 'test#test.com',
'password' => 'password',
'hashed_email' => Hash:make('test#test.com'),
]);
}

Try to use this instead:
\Hash::make('test#test.com'),
It's a good idea to use bcrypt() global helper instead of Hash::make()
Also, add this to setUp() method:
parent::setUp();

You could use the DatabaseMigrations or DatabaseTransactions trait that comes with Laravel so you don't have to delete the User manually.
You could add a Mutator to your User class, which will automatically hash the password when a User is created.
// https://laravel.com/docs/5.3/eloquent-mutators
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}

Related

How to allow to use the master password in Laravel 8 by overriding Auth structure?

I've got a website written in pure PHP and now I'm learning Laravel, so I'm remaking this website again to learn the framework. I have used built-in Auth Fasade to make authentication. I would like to understand, what's going on inside, so I decided to learn more by customization. Now I try to make a master password, which would allow direct access to every single account (as it was done in the past).
Unfortunately, I can't find any help, how to do that. When I was looking for similar issues I found only workaround solutions like login by admin and then switching to another account or solution for an older version of Laravel etc.
I started studying the Auth structure by myself, but I lost and I can't even find a place where the password is checked. I also found the very expanded solution on GitHub, so I tried following it step by step, but I failed to make my own, shorter implementation of this. In my old website I needed only one row of code for making a master password, but in Laravel is a huge mountain of code with no change for me to climb on it.
As far I was trying for example changing all places with hasher->check part like here:
protected function validateCurrentPassword($attribute, $value, $parameters)
{
$auth = $this->container->make('auth');
$hasher = $this->container->make('hash');
$guard = $auth->guard(Arr::first($parameters));
if ($guard->guest()) {
return false;
}
return $hasher->check($value, $guard->user()->getAuthPassword());
}
for
return ($hasher->check($value, $guard->user()->getAuthPassword()) || $hasher->check($value, 'myHashedMasterPasswordString'));
in ValidatesAttributes, DatabaseUserProvider, EloquentUserProvider and DatabaseTokenRepository. But it didn't work. I was following also all instances of the getAuthPassword() code looking for more clues.
My other solution was to place somewhere a code like this:
if(Hash::check('myHashedMasterPasswordString',$given_password))
Auth::login($user);
But I can't find a good place for that in middlewares, providers, or controllers.
I already learned some Auth features, for example, I succeed in changing email authentication for using user login, but I can't figure out, how the passwords are working here. Could you help me with the part that I'm missing? I would appreciate it if someone could explain to me which parts of code should I change and why (if it's not so obvious).
I would like to follow code execution line by line, file by file, so maybe I would find a solution by myself, but I feel like I'm jumping everywhere without any idea, how this all is connected with each other.
First of all, before answering the question, I must say that I read the comments following your question and I got surprised that the test you made returning true in validateCredentials() method in EloquentUserProvider and DatabaseUserProvider classes had failed.
I tried it and it worked as expected (at least in Laravel 8). You just need a an existing user (email) and you will pass the login with any non-empty password you submit.
Which of both classes are you really using (because you don't need to edit both)? It depends of the driver configuration in your auth.php configuration file.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
As you already thought, you can simply add an "or" to the validation in the validateCredentials() method, comparing the $credentials['password'] to your custom master password.
Having said that, and confirming that's the place where you'd have to add your master password validation, I think the best (at least my recommended) way to accomplish your goal is that you track the classes/methods, starting from the official documentation, which recommends you to execute the login through the Auth facade:
use Illuminate\Support\Facades\Auth;
class YourController extends Controller
{
public function authenticate(Request $request)
{
//
if (Auth::attempt($credentials)) {
//
}
//
}
}
You would start by creating your own controller (or modifying an existing one), and creating your own Auth class, extending from the facade (which uses the __callStatic method to handle calls dynamically):
use YourNamespace\YourAuth;
class YourController extends Controller
{
//
public function authenticate(Request $request)
{
//
if (YourAuth::attempt($credentials)) {
//
}
//
}
}
//
* #method static \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard guard(string|null $name = null)
//
class YourAuth extends Illuminate\Support\Facades\Facade
{
//
}
And use the same logic, overriding all the related methods in the stack trace until you get to use the validateCredentials() method, which in the end will also be overrided in your own CustomEloquentUserProvider class which will be extending fron the original EloquentUserProvider.
This way, you will have accomplished your goal, and kept a correct override of the whole process, being able to update your laravel installation without the risk of loosing your work. Worst case scenario? You'll have to fix any of your overriding methods in case that any of them has drastically changed in the original classes (which has a ver low chance to happen).
Tips
When making the full overriding, maybe you'll prefer to add some significant changes, like evading the interfaces and going straight for the classes and methods you really need. For example: Illuminate/Auth/SessionGuard::validate.
You would also wish to save your master password in an environment variable in your .env file. For example:
// .env
MASTER_PASSWORD=abcdefgh
and then call it with the env() helper:
if ($credentials['password'] === env('MASTER_PASSWORD')) {
//
}
Nice journey!
A more complete solution would be the define a custom guard and use that instead of trying to create your own custom auth mechanism.
Firstly, define a new guard within config/auth.php:
'guards' => [
'master' => [
'driver' => 'session',
'provider' => 'users',
]
],
Note: It uses the exact same setup as the default web guard.
Secondly, create a new guard located at App\Guards\MasterPasswordGuard:
<?php
namespace App\Guards;
use Illuminate\Auth\SessionGuard;
use Illuminate\Support\Facades\Auth;
class MasterPasswordGuard extends SessionGuard
{
public function attempt(array $credentials = [], $remember = false): bool
{
if ($credentials['password'] === 'master pass') {
return true;
} else {
return Auth::guard('web')->attempt($credentials, $remember);
}
}
}
Note:
You can replace 'master pass' with an env/config variable or simply hardcode it. In this case I'm only checking for a specific password. You might want to pair that with an email check too
If the master pass isn't matched it falls back to the default guard which checks the db
Thirdly, register this new guard in the boot method of AuthServiceProvider:
Auth::extend('master', function ($app, $name, array $config) {
return new MasterPasswordGuard(
$name,
Auth::createUserProvider($config['provider']),
$app->make('session.store'),
$app->request
);
});
Fourthly, in your controller or wherever you wish to verify the credentials, use:
Auth::guard('master')->attempt([
'email' => 'email',
'password' => 'pass'
]);
Example
Register the route:
Route::get('test', [LoginController::class, 'login']);
Create your controller:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
class LoginController
{
public function login()
{
dd(
Auth::guard('master')->attempt([
'email' => 'demo#demo.com',
'password' => 'master pass'
]),
Auth::guard('master')->attempt([
'email' => 'demo#demo.com',
'password' => 'non master'
]),
);
}
}
and if you hit this endpoint, you'll see:
Where true is where the master password was used and false is where it tried searching for a user.
Final Thoughts
From a security standpoint you're opening yourself up to another attack vector and one which is extremely detrimental to the security of your system and the privacy of your users' data. It would be wise to reconsider.
This validation of credentials should ideally be separated from your controller and moved to a Request class. It'll help keep your codebase more clean and maintainable.
Instead of trying to roll your own, you could as well as use a library, which does just that:laravel-impersonate (it's better tested already). This also comes with Blade directives; just make sure to configure it properly, because by default anybody can impersonate anybody else.
There even is (or was) rudimentary support available with: Auth::loginAsId().
Here is a possible solution.
To use a master password, you can use the loginUsingId function
Search the user by username, then check if the password matches the master password, and if so, log in with the user ID that it found
public function loginUser($parameters)
{
$myMasterHashPassword = "abcde";
$username = $parameters->username;
$password = $parameters->password;
$user = User::where('username', $username)->first();
if (!$user) {
return response("Username not found", 404);
}
if (Hash::check($myMasterHashPassword, $password)) {
Auth::loginUsingId($user->id);
}
}

How can I create (register) an user while being logged in?

I defined an option in my website named "define user". So I need to do some changes in the current laravel registration system. Actually I did what I need:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
if ( !isset($request->registered_by_id) ) { -- added
$this->guard()->login($user);
$status = ""; -- added
$msg = ""; -- added
} else { -- added
$status = "define-user-alert-success"; -- added
$msg = "the user registered successfully";
} -- added
return $this->registered($request, $user)
?: redirect($this->redirectPath())
->with($status, $msg); -- added
}
As you know, function above is located under /vendor/laravel/framework/src/illuminate/Foundation/Auth/RegisterUsers.php path. The problem is all the change I made will be ignored when I upload my website and execute composer install command.
Any idea how can I keep my changes in the vendor directory?
composer install will overwrite your changes as it just fetches the latest version from the public repo and installs that.
I would suggest one of the following;
Create your own fork of laravel and have composer load this over default laravel. I did this recently with a Symfony component fork, the idea is to change the repo branch name to your modified one and override the source with your own repo. Instruction from my fork are here.
Upload the file manually via after executing composer install (not recommended, only use a stop-gap).
Override/extend the original class, this answer lays out the process nicely.
As defined in this answer on Laracasts (which is very similar to your case), use event listeners to execute your code after user registration.
Hope this helps!
I would strongly recommend against making any changes to the core framework - aside from the issue you mentioned, it can also make upgrades extremely difficult.
Fortunately, Laravel makes user registrations easy. All you need to do is create a new controller (E.g. UserController) and then use a function like this to create a model for them ...
public function registerUser(Request $request){
$request->validate([
'username' => 'bail|required|unique:users,username|max:255',
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email'
]);
$user = User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'username' => $request->username,
'password' => Hash::make($request->password),
'email' => $request->email
]);
return redirect('/settings/people/'.$user->user_id);
}
The key here is to use the hash facade to encrypt the password before committing the model to the database. Otherwise, it's essentially like working with any other model.
Yea, don't edit the file in vendor.
This trait is used in the RegisterController which exists in your app, not the framework. You can simply override that method in your controller, done.
Perhaps your changes can go in registered which is called after registration so you don't have to override this functionality of register itself (since registered is a blank method waiting to be overridden)

Change the Laravel Login System in Laravel 5.5

I'm trying to determine if the user is allowed to login. Addiotional to the email with the correct password, I want to check if the user is active or not.
There is a active column in my database with the values "n" and "y". The login is supposed to fail if active == "n".
Now I'm trying to add this to the Login Controller but where ever I'm trying to put this if/else condition, it just gets ignored.
In the Laravel Doc. I found this:
Specifying Additional Conditions:
If you wish, you may also add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as "active":
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1 ( in my case "y"])) {
// The user is active, not suspended, and exists.
}
But this haven't workd for me.. Thats why I want to ask where do I have to put this code ( I've tried in the authenticatesUsers.php #login function ) and if I have to modify the code in a specific way? Laravel 5.5 is handling the login system a little bit different then 5.4 ( thats what I think at least )
Thanks for any help!
Your best way to do this is to add a method login to your LoginController
public function login(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request->password, 'active' => 'y'])) {
return redirect()->intended('dashboard');
} else{
return redirect('/');
}
}
Remember to add use Illuminate\Support\Facades\Auth; and use Illuminate\Http\Request; to the top of your controller.
Tested with 0 and 1, and with n and y and it worked as expected
You need to create a method named 'attemptLogin' in your LoginController and add that code to the method as follows
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
return Auth::attempt(['email' => $request->email, 'password' => $request->password, 'active' => '1'], $request->filled('remember')
);
}
This will override the method in the authenticatesusers trait while still utilising all the built in features of laravel authentication.
You must not forget to add this at the top of the page among your use directives
use Illuminate\Support\Facades\Auth;
Then you are good to go.
Hope it helps someone

Using ValidatesRequests trait in Laravel

Here's the code from my AuthController:
public function postRegister(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users',
'password' => 'required|min:5|max:15',
]);
}
If the validation fails I'm getting redirected to the previous page. Is there a way to pass additional data along with the input and the errors (which are handled by the trait)?
Edit: Actually, the trait does exactly what I want, except the additional data I want to pass. As #CDF suggested in the answers I should modify the buildFailedValidationResponse method which is protected.
Should I create a new custom trait, which will have the same functionality as the ValidatesRequests trait (that comes with Laravel) and edit the buildFailedValidationResponse method to accept one more argument or traits can be easily modified following another approach (if any exists)?
Sure you can, check the example in the documentation:
http://laravel.com/docs/5.1/validation#other-validation-approaches1
Using the fails(); method, you can flash the errors and inputs values in the session and get them back with after redirect. To pass other datas just flash them with the with(); method.
if ($validator->fails()) {
return back()->withErrors($validator)
->withInput()
->with($foo);
}

Laravel 5.1 auth system with status

I am new to laravel I have integrated inbuilt authentication system and works perfect. Now I also want to consider status field of user table while authenticate. I search a lot but could not find proper way to integrate such functionality with inbuilt laravel's authentication system.
Considering user status when authenticating is simple. There are 2 ways to do that, depending whether you call Auth::attempt() manually or you use AuthenticatesUsers or RegistersAndAuthenticatesUsers trait in your controller.
If you are calling Auth::attempt() manually, you always pass an array of credentials to the method. Those credentials are used to fetch user from the database. Add status field to those credentials and only users with given status will be able to log in, e.g.:
Auth::attempt([
'username' => Request::input('username'),
'password' => Request::input('password'),
'status' => 'active'
]);
Above will allow only users with status=active to log in.
If you are using AuthenticatesUsers or RegistersAndAuthenticatesUsers trait in your controller, you need to override the getCredentials() method. This method should return the same array that you'd pass to Auth::attempt():
protected function getCredentials(Request $request) {
return [
'username' => Request::input('username'),
'password' => Request::input('password'),
'status' => 'active'
];
}

Categories