Key.php 8.25 KB
Newer Older
1
<?php
Davide Aprea's avatar
Davide Aprea committed
2
3
4

namespace App\Models;

5
6
use Illuminate\Support\Facades\Redis;
use Request;
7
use \Carbon\Carbon;
8

9
10
class Key
{
Davide Aprea's avatar
Davide Aprea committed
11
    public $key;
12
    public $status; # Null If Key invalid | false if valid but has no adFreeSearches | true if valid and has adFreeSearches
13
    private $keyserver = "https://key.metager.de/";
14
    private $keyinfo;
Davide Aprea's avatar
Davide Aprea committed
15

16
17
    public function __construct($key, $status = null)
    {
Davide Aprea's avatar
Davide Aprea committed
18
        $this->key = $key;
Davide Aprea's avatar
Davide Aprea committed
19
        $this->status = $status;
20
        if (getenv("APP_ENV") !== "production") {
Dominik Hebeler's avatar
Dominik Hebeler committed
21
            $this->keyserver = "https://dev.key.metager.de/";
22
        }
Davide Aprea's avatar
Davide Aprea committed
23
24
    }

Davide Aprea's avatar
Davide Aprea committed
25
    # always returns true or false
26
27
28
    public function getStatus()
    {
        if ($this->key !== '' && $this->status === null) {
Davide Aprea's avatar
Davide Aprea committed
29
            $this->updateStatus();
30
            if($this->status === null){
31
32
                // The user provided an invalid key which we will log to fail2ban
                $fail2banEnabled = config("metager.metager.fail2ban_enabled");
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
                if (!empty($fail2banEnabled) && $fail2banEnabled && !empty(env("fail2banurl", false)) && !empty(env("fail2banuser")) && !empty(env("fail2banpassword"))) {
                    // Submit fetch job to worker
                    $mission = [
                            "resulthash" => "captcha",
                            "url" => env("fail2banurl") . "/mgkeytry/",
                            "useragent" => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0",
                            "username" => env("fail2banuser"),
                            "password" => env("fail2banpassword"),
                            "headers" => [
                                "ip" => Request::ip()
                            ],
                            "cacheDuration" => 0,
                            "name" => "Captcha",
                        ];
                    $mission = json_encode($mission);
                    Redis::rpush(\App\MetaGer::FETCHQUEUE_KEY, $mission);
49
50
                }
            }
Davide Aprea's avatar
Davide Aprea committed
51
        }
52
        return $this->status;
Davide Aprea's avatar
Davide Aprea committed
53
54
    }

55
56
    public function updateStatus()
    {
57
        $authKey = base64_encode(env("KEY_USER", "test") . ':' . env("KEY_PASSWORD", "test"));
Davide Aprea's avatar
Davide Aprea committed
58
59
60
61
62
63
64
65
66

        $opts = array(
            'http' => array(
                'method' => 'GET',
                'header' => 'Authorization: Basic ' . $authKey ,
            ),
        );
        $context = stream_context_create($opts);

Davide Aprea's avatar
Davide Aprea committed
67
        try {
Davide Aprea's avatar
Davide Aprea committed
68
69
            $link = $this->keyserver . "v2/key/". urlencode($this->key);
            $result = json_decode(file_get_contents($link, false, $context));
70
71
72
73
74
75
76
            if(!empty($result)){
                $this->keyinfo = $result;
                if($this->keyinfo->adFreeSearches > 0 || $this->keyinfo->apiAccess === "unlimited"){
                    $this->status = true;
                }else{
                    $this->status = false;
                }
Davide Aprea's avatar
Davide Aprea committed
77
                return true;
78
            }else{
Davide Aprea's avatar
Davide Aprea committed
79
80
81
82
83
84
85
                return false;
            }
        } catch (\ErrorException $e) {
            return false;
        }
    }

86
87
    public function requestPermission()
    {
88
        $authKey = base64_encode(env("KEY_USER", "test") . ':' . env("KEY_PASSWORD", "test"));
Davide Aprea's avatar
Davide Aprea committed
89
90
91
        $postdata = http_build_query(array(
            'dummy' => 0,
        ));
Davide Aprea's avatar
Davide Aprea committed
92
93
94
        $opts = array(
            'http' => array(
                'method' => 'POST',
95
96
97
98
                'header' => [
                    'Content-type: application/x-www-form-urlencoded',
                    'Authorization: Basic ' . $authKey
                ],
Davide Aprea's avatar
Davide Aprea committed
99
100
101
102
103
104
105
                'content' => $postdata,
            ),
        );

        $context = stream_context_create($opts);

        try {
Davide Aprea's avatar
Davide Aprea committed
106
            $link = $this->keyserver . "v2/key/". urlencode($this->key) . "/request-permission";
Davide Aprea's avatar
Davide Aprea committed
107
            $result = json_decode(file_get_contents($link, false, $context));
Davide Aprea's avatar
Davide Aprea committed
108
            if ($result->{'apiAccess'} == true) {
Davide Aprea's avatar
Davide Aprea committed
109
110
                return true;
            } else {
111
                $this->status = false;
Davide Aprea's avatar
Davide Aprea committed
112
113
114
115
116
117
                return false;
            }
        } catch (\ErrorException $e) {
            return false;
        }
    }
118
    public function generateKey($payment = null, $adFreeSearches = null, $key = null, $notes = "")
119
120
    {
        $authKey = base64_encode(env("KEY_USER", "test") . ':' . env("KEY_PASSWORD", "test"));
121
        $postdata = array(
122
            'apiAccess' => 'normal',
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
            'expiresAfterDays' => 365,
            'notes' => $notes
        );
        if(!empty($key)){
            $postdata["key"] = $key;
        }
    
        if(!empty($payment)){
            $postdata["payment"] = $payment;
        }else if(!empty($adFreeSearches)){
            $postdata["adFreeSearches"] = $adFreeSearches;
        }else{
            return false;
        }
        $postdata = http_build_query($postdata, "", "&", PHP_QUERY_RFC3986);
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => [
                    'Content-type: application/x-www-form-urlencoded',
                    'Authorization: Basic ' . $authKey
                ],
                'content' => $postdata,
                'timeout' => 5
            ),
        );

        $context = stream_context_create($opts);

        try {
            $link = $this->keyserver . "v2/key/";
            $result = json_decode(file_get_contents($link, false, $context));
            return $result->{'mgKey'};
        } catch (\ErrorException $e) {
            return false;
        }
    }
160

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    public function reduce($count){
        $authKey = base64_encode(env("KEY_USER", "test") . ':' . env("KEY_PASSWORD", "test"));
        $postdata = http_build_query(array(
            'adFreeSearches' => $count,
        ));
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => [
                    'Content-type: application/x-www-form-urlencoded',
                    'Authorization: Basic ' . $authKey
                ],
                'content' => $postdata,
                'timeout' => 5
            ),
        );

        $context = stream_context_create($opts);

        try {
            $link = $this->keyserver . "v2/key/" . $this->key . "/reduce-searches";
            $result = json_decode(file_get_contents($link, false, $context));
            return $result;
        } catch (\ErrorException $e) {
            return false;
        }
    }

189
190
191
192
193
194
195
196
    /**
     * Tells if this key is liable to change to a custom key
     * Currently only members are allowed to do so and only every 2 days
     * Also only the original member key is allowed to be changed
     * 
     * @return boolean
     */
    public function canChange(){
197
        if(empty($this->status) || !preg_match("/^Mitgliederschlüssel\./", $this->keyinfo->notes) || $this->keyinfo->adFreeSearches < \App\Http\Controllers\KeyController::KEYCHANGE_ADFREE_SEARCHES){
198
199
200
201
202
203
204
205
206
207
208
209
210
            return false;
        }
        if(!empty($this->keyinfo->KeyChangedAt)){
            // "2021-03-09T09:19:44.000Z"
            $keyChangedAt = Carbon::createFromTimeString($this->keyinfo->KeyChangedAt, 'Europe/London');
            if($keyChangedAt->diffInSeconds(Carbon::now()) > (2 * 24 * 60 * 60)){
                return true;
            }else{
                return false;
            }
        }
        return true;
    }
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

    public function checkForChange($newkey = "", $hash){
        $authKey = base64_encode(env("KEY_USER", "test") . ':' . env("KEY_PASSWORD", "test"));
        $postdata = http_build_query(array(
            'hash' => $hash,
            'key' => $newkey,
        ));
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => [
                    'Content-type: application/x-www-form-urlencoded',
                    'Authorization: Basic ' . $authKey
                ],
                'content' => $postdata,
                'timeout' => 5
            ),
        );

        $context = stream_context_create($opts);

        try {
            $link = $this->keyserver . "v2/key/can-change";
            $result = json_decode(file_get_contents($link, false, $context));

            if(!empty($result) && $result->status === "success" && empty($result->results)){
                return true;
            }else{
                return false;
            }
        } catch (\ErrorException $e) {
            return false;
        }
    }
245
}