Completed
Pull Request — develop (#91)
by Boy
02:58
created

SmsController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 10
c 4
b 1
f 0
lcom 1
cbo 7
dl 0
loc 118
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B verifySmsSecondFactorAction() 0 49 4
B verifySmsSecondFactorChallengeAction() 0 55 6
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupGateway\GatewayBundle\Controller;
20
21
use Surfnet\StepupBundle\Command\VerifyPossessionOfPhoneCommand;
22
use Surfnet\StepupBundle\Value\PhoneNumber\InternationalPhoneNumber;
23
use Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext;
24
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
25
use Symfony\Component\Form\FormError;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpFoundation\Response;
28
use Surfnet\StepupGateway\GatewayBundle\Command\SendSmsChallengeCommand;
29
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
30
31
class SmsController extends Controller
32
{
33
    /**
34
     * @Template
35
     * @param Request $request
36
     * @return array|Response
37
     */
38
    public function verifySmsSecondFactorAction(Request $request)
39
    {
40
        /** @var ResponseContext $responseContext */
41
        $context = $this->get(
42
          $this->get('gateway.proxy.state_handler')->getResponseContextServiceId()
43
        );
44
        $originalRequestId = $context->getInResponseTo();
45
46
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
47
48
        $selectedSecondFactor = $this->get('gateway.service.require_selected_factor')
49
          ->requireSelectedSecondFactor($logger);
50
51
        $logger->notice('Verifying possession of SMS second factor, preparing to send');
52
53
        $command = new SendSmsChallengeCommand();
54
        $command->secondFactorId = $selectedSecondFactor;
55
56
        $form = $this->createForm('gateway_send_sms_challenge', $command)->handleRequest($request);
57
58
        $stepupService = $this->get('gateway.service.stepup_authentication');
59
        $phoneNumber = InternationalPhoneNumber::fromStringFormat(
60
          $stepupService->getSecondFactorIdentifier($selectedSecondFactor)
61
        );
62
63
        $otpRequestsRemaining = $stepupService->getSmsOtpRequestsRemainingCount();
64
        $maximumOtpRequests = $stepupService->getSmsMaximumOtpRequestsCount();
65
        $viewVariables = ['otpRequestsRemaining' => $otpRequestsRemaining, 'maximumOtpRequests' => $maximumOtpRequests];
66
67
        if ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
68
            return $this->forward('SurfnetStepupGatewayGatewayBundle:Failure:sendAuthenticationCancelledByUser');
69
        }
70
71
        if (!$form->isValid()) {
72
            return array_merge($viewVariables, ['phoneNumber' => $phoneNumber, 'form' => $form->createView()]);
73
        }
74
75
        $logger->notice('Verifying possession of SMS second factor, sending challenge per SMS');
76
77
        if (!$stepupService->sendSmsChallenge($command)) {
78
            $form->addError(new FormError('gateway.form.send_sms_challenge.sms_sending_failed'));
79
80
            return array_merge($viewVariables, ['phoneNumber' => $phoneNumber, 'form' => $form->createView()]);
81
        }
82
83
        return $this->redirect(
84
          $this->generateUrl('gateway_verify_second_factor_sms_verify_challenge')
85
        );
86
    }
87
88
    /**
89
     * @Template
90
     * @param Request $request
91
     * @return array|Response
92
     */
93
    public function verifySmsSecondFactorChallengeAction(Request $request)
94
    {
95
        /** @var ResponseContext $context */
96
        $context = $this->get(
97
          $this->get('gateway.proxy.state_handler')->getResponseContextServiceId()
98
        );
99
        $originalRequestId = $context->getInResponseTo();
100
101
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
102
103
        $selectedSecondFactor = $this->get('gateway.service.require_selected_factor')
104
          ->requireSelectedSecondFactor($logger);
105
106
        $command = new VerifyPossessionOfPhoneCommand();
107
        $form = $this->createForm('gateway_verify_sms_challenge', $command)->handleRequest($request);
108
109
        if ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
110
            return $this->forward('SurfnetStepupGatewayGatewayBundle:Failure:sendAuthenticationCancelledByUser');
111
        }
112
113
        if (!$form->isValid()) {
114
            return ['form' => $form->createView()];
115
        }
116
117
        $logger->notice('Verifying input SMS challenge matches');
118
119
        $verification = $this->get('gateway.service.stepup_authentication')->verifySmsChallenge($command);
120
121
        if ($verification->wasSuccessful()) {
122
            $this->get('gateway.service.stepup_authentication')->clearSmsVerificationState();
123
124
            $context->markSecondFactorVerified();
125
            $this->get('gateway.authentication_logger')->logSecondFactorAuthentication($originalRequestId);
126
127
            $logger->info(
128
              sprintf(
129
                'Marked Sms Second Factor "%s" as verified, forwarding to Saml Proxy to respond',
130
                $selectedSecondFactor
131
              )
132
            );
133
134
            return $this->forward($context->getResponseAction());
135
        } elseif ($verification->didOtpExpire()) {
136
            $logger->notice('SMS challenge expired');
137
            $form->addError(new FormError('gateway.form.send_sms_challenge.challenge_expired'));
138
        } elseif ($verification->wasAttemptedTooManyTimes()) {
139
            $logger->notice('SMS challenge verification was attempted too many times');
140
            $form->addError(new FormError('gateway.form.send_sms_challenge.too_many_attempts'));
141
        } else {
142
            $logger->notice('SMS challenge did not match');
143
            $form->addError(new FormError('gateway.form.send_sms_challenge.sms_challenge_incorrect'));
144
        }
145
146
        return ['form' => $form->createView()];
147
    }
148
}
149