I am using Zend Framework 2 and having trouble getting the user role. I am using zfc user and Zfc Rbac. The roles currently work however I would like to get the values to use in an if statement (in the controller). What is the function to call these? I have the developer tool turned on so I can see the role assigned but can't figure out out to call it.
Thanks
Matt
If you have setup you identify correctly in ZfcRbac, then you can use the authorization service (ZfcRbac\Service\AuthorizationService) to get the identity and its roles.
$authorizationService->getIdentity()->getRoles();
I was used the below code and was able to get the role of the logged in user.
$viewmodel = new ViewModel();
$authorize = $this->getServiceLocator()->get('UserRbac\Identity\IdentityRoleProvider');
$roles = $authorize->getIdentityRoles();
echo $roles[0];
$viewmodel->setVariable("roles", $roles);
return $viewmodel;
Related
I am currently doing a website wherein the login URLs are varying and displays the data according to the assigned projects to them.
For example, user A can only access www.example.com/projects/proj1. This is the homepage for user A and if he logs in he uses www.example.com/projects/proj1/login
While user B can only access www.example.com/projects/proj2. This is the homepage for user B and if he logs in he uses www.example.com/projects/proj2/login
Please note that proj1 and proj2 are varying depending on the database. So I have to check first that these projects are already registered in the database.
I am thinking of having a route like this.
For web.php
Route::get('/projects/{project_name}', 'PageHandler\CustomPageController#projects');
Route::get('/projects/{project_name}/login', 'PageHandler\CustomPageController#login');
Route::put('/projects/{project_name}/auth/{user}', 'PageHandler\TestUserPageController#auth');
Then my customepagecontroller.php looks like this
class CustomPageController extends Controller
{
public function projects(string $projectName)
{
if (auth()->user() == null)
return redirect('/projects'. '/' . $projectName . '/login');
}
public function login(string $projectName)
{
return view('login')->with('projectName', $projectName);
}
public function auth(Request $request, string $projectName)
{
$username = $request->username;
//How to set $username as logged in?
// rest of the code to show the home page after authentication
}
}
login.blade.php basically just looks like a form submitting username and password and calling auth of CustomPageController with a string parameter for the URL
So my question is how can I set $username as logged in already using the Auth of Laravel? Or should I create my custom Authentication Controllers?
Now, this is the only approach I have in mind for me to enable the logging in of users to varying URLs. Please let me know if you have better approach.
Thank you!
If you only want to limit the project the users can access, I do not see a need to use 2 different login URLs (please correct me if there is a reason why you want different URLs for that), instead, you simply find which project the user belongs to from the database.
For authentication, Laravel allows you to implement authentication in a very easy way, you can refer to the documentation. Using Laravel's authentication would be easier and safer than writing your own one, and even if the default functionalities it provides may not be exactly the same as those you would want to achieve, you can still add your own things, which is still a lot easier than implementing it from scratch.
As for setting a user as logged in with Laravel's authentication services, you can use Auth::login($user);. Here, $user must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. You can refer to this part of the documentation for more details.
I have a navbar where I try to display some stuff depending if the user is authenticated or not.
So I have a login form, when I axios.post('/login') with the email / password, and I deal with the potential errors.
I have also a method in my UserController to get the authenticated user (if there is one) via Auth::user() like the docs says, but this methods always returns an empty object ...
public function getUser() {
$user = Auth::user();
Log::info($user);
return $user;
}
This methods always returns me a [2018-06-17 16:29:26] local.INFO:
But the stranger things (like the TV show) is where I try to go on my '/admin' routes, my middleware use also the 'Auth::user()' to determines if the user's role is 'user' or 'admin', that 'Auth::user()' methods returns me well the user ...
I am stuck ...
Please, if someone has experienced the same issue, let me know how to solve it, or if someone want to see more code, let me know as well I'll be glad to show you more proof.
Thanks,
public function getUser() {
$user = Auth::user()->name;
return $user;
}
Use Auth::user()->name; to return your user name on navbar.
You have to provide further info to Log::info(), Something like the name or id of the $user->name, $user->id.
Further more you can use that id, Search with it and get the info of the user.
You should have a proper pattern for the log, By pattern i means proper logging. Passing the whole object $user will not work.
Hello you must use this syntax on laravel version 8 and more
auth('api')->user()->id
api will be used when you have an api if you are on a web version you will use
auth('web')->user()->id
Case: I'm building a forum using Laravel's Authorization as a backbone using policies. Examples of checks I run are stuff like #can('view', $forum), and #can('reply', $topic), Gate::allows('create_topic', $forum) etc. These checks basically checks if the users role has that permission for the specific forum, topic or post. That way I can give roles very specific permissions for each forum in my application.
The issue is that all of these checks go through the Gate class, specifically a method called raw() which in its first line does this:
if (! $user = $this->resolveUser()) {
return false;
}
This presents an issue when dealing with forums. Guests to my application should also be allowed to view my forum, however as you can see from the code above, Laravels Gate class automatically returns false if the user is not logged in.
I need to be able to trigger my policies even if there is no user. Say in my ForumPolicy#view method, I do if(User::guest() && $forum->hasGuestViewAccess()) { return true }
But as you can see, this method will never trigger.
Is there a way for me to still use Laravel's authorization feature with guest users?
I'm not aware of a super natural way to accomplish this, but if it's necessary, you could change the gate's user resolver, which is responsible for finding users (by default it reads from Auth::user()).
Since the resolver is protected and has no setters, you'll need to modify it on creation. The gate is instantiated in Laravel's AuthServiceProvider. You can extend this class and replace the reference to it in the app.providers config with your subclass.
It's going to be up to you what kind of guest object to return (as long as it's truthy), but I'd probably use something like an empty User model:
protected function registerAccessGate()
{
$this->app->singleton(GateContract::class, function ($app) {
return new Gate($app, function () use ($app) {
$user = $app['auth']->user();
if ($user) {
return $user;
}
return new \App\User;
});
});
}
You could go a step further and set a special property on it like $user->isGuest, or even define a special guest class or constant.
Alternatively you could adjust your process at the Auth level so that all logged-out sessions are wrapped in a call to Auth::setUser($guestUserObject).
I just released a package that allows permission logic to be applied to guest users. It slightly modifies Laravel's Authorization to return a Guest object instead of null when no user is resolved. Also every authorization check now makes it to the Gate instead of failing authorization instantly because there isn't an authenticated user.
I am currently developping an application using Symfony2.6 And I have some trouble. I have two kind of users customers and employee so in my Database I have a table customer and a table employee. How can I tell symfony to go look in these two tables for the user credentials when the user try to log in?
I know that you can define a provider in the security.yml file which can be the entity but how can I declare two providers? is that possible or do I have to do this another way ?
thank all for you answers
I've got something similar with (currently) two different types of users. To handle all of the login and permissions though, I'm using FosUserBundle, and assigning them roles which I can check and then fetch user-profiles based on that.
To ensure that they get the correct ROLE_* assigned on the user creation I've followed the SO question, Adding new FOSUserBundle users to a default group on creation. They pickup a session variable with the future-role they will take, and then I have an event listener to set that role to the newly minted FosUser:
<?php
class UserCreationListener implements EventSubscriberInterface
{
// lots of constructor setup, debugging, logging and checks removed from code
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
);
}
public function onRegistrationSuccess(FormEvent $event)
{
$user = $event->getForm()->getData();
$newRole = $this->session->get('futureRole', 'ROLE_CUSTOMER');
$user->addRole($role);
$this->userManager->updateUser($user);
return $this->redirect->redirect('app_profile', 302);
}
}
So thx to someone here i've found the answer to this specific problem here
http://symfony.com/doc/current/cookbook/security/multiple_user_providers.html
Symfony allows us to declare a multiple user providers
I'm using FOSUserBundle. What is the difference between these two?
$this->get('fos_user.user_manager');
...and...
$this->getUser();
I've found I've used both of the above at different times and everything works fine.
I'm guessing the first one is from FOS and the second one is the default one, but I'm guessing I should always use the same one.
This is one piece of code I've used:
$user = $this->getUser();
if($user) {
$email = $user->getEmail();
} else {
$email = "no email";
}
..and another...
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('memberID' => '123'));
...so should I have used the same method for both?
With $this->getUser() is only a shortcut to
$this->get('security.context')->getToken()->getUser()
So this means you get the user object according to the current security token. It's perfect and easy, when you want to retrieve the actual logged in user.
But if you want to get other users, fos_user.user_manager is the choice, as it has methods to find users easy and hiding the implementation behind. And it provides also methods for creating new users and updating them. And also if you retrieve the current logged in user with $this->getUser() and made modifcations to them, you should use the fos user manager to update them. Take a look in the docs for more!
They return different objects. $this->get('fos_user.user_manager') returns a FOS\UserBudle\Doctrine\UserManager object and $this->getUser() returns a FOS\UserBundle\Model\User object. The former handles users and the latter is a user. So no, you are using it right.
Where the two differ is in saving a user or creating a new user. If using the FOSUserBundle, you should always use the $this->get('fos_user.user_manager') method. This gives you access to the updateUser() function that works with the FOSUserBundle to make sure it updates all the user attributes that you don't need to explicitly declare in your User model, like date_created and roles.
That function is different than using Doctrine to persist() and then flush() the model.