So I have tried to make a symfony project that contains private profiles, and I use FriendsOfSymfony, but if I create a two users, each one can see the others uploaded file. I tried to search on multiple websites and failed to find something that worked for me.
example:
Adding extended profile entity to FOS UserBundle
I want to create private profiles for each user to upload files, no one except them should be able to see them(only the admin and the specific user).
Provided you have extended
Symfony\Bundle\FrameworkBundle\Controller\Controller
or FOSUserBundle Controller you could try doing something like this:
public function publicProfileAction($handleOrHash = '')
{
if ($handleOrHash == '') {
throw new NotFoundHttpException("Unable to find this user");
}
$user = $this->getUserService()->getUserByHandleOrHash($handleOrHash);
if (!$user) {
throw new NotFoundHttpException("Unable to find this user");
}
if ($user != $this->getUser()) {
throw new AccessDeniedException("You cannot see this user profile");
}
return $this->render('MyUserBundle:Default:public-profile.html.twig',
array('user' => $user)
);
}
Where getUserService() will return an object which has access to the userRepository with a method called getUserByHandleOrHash() which uses the repository to make the doctrine query.
Question is very broad.
You need to introduce authentication to your application.
And add user id or user relation to your uploaded files. Then in controller where you list/show that files (/profile/my-uploads) - load only files which belongs to this specific (logged in) user.
For admin access - best will be creating special back-office or implement User Impersonation.
Read more about it in Symfony documentation: http://symfony.com/doc/current/components/security/authentication.html
Related
I am trying to make a global variable in AppServiceProvider.php that I will need throught my whole application meaning in all blade files. This variable is $profile which gets the profile data from user and displays them in blades. I made it so when I am on my profile it shows authenticated user which is me and it is fine (in url is like this profile/Authuser), that Authuser is username from database. Problem is when I go to some other profile then I get error undefined username (in url profile/Someuser). I need help on to get that username in AppServiceProvider.php. Problem is in that $username in service provider. I don't know how to pass it in there globally. Any help is appreciated. Here is my code.
AppServiceProvider.php
public function boot()
{
$profileId = $this->getIdFromUsername($username); // Here is problem, I don't know how to get that username
view()->composer('*', function ($view) {
$view->with('profile', Auth::id() ? UserProfile::profileDetails($profileId, Auth::user()->id) : []);
});
Builder::defaultStringLength(191); // Update defaultStringLength
}
public function getIdFromUsername($username)
{
if ($user = User::where('username', $username)->first()) {
return $user->id;
}
return abort(404);
}
web.php
Route::get('profile/{profile}', 'UserProfileController#showProfile')->name('profile.show');
I believe you are over complicating yourself.
If I understand your app. A user has a Profile correct?
Go to your User Model and create a relation between User and Profile
public function userProfile()
{
return $this->hasOne('App\UserProfile');
}
With that, the profile will follow the user, and you don't need to be passing it around.
If you want the Profile for the current User.
Auth::user()->userProfile();
If you want the profile of another user then
$owner = User::where('username', $username)->first();
$owner->userProfile();
Basically you can have access to the profile of your logged in user, or any other user easily by just finding the user you want.
Now, if you really wish to have a Model in every view, you are placing it in the wrong place. You see, Service Providers are intended to tie things up, not to get data. What you are probably thinking about is a View Composer that you do tie in with a Service Provider, but the actual data comes from the Composer itself. You can learn more about View Composer in the Docs. https://laravel.com/docs/7.x/views#view-composers
View Composers are just one way of doing it, a quick google search brought up this question which offers 3 additional alternatives to the view composer.
How to pass data to all views in Laravel 5?
Hope that helps.
How in SonataAdminBundle
get the current admin class without using AdminPool?
Now I'm trying to do it like this
$entityClass = get_class($entity);
$adminClass = $this->adminPool->getAdminByClass($entityClass);
But this method has a problem. If the entity is associated with several classes of the admin, an exception will be thrown.
Is there a way to find out what exactly the admin service should handle the current route?
Thanks!
If you have multiple admins registered for this entity's class, nothing can choose the correct one for you.
You can still get a specific admin with the method Pool::getAdminByAdminCode(string $code).
For example, an usage for you could be:
if ($entityClass === MultipleAdminRegisteredEntity::class) {
$admin = $this->adminPool->getAdminById('specific_admin_id');
} else {
$entityClass = get_class($entity);
$admin = $this->adminPool->getAdminByClass($entityClass);
}
Please pay attention to the fact that the Pool::getAdminByClass(string $class) returns an Admin and not a class string: you named your variable $adminClass which suggests you made this confusion.
Also note that there is an open issue on Github here: https://github.com/sonata-project/SonataAdminBundle/issues/3908 to determine a way to be able define default admins when there are more than one admin for an entity, so that the Pool:getAdminByClass() method doesn't throw an exception. Nobody seems to have care enough about this to implement it, feel free to contribute there if you want.
I'm trying to add some functionality to the back end of a Bolt CMS installation that does the following:
Check if the user is a member of the "limited editor" group.
If so, only list content which they, personally, own.
This needs to be within the controller, not using Twig.
I've got the user object using
$user = $app['users']->getCurrentUser();
I guess I could use
in_array('limitededitor', $user["roles"]);
But I wondered if there was any existing function in Bolt that would streamline this, like "isAllowed" but for checking role membership?
This is what I've used in the past to determine whether I mount a controller (and thus give access to the new urls), the key part is the users service has a hasRole method but you need to check by user id.
public function checkAuth()
{
$currentUser = $this->app['users']->getCurrentUser();
$currentUserId = $currentUser['id'];
foreach (['admin', 'root', 'developer', 'editor'] as $role) {
if ($this->app['users']->hasRole($currentUserId, $role)) {
return true;
}
}
return false;
}
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 am making a social website using Zend. The site allows users to become friends and access each other's profiles and blogs. I also want users to have control over their privacy, which can take parameters "Friends Only" and "Public". I looked at Zend_Acl but it seems to be only able to to handle single user's accessibility not users have relationship. Any ideas about the best way to do this?
For your purposes, if you use Zend_Acl, you should look at assertions.
Given the complex nature of the relationships between users in your applications, most of the access rules you will query seem very dynamic so they will largely rely on assertions that can use more complex logic to determine accessibility.
You should be able to accomplish what you want using Zend_Acl though.
You may set up an ACL rule like this:
$acl->allow('user', 'profile', 'view', new My_Acl_Assertion_UsersAreFriends());
The ACL assertion itself:
<?php
class My_Acl_Assertion_UsersAreFriends implements Zend_Acl_Assert_Interface
{
public function assert(Zend_Acl $acl,
Zend_Acl_Role_Interface $role = null,
Zend_Acl_Resource_Interface $resource = null,
$privilege = null)
{
return $this->_usersAreFriends();
}
protected function _usersAreFriends()
{
// get UserID of current logged in user
// assumes Zend_Auth has stored a User object of the logged in user
$user = Zend_Auth::getInstance()->getStorage();
$userId = $user->getId();
// get the ID of the user profile they are trying to view
// assume you can pull it from the URL
// or your controller or a plugin can set this value another way
$userToView = $this->getRequest()->getParam('id', null);
// call your function that checks the database for the friendship
$usersAreFriends = usersAreFriends($userId, $userToView);
return $usersAreFriends;
}
}
Now with this assertion in place, the access will be denied if the 2 user IDs are not friends.
Check it like:
if ($acl->isAllowed('user', 'profile', 'view')) {
// This will use the UsersAreFriends assertion
// they can view profile
} else {
// sorry, friend this person to view their profile
}
Hope that helps.