summaryrefslogtreecommitdiff
path: root/src/web/_model/auth.php
blob: c975eb4a8a3895342616639ff440af39d06abc9a (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
<?php /* Copyright (c) 2024 Freya Murphy */
class Auth_model extends XSS_Model {

	private static ?array $session = NULL;

	/**
	 * Loads current session
	 * @param string $jwt - the user provided JWT
	 */
	public function session(): ?array {
		// check
		if (self::$session)
			return self::$session;
		// get jwt
		$jwt = $_SESSION['jwt'] ?? '';
		if (!$jwt)
			return NULL;
		// get session
		$result = $this->db()
			->select("_api.verify_jwt(?) AS user_id;")
			->row($jwt);
		// invalid JWT
		if (!$result)
			return NULL;
		// load user inside session
		$user_id = $result['user_id'];
		$user = $this->db()
			->select('*')
			->from('api.user')
			->where('id')
			->eq($user_id)
			->row();
		// valid JWT, but invalid user
		if (!$user)
			return NULL;
		// return session
		self::$session = array_merge(
			$user,
			array('jwt' => $jwt));
		return self::$session;
	}
}