Passed
Pull Request — develop (#52)
by Peter
05:08
created

Tiqr_Message_FCM::getGoogleAccessToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 7
ccs 0
cts 7
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of the tiqr project.
4
 *
5
 * The tiqr project aims to provide an open implementation for
6
 * authentication using mobile devices. It was initiated by
7
 * SURFnet and developed by Egeniq.
8
 *
9
 * More information: http://www.tiqr.org
10
 *
11
 * @author Joost van Dijk <[email protected]>
12
 *
13
 * @package tiqr
14
 *
15
 * @license New BSD License - See LICENSE file for details.
16
 *
17
 * @copyright (C) 2010-2024 SURF BV
18
 */
19
20
/**
21
 * Android Cloud To Device Messaging message.
22
 * @author peter
23
 */
24
class Tiqr_Message_FCM extends Tiqr_Message_Abstract
25
{
26
    /**
27
     * Send message.
28
     *
29
     * @throws Tiqr_Message_Exception_AuthFailure
30
     * @throws Tiqr_Message_Exception_SendFailure
31
     * @throws \Google\Exception
32
     */
33
    public function send()
34
    {
35
        $options = $this->getOptions();
36
        $projectId = $options['firebase.projectId'];
37
        $credentialsFile = $options['firebase.credentialsFile'];
38
39
        $translatedAddress = $this->getAddress();
40
        $alertText = $this->getText();
41
        $url = $this->getCustomProperty('challenge');
42
43
        $this->_sendFirebase($translatedAddress, $alertText, $url, $projectId, $credentialsFile);
44
    }
45
46
    /**
47
     * @throws \Google\Exception
48
     */
49
    private function getGoogleAccessToken($credentialsFile){
50
        $client = new \Google_Client();
51
        $client->setAuthConfig($credentialsFile);
52
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
53
        $client->fetchAccessTokenWithAssertion();
54
        $token = $client->getAccessToken();
55
        return $token['access_token'];
56
    }
57
58
    /**
59
     * Send a message to a device using the firebase API key.
60
     *
61
     * @param $deviceToken string device ID
62
     * @param $alert string alert message
63
     * @param $challenge string tiqr challenge url
64
     * @param $projectId string the id of the firebase project
65
     * @param $credentialsFile string The location of the firebase secret json
66
     * @param $retry boolean is this a 2nd attempt
67
     * @throws Tiqr_Message_Exception_SendFailure
68
     * @throws \Google\Exception
69
     */
70
    private function _sendFirebase(string $deviceToken, string $alert, string $challenge, string $projectId, string $credentialsFile, bool $retry=false)
71
    {
72
        $apiurl = 'https://fcm.googleapis.com/v1/projects/'.$projectId.'/messages:send';
73
74
        $fields = [
75
            'message' => [
76
                'token' => $deviceToken,
77
                'data' => [
78
                    'challenge' => $challenge,
79
                    'text'      => $alert,
80
                ],
81
                "android" => [
82
                    "ttl" => "300s",
83
                ],
84
            ],
85
        ];
86
87
        $headers = array(
88
            'Authorization: Bearer ' . $this->getGoogleAccessToken($credentialsFile),
89
            'Content-Type: application/json',
90
        );
91
92
        $ch = curl_init();
93
        curl_setopt($ch, CURLOPT_URL, $apiurl);
94
        curl_setopt($ch, CURLOPT_POST, true);
95
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
96
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
97
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
98
        $result = curl_exec($ch);
99
        $errors = curl_error($ch);
100
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
101
        $remoteip = curl_getinfo($ch,CURLINFO_PRIMARY_IP);
102
        curl_close($ch);
103
104
        if ($result === false) {
105
            throw new Tiqr_Message_Exception_SendFailure("Server unavailable", true);
106
        }
107
108
        if (!empty($errors)) {
109
            throw new Tiqr_Message_Exception_SendFailure("Http error occurred: ". $errors, true);
110
        }
111
112
        // Wait and retry once in case of a 502 Bad Gateway error
113
        if ($statusCode === 502 && !($retry)) {
114
          sleep(2);
115
          $this->_sendFirebase($deviceToken, $alert, $challenge, $projectId, $credentialsFile, true);
116
          return;
117
        }
118
119
        if ($statusCode !== 200) {
120
            throw new Tiqr_Message_Exception_SendFailure(sprintf('Invalid status code : %s. Server : %s. Response : "%s".', $statusCode, $remoteip, $result), true);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
            throw new Tiqr_Message_Exception_SendFailure(sprintf('Invalid status code : %s. Server : %s. Response : "%s".', $statusCode, $remoteip, /** @scrutinizer ignore-type */ $result), true);
Loading history...
121
        }
122
123
        // handle errors, ignoring registration_id's
124
        $response = json_decode($result, true);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

124
        $response = json_decode(/** @scrutinizer ignore-type */ $result, true);
Loading history...
125
        foreach ($response as $k => $v) {
126
            if ($k=="error") {
127
                throw new Tiqr_Message_Exception_SendFailure(sprintf("Error in FCM response: %s", $result), true);
128
            }
129
        }
130
    }
131
}
132