Welcome to mirror list, hosted at ThFree Co, Russian Federation.

signup.php « lib - github.com/nextcloud/nextcloud.com.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6171470ae91b236ffd677bb9979f103f63e405c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
<?php

use GeoIp2\Database\Reader;

require_once realpath(dirname(__FILE__)) . '/../vendor/autoload.php';
require_once realpath(dirname(__FILE__)) . '/newsletter-api.php';
require_once realpath(dirname(__FILE__)) . '/../config.php';

const USER_AGENT_CLIENT_ANDROID = '/^Mozilla\/5\.0 \(Android\) (ownCloud|Nextcloud)\-android.*$/';
const USER_AGENT_TALK_ANDROID = '/^Mozilla\/5\.0 \(Android\) Nextcloud\-Talk v.*$/';
const USER_AGENT_CLIENT_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
const USER_AGENT_CLIENT_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
const USER_AGENT_TALK_IOS = '/^Mozilla\/5\.0 \(iOS\) Nextcloud\-Talk v.*$/';

add_action('rest_api_init', 'registration_register_routes');

$redis = new Predis\Client(REDIS);
$readerCity = new Reader(realpath(dirname(__FILE__)) . '/../assets/GeoLite2/GeoLite2-City.mmdb');
$readerCountry = new Reader(realpath(dirname(__FILE__)) . '/../assets/GeoLite2/GeoLite2-Country.mmdb');

// Get proper ip in case of reverse proxy
function whatismyip() {
	return $_SERVER['REMOTE_ADDR'];
}

function get_device() {
	$userAgents = [
		'Android' => USER_AGENT_CLIENT_ANDROID,
		'Android Talk' => USER_AGENT_TALK_ANDROID,
		'Desktop' => USER_AGENT_CLIENT_DESKTOP,
		'iOS' => USER_AGENT_CLIENT_IOS,
		'iOS Talk' => USER_AGENT_TALK_IOS
	];

	if (isset($_SERVER['HTTP_USER_AGENT'])) {
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
		foreach ($userAgents as $name => $regex) {
			if (preg_match($regex, $userAgent)) {
				return $name;
			}
		}
		return 'Website';
	}
	return 'unknown';
}

function registration_register_routes() {
	// signup post method
	register_rest_route('signup', '/account', array(
		'methods'  => WP_REST_Server::CREATABLE,
		'callback' => 'request_account',
		'args'     => array(
			'id'    => array(
				'validate_callback' => function ($param) {
					return is_numeric($param);
				}
			),
			'email' => array(
				'validate_callback' => function ($param) {
					return filter_var($param, FILTER_VALIDATE_EMAIL);
				}
			)
		)
	));

	// providers json
	register_rest_route('signup', '/providers', array(
		'methods'  => WP_REST_Server::READABLE,
		'callback' => 'get_providers_list'
	));

	// get statistics
	register_rest_route('signup', '/stats', array(
		'methods'  => WP_REST_Server::READABLE,
		'callback' => 'get_statistics',
		'args'     => array(
			'key'  => array(
				'required'          => true,
				'validate_callback' => function ($key) {
					return strlen($key) === 32;
				}
			),
			'time' => array(
				'validate_callback' => function ($time) {
					return is_numeric($time);
				}
			)
		)
	));
}

function request_account($request) {

	// redis rate limit
	global $redis;
	global $readerCountry;

	$limit = [
		'interval'     => 300, // seconds
		'num_requests' => 10, // number of requests allowed per interval
		'user_ip'      => whatismyip() // getting the user IP.
	];

	$rateId    = "requests_count_{$limit['user_ip']}";
	$rateLimit = (int) $redis->get($rateId);
	if ($rateLimit + 1 > $limit['num_requests']) {
		$remainingTTL = $redis->ttl($rateId);
		if ($remainingTTL < 1) {
			$remainingTTL = $limit['interval'];
		}
		$minutes = max((int)round($remainingTTL / 60), 1);
		$text = "Please retry in $minutes minutes";
		if ($minutes === 1) {
			$text = "Please retry in 1 minute";
		}
		return new WP_Error('rate_limit_exceeded', 'Too many requests - ' . $text, array('status' => 429));
	}

	$request = json_decode($request->get_body(), true);

	// verify data
	if (!array_key_exists('email', $request) || !array_key_exists('id', $request)) {
		return new WP_Error('rest_invalid_param', 'Invalid parameter(s)', array('status' => 400));
	}

	// init vars
	$email      = $request['email'];
	$providerId = intval($request['id']);
	$locationId = intval($request['location']);
	$newsletter = array_key_exists('newsletter', $request) ? true : false;
	$subscribe  = boolval($request['subscribe']);

	// get providers list && check provider id
	$json = json_decode(file_get_contents(PROVIDERS_FILE));
	if (!array_key_exists($providerId, $json)) {
		return new WP_Error('rest_invalid_param', 'Invalid parameter(s)', array('status' => 400));
	}

	// init post request
	$provider = $json[$providerId];
	$url      = $provider->locations[$locationId]->url . '/ocs/v2.php/account/request/' . $provider->locations[$locationId]->key;
	$data     = array(
		'headers' => array(
			'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
		),
		'body'    => 'email=' . $email,
		'timeout' => 60
	);

	// request account && consume one rate token
	$post = wp_remote_post($url, $data);
	$ttl  = $redis->ttl($rateId);
	$redis->set($rateId, $rateLimit + 1);
	$redis->expire($rateId, $ttl > 0 ? $ttl : $limit['interval']);


	if (!array_key_exists('response', $post)) {
		error_log('Provider did not returned 201: ' . json_encode($post));
		return new WP_Error('unknown_error', 'Something happened', array('status' => 400));
	} else if ($post['response']['code'] !== 201) {
		if ($post['response']['code'] === 400 && $post['response']['message'] === 'invalid mail address') {
			return new WP_Error('invalid_mail_address', 'invalid mail address', array('status' => 400));
		}
		if ($post['response']['code'] === 400 && $post['response']['message'] === 'Bad Request') {
			$decodedBody = json_decode($post['body'], true);
			if ($decodedBody !== null &&
				isset($decodedBody['data']['message']) &&
				$decodedBody['data']['message'] === 'user already exists') {

				return new WP_Error('username_already_used', 'User already exists', array('status' => 400));
			}
		}
		error_log('Provider did not returned 201: ' . json_encode($post));
		return new WP_Error('unknown_error', 'Something happened', array('status' => 400));
	}

	$response = json_decode($post['body'])->data;

	if (!is_string($response->setPassword)) {
		return new WP_Error('rest_invalid_param', 'An unknown error occured', array('status' => 400));
	}

	// SUCCESS let's continue
	if ($subscribe) {
		// don't do anything else even if it fails.
		// let's focus on the ux flow
		subscribe($email);
	}

    // store stats
    try {
        $country = $readerCountry->country(whatismyip())->country->isoCode;
    } catch (Exception $e) {
        $country = 'unknown';
    }
    try {
	    $redis->set(time(), json_encode([
	        'device' => get_device(),
	        'country' => $country,
	        'provider' => $provider->name
	    ]));
	} catch (Exception $e) {
		error_log($e->getMessage());
	}

	// return nc://url
	if (array_key_exists('ocsapi', $request) && $request['ocsapi'] === true) {
		return $response->setPassword . '/ocs';
	}

	return $response->setPassword;
}

function get_providers_list() {
	// get providers list
	$json = json_decode(file_get_contents(PROVIDERS_FILE));

	if (!is_array($json)) {
		return new WP_Error('unknown_error', 'Invalid provider file', array('status' => 400, 'json' => PROVIDERS_FILE));
	}

	// obfuscate keys
	foreach ($json as $provider) {
		// safety fallback
		unset($provider->key);
		unset($provider->url);
		foreach ($provider->locations as $location) {
			unset($location->key);
			unset($location->url);
		}
	}

	return $json;
}

function get_statistics($params) {
	if ($_GET['key'] && $_GET['key'] === PPP_KEY) {
		global $redis;

		// select every proper timestamp ()
		// TODO: change the timestamp for May 18, 2033 @ 5:33:20 am 😂
		$keys = $redis->keys('1*');

		// filter out
		if ($_GET['time']) {
			$keys = array_filter($keys, function($time) {
				return $time > $_GET['time'];
			});
		}

		// no results
		if (count($keys) === 0) {
			return [];
		}

		set_time_limit(0);
		$data = array_reduce($keys, function ($array, $key) {
			global $redis;
			$array[$key] = json_decode($redis->get($key));

			return $array;
		});

		return $data;
	}

	return new WP_Error('forbidden', 'Forbidden', array('status' => 403));
}