summaryrefslogtreecommitdiff
path: root/app/Core/Security/Token.php
blob: 5efc6201387c7f1fbc60dd2be5b20b222d07dd8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

namespace Kanboard\Core\Security;

use Kanboard\Core\Base;

/**
 * Token Handler
 *
 * @package  security
 * @author   Frederic Guillot
 */
class Token extends Base
{
    /**
     * Generate a random token with different methods: openssl or /dev/urandom or fallback to uniqid()
     *
     * @static
     * @access public
     * @return string  Random token
     */
    public static function getToken()
    {
        return bin2hex(random_bytes(30));
    }

    /**
     * Generate and store a one-time CSRF token
     *
     * @access public
     * @return string  Random token
     */
    public function getCSRFToken()
    {
        return $this->createSessionToken('csrf');
    }

    /**
     * Generate and store a reusable CSRF token
     *
     * @access public
     * @return string
     */
    public function getReusableCSRFToken()
    {
        return $this->createSessionToken('pcsrf');
    }

    /**
     * Check if the token exists for the current session (a token can be used only one time)
     *
     * @access public
     * @param  string   $token   CSRF token
     * @return bool
     */
    public function validateCSRFToken($token)
    {
        $tokens = session_get('csrf');
        if (isset($tokens[$token])) {
            unset($tokens[$token]);
            session_set('csrf', $tokens);
            return true;
        }

        return false;
    }

    public function validateReusableCSRFToken($token)
    {
        $tokens = session_get('pcsrf');
        if (isset($tokens[$token])) {
            return true;
        }

        return false;
    }

    protected function createSessionToken($key)
    {
        if (! session_exists($key)) {
            session_set($key, []);
        }

        $nonce = self::getToken();
        session_merge($key, [$nonce => true]);

        return $nonce;
    }
}