Why running a Laravel 9 test is deleting my database? - unit-testing

I am usgin Laravel 9 test tool.
I dropped the database, recreated and imported using SQL statement.
With all the database set, I used the browser to log in with my user, and everything worded just fine.
Then I ran the php artisan test --filter HomeControllerTest and all the database was deleted! HOW COME?????
here is the test code:
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class HomeControllerTest extends TestCase
{
use RefreshDatabase;
public function test_home_view_requires_authentication()
{
// Log in as the created user and try to access the home page
$response = $this->postJson('/login', [
'email' => 'test#example.com',
'password' => 'password',
]);
$response->assertStatus(302);
$response->assertRedirect(route('home'));
$response = $this->get(route('home'));
$response->assertOk();
$response->assertViewIs('home');
$response->assertViewHasAll(['corretora', 'propostas']);
}
/**
* Test if home page can be accessed by a guest user.
*
* #return void
*/
public function test_home_view_requires_guest()
{
$response = $this->get(route('home'));
$response->assertStatus(302);
$response->assertRedirect(route('login'));
}
}
Why my database was deleted? i do have a backup, of course, but should test do it?

There was not an error. The use of the use RefreshDatabase; do the erasing.
I remove it and now is working good.

Related

POST failed via Postman API to Laravel migrations database

GET is working, but POST does not. This is because it fails via Postman API to the Laravel migrations database.
function add_user(Request $request)
{
$user = new user_a;
csrf_token();
$user->user_name = $request->user_name;
$user->password = $request->password;
$res = $user->save;
if ($res) {
return ["operationn" => "Done"];
} else {
return ["operation" => "failed_404"];
}
}
in API file:
Route::post('registeruser',[dynamic_small_controller::class,'add_user']);
You are trying to send the password in integer format so it is not accepting try with giving password also in ""
{
"user_name":"yahay",
"password":"8888"
}

Location of auth:api Middleware

Can somebody please tell the location of auth:api middleware?
As per the auth:api middleware, the api routes are protected by not null users.
I have a boolean field in user table called Is_Admin_Url_Accessible. I want to add a condition in the auth:api middleware for some routes to make user that only those user access such routes whoever are permitted to access the admin area.
I checked the class here but could not help.
\app\Http\Middleware\Authenticate.php
You can add a middleware that makes control user accessible, and you can set it as middleware to your route group like auth:api
Please run php artisan make:middleware UserAccessible on your terminal.
After run above artisan command, you will see generated a file named UserAccessible.php in the App/Http/Middleware folder.
UserAccessible.php Contents
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class UserAccessible
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = Auth::user();
if(!$user->accesible){
// redirect page or error.
}
return $next($request);
}
}
Then, you must define a route middleware via App/Http/Kernel.php
Kernel.php Contents
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
...
'user_accessible' => \App\Http\Middleware\UserAccessible::class
];
And finally, you can define route middleware to your route group;
api.php Contents
Route::group(['middleware' => ['auth:api', 'user_accessible']], function () {
// your protected routes.
});
I hope this solve your problem.

Laravel Socialite - Facebook extend/replace token with a one with more permissions

I'm using Laravel 5.4 and Socialite to allow the visitor of my site to log in.
Situation
I recently obtained the user_events permission cause I wanted to add some functionalities to my website.
Before this, some users got registered in my database along with their user token in the database. (token than includes the default permissions but not user_events)
I updated the SocialAuthController.php to reflect the new permission on the new created user and this is working great
return Socialite::driver('facebook')
->scopes(['public_profile', 'user_events'])
->redirect();
Problem
If a user is already registered in the database with his token, it is impossible to run this command $fb->get('me/events') since the token does not include the user_events permissions.
Questions
Is there a way to force a user to grab a new token with a new permission without having to remove him from the database ? ( I have data associated with users) ?
SocialAuthController
public function handleProviderCallback(SocialAccountService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->user());
}
SocialeAccountService
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialAccount::whereProvider('facebook')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook',
'nickname' => $providerUser->getNickname(),
'avatar' => $providerUser->avatar_original,
'token' => $providerUser->token,
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}

Old users can't login after changing password validation rule

i am using symfony 2 to build a web platform for my company. Recently, i have changed the validation rule inside my User entity by adding the following code:
/**
* #Assert\Regex(
* pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,127}$/",
* message="edit.personnal_info.udpate.message.password_info_regex",
* groups={"registration"}
* )
*/
protected $plainPassword;
After this change, all my old created users can't login anymore. Just new users, with valid password can get connected.
I don't want to change all old passwords. So, if there is a way to skip validation rules while login, it will be OK.
Ps: i'm using FOSUserBundle.
Solution if your issue is that old users used shorter passwords and you want to support them until next password change
Instead of adding this constrain to entity you could add it to your registration and change password forms
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('plainPassword', PasswordType::class, [
'constraints' => [
new Regex([
'pattern' => '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,127}$/'
]),
new NotBlank()
]
]);
}
this way you can enforce new password policy for new users without breaking logic for old users.

access database from bootstrap zend framework 2 (doctrine2)

How I can access to DB from bootstrap using official DoctrineORMModule ?
for example, in my controller:
$allusers = $this->getEntityManager()->getRepository('Users\Entity\User')->findAll();
but I can't access to getEntityManager() and getRepository() when i'm in bootstrap.
I follow up this guide: http://ivangospodinow.com/zend-framework-2-acl-setup-in-5-minutes-tutorial/
but I'm stuck when trying to connect to db
public function getDbRoles(MvcEvent $e){
// I take it that your adapter is already configured
$dbAdapter = $e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter');
...
}
Using doctrine you would need to fetch the EntityManager with
$entityManager = $e->getApplication()->getServiceManager()->get('Doctrine\ORM\EntityManager');
//in my case:
var_dump( $entityManager->getRepository('Users\Entity\User') );