Laravel: Dependency Inject Auth - authentication

How do I dependency inject Auth in Laravel?
Like this:
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
If I do that then this does not work:
$user_type = Auth::user()->user_type;

You should type hint Illuminate\Auth\AuthManager:
public function __construct(Illuminate\Auth\AuthManager $auth)
{
$this->auth = $auth;
}

If you want to inject Auth, you actually need to inject this class:
use Illuminate\Contracts\Auth\Guard;
That will resolve everything what you define inside:
config/auth.php
If you want to extend Auth you can do that but only for:
Guard Driver which is Guard Class - it needs to implement Guard or StatefulGuard interface.
Provider which is UserProvider Class - it needs to implement UserProvider interface.
Standard Auth Guard drivers in Laravel / Lumen are:
SessionGuard
TokenGuard
Standard Auth UserProviders are in Laravel / Lumen are:
EloquentUserProvider
DatabaseUserProvider
More about extending Auth you have in official Laravel documentation. See link below:
https://laravel.com/docs/5.0/extending#authentication
This is the code which I have in my controller and it is working like a charm:
public function createToken(Request $request, Guard $guard)
{
// return 'in progress...';
}
Best Practise for extending Auth class is in ServiceProvider boot() method.
Hope this helps!
Cheers.

Related

ServiceStack - IAuthRepository vs IUserAuthRepository

I’ve to configure my web application to use the ServiceStack built-in ApiKeyAuthProvider. I’ve registered in the container the OrmLiteAuthRepository with the IAuthRepository interface but it throws an exception saying that I’ve not registered the IUserAuthRepository.
Could someone explain me the difference?
Thanks in advance
EDIT:
Sorry, i've made confusion
The error is
System.NotSupportedException: 'ApiKeyAuthProvider requires a registered IAuthRepository'
Our AppHost's Configure method is
public override void Configure(Container container)
{
var dbFactory = new OrmLiteConnectionFactory("connString", SqlServerDialect.Provider);
container.Register<IDbConnectionFactory>(dbFactory);
container.Register<IUserAuthRepository>(_ => new OrmLiteAuthRepository(dbFactory));
container.Resolve<IUserAuthRepository>().InitSchema();
var authProvider = new ApiKeyAuthProvider()
{
RequireSecureConnection = false
};
Plugins.Add(new AuthFeature(
() => new AuthUserSession(),
new IAuthProvider[] {
authProvider
}
));
}
Could you explain me the difference between these two interfaces? we can't figure out (ServiceStack v.6.0.2)
Please refer to the Auth Repository docs for examples of correct usage, e.g:
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(connectionString, SqlServer2012Dialect.Provider));
container.Register<IAuthRepository>(c =>
new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
container.Resolve<IAuthRepository>().InitSchema();
The IAuthRepository is the minimum interface all Auth Repositories have to implement whilst IUserAuthRepository is the extended interface to enable extended functionality to enabled additional features which all ServiceStack built-in Auth Repositories also implement. But you should never need to register or resolve a IUserAuthRepository, i.e. they should only be registered against the primary IAuthRepository interface.
Resolving Auth Repository
If you need to, the Auth Repository can be accessed from base.AuthRepository or base.AuthRepositoryAsync in your Service where you'll be able to use any IUserAuthRepository APIs since they're all available as extension methods on IAuthRepository, e.g. This example Service calls the IUserAuthRepository.GetUserAuth() method:
public class MyServices : Service
{
public object Get(MyRequest request) =>
AuthRepository.GetUserAuth(request.UserId);
}
Whilst here are the recommended APIs to access the Auth Repository outside of your Services:
var authRepo = HostContext.AppHost.GetAuthRepository();
var authRepoAsync = HostContext.AppHost.GetAuthRepositoryAsync();

Phalcon Controller $this->session and Phalcon\Session\Manager()

I'm using Phalcon v.4 and I have seen that are two ways to create the session inside a controller:
class PostController extends Controller
{
public function postAction(): Response
{
$session = new Phalcon\Session\Manager()
}
}
or
class PostController extends Controller
{
public function postAction(): Response
{
$this->session;
}
}
I have seen that the methods are the same, but I'm not able to understand the different and which is better to use.
if you created your project using phalcon's cli devtools then the session service would be created by default in app/config/services.php
that being said in your controller when you access the instance's property session aka $this->session this would look for a service called session and by default it would setup session using file adapter and starts it and $this->session would return an instance of Phalcon\Session\Manager

Auth user check role is not working in serviceProvider Laravel

when i use (auth()->user()->hasRole('User')) or (Auth::user()->hasRole('User')) in service provider it gives me this error:
Call to a member function hasRole() on null
I use spatie library and include this in my serviceProvider file:
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Traits\HasRoles;
and the code I write is:
if (Auth::user()->hasRole('User')) {
$count = Complaint::where('user_id', auth()->user()->id)->where('is_deleted', 'not_deleted')->get()->count();
} else {
$count = Complaint::where('status', '!=', null)->where('is_deleted', 'not_deleted')->get()->count();
}
Unfortunately, the Laravel session is initialized in the middleware so you can't access Auth::... from a Service Provider because they are executed before the middleware in the request lifecycle.

Auth data is not accessible in AppServiceProvider Laravel 5.5

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use App\Classes\DynamicMenu;
use App\Http\Controllers\WelcomeController;
use Auth;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
dd(Auth::user());
}
}
This returns 'null' for me, but other controllers returns user details. How to fix this?
Why?
It is because, when the boot method of a service provider is being called, the user is not yet authenticated.
Solution:
I guess you are trying to use View Composers
From the documentation:
So, what if we need to register a view composer within our service
provider? This should be done within the boot method. This method is
called after all other service providers have been registered, meaning
you have access to all other services that have been registered by the
framework:
So you can use the following:
public function boot(Guard $auth) {
view()->composer('*', function($view) use ($auth) {
$user = $auth->user();
// other application logic...
$view->with('currentUser', $user);
});
}

Laravel 5.3 RESTFul API without authentication

I want to create an API with Laravel 5.3 but i don't need any kind of authentication. Is it possible to get rid of it? I don't want any token or any kind of authentication.
Yes, it's possible
normally in your
route/api.php
you'd have something like
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
you just need to remove the part of the middleware that's referencing auth.
So the above would look like:
Route::middleware('api')->get('/user', function (Request $request) {
return $request->user();
//middleware('api') URI prefix. which would become '/api/user'
});
or
Route::apiResource('user', 'UserController');
//same as above but includes crud methods excluding 'create and edit'
To help anyone in my situation who arrive here : be aware that any route in api.php is prefixed by "api/".
It is set in /app/Providers/RouteServiceProvider.php.
So :
Route::get('/delegates', "APIController#delegate");
Will be accessible from
http://www.yourdomain.com/api/delegates
Sorry if it's a bit off-topic, but hope it can help someone.
Of course you can get rid of it. Just setup your routes to don't use any middleware.
Create your API routes on routes/api.php file, then modify the app/Http/Kernel.php file to set your middlewares correctly:
Remove (or add) the middlewares you don't want on api middleware group.
By default, L5.3 comes with two middlewares on api group:
'api' => [
'throttle:60,1',
'bindings',
],
The first one provides a rate limiting to your API (60 requests/minute),
the second substitutes your model bindings.
It's possible, just create route to your controller and return data (Without any auth middleware).
Allow your route to run without auth
Http\Middleware\VerifyCsrfToken
public function handle($request, Closure $next)
{
if (!$request->is('api/*'))
{
return parent::handle($request, $next);
}
return $next($request);
}
Set route like this
'api' => 'APIController'
This is method in APIController ('/api/data')
public function getData(Request $request)
{
return "Hello";
}