Completed
Pull Request — master (#44)
by Hiraku
08:54 queued 06:28
created

AspectAuth::before()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 21.5206

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 21
ccs 5
cts 15
cp 0.3333
rs 7.551
cc 7
eloc 12
nc 4
nop 1
crap 21.5206
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
        $name = (string)$ev;
21 5
        if ('pre-download' === $name) {
22 5
            return $this->before($ev->refRequest());
23 5
        }
24 5
        if ('post-download' === $name) {
25 5
            $this->after($ev->refResponse());
26 5
        }
27
    }
28 5
29
    private function before(HttpGetRequest $req)
30 5
    {
31
        if (!$req->username || !$req->password) {
32 5
            $req->username = $req->password = null;
33 5
            return;
34 5
        }
35 5
36
        if ($req instanceof GitHubRequest && $req->password === 'x-oauth-basic') {
37
            $req->query['access_token'] = $req->username;
38
            // forbid basic-auth
39
            $req->username = $req->password = null;
40
            return;
41
        }
42
43
        if ($req instanceof GitLabRequest && $req->password === 'oauth2') {
44
            $req->headers[] = 'Authorization: Bearer ' . $req->username;
45
            // forbid basic-auth
46
            $req->username = $req->password = null;
47
            return;
48
        }
49
    }
50
51
    private function after(HttpGetResponse $res)
52
    {
53
        if (CURLE_OK !== $res->errno) {
54
            throw new Downloader\TransportException("$res->error:$res->errno");
55
        }
56
57
        switch ($res->info['http_code']) {
58
            case 200: //OK
59
                return;
60
            case 401: //Unauthorized
61 5
            case 403: //Forbidden
62
            case 404: //Not Found
63 5
                $res->setNeedAuth();
64
                break;
65
            case 407: //Proxy Authentication Required
66
                break;
67 5
        }
68 5
    }
69
}
70