SessionController::delete()   A
last analyzed

Complexity

Conditions 5
Paths 9

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.2728
c 0
b 0
f 0
cc 5
nc 9
nop 1
1
<?php
2
3
namespace Ntb\RestAPI;
4
5
/**
6
 * ApiSession controller is the controller for the session resource.
7
 * @author Christian Blank <[email protected]>
8
 */
9
class SessionController extends BaseRestController {
10
11
    private static $allowed_actions = array (
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
12
        'post' => true,
13
        'delete' => '->isAuthenticated'
14
    );
15
16
	/**
17
	 * @param \SS_HTTPRequest $request
18
	 * @return array
19
	 * @throws RestSystemException
20
	 * @throws RestUserException
21
	 */
22
    public function post($request) {
23
        $data = json_decode($request->getBody(), true);
24
        if (!$data) {
25
            throw new RestUserException("No data for session provided.", 401, 401);
26
        }
27
        try{
28
            $validated = \Injector::inst()->get('SessionValidator')->validate($data);
29
            $user = \Injector::inst()->get('ApiMemberAuthenticator')->authenticate($validated);
30
            $session = $user ? AuthFactory::createAuth()->createSession($user) : null;
31
            if (!$session) {
32
                throw new RestUserException("Login incorrect", 401, 401);
33
            }
34
        } catch(\ValidationException $e) {
35
	        throw new RestUserException($e->getMessage(), 422, 422);
36
        } catch(RestUserException $e) {
37
	        throw $e;
38
        } catch(\Exception $e) {
39
            throw new RestSystemException($e->getMessage(), $e->getCode() ?: 500);
40
        }
41
        $meta = ['timestamp' => time()];
42
        $result = [
43
            'session' => SessionFormatter::format($session)
44
        ];
45
        $result['meta'] = $meta;
46
        return $result;
47
    }
48
49
    /**
50
     * @param \SS_HTTPRequest $request
51
     * @return array
52
     * @throws RestUserException
53
     */
54
    public function delete($request) {
55
        // check param for id
56
        $data = [];
57
        try {
58
            if($id = $request->param('ID')) {
59
                if($id != 'me') {
60
                    throw new RestUserException("No session found", 404);
61
                }
62
                AuthFactory::createAuth()->delete($request);
63
            } else {
64
                throw new RestUserException("No id specified for deletion", 404);
65
            }
66
        } catch(RestUserException $e) {
67
            throw $e;
68
        } catch(\Exception $e) {
69
            throw new RestUserException("ApiSession was not found", 404);
70
        }
71
        $meta = ['timestamp' => time()];
72
        $data['meta'] = $meta;
73
        return $data;
74
    }
75
}
76