<?php
namespace nur\b\authnz;

use nur\A;
use nur\str;

/**
 * Class CasUserManager: un utilisateur CAS v3
 */
class CasUserManager extends SimpleUserManager {
  function __construct(?string $appcode=null) {
    $this->appcode = $appcode;
  }

  protected $appcode;

  function _getUser(string $username): ?array {
    return ["username" => $username];
  }

  function getUser(string $username, ?array $overrides, ?bool &$found=null): array {
    $user = parent::getUser($username, $overrides, $found);
    # support des attributs CAS
    $cas_attrs = A::get($overrides, "cas_attrs");
    if ($cas_attrs !== null) {
      $authzs = A::get($cas_attrs, "rununivauthorization");
      if ($authzs !== null) {
        $authzs = explode(",", $authzs);
        $appcode = $this->appcode;
        $groups = [];
        $role = null;
        $perms = [];
        foreach ($authzs as $authz) {
          if ($authz == "*:*") {
            $perms[] = "*";
          } elseif (str::del_prefix($authz, "$appcode:")) {
            if ($authz == "*") $perms[] = "*";
            elseif (str::del_prefix($authz, "@")) $groups[] = $authz;
            elseif (str::del_prefix($authz, "*")) $role = $authz;
            else $perms[] = $authz;
          }
        }
        A::merge($user["groups"], $groups);
        if ($role !== null) $user["role"] = $role;
        A::merge($user["perms"], $perms);
      }
    }
    return $user;
  }
}
