1

Use-case is to provide a set of permissions to an "anonymous" user i.e. we don't know who they are and they haven't logged in, we just have their IP range to confirm where they're coming from (yes I know... it's not a system I would design :) ).

I don't necessarily know what permissions these users need down the line i.e. it may be access to certain node types, it may be access to certain file entities.. it will be an evolving set of permissions that should be configurable later as a role would be.

Is it possible to define a role and then temporarily give it to anonymous sessions that meet our criteria? I tentatively tried using an EventSubscriber to check each time our module loads but that isn't working because obviously we can't really "save" an anon user i.e.:

class CivicrmIpAccessSubscriber implements EventSubscriberInterface {

  public function CivicrmIpAccessLoad(GetResponseEvent $event) {
    $proxy = \Drupal::currentUser();
    $roles = $proxy->getRoles();
    if ($roles === ['anonymous']) {
//Business logic to determine if a user gets access would go here
      $user = User::load($proxy->id());
      $user->addRole('ip_access');
//This user save doesn't work, and I wouldn't have really expected it to but I tried it
      User::save($user);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['CivicrmIpAccessLoad', 250];
    return $events;
  }

}

Is there a good way to accomplish something like this for a session? I feel like anonymous user is barking up the wrong tree and session would be correct but i'm not sure how to interact with access from there.

Edit: $user->save(); also not working. The result of these saves seems to be no log feedback but the role is not added if I go get the current user again and check the roles so they still get access denied.

2
  • Have you tried $user->save() Plus instead of checking on the roles you can just check if $proxy->isAnonymous().
    – user72672
    Sep 26, 2019 at 16:47
  • Thanks for the optimization! I tried $user->save(); I should update the ticket with the results. TLDR it doesn't give any feedback in terms of logs but the role isn't added successfully if I go get my current user again and check roles (nor can I remove anonymous). Sep 26, 2019 at 16:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.