Completed
Pull Request — master (#37)
by Boris
03:48 queued 01:31
created

AspectAuth::before()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 28.6715

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
ccs 5
cts 21
cp 0.2381
rs 6.7272
cc 7
eloc 20
nc 6
nop 1
crap 28.6715
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
            case 'pre-download':
22 5
                $this->before($ev->refRequest());
23 5
                break;
24
            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 = null;
34 5
            $req->password = null;
35 5
            return;
36
        }
37
38
        switch ($req->special) {
39
            case 'github':
40
                if ($req->password === 'x-oauth-basic') {
41
                    $req->query['access_token'] = $req->username;
42
                    // forbid basic-auth
43
                    $req->username = null;
44
                    $req->password = null;
45
                    return;
46
                }
47
                break;
48
            case 'gitlab':
49
                if ($req->password === 'oauth2') {
50
                    $req->headers[] = 'Authorization: Bearer ' . $req->username;
51
                    // forbid basic-auth
52
                    $req->username = null;
53
                    $req->password = null;
54
                    return;
55
                }
56
                break;
57
        }
58
    }
59
60
    // どうしようもない失敗なのか、リトライする余地があるのかを判別する
61 5
    public function after(HttpGetResponse $res)
62
    {
63 5
        if (CURLE_OK !== $res->errno) {
64
            throw new Downloader\TransportException("$res->error:$res->errno");
65
        }
66
67 5
        switch ($res->info['http_code']) {
68
            case 200: //OK
69 2
                return;
70
            case 401: //Unauthorized
71
            case 403: //Forbidden
72
            case 404: //Not Found
73 3
                $res->setNeedAuth();
74 3
                break;
75
            case 407: //Proxy Authentication Required
76
                break;
77
        }
78 3
    }
79
}
80