summaryrefslogtreecommitdiff
path: root/src/web/helpers/auth.php
blob: 4d7f184885cb6f0270804b553f4086e5b719645d (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
<?php /* Copyright (c) 2024 Freya Murphy */

class AuthHelper {

	private $session_lifetime_seconds;

	function __construct() {
		$this->session_lifetime_seconds = 60 * 60 * 24 * 3;
	}

	/**
	 * Generate a random token
	 * @param int $length
	 */
	private function gen_token(int $length): string {
	    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	    $random = '';

	    for ($i = 0; $i < $length; $i++) {
	        $index = rand(0, strlen($characters) - 1);
	        $random .= $characters[$index];
	    }

	    return $random;
	}

	/**
	 * Saves a user into the session specified by their auth key
	 * @param Session $session - the session user data
	 */
	public function save_session(Session $session): void {
		$path = "/tmp/{$session->token}";
		$data = json_encode($session->to_array());
		file_put_contents($path, $data, LOCK_EX);
	}

	public function delete_session(Session $session): int {
		$path = "/tmp/{$session->token}";
		return unlink($path) ? 0 : 1;
	}

	/**
	 * Loads the auth session associated with a specific key
	 * @param string $token - the session $key
	 */
	private function load_session(string $token): ?Session {
		try {
			$path = "/tmp/$token";
			if (!file_exists($path)) {
				return NULL;
			}
			$content = file_get_contents($path);
			$json = json_decode($content, TRUE);
			$session = new Session();
			if ($session->from_array($json))
				return NULL;
			return $session;
		} catch (Exception $e) {
			return NULL;
		}
	}

	/**
	 * Creates a new session for a user
	 */
	public function create_session(User $user): Session {
		$session = new Session();
		$session->token = $this->gen_token(128);
		$session->created = time();
		$session->user = $user;
		$session->reset_expiry();
		$this->save_session($session);
		return $session;
	}

	/**
	 * Gets the current authed session
	 */
	public function get_session(): ?Session {
		$cookie_name = getenv("COOKIE_NAME");
		if(!isset($_COOKIE[$cookie_name])) {
			return NULL;
		}
		$token = $_COOKIE[$cookie_name];
		return $this->load_session($token);
	}

}