nugrohoe_ku

app/Entities/User.php

Jan 29th, 2021
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.21 KB | None | 0 0
  1. <?php namespace App\Entities;
  2.  
  3. use CodeIgniter\Entity;
  4. use Myth\Auth\Authorization\GroupModel;
  5. use Myth\Auth\Authorization\PermissionModel;
  6.  
  7. class User extends Entity
  8. {
  9.     /**
  10.      * Maps names used in sets and gets against unique
  11.      * names within the class, allowing independence from
  12.      * database column names.
  13.      *
  14.      * Example:
  15.      *  $datamap = [
  16.      *      'db_name' => 'class_name'
  17.      *  ];
  18.      */
  19.     protected $datamap = [];
  20.  
  21.     /**
  22.      * Define properties that are automatically converted to Time instances.
  23.      */
  24.     protected $dates = ['reset_at', 'reset_expires', 'created_at', 'updated_at', 'deleted_at'];
  25.  
  26.     /**
  27.      * Array of field names and the type of value to cast them as
  28.      * when they are accessed.
  29.      */
  30.     protected $casts = [
  31.         'active'           => 'boolean',
  32.         'force_pass_reset' => 'boolean',
  33.     ];
  34.  
  35.     /**
  36.      * Per-user permissions cache
  37.      * @var array
  38.      */
  39.     protected $permissions = [];
  40.  
  41.     /**
  42.      * Per-user roles cache
  43.      * @var array
  44.      */
  45.     protected $roles = [];
  46.  
  47.     /**
  48.      * Automatically hashes the password when set.
  49.      *
  50.      * @see https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence
  51.      *
  52.      * @param string $password
  53.      */
  54.     public function setPassword(string $password)
  55.     {
  56.         $config = config('Auth');
  57.  
  58.         if (
  59.             (defined('PASSWORD_ARGON2I') && $config->hashAlgorithm == PASSWORD_ARGON2I)
  60.                 ||
  61.             (defined('PASSWORD_ARGON2ID') && $config->hashAlgorithm == PASSWORD_ARGON2ID)
  62.             )
  63.         {
  64.             $hashOptions = [
  65.                 'memory_cost' => $config->hashMemoryCost,
  66.                 'time_cost'   => $config->hashTimeCost,
  67.                 'threads'     => $config->hashThreads
  68.                 ];
  69.         }
  70.         else
  71.         {
  72.             $hashOptions = [
  73.                 'cost' => $config->hashCost
  74.                 ];
  75.         }
  76.  
  77.         $this->attributes['password_hash'] = password_hash(
  78.             base64_encode(
  79.                 hash('sha384', $password, true)
  80.             ),
  81.             $config->hashAlgorithm,
  82.             $hashOptions
  83.         );
  84.  
  85.         /*
  86.             Set these vars to null in case a reset password was asked.
  87.             Scenario:
  88.                 user (a *dumb* one with short memory) requests a
  89.                 reset-token and then does nothing => asks the
  90.                 administrator to reset his password.
  91.             User would have a new password but still anyone with the
  92.             reset-token would be able to change the password.
  93.         */
  94.         $this->attributes['reset_hash'] = null;
  95.         $this->attributes['reset_at'] = null;
  96.         $this->attributes['reset_expires'] = null;
  97.     }
  98.  
  99.     /**
  100.      * Force a user to reset their password on next page refresh
  101.      * or login. Checked in the LocalAuthenticator's check() method.
  102.      *
  103.      * @param User $user
  104.      *
  105.      * @return User
  106.      * @throws \Exception
  107.      */
  108.     public function forcePasswordReset()
  109.     {
  110.         $this->generateResetHash();
  111.         $this->attributes['force_pass_reset'] = 1;
  112.  
  113.         return $this;
  114.     }
  115.  
  116.     /**
  117.      * Generates a secure hash to use for password reset purposes,
  118.      * saves it to the instance.
  119.      *
  120.      * @return $this
  121.      * @throws \Exception
  122.      */
  123.     public function generateResetHash()
  124.     {
  125.         $this->attributes['reset_hash'] = bin2hex(random_bytes(16));
  126.         $this->attributes['reset_expires'] = date('Y-m-d H:i:s', time() + config('Auth')->resetTime);
  127.  
  128.         return $this;
  129.     }
  130.  
  131.     /**
  132.      * Generates a secure random hash to use for account activation.
  133.      *
  134.      * @return $this
  135.      * @throws \Exception
  136.      */
  137.     public function generateActivateHash()
  138.     {
  139.         $this->attributes['activate_hash'] = bin2hex(random_bytes(16));
  140.  
  141.         return $this;
  142.     }
  143.  
  144.     /**
  145.      * Activate user.
  146.      *
  147.      * @return $this
  148.      */
  149.     public function activate()
  150.     {
  151.         $this->attributes['active'] = 1;
  152.         $this->attributes['activate_hash'] = null;
  153.  
  154.         return $this;
  155.     }
  156.  
  157.     /**
  158.      * Unactivate user.
  159.      *
  160.      * @return $this
  161.      */
  162.     public function deactivate()
  163.     {
  164.         $this->attributes['active'] = 0;
  165.  
  166.         return $this;
  167.     }
  168.  
  169.     /**
  170.      * Checks to see if a user is active.
  171.      *
  172.      * @return bool
  173.      */
  174.     public function isActivated(): bool
  175.     {
  176.         return isset($this->attributes['active']) && $this->attributes['active'] == true;
  177.     }
  178.  
  179.     /**
  180.      * Bans a user.
  181.      *
  182.      * @param string $reason
  183.      *
  184.      * @return $this
  185.      */
  186.     public function ban(string $reason)
  187.     {
  188.         $this->attributes['status'] = 'banned';
  189.         $this->attributes['status_message'] = $reason;
  190.  
  191.         return $this;
  192.     }
  193.  
  194.     /**
  195.      * Removes a ban from a user.
  196.      *
  197.      * @return $this
  198.      */
  199.     public function unBan()
  200.     {
  201.         $this->attributes['status'] = $this->status_message = '';
  202.  
  203.         return $this;
  204.     }
  205.  
  206.     /**
  207.      * Checks to see if a user has been banned.
  208.      *
  209.      * @return bool
  210.      */
  211.     public function isBanned(): bool
  212.     {
  213.         return isset($this->attributes['status']) && $this->attributes['status'] === 'banned';
  214.     }
  215.  
  216.     /**
  217.      * Determines whether the user has the appropriate permission,
  218.      * either directly, or through one of it's groups.
  219.      *
  220.      * @param string $permission
  221.      *
  222.      * @return bool
  223.      */
  224.     public function can(string $permission)
  225.     {
  226.         return in_array(strtolower($permission), $this->getPermissions());
  227.     }
  228.  
  229.     /**
  230.      * Returns the user's permissions, formatted for simple checking:
  231.      *
  232.      * [
  233.      *    id => name,
  234.      *    id=> name,
  235.      * ]
  236.      *
  237.      * @return array|mixed
  238.      */
  239.     public function getPermissions()
  240.     {
  241.         if (empty($this->id))
  242.         {
  243.             throw new \RuntimeException('Users must be created before getting permissions.');
  244.         }
  245.  
  246.         if (empty($this->permissions))
  247.         {
  248.             $this->permissions = model(PermissionModel::class)->getPermissionsForUser($this->id);
  249.         }
  250.  
  251.         return $this->permissions;
  252.     }
  253.  
  254.     /**
  255.      * Returns the user's roles, formatted for simple checking:
  256.      *
  257.      * [
  258.      *    id => name,
  259.      *    id => name,
  260.      * ]
  261.      *
  262.      * @return array|mixed
  263.      */
  264.     public function getRoles()
  265.     {
  266.         if (empty($this->id))
  267.         {
  268.             throw new \RuntimeException('Users must be created before getting roles.');
  269.         }
  270.  
  271.         if (empty($this->roles))
  272.         {
  273.             $groups = model(GroupModel::class)->getGroupsForUser($this->id);
  274.  
  275.             foreach ($groups as $group)
  276.             {
  277.                 $this->roles[$group['group_id']] = strtolower($group['name']);
  278.             }
  279.         }
  280.  
  281.         return $this->roles;
  282.     }
  283.  
  284.     /**
  285.      * Warns the developer it won't work, so they don't spend
  286.      * hours tracking stuff down.
  287.      *
  288.      * @param array $permissions
  289.      *
  290.      * @return $this
  291.      */
  292.     public function setPermissions(array $permissions = null)
  293.     {
  294.         throw new \RuntimeException('User entity does not support saving permissions directly.');
  295.     }
  296.  
  297.     public function setPhone(string $phone)
  298.     {
  299.         $this->attributes['phone'] = $phone;
  300.         return $this;
  301.     }
  302.    
  303. }
  304.  
Add Comment
Please, Sign In to add comment