aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Module/Totp_check.php
blob: c0b38a51326e4e56e8c88e728aadaeb88f7dbc5c (plain) (blame)
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
<?php

namespace Zotlabs\Module;

use App;
use Zotlabs\Web\Controller;
use OTPHP\TOTP;

class Totp_check extends Controller {

	public function post() {
		$retval = ['status' => false];
		$static = $_POST['totp_code_static'] ?? false;

		if (!local_channel()) {
			if ($static) {
				goaway(z_root());
			}

			json_return_and_die($retval);
		}

		$account = App::get_account();
		if (!$account) {
			json_return_and_die($retval);
		}

		$secret = $account['account_external'];
		$input = (isset($_POST['totp_code'])) ? trim($_POST['totp_code']) : '';

		if ($secret && $input) {
			$otp = TOTP::create($secret); // create TOTP object from the secret.
			if ($otp->verify($_POST['totp_code']) || $input === $secret ) {
				logger('otp_success');
				$_SESSION['2FA_VERIFIED'] = true;

				if ($static) {
					goaway(z_root());
				}

				$retval['status'] = true;
				json_return_and_die($retval);
			}
			logger('otp_fail');
		}

		if ($static) {
			if(empty($_SESSION['totp_try_count'])) {
				$_SESSION['totp_try_count'] = 1;
			}

			if ($_SESSION['totp_try_count'] > 2) {
				goaway('logout');
			}

			$_SESSION['totp_try_count']++;
			goaway(z_root());
		}

		json_return_and_die($retval);
	}

	public function get() {

		if (!local_channel()) {
			return;
		}

		$account = App::get_account();
		if (!$account) {
			return t('Account not found.');
		}

		$id = $account['account_email'];

		return replace_macros(get_markup_template('totp.tpl'),
			[
				'$header' => t('Multifactor Verification'),
				'$id' => $id,
				'$desc'   => t('Please enter the verification key from your authenticator app'),
				'$submit' => t('Verify'),
				'$static' => $static
			]
		);
	}
}