aboutsummaryrefslogtreecommitdiff
path: root/lib/session/CacheSessionHandler.php
blob: 6eea688e4b58304fa455ec5c94496bf0304ab2a0 (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
90
91
<?php
/**
 * Session handler for using Stud.IP Cache as session storage
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * @author      André Noack <noack@data-quest.de>
 */
namespace Studip\Session;

use SessionHandlerInterface;
use SessionIdInterface;
use SessionUpdateTimestampHandlerInterface;
use Studip\Cache\Cache;
use Studip\Cache\Factory;

class CacheSessionHandler implements
    SessionHandlerInterface,
    SessionIdInterface,
    SessionUpdateTimestampHandlerInterface
{

    private const CACHE_KEY_PREFIX = 'session_data';

    private int $session_lifetime = 7200;

    private Cache $cache;

    public function __construct(?int $session_lifetime = null)
    {
        if ($session_lifetime) {
            $this->session_lifetime = $session_lifetime;
        }
    }

    public function close(): bool
    {
        return true;
    }

    public function destroy(string $id): bool
    {
        $cache_key = self::CACHE_KEY_PREFIX . '/' . $id;
        $this->cache->expire($cache_key);
        return true;
    }

    public function gc(int $max_lifetime): int|false
    {
        return false;
    }

    public function open(string $path, string $name): bool
    {
        $this->cache = Factory::getCache();
        return true;
    }

    public function read(string $id): string|false
    {
        $cache_key = self::CACHE_KEY_PREFIX . '/' . $id;
        return $this->cache->read($cache_key);
    }

    public function write(string $id, string $data): bool
    {
        $cache_key = self::CACHE_KEY_PREFIX . '/' . $id;
        return $this->cache->write($cache_key, $data, $this->session_lifetime);
    }

    public function create_sid(): string
    {
        do {
            $new_id = md5(bin2hex(random_bytes(128)));
        } while ($this->read($new_id));
        return $new_id;
    }

    public function updateTimestamp(string $id, string $data): bool
    {
        return $this->write($id, $data);
    }

    public function validateId(string $id): bool
    {
        return (bool) $this->read($id);
    }
}