haspermission php function pdo

Solutions on MaxInterview for haspermission php function pdo by the best coders in the world

showing results for - "haspermission php function pdo"
Emma
25 Oct 2019
1<?php
2class PrivilegedUser extends User
3{
4    private $roles;
5
6    public function __construct() {
7        parent::__construct();
8    }
9
10    // override User method
11    public static function getByUsername($username) {
12        $sql = "SELECT * FROM users WHERE username = :username";
13        $sth = $GLOBALS["DB"]->prepare($sql);
14        $sth->execute(array(":username" => $username));
15        $result = $sth->fetchAll();
16
17        if (!empty($result)) {
18            $privUser = new PrivilegedUser();
19            $privUser->user_id = $result[0]["user_id"];
20            $privUser->username = $username;
21            $privUser->password = $result[0]["password"];
22            $privUser->email_addr = $result[0]["email_addr"];
23            $privUser->initRoles();
24            return $privUser;
25        } else {
26            return false;
27        }
28    }
29
30    // populate roles with their associated permissions
31    protected function initRoles() {
32        $this->roles = array();
33        $sql = "SELECT t1.role_id, t2.role_name FROM user_role as t1
34                JOIN roles as t2 ON t1.role_id = t2.role_id
35                WHERE t1.user_id = :user_id";
36        $sth = $GLOBALS["DB"]->prepare($sql);
37        $sth->execute(array(":user_id" => $this->user_id));
38
39        while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
40            $this->roles[$row["role_name"]] = Role::getRolePerms($row["role_id"]);
41        }
42    }
43
44    // check if user has a specific privilege
45    public function hasPrivilege($perm) {
46        foreach ($this->roles as $role) {
47            if ($role->hasPerm($perm)) {
48                return true;
49            }
50        }
51        return false;
52    }
53}