i have a Laravel 5.4 application where i do all Authentication based logic through PHP and then redirect the user to a catchAll route when they are authenticated, and let VueRouter take it from there...
I'd like to also use Entrust because my app will have several types of users and some elements (like an Edit User button) will only be visible to some user Roles.
I might also want to implement specific permissions, like some Admins can edit user Permissions, while others do not.
The issue is, alright i'm in Javascript territory now, so how do i know what my current Auth user is? Setting a global JS variable for Auth::user doesn't seem like a good idea to me.
Perhaps i would instead pass just an ID, but how exactly without making it globally visible as a window variable?
I think you may create an auth/check API call, like this:
protected function check()
{
if(Auth::guard('api')->check()) {
return Auth::guard('api')->user();
}
return ['success' => false];;
}
And then get current user with this call.
Related
I am new to laravel. I am trying to implement email verification on my laravel6 project.
On my project, there're three user types named 'user' 'vendor' and 'admin'. I have prepared separate directories for each user type in 'Controllers' and each of them has their own Auth files (e.g. Directory 'App/Http/Controllers/Vendor/Auth' has its own VerificationController.php, etc). So far, I've successfully implemented registration and login/logout function for each type with separate table in my DB.
A issue popped up when I tried to implement email verification. When I tried to access to a page where email verification is required, 'Auth\VerificationController#show' method seemed to be called regardless of the user type.
I went over laravel source code and learned that within the process, router calls Illuminate/Routing/Router->emailVerification() method. And the emailVerification() method routes to 'Auth\VerificationController#show' regardless of the user type.
What I wanted to do is to route depending on user type (e.g. if 'vendor' tries to login, I want to call 'Vendor\Auth\VerificationController#show').
I don't come up with any idea how to do for that. Can anyone please give me any advice?
Illuminate\Routing\Router class
public function emailVerification()
{
$this->get('email/verify', 'Auth\VerificationController#show')->name('verification.notice');
$this->get('email/verify/{id}/{hash}', 'Auth\VerificationController#verify')->name('verification.verify');
$this->post('email/resend', 'Auth\VerificationController#resend')->name('verification.resend');
}
Thank you in advance.
I am trying to get user's unread notifications though my controller.
This works:
public function notifications(){
return \App\User::find(auth()->user()->id)->unreadNotifications()->limit(5)->get();
}
This doesn't, it returns an empty collection:
public function notifications(){
return auth()->user()->unreadNotifications()->limit(5)->get();
}
Could you tell me what I am missing? Thanks in advance.
Using Laravel 5.8 with Backpack 3.5.
The default auth guard of Laravel is overwitten to use Backpack auth in backpack routes, using the UseBackpackAuthGuardInsteadOfDefaultAuthGuard middleware of the permissions manager package. In the rest of the controller auth() and backpack_auth works normally.
Try this:
public function notifications()
return Auth::user()->unreadNotifications()->limit(5)->get();
}
As said in the docs:
You may access the authenticated user via the Auth facade:
Alternatively, once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance. Remember, type-hinted classes will automatically be injected into your controller methods:
Auth and auth() likely don't work here because you're using the Backpack For Laravel authentication which uses a different guard than the default one Laravel uses.
This would probably work for you:
backpack_user()->unreadNotifications()->limit(5)->get();
If that works, here's why:
If you take a look at project/vendor/backpack/base/src/helpers.php you'll see that backpack_user() is an alias for backpack_auth()->user() and backpack_auth does a:
return \Auth::guard(backpack_guard_name());
That's the important bit because it grabs the guard defined config/backpack/base.php (which is backpack by default) and uses that instead of Laravel's default guard of web.
I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.
I have 2 laravel projects, 1 for the front end where i m using html css angularjs. The second for api controllers. I call using http post and get the api controllers functions using angularjs to get content data.
In the front end i have a menu this menu appears differently based on user role, if admin or no.
This is done. My problem is the access for views using the url in the browser.
So I have a query where I get for each user what modules in the menu can he see. Now I'm putting the result in Laravel session.
$menu = DB::select menu by user id ... //Getting menu query based on user if admin or no
session(["menu" => $menu);
return session('menu');
I'm getting the results and the menu is showing good in the website based on the logged user if he s admin or no.
Now, to solve the direct url access issue, I want to use this session and compare the url to this session, if the url exists in the session i will let him access, if no i will redirect him to somewhere.
any idea?
I would strongly suggest looking at the Laravel documentation on Authorization before going too far down a custom implementation:
https://laravel.com/docs/5.1/authorization
Without knowing more about how your front-end and back-end applications interact with each other, it is a little difficult to get into speciifics but i shall do my best.
Each page returned by Laravel has access to a Request object which contains information about the request which returned the page. You can access this Request and its assocaited Route using Laravels helper functions (if you are not passing it to the view already). The getPrefix() method will return the root relative url which you can then use as you see fit. For example:
// Return and store the URL as a string
$url = request()->route()->getPrefix();
// Check your session for the URL/s you want to allow and compare to the stored URL
if (session()->get('URL') == $url) {
// User is allowed access to the page
// Do something ...
} else {
// User is not allowed access to this page
// Redirect back or to a route of your choice
return redirect()->back();
}
I hope this gives you some ideas, good luck!
I am building an administrative back-end and thus need to hide public user registration. It appears that if you want to use the built-in Illuminate authentication you need to add
use AuthenticatesAndRegistersUsers to your controller definition. This trait is defined here.
It appears as if it is impossible to disable registration if you want to use the built-in auth handlers... can someone show me wrong?
I'm using Laravel 5.2+ and I found that if you remove the Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers and use just Illuminate\Foundation\Auth\AuthenticatesUsers does the trick too.
Though /register is still accessible and will throw a fatal error.
This page talks about overriding the auth controller. Its worth a read, at a basic level it seems you can add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function getRegister() {
return redirect('/');
}
public function postRegister() {
return redirect('/');
}
So if a user accesses the registration url it will redirect them away to a place of your choosing.
You can have your own form of registration. The only thing Laravel does is make it easy to authenticate on a users table because they create the model, build the db schema for users and provide helper methods to authenticate on that model/table.
You don't have to have a view hitting the registration page... But if you want to use the built in auth you still need to use (or set) a Model and a driver for database connections.
You can just remove that view and/or controller method from the route that links to the registration view and create your own (or seed the database manually).
But, no, you cannot forgo using Eloquent, and the User model and expect to use built in auth. Built in authentication requires that you specify settings in /config/auth.php. You may specific a different model (other than User) and you may specify a different table, but you cannot forgo the configuration completely.
Laravel is very customizable though, so you can achieve what you are looking to do... plus why not use Eloquent, it's nice.
Based on #shoo's answer, working with Laravel 5.2
Add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function showRegistrationForm() {
return redirect('/');
}
public function register() {
return redirect('/');
}