summaryrefslogtreecommitdiffstats
path: root/application/controllers/api/v1/user.php
blob: 38247d02c003cd6ba6c3fd53cf61b2ae3304a753 (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
<?php
/*
 * Copyright 2014 Florian "Bluewind" Pritz <bluewind@server-speed.net>
 *
 * Licensed under AGPLv3
 * (see COPYING for full license text)
 *
 */
namespace controllers\api\v1;

class user extends \controllers\api\api_controller {
	public function __construct()
	{
		parent::__construct();

		$this->load->model('muser');
	}

	public function apikeys()
	{
		$this->muser->require_access("full");
		return \service\user::apikeys($this->muser->get_userid());
	}

	public function create_apikey()
	{
		$username = $this->input->post("username");
		$password = $this->input->post("password");
		if ($username && $password) {
			if (!$this->muser->login($username, $password)) {
				throw new \exceptions\NotAuthenticatedException("user/login-failed", "Login failed");
			}
		}

		$this->muser->require_access("full");

		$userid = $this->muser->get_userid();
		$comment = $this->input->post("comment");
		$comment = $comment === false ? "" : $comment;
		$access_level = $this->input->post("access_level");

		$key = \service\user::create_apikey($userid, $comment, $access_level);

		return array(
			"new_key" => $key,
		);
	}

	public function delete_apikey()
	{
		$this->muser->require_access("full");

		$userid = $this->muser->get_userid();
		$key = $this->input->post("delete_key");

		$this->db->where('user', $userid)
			->where('key', $key)
			->delete('apikeys');

		$affected = $this->db->affected_rows();

		assert($affected >= 0 && $affected <= 1);
		if ($affected == 1) {
			return array(
				"deleted_keys" => array(
					$key => array (
						"key" => $key,
					),
				),
			);
		} else {
			throw new \exceptions\PublicApiException('user/delete_apikey/failed', 'Apikey deletion failed. Possibly wrong owner.');
		}
	}
}