AuthController::changepasswordAction()   B
last analyzed

Complexity

Conditions 7
Paths 9

Size

Total Lines 53
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 53
rs 7.5251
c 1
b 0
f 0
cc 7
eloc 34
nc 9
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Vivait\AuthBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6
use Symfony\Component\Security\Core\SecurityContext;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\Form\FormError;
10
use Vivait\AuthBundle\Entity\User;
11
12
class AuthController extends Controller {
13
14
	public function loginAction() {
15
		$request = $this->getRequest();
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: Deprecated since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
16
		$session = $request->getSession();
17
18
		// get the login error if there is one
19
		if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
20
			$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
21
		}
22
		else {
23
			$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
24
			$session->remove(SecurityContext::AUTHENTICATION_ERROR);
25
		}
26
27
		return $this->render('VivaitAuthBundle:Default:login.html.twig', array(
28
			// last username entered by the user
29
			'last_username' => $session->get(SecurityContext::LAST_USERNAME),
30
			'error'         => $error,
31
		));
32
	}
33
34
	public function heartbeatAction(Request $request) {
35
		$em   = $this->getDoctrine()->getManager();
36
		$user = $this->get('security.context')->getToken()->getUser();
37
38
		$user->setLastResponse(new \DateTime());
39
		$user->setLastIP($request->getClientIp());
40
41
		$status = $request->query->get('status', 0);
42
		if ($status == 'active') {
43
			$user->setStatus(User::STATUS_ONLINE);
44
			$user->setLastActivity(new \DateTime());
45
		} elseif ($status == 'idle') {
46
			$user->setStatus(User::STATUS_AWAY);
47
		} else {
48
			$user->setStatus(0);
49
		}
50
51
		$em->persist($user);
52
		$em->flush();
53
54
		$response = new Response();
55
		$response->setContent('OK');
56
		$response->setStatusCode(200);
57
		$response->headers->set('Content-Type', 'text/html');
58
		return $response;
59
	}
60
61
	public function changepasswordAction(Request $request) {
62
63
		$user = $this->getUser();
64
65
		$defaultData = array('message' => 'Change Password');
66
		$form        = $this->createFormBuilder($defaultData)
67
			->add('oldpassword', 'password', array('label' => 'Old Password'))
68
			->add('newpassword1', 'password', array('label' => 'New Password'))
69
			->add('newpassword2', 'password', array('label' => 'Repeat New Password'))
70
			->getForm();
71
72
		if ($request->isMethod('POST')) {
73
			$form->bind($request);
74
			$data = $form->getData();
75
76
			$factory = $this->get('security.encoder_factory');
77
			$encoder = $factory->getEncoder($this);
78
			if ($encoder->encodePassword($data['oldpassword'], $user->getSalt()) == $user->getPassword()) {
79
				#old password verified
80
				if ((!$data['newpassword1']) || (strlen($data['newpassword1']) < 8)) {
81
					$form->get('newpassword1')->addError(new FormError('Your new password must be at least 8 letters!'));
82
				} elseif ($data['newpassword1'] == $data['newpassword2']) {
83
					#both new passwords match
84
					$user->newSalt();
85
					$user->setPassword($encoder->encodePassword($data['newpassword1'], $user->getSalt()));
86
87
					#persist
88
					$em = $this->getDoctrine()->getManager();
89
					$em->persist($user);
90
					$em->flush();
91
					$this->get('session')->getFlashBag()->add('success', 'Your password has been changed successfully!');
92
93
					return $this->render('VivaitBootstrapBundle:Default:redirect.html.twig', array('redirect' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))));
94
				} else {
95
					// send error about mismatch new passwords
96
					$form->get('newpassword1')->addError(new FormError('The two new passwords do not match!'));
97
					$form->get('newpassword2')->addError(new FormError('The two new passwords do not match!'));
98
				}
99
			} else {
100
				// send error about invalid old password
101
				$form->get('oldpassword')->addError(new FormError('The old password is incorrect!'));
102
			}
103
		}
104
105
106
		if (isset($form)) {
107
			$formtpl['form'] = $form->createView();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$formtpl was never initialized. Although not strictly required by PHP, it is generally a good practice to add $formtpl = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
108
		}
109
110
		$formtpl['action'] = $this->generateUrl($this->container->get('request')->get('_route'), $request->query->all());
0 ignored issues
show
Bug introduced by
The variable $formtpl does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
111
		$formtpl['title']  = 'Change Password';
112
		return $this->render('VivaitAuthBundle:Form:changepassword.html.twig', array('form' => array_merge($formtpl, array('parent' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))))));
113
	}
114
115
	public function changetenantAction(Request $request) {
116
		$user           = $this->getUser();
117
		$tenants        = $user->getTenants();
118
		$new_tenant     = $request->get('_tenant');
119
		$session        = $request->getSession();
120
		$current_tenant = $this->get('vivait_auth.tenant_manager')->getTenant();
121
122
		if ($new_tenant) {
123
			$session->getFlashBag()->add('success', sprintf('Tenant has been changed to %s', $current_tenant->getTenant()));
124
			// Redirect them
125
			return $this->render('VivaitBootstrapBundle:Default:redirect.html.twig', array('redirect' => $request->query->get('parent', $request->request->get('parent', $request->headers->get('referer')))));
126
		}
127
128
		return $this->render('VivaitAuthBundle:Form:changetenants.html.twig', array(
129
			'tenants' => $tenants
130
		));
131
	}
132
}
133