Auth::isAdminLoggedIn()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Jidaikobo\Kontiki\Core;
4
5
use Aura\Session\Session;
6
use Jidaikobo\Kontiki\Core\Database;
7
use Jidaikobo\Kontiki\Models\UserModel;
8
9
class Auth
10
{
11
    private UserModel $userModel;
12
    private Session $session;
13
    private string $segment = 'jidaikobo\kontiki\auth';
14
15
    public function __construct(Session $session, UserModel $userModel)
16
    {
17
        $this->session = $session;
18
        $this->userModel = $userModel;
19
    }
20
21
    /**
22
     * Handles user login.
23
     *
24
     * @param string $username Username or email address.
25
     * @param string $password Password.
26
     * @return bool Returns true if login is successful, false otherwise.
27
     */
28
    public function login(string $username, string $password): bool
29
    {
30
        $user = $this->userModel->getByField('username', $username);
31
        $stored_password = $user['password'] ?? null ;
32
33
        if ($stored_password !== null && password_verify($password, $stored_password)) {
34
            // Login Success
35
            $segment = $this->session->getSegment($this->segment);
36
            $segment->set('user', $user);
37
            return true;
38
        }
39
40
        return false;
41
    }
42
43
    /**
44
     * Handles user logout.
45
     *
46
     * @return void
47
     */
48
    public function logout(): void
49
    {
50
        $this->session->destroy();
51
    }
52
53
    /**
54
     * Retrieves the current user's information.
55
     *
56
     * @return array|null Returns the logged-in user's information, or null if not logged in.
57
     */
58
    public function getCurrentUser(): ?array
59
    {
60
        $segment = $this->session->getSegment($this->segment);
61
        return $segment->get('user');
62
    }
63
64
    /**
65
     * Checks if a user is logged in.
66
     *
67
     * @return bool Returns true if a user is logged in, false otherwise.
68
     */
69
    public function isLoggedIn(): bool
70
    {
71
        return $this->getCurrentUser() !== null;
72
    }
73
74
    /**
75
     * Checks if a user is logged in.
76
     *
77
     * @return bool Returns true if a user is logged in, false otherwise.
78
     */
79
    public function isAdminLoggedIn(): bool
80
    {
81
        return $this->getCurrentUser() !== null &&
82
            $this->getCurrentUser()["role"] === 'admin';
83
    }
84
}
85