Completed
Pull Request — master (#44)
by Hiraku
09:04
created

AspectAuth   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 51.28%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 17
c 2
b 0
f 0
lcom 0
cbo 5
dl 0
loc 55
ccs 20
cts 39
cp 0.5128
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A update() 0 11 3
B before() 0 21 7
B after() 0 18 7
1
<?php
2
/*
3
 * hirak/prestissimo
4
 * @author Hiraku NAKANO
5
 * @license MIT https://github.com/hirak/prestissimo
6
 */
7
namespace Hirak\Prestissimo\Aspects;
8
9
use SplObserver;
10
use SplSubject;
11
use Composer\Downloader;
12
13
/**
14
 * Authentication aspects.
15
 */
16
class AspectAuth implements SplObserver
17
{
18 5
    public function update(SplSubject $ev)
19
    {
20 5
        switch ((string)$ev) {
21 5
            case 'pre-download':
22 5
                $this->before($ev->refRequest());
23 5
                break;
24 5
            case 'post-download':
25 5
                $this->after($ev->refResponse());
26 5
                break;
27
        }
28 5
    }
29
30 5
    public function before(HttpGetRequest $req)
31
    {
32 5
        if (!$req->username || !$req->password) {
33 5
            $req->username = $req->password = null;
34 5
            return;
35 5
        }
36
37
        if ($req instanceof GitHubRequest && $req->password === 'x-oauth-basic') {
38
            $req->query['access_token'] = $req->username;
39
            // forbid basic-auth
40
            $req->username = $req->password = null;
41
            return;
42
        }
43
44
        if ($req instanceof GitLabRequest && $req->password === 'oauth2') {
45
            $req->headers[] = 'Authorization: Bearer ' . $req->username;
46
            // forbid basic-auth
47
            $req->username = $req->password = null;
48
            return;
49
        }
50
    }
51
52
    public function after(HttpGetResponse $res)
53
    {
54
        if (CURLE_OK !== $res->errno) {
55
            throw new Downloader\TransportException("$res->error:$res->errno");
56
        }
57
58
        switch ($res->info['http_code']) {
59
            case 200: //OK
60
                return;
61 5
            case 401: //Unauthorized
62
            case 403: //Forbidden
63 5
            case 404: //Not Found
64
                $res->setNeedAuth();
65
                break;
66
            case 407: //Proxy Authentication Required
67 5
                break;
68 5
        }
69 2
    }
70
}
71