Completed
Push — develop ( ed6c74...ceecfe )
by Patrick
04:06
created

GoogleAuthenticator::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
1
<?php
2
namespace Flipside\Auth;
3
require dirname(__FILE__).'/../vendor/autoload.php';
4
5
class GoogleAuthenticator extends Authenticator
6
{
7
    protected $client;
8
    protected $token = null;
9
10
    public function __construct($params)
11
    {
12
        parent::__construct($params);
13
        if(!isset($params['client_secrets_path']))
14
        {
15
            throw new \Exception('Missing required parameter client_secrets_path!');
16
        }
17
        if(!isset($params['redirect_url']))
18
        {
19
            $params['redirect_url'] = 'https://'.$_SERVER['HTTP_HOST'].'/oauth2callback.php?src=google';
20
        }
21
        $this->token = \Flipside\FlipSession::getVar('GoogleToken', null);
22
        $this->client = new \Google_Client();
23
        $this->client->setAuthConfigFile($params['client_secrets_path']);
0 ignored issues
show
Deprecated Code introduced by
The method Google_Client::setAuthConfigFile() has been deprecated.

This method has been deprecated.

Loading history...
24
        $this->client->addScope(array(\Google_Service_Oauth2::USERINFO_PROFILE, \Google_Service_Oauth2::USERINFO_EMAIL));
25
        $this->client->setRedirectUri($params['redirect_url']);
26
    }
27
28
    /**
29
     * Get the link to login using this method
30
     *
31
     * @return string The link to login using this method
32
     */
33
    public function getSupplementLink()
34
    {
35
        $authUrl = $this->client->createAuthUrl();
36
        return '<a href="'.filter_var($authUrl, FILTER_SANITIZE_URL).'"><img src="/img/common/google_sign_in.png" style="width: 2em;"/></a>';
37
    }
38
39
    public function authenticate($code, &$currentUser = false)
40
    {
41
        $googleUser = false;
42
        try
43
        {
44
            $this->client->authenticate($code);
0 ignored issues
show
Deprecated Code introduced by
The method Google_Client::authenticate() has been deprecated.

This method has been deprecated.

Loading history...
45
            $this->token = $this->client->getAccessToken();
46
            \FlipSession::setVar('GoogleToken', $this->token);
47
            $oauth2Service = new \Google_Service_Oauth2($this->client);
48
            $googleUser = $oauth2Service->userinfo->get();
49
        }
50
        catch(\Exception $ex)
51
        {
52
            return self::LOGIN_FAILED;
53
        }
54
55
        $auth = \AuthProvider::getInstance();
56
        $localUsers = $auth->getUsersByFilter(new \Data\Filter('mail eq '.$googleUser->email));
57
        if($localUsers !== false && isset($localUsers[0]))
58
        {
59
            if($localUsers[0]->canLoginWith('google.com'))
60
            {
61
                $auth->impersonateUser($localUsers[0]);
62
                return self::SUCCESS;
63
            }
64
            $currentUser = $localUsers[0];
65
            return self::ALREADY_PRESENT;
66
        }
67
        else
68
        {
69
            $user = new PendingUser();
70
            $user->mail = $googleUser->email;
71
            $user->givenName = $googleUser->givenName;
72
            $user->sn = $googleUser->familyName;
73
            $user->addLoginProvider('google.com');
74
            $ret = $auth->activatePendingUser($user);
75
            if($ret === false)
76
            {
77
                throw new \Exception('Unable to create user! '.$res);
78
            }
79
            return self::SUCCESS;
80
        }
81
    }
82
83
    public function getUser($data = false)
84
    {
85
        if($data === false)
86
        {
87
            $data = $this->token;
88
        }
89
        try
90
        {
91
            $this->client->setAccessToken($data);
92
            $oauth2Service = new \Google_Service_Oauth2($this->client);
93
            $googleUser = $oauth2Service->userinfo->get();
94
            $profileUser = new \Auth\PendingUser();
95
            $profileUser->addLoginProvider('google.com');
96
            $profileUser->mail = $googleUser->email;
97
            $profileUser->sn = $googleUser->familyName;
98
            $profileUser->givenName = $googleUser->givenName;
99
            $profileUser->displayName = $googleUser->name;
100
            $profileUser->jpegPhoto = base64_encode(file_get_contents($googleUser->picture));
101
            return $profileUser;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $profileUser; (Auth\PendingUser) is incompatible with the return type of the parent method Flipside\Auth\Authenticator::getUser of type null|Auth\User.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
102
        }
103
        catch(\Exception $e)
104
        {
105
            return null;
106
        }
107
    }
108
}
109
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
110