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
<?php
include_once __ROOT_DIR . '/libs/php-jwt/src/BeforeValidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/ExpiredException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/SignatureInvalidException.php';
include_once __ROOT_DIR . '/libs/php-jwt/src/JWT.php';
use \Firebase\JWT\JWT;
class UserController extends Controller
{
public function __construct($name, $request)
{
parent::__construct($name, $request);
}
// ==============
// Actions
// ==============
public function processRequest()
{
switch ($this->request->getHttpMethod()) {
case 'GET':
if ($this->request->getUriParams()) {
return $this->getUser($this->request->getUriParams()[0]);
}
return $this->getAllUsers();
break;
case 'PUT':
if ($this->request->getUriParams()) {
return $this->updateUser(array_merge($this->request->getData(), ['id'=>$this->request->getUriParams()[0]]));
}
break;
}
return Response::errorResponse("unsupported parameters or method in users");
}
protected function getAllUsers()
{
$users = User::getList();
$response = Response::okResponse(json_encode($users));
//var_dump($json);die;
// TODO
return $response;
}
protected function getUser($id)
{
$user = User::getRow($id);
$response = Response::okResponse(json_encode($user));
return $response;
}
protected function updateUser($array)
{
try {
//var_dump($array);die;
$jwt_token = $this->request->getJwtToken();
// echo "jwt = $jwt_token";
$decodedJWT = JWT::decode($jwt_token, JWT_BACKEND_KEY, array('HS256'));
if ($decodedJWT->data->id != $array['id']) {
throw new Exception("You don't have access to this account.", 1);
}
User::updateUser($array);
} catch (Exception $e) {
header('WWW-Authenticate: Bearer realm="'.JWT_ISSUER.'"');
$jsonResult = json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
));
return Response::unauthorizedResponse($jsonResult);
}
$response = Response::okResponse('User succesfully updated !');
return $response;
}
}