Test Failed
Push — master ( f54b15...1ba8eb )
by Ashish
06:13
created

TwoFactorAuthenticationController::strRandom()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace Thecodework\TwoFactorAuthentication\Http\Controllers;
4
5
use ParagonIE\ConstantTime\Base32;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\Schema;
8
use OTPHP\TOTP;
9
use Thecodework\TwoFactorAuthentication\AuthenticatesUsersWith2FA;
10
use Thecodework\TwoFactorAuthentication\Contracts\TwoFactorAuthenticationInterface;
11
use Thecodework\TwoFactorAuthentication\Exceptions\TwoFactorAuthenticationExceptions;
12
use Thecodework\TwoFactorAuthentication\TwoFactorAuthenticationServiceProvider;
13
14
class TwoFactorAuthenticationController extends Controller implements TwoFactorAuthenticationInterface
15
{
16
    use AuthenticatesUsersWith2FA;
17
18
    /**
19
     * User Model.
20
     */
21
    protected $TwoFAModel;
22
23
    /**
24
     * Assigns $usersModel Property a Model instance.
25
     * Set authenticated users data to $user Property.
26
     */
27
    public function __construct()
28
    {
29
        $this->TwoFAModel = TwoFactorAuthenticationServiceProvider::getTwoFAModelInstance();
30
31
        $this->middleware(function ($request, $next) {
32
            $this->setUser(\Auth::guard(config('2fa-config.guard'))->user());
33
34
            return $next($request);
35
        });
36
    }
37
38
    /**
39
     * Setup two factor authentication.
40
     *
41
     * @param \Illuminate\Http\Request
42
     * @param \Illuminate\Http\Response
43
     *
44
     * @throws \Thecodework\TwoFactorAuthentications\Exceptions\TwoFactorAuthenticationExceptions
45
     *
46
     * @return mixed
47
     */
48
    public function setupTwoFactorAuthentication(Request $request)
49
    {
50
        // $this->updateUserWith2FAGeneratedKey();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
51
        $user = $this->getUser();
52
        $totp = TOTP::create(
53
            $this->base32EncodedString(),
54
            config('2fa-config.period'),
55
            config('2fa-config.digest_algorithm'),
56
            config('2fa-config.number_of_digits')
57
        );
58
        $totp->setLabel(config('2fa-config.account_name'));
59
        $this->updateUserWithProvisionedUri($totp->getProvisioningUri());
60
        $barcode = $totp->getQrCodeUri();
61
        // info($totp->getProvisioningUri());
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
62
        if ($request->ajax()) {
63
            return $barcode;
64
        }
65
66
        return view('2fa::setup', compact('barcode', 'user'));
67
    }
68
69
    /**
70
     * Disable 2FA.
71
     *
72
     * @param \Illuminate\Http\Request
73
     *
74
     * @return mixed
75
     */
76 View Code Duplication
    public function enableTwoFactorAuthentication(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
    {
78
        $user = $this->getUser();
79
        $user->is_two_factor_enabled = 1;
80
        $user->update();
81
82
        if ($request->ajax()) {
83
            return [
84
                'data' => [
85
                    'message'     => 'success',
86
                    'description' => '2FA Enabled',
87
                ],
88
            ];
89
        }
90
91
        return redirect('home');
92
    }
93
94
    /**
95
     * Enable 2FA.
96
     *
97
     * @param \Illuminate\Http\Request
98
     *
99
     * @return mixed
100
     */
101 View Code Duplication
    public function disableTwoFactorAuthentication(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        $user = $this->getUser();
104
        $user->is_two_factor_enabled = 0;
105
        $user->two_factor_secret_key = null;
106
        $user->update();
107
108
        if ($request->ajax()) {
109
            return [
110
                'data' => [
111
                    'message'     => 'success',
112
                    'description' => '2FA Disabled',
113
                ],
114
            ];
115
        }
116
117
        return redirect('home');
118
    }
119
120
    /**
121
     * Verify Two Factor Authentication.
122
     *
123
     * @param \Illuminate\Http\Request $request
124
     */
125
    public function verifyTwoFactorAuthentication(Request $request)
126
    {
127
        if ($request->session()->has('2fa:user:id')) {
128
            $secret = getenv('HMAC_SECRET');
129
            $signature = hash_hmac('sha256', decrypt($request->session()->get('2fa:user:id')), $secret);
130
131
            if (md5($signature) !== md5($request->signature)) {
132
                return redirect()->intended('login');
133
            }
134
135
            return view('2fa::verify');
136
        }
137
138
        return redirect()->back(); //shoud be configurable
139
    }
140
141
    /**
142
     * Encode Random String to 32 Base Transfer Encoding.
143
     *
144
     * @param int $length Length of the encoded string.
0 ignored issues
show
Bug introduced by
There is no parameter named $length. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
145
     *
146
     * @return string
147
     */
148
    private function base32EncodedString():
149
    string
150
    {
151
        return trim(Base32::encodeUpper(random_bytes(128)), '=');
152
    }
153
154
    /**
155
     * Update User data with 2FA generated Key.
156
     *
157
     * @return void
158
     */
159
    private function updateUserWithProvisionedUri($twoFactorProvisionedUri)
160
    {
161
        $user = $this->TwoFAModel->find($this->getUser()->id);
162
        if (!Schema::hasColumn(config('2fa-config.table'), 'two_factor_provisioned_uri') ||
163
            !Schema::hasColumn(config('2fa-config.table'), 'is_two_factor_enabled')) {
164
            throw TwoFactorAuthenticationExceptions::columnNotFound();
165
        }
166
        $user->two_factor_provisioned_uri = $twoFactorProvisionedUri;
167
        $user->update();
168
    }
169
}
170