summaryrefslogtreecommitdiffstats
path: root/app/Http/Controllers/Home.php
blob: 7632c17a48e37c384c2187dc194c37c10d15c6cc (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
<?php

namespace App\Http\Controllers;

use Storage;
use Google2FA;

class Home extends Controller
{
    private $fileName = 'google2fasecret.key';

    private $name = 'PragmaRX';

    private $email = 'google2fa@pragmarx.com';

    private $secretKey;

    private $keySize = 25;

    private $keyPrefix = '';

    public function check2fa()
    {
        $isValid = $this->validateInput();

        // Render index and show the result
        return $this->index($isValid);
    }

    /**
     * @param $key
     * @return mixed
     */
    private function getGoogleUrl($key)
    {
        return Google2FA::getQRCodeGoogleUrl(
            $this->name,
            $this->email,
            $key
        );
    }

    /**
     * @param $key
     * @return mixed
     */
    private function getInlineUrl($key)
    {
        return Google2FA::getQRCodeInline(
            $this->name,
            $this->email,
            $key
        );
    }

    private function getSecretKey()
    {
        if (! $key = $this->getStoredKey())
        {
            $key = Google2FA::generateSecretKey($this->keySize, $this->keyPrefix);

            $this->storeKey($key);
        }

        return $key;
    }

    /**
     * @return mixed
     */
    private function getStoredKey()
    {
        // No need to read it from disk it again if we already have it
        if ($this->secretKey)
        {
            return $this->secretKey;
        }

        if (! Storage::exists($this->fileName))
        {
            return null;
        }

        return Storage::get($this->fileName);
    }

    public function index()
    {
        $valid = $this->validateInput($key = $this->getSecretKey());

        $googleUrl = $this->getGoogleUrl($key);

        $inlineUrl = $this->getInlineUrl($key);

        return view('welcome')->with(compact('key', 'googleUrl', 'inlineUrl', 'valid'));
    }

    /**
     * @param $key
     */
    private function storeKey($key)
    {
        Storage::put($this->fileName, $key);
    }

    /**
     * @return mixed
     */
    private function validateInput($key)
    {
        // Get the code from input
        if (! $code = request()->get('code'))
        {
            return false;
        }

        // Verify the code
        return Google2FA::verifyKey($key, $code);
    }
}