Completed
Pull Request — master (#32767)
by Sujith
12:47
created

Add::createUser()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 24

Duplication

Lines 4
Ratio 16.67 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 4
dl 4
loc 24
rs 9.536
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 * @author Laurens Post <[email protected]>
5
 * @author Thomas Müller <[email protected]>
6
 *
7
 * @copyright Copyright (c) 2018, ownCloud GmbH
8
 * @license AGPL-3.0
9
 *
10
 * This code is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License, version 3,
12
 * as published by the Free Software Foundation.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License, version 3,
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
21
 *
22
 */
23
24
namespace OC\Core\Command\User;
25
26
use OC\AppFramework\Http;
27
use OC\Files\Filesystem;
28
use OC\User\Service\SigninWithEmail;
29
use OCP\IGroupManager;
30
use OCP\IUser;
31
use OCP\IUserManager;
32
use OCP\Mail\IMailer;
33
use Symfony\Component\Console\Command\Command;
34
use Symfony\Component\Console\Input\InputInterface;
35
use Symfony\Component\Console\Input\InputOption;
36
use Symfony\Component\Console\Output\OutputInterface;
37
use Symfony\Component\Console\Input\InputArgument;
38
use Symfony\Component\Console\Question\Question;
39
40
class Add extends Command {
41
	/** @var \OCP\IUserManager */
42
	protected $userManager;
43
44
	/** @var \OCP\IGroupManager */
45
	protected $groupManager;
46
47
	/** @var IMailer  */
48
	protected $mailer;
49
50
	/** @var SigninWithEmail  */
51
	protected $signinWithEmail;
52
53
	/**
54
	 * Add User constructor.
55
	 *
56
	 * @param IUserManager $userManager
57
	 * @param IGroupManager $groupManager
58
	 * @param IMailer $mailer
59
	 * @param SigninWithEmail $signinWithEmail
60
	 */
61
	public function __construct(IUserManager $userManager, IGroupManager $groupManager,
62
								IMailer $mailer, SigninWithEmail $signinWithEmail) {
63
		parent::__construct();
64
		$this->userManager = $userManager;
65
		$this->groupManager = $groupManager;
66
		$this->mailer = $mailer;
67
		$this->signinWithEmail = $signinWithEmail;
68
	}
69
70
	protected function configure() {
71
		$this
72
			->setName('user:add')
73
			->setDescription('adds a user')
74
			->addArgument(
75
				'uid',
76
				InputArgument::REQUIRED,
77
				'User ID used to login (must only contain a-z, A-Z, 0-9, -, _ and @).'
78
			)
79
			->addOption(
80
				'password-from-env',
81
				null,
82
				InputOption::VALUE_NONE,
83
				'Read password from the OC_PASS environment variable.'
84
			)
85
			->addOption(
86
				'password-from-cmdline',
87
				'p',
88
				InputOption::VALUE_NONE,
89
				'Read password from user input'
90
			)
91
			->addOption(
92
				'display-name',
93
				null,
94
				InputOption::VALUE_OPTIONAL,
95
				'User name used in the web UI (can contain any characters).'
96
			)
97
			->addOption(
98
				'email',
99
				null,
100
				InputOption::VALUE_OPTIONAL,
101
				'Email address for the user.'
102
			)
103
			->addOption(
104
				'group',
105
				'g',
106
				InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
107
				'The groups the user should be added to (The group will be created if it does not exist).'
108
			);
109
	}
110
111
	protected function addUserToGroup(InputInterface $input, OutputInterface $output, IUser $user) {
112
		$groups = $input->getOption('group');
113
114
		if (!empty($groups)) {
115
			// Make sure we init the Filesystem for the user, in case we need to
116
			// init some group shares.
117
			Filesystem::init($user->getUID(), '');
118
		}
119
120
		foreach ($groups as $groupName) {
121
			$group = $this->groupManager->get($groupName);
122
			if (!$group) {
123
				$this->groupManager->createGroup($groupName);
124
				$group = $this->groupManager->get($groupName);
125
				$output->writeln('Created group "' . $group->getGID() . '"');
126
			}
127
			$group->addUser($user);
128
			$output->writeln('User "' . $user->getUID() . '" added to group "' . $group->getGID() . '"');
129
		}
130
	}
131
132
	protected function createUser(InputInterface $input, OutputInterface $output, $password, $email) {
133
		$user = $this->userManager->createUser(
134
			$input->getArgument('uid'),
135
			$password
136
		);
137
138
		if ($user instanceof IUser) {
139
			$output->writeln('<info>The user "' . $user->getUID() . '" was created successfully</info>');
140
		} else {
141
			$output->writeln('<error>An error occurred while creating the user</error>');
142
			return 1;
143
		}
144
145 View Code Duplication
		if ($input->getOption('display-name')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
146
			$user->setDisplayName($input->getOption('display-name'));
147
			$output->writeln('Display name set to "' . $user->getDisplayName() . '"');
148
		}
149
150
		// Set email if supplied & valid
151
		if ($email !== null) {
152
			$user->setEMailAddress($email);
153
			$output->writeln('Email address set to "' . $user->getEMailAddress() . '"');
154
		}
155
	}
156
157
	protected function execute(InputInterface $input, OutputInterface $output) {
158
		$uid = $input->getArgument('uid');
159
		if ($this->userManager->userExists($uid)) {
160
			$output->writeln('<error>The user "' . $uid . '" already exists.</error>');
161
			return 1;
162
		}
163
164
		$readPasswordFromCmdLine = $input->getOption('password-from-cmdline');
165
		// Validate email before we create the user
166
		if ($input->getOption('email')) {
167
			// Validate first
168
			if (!$this->mailer->validateMailAddress($input->getOption('email'))) {
169
				// Invalid! Error
170
				$output->writeln('<error>Invalid email address supplied</error>');
171
				return 1;
172
			} else {
173
				$email = $input->getOption('email');
174
			}
175
		} else {
176
			$email = null;
177
		}
178
179
		if ($input->getOption('password-from-env')) {
180
			$password = \getenv('OC_PASS');
181
			if (!$password) {
182
				$output->writeln('<error>--password-from-env given, but OC_PASS is empty!</error>');
183
				return 1;
184
			}
185
			$this->createUser($input, $output, $password, $email);
186
			$this->addUserToGroup($input, $output, $this->userManager->get($uid));
0 ignored issues
show
Bug introduced by
It seems like $this->userManager->get($uid) can be null; however, addUserToGroup() 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...
187
		} elseif ($readPasswordFromCmdLine) {
188
			/** @var $dialog \Symfony\Component\Console\Helper\QuestionHelper */
189
			$dialog = $this->getHelperSet()->get('question');
190
			$q = new Question('<question>Enter password: </question>', false);
191
			$q->setHidden(true);
192
			$password = $dialog->ask($input, $output, $q);
193
			$q = new Question('<question>Confirm password: </question>', false);
194
			$q->setHidden(true);
195
			$confirm = $dialog->ask($input, $output, $q);
196
197
			if ($password !== $confirm) {
198
				$output->writeln("<error>Passwords did not match!</error>");
199
				return 1;
200
			}
201
202
			$this->createUser($input, $output, $password, $email);
203
			$this->addUserToGroup($input, $output, $this->userManager->get($uid));
0 ignored issues
show
Bug introduced by
It seems like $this->userManager->get($uid) can be null; however, addUserToGroup() 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...
204
		} elseif ($input->getOption('email') && ($email !== null)) {
205
			$response = $this->signinWithEmail->create($uid, '', $input->getOption('group'), $email);
206
			if ($response->getStatus() === Http::STATUS_CREATED) {
207
				$output->writeln('<info>The user "' . $response->getData()['name'] . '" was created successfully</info>');
208
			}
209 View Code Duplication
			if ($input->getOption('display-name')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
210
				$user = $this->userManager->get($uid);
211
				$user->setDisplayName($input->getOption('display-name'));
212
				$output->writeln('Display name set to "' . $user->getDisplayName() . '"');
213
			}
214
			if ($input->getOption('group')) {
215
				if (\is_array($input->getOption('group'))) {
216
					foreach ($input->getOption('group') as $group) {
217
						if ($this->groupManager->isInGroup($uid, $group)) {
218
							$output->writeln('User "' . $uid . '" added to group "' . $group . '"');
219
						}
220
					}
221
				}
222
			}
223
		} else {
224
			$output->writeln("<error>Interactive input or --password-from-env is needed for entering a password!</error>");
225
			return 1;
226
		}
227
	}
228
}
229