Passed
Pull Request — master (#19)
by Samuel
02:44
created

MultiauthActions::multiauthActingAs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
3
namespace SMartins\PassportMultiauth\Testing;
4
5
use Laravel\Passport\Client;
6
use Illuminate\Support\Facades\App;
7
use Illuminate\Contracts\Auth\Authenticatable;
8
use Illuminate\Database\Eloquent\ModelNotFoundException;
9
10
trait MultiauthActions
11
{
12
    /**
13
     * The route to generate the access token. The default value is the standard
14
     * route from Laravel\Passport.
15
     *
16
     * @var string
17
     */
18
    protected $oauthTokenRoute = 'oauth/token';
19
20
    /**
21
     * @codeCoverageIgnore
22
     */
23
    public function setUp()
24
    {
25
        parent::setUp();
26
27
        $this->artisan('passport:install');
0 ignored issues
show
Bug introduced by
It seems like artisan() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
28
    }
29
30
    /**
31
     * Set the the Authorization header with an access token created using
32
     * Laravel Passport. The method `ẁithHeader` of trait `MakesHttpRequests` is
33
     * avaiable after version 5.5 of Laravel Framework.
34
     *
35
     * @todo Change way to issue token from $this->json() to creating accessing
36
     *       AccessTokenController@issueToken directly.
37
     * @todo Pass this method to PassportMultiauth::actingAs().
38
     *
39
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
40
     * @param  string $scope
41
     * @return $this
42
     */
43 10
    public function multiauthActingAs(Authenticatable $user, $scope = '')
44
    {
45 10
        if ((float) App::version() < 5.5) {
46 1
            throw new \RuntimeException('The method is only available to Laravel >= 5.5. To older versions try use $this->multiauthAccessToken() to get access token.');
47
        }
48
49 9
        $this->withHeader('Authorization', $this->multiauthAccessToken($user, $scope));
0 ignored issues
show
Bug introduced by
It seems like withHeader() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
50
51 8
        return $this;
52
    }
53
54
    /**
55
     * Get multiauth header to be used on request to get access token.
56
     *
57
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
58
     * @param  string $scope
59
     * @return string
60
     */
61 9
    public function multiauthAccessToken(Authenticatable $user, $scope = '')
62
    {
63
        // @todo Change to specific repository
64 9
        $client = Client::where('personal_access_client', false)
65 9
                        ->where('revoked', false)
66 9
                        ->first();
67
68 9
        if (! $client) {
69 1
            throw new ModelNotFoundException('Laravel\Passport password grant not found. Please run `passport:install` to generate client.');
70
        }
71
72 8
        $provider = $this->getUserProvider($user);
73
74
        $params = [
75 8
            'grant_type' => 'password',
76 8
            'client_id' => $client->id,
77 8
            'client_secret' => $client->secret,
78 8
            'username' => $user->email,
0 ignored issues
show
Bug introduced by
Accessing email on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
79 8
            'password' => 'secret',
80 8
            'scope' => $scope,
81
        ];
82
83
        // If model to be authenticated don't is the default provider
84 8
        if (! $this->isDefaultProvider($provider)) {
85 4
            $params = array_merge($params, ['provider' => $provider]);
86
        }
87
88 8
        $response = $this->json('POST', $this->oauthTokenRoute, $params);
0 ignored issues
show
Bug introduced by
It seems like json() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
89
90 8
        $accessToken = json_decode($response->getContent())->access_token;
91
92 8
        return 'Bearer '.$accessToken;
93
    }
94
95
    /**
96
     * Get the user provider on configs.
97
     *
98
     * @todo Move to class specialized in check auth configs.
99
     * @param  \Illuminate\Contracts\Auth\Authenticatable $user
100
     * @return string
101
     */
102 8
    protected function getUserProvider(Authenticatable $user)
103
    {
104 8
        $provider = '';
105 8
        foreach (config('auth.providers') as $p => $config) {
106 8
            if ($user instanceof $config['model']) {
107 8
                $provider = $p;
108
            }
109
        }
110
111 8
        return $provider;
112
    }
113
114
    /**
115
     * Check if provider is the default provider used by Laravel\Passport.
116
     *
117
     * @todo Move to class specialized in check auth configs.
118
     * @param string $provider
119
     * @return bool
120
     */
121 8
    protected function isDefaultProvider($provider)
122
    {
123 8
        return config('auth.guards.api.provider') === $provider;
124
    }
125
}
126