csrf_lib::check_csrf_token()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
class csrf_lib extends Library {
4
5
    public function __construct() {
6
        if (session_status() == PHP_SESSION_NONE) {
7
            session_start();
8
        }
9
    }
10
    /**
11
     * Generates a new CSRF token
12
     * @return string Base64 encoded token
13
     */
14
    public static function generate_token() {
15
        return base64_encode(openssl_random_pseudo_bytes(12));
16
    }
17
18
    /**
19
     * Generates a new CSRF token and sets it as the current token
20
     * @return string The token
21
     */
22
    public function new_csrf_token() {
23
        if (! isset($_SESSION['csrf_token'])) {
24
            $_SESSION['csrf_token'] = self::generate_token();
25
        }
26
        return $_SESSION['csrf_token'];
27
    }
28
29
    /**
30
     * Resets the CSRF token saved in session
31
     */
32
    public function reset_csrf_token() {
33
        unset($_SESSION['csrf_token']);
34
    }
35
36
    /**
37
     * Checks whether CSRF is set and whether the current CSRF token from
38
     * the POST data is correct. If not, returns a 400 HTTP response code,
39
     * loads the 400 view and quits.
40
     */
41
    public function check_csrf_token($value) {
42
        if (! isset($_SESSION['csrf_token'])
43
            || $value !== $_SESSION['csrf_token']
44
        ) {
45
            // If no CSRF token is set, or the $value does not match it, error
46
            $this->load_library('http_lib', 'http');
47
            $this->http->response_code(400);
0 ignored issues
show
Bug Best Practice introduced by
The property http does not exist on csrf_lib. Did you maybe forget to declare it?
Loading history...
48
            return false;
49
        }
50
        return true;
51
    }
52
}
53