Completed
Push — master ( 1f48f6...828106 )
by Lukas
10:12
created

AuthSettingsController   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 144
Duplicated Lines 6.25 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 9
loc 144
rs 10
wmc 15
lcom 1
cbo 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 9 9 1
B index() 0 28 5
B create() 0 28 4
A getServiceNotAvailableResponse() 0 5 1
A generateRandomDeviceToken() 0 7 2
A destroy() 0 9 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @author Christoph Wurst <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OC\Settings\Controller;
23
24
use OC\AppFramework\Http;
25
use OC\Authentication\Exceptions\InvalidTokenException;
26
use OC\Authentication\Exceptions\PasswordlessTokenException;
27
use OC\Authentication\Token\IProvider;
28
use OC\Authentication\Token\IToken;
29
use OCP\AppFramework\Controller;
30
use OCP\AppFramework\Http\JSONResponse;
31
use OCP\IRequest;
32
use OCP\ISession;
33
use OCP\IUserManager;
34
use OCP\Security\ISecureRandom;
35
use OCP\Session\Exceptions\SessionNotAvailableException;
36
37
class AuthSettingsController extends Controller {
38
39
	/** @var IProvider */
40
	private $tokenProvider;
41
42
	/** @var IUserManager */
43
	private $userManager;
44
45
	/** @var ISession */
46
	private $session;
47
48
	/** @var string */
49
	private $uid;
50
51
	/** @var ISecureRandom */
52
	private $random;
53
54
	/**
55
	 * @param string $appName
56
	 * @param IRequest $request
57
	 * @param IProvider $tokenProvider
58
	 * @param IUserManager $userManager
59
	 * @param ISession $session
60
	 * @param ISecureRandom $random
61
	 * @param string $uid
62
	 */
63 View Code Duplication
	public function __construct($appName, IRequest $request, IProvider $tokenProvider, IUserManager $userManager,
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...
64
		ISession $session, ISecureRandom $random, $uid) {
65
		parent::__construct($appName, $request);
66
		$this->tokenProvider = $tokenProvider;
67
		$this->userManager = $userManager;
68
		$this->uid = $uid;
69
		$this->session = $session;
70
		$this->random = $random;
71
	}
72
73
	/**
74
	 * @NoAdminRequired
75
	 * @NoSubadminRequired
76
	 *
77
	 * @return JSONResponse
78
	 */
79
	public function index() {
80
		$user = $this->userManager->get($this->uid);
81
		if (is_null($user)) {
82
			return [];
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(); (array) is incompatible with the return type documented by OC\Settings\Controller\A...ttingsController::index of type OCP\AppFramework\Http\JSONResponse.

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...
83
		}
84
		$tokens = $this->tokenProvider->getTokenByUser($user);
85
		
86
		try {
87
			$sessionId = $this->session->getId();
88
		} catch (SessionNotAvailableException $ex) {
89
			return $this->getServiceNotAvailableResponse();
90
		}
91
		try {
92
			$sessionToken = $this->tokenProvider->getToken($sessionId);
93
		} catch (InvalidTokenException $ex) {
94
			return $this->getServiceNotAvailableResponse();
95
		}
96
97
		return array_map(function(IToken $token) use ($sessionToken) {
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_map(functio...urn $data; }, $tokens); (array) is incompatible with the return type documented by OC\Settings\Controller\A...ttingsController::index of type OCP\AppFramework\Http\JSONResponse.

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...
98
			$data = $token->jsonSerialize();
99
			if ($sessionToken->getId() === $token->getId()) {
100
				$data['canDelete'] = false;
101
			} else {
102
				$data['canDelete'] = true;
103
			}
104
			return $data;
105
		}, $tokens);
106
	}
107
108
	/**
109
	 * @NoAdminRequired
110
	 * @NoSubadminRequired
111
	 *
112
	 * @return JSONResponse
113
	 */
114
	public function create($name) {
115
		try {
116
			$sessionId = $this->session->getId();
117
		} catch (SessionNotAvailableException $ex) {
118
			return $this->getServiceNotAvailableResponse();
119
		}
120
121
		try {
122
			$sessionToken = $this->tokenProvider->getToken($sessionId);
123
			$loginName = $sessionToken->getLoginName();
124
			try {
125
				$password = $this->tokenProvider->getPassword($sessionToken, $sessionId);
126
			} catch (PasswordlessTokenException $ex) {
127
				$password = null;
128
			}
129
		} catch (InvalidTokenException $ex) {
130
			return $this->getServiceNotAvailableResponse();
131
		}
132
133
		$token = $this->generateRandomDeviceToken();
134
		$deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN);
135
136
		return [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array('token' => ...oken' => $deviceToken); (array<string,string|OC\A...ntication\Token\IToken>) is incompatible with the return type documented by OC\Settings\Controller\A...tingsController::create of type OCP\AppFramework\Http\JSONResponse.

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...
137
			'token' => $token,
138
			'loginName' => $loginName,
139
			'deviceToken' => $deviceToken
140
		];
141
	}
142
143
	private function getServiceNotAvailableResponse() {
144
		$resp = new JSONResponse();
145
		$resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE);
146
		return $resp;
147
	}
148
149
	/**
150
	 * Return a 20 digit device password
151
	 *
152
	 * Example: ABCDE-FGHIJ-KLMNO-PQRST
153
	 *
154
	 * @return string
155
	 */
156
	private function generateRandomDeviceToken() {
157
		$groups = [];
158
		for ($i = 0; $i < 4; $i++) {
159
			$groups[] = $this->random->generate(5, implode('', range('A', 'Z')));
160
		}
161
		return implode('-', $groups);
162
	}
163
164
	/**
165
	 * @NoAdminRequired
166
	 * @NoSubadminRequired
167
	 *
168
	 * @return JSONResponse
169
	 */
170
	public function destroy($id) {
171
		$user = $this->userManager->get($this->uid);
172
		if (is_null($user)) {
173
			return [];
174
		}
175
176
		$this->tokenProvider->invalidateTokenById($user, $id);
177
		return [];
178
	}
179
180
}
181