Completed
Push — master ( 812bae...fa8bfe )
by Thomas
13:53
created

TwoFactorChallengeController::solveChallenge()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
c 0
b 0
f 0
nc 4
nop 3
dl 0
loc 20
rs 9.2
1
<?php
2
/**
3
 * @author Christoph Wurst <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 *
6
 * @copyright Copyright (c) 2016, ownCloud GmbH.
7
 * @license AGPL-3.0
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace OC\Core\Controller;
24
25
use OC\Authentication\TwoFactorAuth\Manager;
26
use OCP\AppFramework\Controller;
27
use OCP\AppFramework\Http\RedirectResponse;
28
use OCP\AppFramework\Http\TemplateResponse;
29
use OCP\Authentication\TwoFactorAuth\IProvider2;
30
use OCP\IRequest;
31
use OCP\ISession;
32
use OCP\IURLGenerator;
33
use OCP\IUserSession;
34
35
class TwoFactorChallengeController extends Controller {
36
37
	/** @var Manager */
38
	private $twoFactorManager;
39
40
	/** @var IUserSession */
41
	private $userSession;
42
43
	/** @var ISession */
44
	private $session;
45
46
	/** @var IURLGenerator */
47
	private $urlGenerator;
48
49
	/**
50
	 * @param string $appName
51
	 * @param IRequest $request
52
	 * @param Manager $twoFactorManager
53
	 * @param IUserSession $userSession
54
	 * @param ISession $session
55
	 * @param IURLGenerator $urlGenerator
56
	 */
57
	public function __construct($appName, IRequest $request, Manager $twoFactorManager, IUserSession $userSession,
58
		ISession $session, IURLGenerator $urlGenerator) {
59
		parent::__construct($appName, $request);
60
		$this->twoFactorManager = $twoFactorManager;
61
		$this->userSession = $userSession;
62
		$this->session = $session;
63
		$this->urlGenerator = $urlGenerator;
64
	}
65
66
	/**
67
	 * @return string
68
	 */
69
	protected function getLogoutAttribute() {
70
		return \OC_User::getLogoutAttribute();
71
	}
72
73
	/**
74
	 * @NoAdminRequired
75
	 * @NoCSRFRequired
76
	 *
77
	 * @param string $redirect_url
78
	 * @return TemplateResponse
79
	 */
80
	public function selectChallenge($redirect_url) {
81
		$user = $this->userSession->getUser();
82
		$providers = $this->twoFactorManager->getProviders($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 81 can be null; however, OC\Authentication\TwoFac...Manager::getProviders() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
83
		if (count($providers) === 1) {
84
			// redirect to the challenge page
85
			$provider = current($providers);
86
			return new RedirectResponse(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \OCP\AppFrame...l' => $redirect_url))); (OCP\AppFramework\Http\RedirectResponse) is incompatible with the return type documented by OC\Core\Controller\TwoFa...roller::selectChallenge of type OCP\AppFramework\Http\TemplateResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
87
				$this->urlGenerator->linkToRoute(
88
					'core.TwoFactorChallenge.showChallenge',
89
					[
90
						'challengeProviderId' => $provider->getId(),
91
						'redirect_url' => $redirect_url,
92
					]
93
				)
94
			);
95
		}
96
97
		$data = [
98
			'providers' => $providers,
99
			'redirect_url' => $redirect_url,
100
			'logout_attribute' => $this->getLogoutAttribute(),
101
		];
102
		return new TemplateResponse($this->appName, 'twofactorselectchallenge', $data, 'guest');
103
	}
104
105
	/**
106
	 * @NoAdminRequired
107
	 * @NoCSRFRequired
108
	 * @UseSession
109
	 *
110
	 * @param string $challengeProviderId
111
	 * @param string $redirect_url
112
	 * @return RedirectResponse|TemplateResponse
113
	 */
114
	public function showChallenge($challengeProviderId, $redirect_url) {
115
		$user = $this->userSession->getUser();
116
		$provider = $this->twoFactorManager->getProvider($user, $challengeProviderId);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 115 can be null; however, OC\Authentication\TwoFac...\Manager::getProvider() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
117
		if (is_null($provider)) {
118
			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
119
		}
120
121
		if ($this->session->exists('two_factor_auth_error')) {
122
			$this->session->remove('two_factor_auth_error');
123
			$error = true;
124
		} else {
125
			$error = false;
126
		}
127
		$tmpl = $provider->getTemplate($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 115 can be null; however, OCP\Authentication\TwoFa...Provider::getTemplate() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
128
		$tmpl->assign('redirect_url', $redirect_url);
129
		$data = [
130
			'error' => $error,
131
			'provider' => $provider,
132
			'logout_attribute' => $this->getLogoutAttribute(),
133
			'template' => $tmpl->fetchPage(),
134
		];
135
		//Generate the response and add the custom CSP (if defined)
136
		$response = new TemplateResponse($this->appName, 'twofactorshowchallenge', $data, 'guest');
137
138
		//Attempt to get custom ContentSecurityPolicy(CSP) from 2FA provider
139
		if ($provider instanceof IProvider2) {
140
			$response->setContentSecurityPolicy($provider->getCSP());
141
		}
142
		return $response;
143
	}	
144
145
	/**
146
	 * @NoAdminRequired
147
	 * @NoCSRFRequired
148
	 * @UseSession
149
	 *
150
	 * @param string $challengeProviderId
151
	 * @param string $challenge
152
	 * @param string $redirect_url
153
	 * @return RedirectResponse
154
	 */
155
	public function solveChallenge($challengeProviderId, $challenge, $redirect_url = null) {
156
		$user = $this->userSession->getUser();
157
		$provider = $this->twoFactorManager->getProvider($user, $challengeProviderId);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 156 can be null; however, OC\Authentication\TwoFac...\Manager::getProvider() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
158
		if (is_null($provider)) {
159
			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
160
		}
161
162
		if ($this->twoFactorManager->verifyChallenge($challengeProviderId, $user, $challenge)) {
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 156 can be null; however, OC\Authentication\TwoFac...ager::verifyChallenge() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
163
			if (!is_null($redirect_url)) {
164
				return new RedirectResponse($this->urlGenerator->getAbsoluteURL(urldecode($redirect_url)));
165
			}
166
			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
167
		}
168
169
		$this->session->set('two_factor_auth_error', true);
170
		return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.showChallenge', [
171
			'challengeProviderId' => $provider->getId(),
172
			'redirect_url' => $redirect_url,
173
		]));
174
	}
175
176
}
177