Laravel Middleware Auth Group is not working - laravel

Good Day. I had a problem with my authentication which I always redirected back into the login page. I found out that when I add in routes/web.php with this code below
Route::group(['middleware' => 'auth'], function() {
}
the page is always redirected back to the login page. But when I remove that code above, I can proceed to the home page. I trying to wonder how to solve this. I use route group in my past projects and I don't have any problems with that.
UPDATE: I used php artisan test and remodify my ExampleTest.php codes.
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use App\User;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
public function testApplication()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->get('/');
}
}
These are the results
C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:273
269| */
270| protected function getRawAttributes(array $attributes = [])
271| {
272| if (! isset($this->definitions[$this->class])) {
> 273| throw new InvalidArgumentException("Unable to locate factory for [{$this->class}].");
274| }
275|
276| $definition = call_user_func(
277| $this->definitions[$this->class],
1 C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:296
Illuminate\Database\Eloquent\FactoryBuilder::getRawAttributes([])
2 C:\xampp\htdocs\nuadu_helpdesk\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:155
Illuminate\Database\Eloquent\FactoryBuilder::Illuminate\Database\Eloquent\{closure}()

inside routes.php file you not write where to redirect. so please add like below..
Route::group(['middleware' => 'auth'], function() {
return redirect('/'); //by default you can change it as your requirments.
}

I found out about my problem. I checked using the auth and dd. I used a different primary key with user_id and it is a string type. I forgot to declare it in my user.php
protected $primaryKey = 'user_id';
protected $keyType = 'string';
public $incrementing = false;
By default, the primary key will always be the id. If you declare a different column name that will serve as your primary key, don't forget to declare the codes that I stated above, or else you end not reading the auth or not logging in.

Related

Login and verify user - Call to a member function getKey() on null

I am trying to create a custom verification flow, where as soon as a user clicks the verification link, it logs him in and also verifies him, instead of first making him log in and only then the verification link works.
I built a custom notification URL in my CustomVerificationNotification, including the registered user_id, to login him later:
protected function verificationUrl($notifiable)
{
if (static::$createUrlCallback) {
return call_user_func(static::$createUrlCallback, $notifiable);
}
return URL::temporarySignedRoute(
'verification.custom-verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
'user_id' => $this->user->id
]
);
}
Then in my web.php I added this route:
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController#login_and_verify')->name('verification.custom-verify');
Then in my CustomVerifyController:
public function login_and_verify(EmailVerificationRequest $request)
{
//..
}
But I get Call to a member function getKey() on null. And I can't edit EmailVerificationRequest, so what can I do? Is it possible to somehow call Auth::login($user); before calling the EmailVerificationRequest? (Because I have the user_id from the route)
I tried to follow the best answer from this post as well: How to Verify Email Without Asking the User to Login to Laravel
But I'm not sure then how to trigger the verify() method from the web.php and send the $request when I'm first calling the verify_and_login method
First you need verify that the URL is signed by adding the middleware signed
You don't want that anoyone having the url /email/verify/{id}/{hash}/{user_id} able to access this ressource without the signature.
web.php
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController#login_and_verify')
->middleware('signed')
->name('verification.custom-verify');
Then you need to verify that the hash correspond the user_id and for that you can use a Request or a Middleware. I think the Request fits better since Laravel already uses a Request for this.
CustomEmailVerificationRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;
class EmailVerificationRequest extends FormRequest
{
public function authorize()
{
$user = User::findOrFail($this->route('id'));
if (! hash_equals((string) $this->route('hash'), sha1($user->getEmailForVerification()))) {
return false;
}
return true;
}
}
Finally you need to login with the user and set is email as verified
CustomVerifyController.php
public function login_and_verify(CustomEmailVerificationRequest $request)
{
$user = User::findOrFail($this->route('id'));
Auth::login($user);
$user->markEmailAsVerified();
event(new Verified($user));
...
}
[Edit to add addition feature from comments]
In order to have a middleware that verify the signed URL and resend automatically the verification email, you need to build a custom middleware.
ValidateSignatureAndResendEmailVerification.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use URL;
class ValidateSignatureAndResendEmailVerification
{
public function handle($request, Closure $next, $relative = null)
{
if(! URL::hasCorrectSignature($request, $relative !== 'relative')( {
throw new InvalidSignatureException;
}
if (URL::signatureHasNotExpired()) {
return $next($request);
}
return redirect()->route('resend-email-confirmation');
}
}
Then you need to add the middleware to Kernel.php
Kernel.php
protected $routeMiddleware = [
...
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'signed.email' => \App\Http\Middleware\ValidateSignatureAndResendEmailVerification::class,
...
];
Then, don't forget to update your route with the new middleware
web.php
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController#login_and_verify')
->middleware('signed.email')
->name('verification.custom-verify');

Use Auth in AppServiceProvider

I need the ID of the user who is logged in to get a photo in the profile table, here I am trying to use View but only in the index function that gets $profile, I want all files in the view to have $profile
public function index(){
$profil = Profil_user::where('user_id',$auth)->first();
View::share('profil', $profil);
return view('user.index');
}
I have also tried AppServiceProvider but I get an error in the form of a null value if I don't log in, is there a solution to my problem?
public function boot(){
$auth = Auth::user();
dd($auth);
}
exist several way to pass a variable to all views. I explain some ways.
1. use middleware for all routes that you need to pass variable to those:
create middleware (I named it RootMiddleware)
php artisan make:middleware RootMiddleware
go to app/Http/Middleware/RootMiddleware.php and do following example code:
public function handle($request, Closure $next) {
if(auth()->check()) {
$authUser = auth()->user();
$profil = Profil_user::where('user_id',$authUser->id)->first();
view()->share([
'profil', $profil
]);
}
return $next($request);
}
then must register this middleware in app/Http/Kernel.php and put this line 'root' => RootMiddleware::class, to protected $routeMiddleware array.
then use this middleware of routes or routes group, for example:
Route::group(['middleware' => 'root'], function (){
// your routes that need to $profil, of course it can be used for all routers(because in handle function in RootMiddleware you set if
});
or set for single root:
Route::get('/profile', 'ProfileController#profile')->name('profile')->middleware('RootMiddleware');
2. other way that you pass variable to all views with view composer
go to app/Http and create Composers folder and inside it create ProfileComposer.php, inside ProfileComposer.php like this:
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ProfileComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$profil = Profil_user::where('user_id', auth()->id)->first();
$view->with([
'profil' => $profil
]);
}
}
now it's time create your service provider class, I named it ComposerServiceProvider
write this command in terminal : php artisan make:provider ComposerServiceProvider
after get Provider created successfully. message go to config/app.php and register your provider with put this \App\Providers\ComposerServiceProvider::class to providers array.
now go to app/Providers/ComposerServiceProvider.php and do like following:
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
View::composer(
'*' , ProfileComposer::class // is better in your case use write your views that want to send $profil variable to those
);
/* for certain some view */
//View::composer(
// ['profile', 'dashboard'] , ProfileComposer::class
//);
/* for single view */
//View::composer(
// 'app.user.profile' , ProfileComposer::class
//);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
}
3. is possible that without create a service provider share your variable in AppServiceProvider, go to app/Provider/AppServiceProvider.php and do as follows:
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
I hope be useful
you can use this
view()->composer('*', function($view)
{
if (Auth::check()) {
$view->with('currentUser', Auth::user());
}else {
$view->with('currentUser', null);
}
});

How to change hard coded Eloquent $connection only in phpunit tests?

I have an Eloquent Model like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SomeModel extends Model
{
protected $connection = 'global_connection';
......................
The problem is that this $connection has to be hard coded because I have a multi tenant web platform and all the tenants should read from this Database.
But when now in tests I am hitting the Controller route store() and I don't have access to the model!
I just do this:
public function store()
{
SomeModel::create($request->validated());
return response()->json(['msg' => 'Success']);
}
Which works great when using it as a user through browser...
But now I want to somehow force that model NOT to use that hard coded $connection and set it to Testing database connection...
And this is my Test
/** #test */
public function user_can_create_some_model(): void
{
$attributes = [
'name' => 'Some Name',
'title' => 'Some Title',
];
$response = $this->postJson($this->route, $attributes)->assertSuccessful();
}
Is there any way to achieve this with some Laravel magic maybe :)?
Because you asked for Laravel magic... Here it goes. Probably an overkill and over engineered way.
Let's first create an interface whose sole purpose is to define a function that returns a connection string.
app/Connection.php
namespace App;
interface Connection
{
public function getConnection();
}
Then let's create a concrete implementation that we can use in real world (production).
app/GlobalConnection.php
namespace App;
class GlobalConnection implements Connection
{
public function getConnection()
{
return 'global-connection';
}
}
And also another implementation we can use in our tests.
app/TestingConnection.php (you can also put this in your tests directory, but make sure to change the namespace to the appropriate one)
namespace App;
class TestingConnection implements Connection
{
public function getConnection()
{
return 'testing-connection';
}
}
Now let's go ahead and tell Laravel which concrete implementation we want to use by default. This can be done by going to the app/Providers/AppServiceProvider.php file and adding this bit in the register method.
app/Providers/AppServiceProvider.php
namespace App\Providers;
use App\Connection;
use App\GlobalConnection;
// ...
public function register()
{
// ...
$this->app->bind(Connection::class, GlobalConnection::class);
// ...
}
Let's use it in our model.
app/SomeModel.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SomeModel extends Model
{
public function __construct(Connection $connection, $attributes = [])
{
parent::__construct($attributes);
$this->connection = $connection->getConnection();
}
// ...
}
Almost there. Now in our tests, we can replace the GlobalConnection implementation with the TestingConnection implementation. Here is how.
tests/Feature/ExampleTest.php
namespace Tests\Feature;
use Tests\TestCase;
use App\Connection;
use App\TestingConnection;
class ExampleTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$this->app->instance(Connection::class, TestingConnection::class);
}
/** #test */
public function your_test()
{
// $connection is 'testing-connection' in here
}
}
Code is untested, but should work. You can also create a facade to access the method statically then use Mockery to mock the method call and return a desired connection string while in testing.
Unfortunately for me, none of these answers didn't do the trick because of my specific DB setup for multi tenancy. I had a little help and this is the right solution for this problem:
Create a custom class ConnectionResolver somewhere under tests/ directory in laravel
<?php
namespace Tests;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\ConnectionResolver as IlluminateConnectionResolver;
class ConnectionResolver extends IlluminateConnectionResolver
{
protected $original;
protected $name;
public function __construct(ConnectionResolverInterface $original, string $name)
{
$this->original = $original;
$this->name = $name;
}
public function connection($name = null)
{
return $this->original->connection($this->name);
}
public function getDefaultConnection()
{
return $this->name;
}
}
In test use it like this
create a method called create() inside tests/TestCase.php
protected function create($attributes = [], $model = '', $route = '')
{
$this->withoutExceptionHandling();
$original = $model::getConnectionResolver();
$model::setConnectionResolver(new ConnectionResolver($original, 'testing'));
$response = $this->postJson($route, $attributes)->assertSuccessful();
$model = new $model;
$this->assertDatabaseHas('testing_db.'.$model->getTable(), $attributes);
$model::setConnectionResolver($original);
return $response;
}
and in actual test you can simply do this:
/** #test */
public function user_can_create_model(): void
{
$attributes = [
'name' => 'Test Name',
'title' => 'Test Title',
'description' => 'Test Description',
];
$model = Model::class;
$route = 'model_store_route';
$this->create($attributes, $model, $route);
}
Note: that test method can have only one line when using setUp() method and $this-> notation
And that's it. What this does is forcing the custom connection name (which should be written inside config/database.php) and the model during that call will work with that connection no matter what you specify inside the model, therefore it will store the data into DB which you have specified in $model::setConnectionResolver(new ConnectionResolver($original, 'HERE'));
This is tested for Laravel 8 & 9 and Super Simple.
Here is an example of switching the connection while testing.
In your model ->
class YourModel extends Model {
protected $connection = 'remote';
public function __construct(array $attributes = [])
{
if(config('app.env') === 'testing') {
$this->connection = 'sqlite';
}
parent::__construct($attributes);
}
}
In the Eloquent Model you have the following method.
/**
* Set the connection associated with the model.
*
* #param string|null $name
* #return $this
*/
public function setConnection($name)
{
$this->connection = $name;
return $this;
}
So you can just do
$user = new User();
$user->setConnection('connectionName')
One option would be to create a new environment file just for testing, that way you can overwrite the connection credentials only for your tests and you would not have to touch your models:
tests/CreatesApplication.php
public function createApplication()
{
$app = require __DIR__ . '/../bootstrap/app.php';
$app->loadEnvironmentFrom('.env.testing'); // add this
$app->make(Kernel::class)->bootstrap();
return $app;
}
Copy your .env file to .env.testing and change your database credentials for the connection global_connection to your test database credentials.
I am not sure how you configured your connection but it probably looks something like the following.
database.php
'global_connection' => [
'database' => env('DB_GLOBAL_DATABASE', ''),
'username' => env('DB_GLOBAL_USERNAME', ''),
'password' => env('DB_GLOBAL_PASSWORD', ''),
],
.env.testing:
DB_GLOBAL_DATABASE=database
DB_GLOBAL_USERNAME=username
DB_GLOBAL_PASSWORD=secret
Now you can use the global_connection connection but it will use your test database.
Additionally you could then remove all environment values from the phpunit.xml file and move them into the .env.testing file so you have all environment values for your tests in one place.
If you don't want to create a new environment file you could of course just update the values in your phpunit.xml file:
<php>
<server name="DB_GLOBAL_DATABASE" value="database"/>
<server name="DB_GLOBAL_USERNAME" value="username"/>
<server name="DB_GLOBAL_PASSWORD" value="password"/>
</php>
The most "magical" thing I suggest you could do is focus exclusively on the test and try to not modify the model at all:
/** #test */
public function user_can_create_some_model(): void
{
config([ "database.connections.global_connection" => [
'driver' => 'mysql', 'host' => x // basically override everything that is in config/database.php
]);
$attributes = [
'name' => 'Some Name',
'title' => 'Some Title',
];
$response = $this->postJson($this->route, $attributes)->assertSuccessful();
}
Hopefully when the configuration needs to be read the new one will be used.
If your global_connection configuration is read from the .env file you can also override the env variables in your test runner configuration (e.g. phpunit.xml)

Laravel Authentication Reset

I'm having difficulty how do I get the user id based on the token generated by laravel? I'm not very familiar with framewrok can anyone help me?
class ForgotPasswordController extends Controller
{
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
ResetPasswordController
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected $redirectTo = '/login';
public function __construct()
{
$this->middleware('guest');
}
protected function guard()
{
return Auth::guard('user');
}
public function broker()
{
return Password::broker('users');
}
public function showResetForm(Request $request, $token = null)
{
var_dump($request->email);
var_dump( $request->token);
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
}
how to update password? I only have the token received by email?
Check this steps so you can understand better how laravel auth works.
Generate the auth scaffolding with: php artisan make:auth
Run the created migrations:php artisan migrate
Check your route list with php artisan route:list, you can see that routes were created too when you ran make:auth command.
Take note of the controllers and methods the Auth routes are calling.
Go to the routes web.php file. See the Auth::routes();, this generate the default Laravel Auth routes, if you don't need em all, comment or delete this line and add the required Lines.
If you took note of the controllers and methods, you can see what's been called on each route. In this particular case, i think you'd be looking for ResetPasswordController which uses ResetsPasswords from vendor/laravel/framework/src/Illuminate/Foundation/Auth/ResetsPasswords.php there you can see the resets method this is what you'll have to override on your ResetPasswordController.

Laravel 5.3 - Best way to implement Entrust role on signup?

I'm working with Laravel 5.3 and I'm trying to set a role when someone signs up, I've used the Zizaco Entrust library.
I'm unsure on the best way to achieve something like this.
I tried to do this inside RegisterController's create method like below:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user = User::where('email', '=', $data['email'])->first();
// role attach alias
$user->attachRole($employee);
}
But obviously that's not right. So I'm a bit unsure on what the best practice is with this sort of thing.
If, as your comment on the OP suggests, you always want to assign the same role to a registered user, you can use a Model Observer for this - it's really simple.
// app/Observers/UserObserver.php
<?php namespace App\Observers;
use App\Models\User;
use App\Models\Role; // or the namespace to the Zizaco Role class
class UserObserver {
public function created( User $user ) {
$role = Role::find( 1 ); // or any other way of getting a role
$user->attachRole( $role );
}
Then you simply register the observer in your AppServiceProvider:
// app/Providers/AppServiceProvider.php
use App\Models\User;
use App\Observers\UserObserver;
class AppServiceProvider extends Provider {
public function boot() {
User::observe( new UserObserver );
// ...
}
// ...
}
This answer is mainly based off looking at your current solution, with a dash of original question.
Rather than filling out your model with methods like createNew, you'll probably find things easier to manage if you create a type of class specifically for interacting with models. You can call this a Repository or a Service or whatever takes your fancy, but we'll run with Service.
// app/Services/UserService.php
<?php namespace App\Services;
use App\Models\User; // or wherever your User model is
class UserService {
public function __construct( User $user ) {
$this->user = $user;
}
public function create( array $attributes, $role = null ) {
$user = $this->user->create( $attributes );
if ( $role ) {
$user->attachRole( $role );
}
return $user;
}
}
Now we need to deal with the fact that we've lost the hashing of passwords:
// app/Models/User.php
class User ... {
public function setPasswordAttribute( $password ) {
$this->attributes[ 'password' ] = bcrypt( $password );
}
}
And now we have the problem of sending out an activation email - that can be solved cleanly with events. Run this in the terminal:
php artisan make:event UserHasRegistered
and it should look something like this:
// app/Events/UserHasRegistered.php
<?php namespace App\Events;
use App\Models\User;
use Illuminate\Queue\SerializesModels;
class UserHasRegistered extends Event {
use SerializesModels;
public $user;
public function __construct( User $user ) {
$this->user = $user;
}
}
Now we need a listener for the event:
php artisan make:listener SendUserWelcomeEmail
And this can be as complex as you like, here's one I'm just copy/pasting from a project I have lying around:
// app/Listeners/SendUserWelcomeEmail.php
<?php namespace App\Listeners;
use App\Events\UserHasRegistered;
use App\Services\NotificationService;
class SendUserWelcomeEmail {
protected $notificationService;
public function __construct( NotificationService $notificationService ) {
$this->notify = $notificationService;
}
public function handle( UserHasRegistered $event ) {
$this->notify
->byEmail( $event->user->email, 'Welcome to the site', 'welcome-user' )
->send();
}
}
All that remains is to tell Laravel that the Event and Listener we've just created are related, then to fire the event.
// app/Providers/EventServiceProvider.php
use App\Events\UserHasRegistered;
use App\Listeners\SendUserWelcomeEmail;
class EventServiceProvider extends ServiceProvider {
// find this array near the top, and add this in
protected $listen = [
UserHasRegistered::class => [
SendUserWelcomeEmail::class,
],
];
// ...
}
Now we just need to raise the event - see my other post about Model Observers. First off you'll need to import Event and App\Events\UserHasRegistered, then in your created method, just call Event::fire( new UserHasRegistered( $user ) ).
What I ended up doing, since I do need to do more than just one operation on the user creation is having another function for user creations.
User model
/**
* Create a new user instance after a valid registration.
*
* #param array $attributes
* #param null $role
* #param bool $send_activation_email
*
* #return User $user
*
* #internal param array $args
*/
public function createNew(array $attributes, $role = null, $send_activation_email = true)
{
$this->name = $attributes['name'];
$this->company_id = $attributes['company_id'];
$this->email = $attributes['email'];
$this->password = bcrypt($attributes['password']);
$this->save();
if (isset($role)) {
// Assigning the role to the new user
$this->attachRole($role);
}
//If the activation email flag is ok, we send the email
if ($send_activation_email) {
$this->sendAccountActivationEmail();
}
return $this;
}
and calling it like:
User Controller
$user = new User();
$user->createNew($request->all(), $request->role);
It might not be the best solution, but it does the job, and it's future prof, so if the logic on the user creation grows can be implemented aswell.

Resources