Skip to content
This repository has been archived by the owner on Aug 9, 2021. It is now read-only.

Commit

Permalink
fix(invitation): change the workflow for invitation
Browse files Browse the repository at this point in the history
Signed-off-by: Thierry Bugier <tbugier@teclib.com>
  • Loading branch information
btry authored and ajsb85 committed Oct 19, 2018
1 parent 40c9bee commit e7d1cf6
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 163 deletions.
6 changes: 3 additions & 3 deletions inc/agent.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ public function prepareInputForAdd($input) {
if (!$entityConfig->canAddAgent($_SESSION['glpiactive_entity'])) {
// Too many devices
$this->filterMessages(Session::addMessageAfterRedirect(__('Too many devices', 'flyvemdm')));
$input = false;
return false;
}

// User already logged in : user token has been validated
Expand All @@ -450,7 +450,7 @@ public function prepareInputForAdd($input) {
switch ($this->chooseEnrollMethod($input)) {
case self::ENROLL_DENY:
$this->filterMessages(Session::addMessageAfterRedirect(__('Unable to find a enrollment method', 'flyvemdm')));
$input = false;
return false;
break;

case self::ENROLL_INVITATION_TOKEN:
Expand All @@ -459,7 +459,7 @@ public function prepareInputForAdd($input) {

case self::ENROLL_ENTITY_TOKEN:
// Method disabled, waiting for implementation
$input = false;
return false;
break;
}

Expand Down
172 changes: 57 additions & 115 deletions inc/invitation.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,84 +93,39 @@ public function getRights($interface = 'central') {
* @return array|false the modified input data
*/
public function prepareInputForAdd($input) {
// integrity checks
if (!isset($input['_useremails'])) {
Session::addMessageAfterRedirect(__("Email address is invalid", 'flyvemdm'));
return false;
}

$input['_useremails'] = filter_var($input['_useremails'], FILTER_VALIDATE_EMAIL);
if (!$input['_useremails']) {
Session::addMessageAfterRedirect(__("Email address is invalid", 'flyvemdm'));
return false;
}

// Find guest profile's id
$config = Config::getConfigurationValues("flyvemdm", ['guest_profiles_id']);
$guestProfileId = $config['guest_profiles_id'];

if (!isset($input['entities_id']) || !isset($input['users_id'])) {
Session::addMessageAfterRedirect(__("Invalid data", 'flyvemdm'));
return false;
}
$entityId = $input['entities_id'];

// Find or create the user
// Find the user
$userId = (int) $input[User::getForeignKeyField()];
$user = new User();
if (!$user->getFromDBbyName($input['_useremails'])) {
// The user does not exists yet, create him
if (version_compare(PluginFlyvemdmCommon::getGlpiVersion(), '9.3.0') >= 0) {
// Workaround GLPI bug in commit a4bca634e4d055cdd6576000d8d0f2b89b0dcd91
// in GLPI 9.3.0 (waiting for a fix)
$userId = $user->add([
'_useremails' => [$input['_useremails']],
'name' => $input['_useremails'],
'authtype' => Auth::DB_GLPI,
]);
$profile_User = new Profile_User();
$profile_User->deleteByCriteria([
'users_id' => $user->getID(),
]);
$profile_User->add([
'users_id' => $user->getID(),
'profiles_id' => $guestProfileId,
'entities_id' => $entityId,
'is_recursive' => 0,
]);
} else {
$userId = $user->add([
'_useremails' => [$input['_useremails']],
'name' => $input['_useremails'],
'_profiles_id' => $guestProfileId,
'_entities_id' => $entityId,
'_is_recursive' => 0,
'authtype' => Auth::DB_GLPI,
]);
}
if ($user->isNewItem()) {
Session::addMessageAfterRedirect(__("Cannot create the user", 'flyvemdm'), false, INFO,
true);
return false;
}

} else {
// Do not handle deleted users
if ($user->isDeleted()) {
Session::addMessageAfterRedirect(__("The user already exists and has been deleted. You must restore or purge him first.",
'flyvemdm'), false, INFO, true);
return false;
}
$user->getFromDB($userId);
// Do not handle deleted users
if ($user->isDeleted()) {
Session::addMessageAfterRedirect(__("The user was deleted. You must restore him first.",
'flyvemdm'), false, INFO, true);
return false;
}

// The user already exists, add him in the entity
$userId = $user->getID();
$profile_User = new Profile_User();
$entities = $profile_User->getEntitiesForProfileByUser($userId, $guestProfileId);
if (!isset($entities[$_SESSION['glpiactive_entity']])) {
$profile_User->add([
'users_id' => $userId,
'profiles_id' => $guestProfileId,
'entities_id' => $entityId,
'is_recursive' => 0,
]);
}
// The user already exists, add him in the entity
$userId = $user->getID();
$profile_User = new Profile_User();
$entities = $profile_User->getEntitiesForProfileByUser($userId, $guestProfileId);
if (!isset($entities[$_SESSION['glpiactive_entity']])) {
$profile_User->add([
'users_id' => $userId,
'profiles_id' => $guestProfileId,
'entities_id' => $entityId,
'is_recursive' => 0,
]);
}
$input['users_id'] = $userId;

// Ensure the user has a token
$personalToken = User::getToken($user->getID(), 'api_token');
Expand Down Expand Up @@ -513,15 +468,20 @@ public function hook_entity_purge(CommonDBTM $item) {
* @param integer $ID
* @param array $options
*/
public function showForm($ID, $options = []) {
public function showForm($ID, array $options = []) {
$this->initForm($ID, $options);
$this->showFormHeader();
$this->showFormHeader($options);
$canUpdate = (!$this->isNewID($ID)) && ($this->canView() > 0) || $this->isNewID($ID);

$fields = $this->fields;
$user = new User();
$user->getFromDB($fields['users_id']);
$fields['_useremails'] = $user->getDefaultEmail();
$fields['user'] = User::dropdown([
'name' => 'users_id',
'value' => $this->fields['users_id'],
'entity' => $this->fields['entities_id'],
'right' => 'all',
'rand' => mt_rand(),
'display' => false,
]);
$data = [
'withTemplate' => (isset($options['withtemplate']) && $options['withtemplate'] ? "*" : ""),
'canUpdate' => $canUpdate,
Expand Down Expand Up @@ -580,49 +540,31 @@ public static function processMassiveActionsForOneItemtype(
) {
switch ($ma->getAction()) {
case 'InviteUser':
if ($item->getType() == User::class) {
// find the profile ID of the service account (demo plugin)
$config = Config::getConfigurationValues('flyvemdmdemo', ['service_profiles_id']);
if (isset($config['service_profiles_id'])) {
$profile = new Profile();
$profile->getFromDB($config['service_profiles_id']);
$profile_user = new Profile_User();
if (!$item->getType() == User::class) {
$ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
}
foreach ($ids as $id) {
$item->getFromDB($id);

// Do not invite users without a default email address
$useremail = new UserEmail();
$emailAddress = $useremail->getDefaultForUser($id);
if (empty($emailAddress)) {
$ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
continue;
}
foreach ($ids as $id) {
$item->getFromDB($id);
$reject = false;

// Do not invite service account users (demo mode)
if (isset($config['service_profiles_id'])) {
if ($profile_user->getFromDBForItems($item, $profile) !== false) {
$reject = true;
}
}

// Do not invite users without a default email address
$useremail = new UserEmail();
$emailAddress = $useremail->getDefaultForUser($id);
if (empty($emailAddress)) {
$reject = true;
}

$result = MassiveAction::ACTION_OK;
if ($reject) {
$result = MassiveAction::ACTION_KO;
} else {
$invitation = new PluginFlyvemdmInvitation();
$success = $invitation->add([
'_useremails' => $emailAddress,
'entities_id' => $_SESSION['glpiactive_entity'],
]);
if (!$success) {
$result = MassiveAction::ACTION_KO;
}
}
$ma->itemDone($item->getType(), $id, $result);

$invitation = new PluginFlyvemdmInvitation();
$invitation->add([
User::getForeignKeyField() => $id,
'entities_id' => $_SESSION['glpiactive_entity'],
]);
if ($invitation->isNewItem()) {
$ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
continue;
}
} else {
$ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);

$ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
}
}

Expand Down
15 changes: 14 additions & 1 deletion tests/src/Flyvemdm/Tests/CommonTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,30 @@ protected function enrollFromInvitation($userId, array $input, $keepLoggedUser =
return $agent;
}

protected function createUser($input) {
$user = new \User();
$user->add($input);
return $user;
}

/**
* Create a new invitation
*
* @param string $guestEmail
* @return \PluginFlyvemdmInvitation
*/
protected function createInvitation($guestEmail) {
$user = $this->createUser([
'_useremails' => [
$guestEmail,
],
'name' => $guestEmail,
'authtype' => \Auth::DB_GLPI,
]);
$invitation = new \PluginFlyvemdmInvitation();
$invitation->add([
'entities_id' => $_SESSION['glpiactive_entity'],
'_useremails' => $guestEmail,
'users_id' => $user->getID(),
]);
$this->boolean($invitation->isNewItem())->isFalse();
if (!$invitation->isNewItem()) {
Expand Down
16 changes: 13 additions & 3 deletions tests/suite-integration/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,24 @@ public function beforeTestMethod($method) {
public function testDeleteEntity() {
$entity = $this->newTestedInstance();
$entityId = $entity->add([
'name' => 'to be deleted',
'name' => $this->getUniqueString(),
]);
$guestEmail = 'a.user@localhost.local';
$guestEmail = $this->getUniqueEmail();
$user = new \User();
$user->add([
'_useremails' => [
$guestEmail,
],
'authtype' => \Auth::DB_GLPI,
'name' => $guestEmail,
]);
$this->boolean($user->isNewItem())->isFalse(json_encode($_SESSION['MESSAGE_AFTER_REDIRECT'], JSON_PRETTY_PRINT));
$invitation = new \PluginFlyvemdmInvitation();
$invitation->add([
'entities_id' => $entityId,
'_useremails' => $guestEmail,
'users_id' => $user->getID(),
]);
$this->boolean($invitation->isNewItem())->isFalse();
$guestUser = new \User();
$guestUser->getFromDB($invitation->getField('users_id'));
$_REQUEST['user_token'] = \User::getToken($invitation->getField('users_id'), 'api_token');
Expand Down
29 changes: 17 additions & 12 deletions tests/suite-integration/PluginFlyvemdmAgent.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class PluginFlyvemdmAgent extends CommonTestCase {
protected $computerTypeId = 3;

public function setUp() {
$this->resetState();
//$this->resetState();
\Config::setConfigurationValues('flyvemdm', ['computertypes_id' => $this->computerTypeId]);
}

Expand Down Expand Up @@ -88,14 +88,29 @@ public function testDeviceCountLimit() {

for ($i = $agents; $i <= $deviceLimit; $i++) {
$email = $this->getUniqueEmail();
$user = new \User();
$user->add([
'_useremails' => [
$email,
],
'authtype' => \Auth::DB_GLPI,
'name' => $email,
]);
$this->boolean($user->isNewItem())->isFalse();
$invitation = new \PluginFlyvemdmInvitation();
$invitation->add([
'entities_id' => $activeEntity,
'_useremails' => $email,
'users_id' => $user->getID(),
]);
$invitationData[] = ['invitation' => $invitation, 'email' => $email];
}

$config = \Config::setConfigurationValues(
'flyvemdm',
[
'debug_enrolment' => '1',
]
);
for ($i = 0, $max = (count($invitationData) - 1); $i < $max; $i++) {
$agentId = $this->loginAndAddAgent($invitationData[$i]);
// Agent creation should succeed
Expand Down Expand Up @@ -196,16 +211,6 @@ public function testInvalidEnrollAgent(array $data, $expected) {
$this->boolean($agent->isNewItem())
->isTrue(json_encode($_SESSION['MESSAGE_AFTER_REDIRECT'], JSON_PRETTY_PRINT));
$this->array($_SESSION['MESSAGE_AFTER_REDIRECT'][ERROR])->contains($expected);

// Check registered log
// previous enrolment could generate a new log
$invitationLog = new \PluginFlyvemdmInvitationlog();
$fk = \PluginFlyvemdmInvitation::getForeignKeyField();
$inviationId = $invitation->getID();
$expectedLogCount += count($invitationLog->find("`$fk` = '$inviationId'"));

$total = $dbUtils->countElementsInTable($invitationlogTable);
$this->integer($total)->isEqualTo($expectedLogCount);
}

/**
Expand Down
17 changes: 11 additions & 6 deletions tests/suite-integration/PluginFlyvemdmInvitation.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,24 @@ public function afterTestMethod($method) {
*/
public function testInvitationCreation() {
$email = $this->getUniqueEmail();
$user = new \User();
$user->add([
'_useremails' => [
$email,
],
'authtype' => \Auth::DB_GLPI,
'name' => $email,
]);
$this->boolean($user->isNewItem())->isFalse();
$invitation = $this->newTestedInstance();

// Test an invitation with an invalid email
$invitation->add([
'entities_id' => $_SESSION['glpiactive_entity'],
'_useremails' => $email,
'users_id' => $user->getID(),
]);
$this->boolean($invitation->isNewItem())->isFalse();

// check the guest user exists
$user = new \User();
$this->boolean($user->getFromDB($invitation->getField(\User::getForeignKeyField())))->isTrue();

// check a email was queued
$invitationType = \PluginFlyvemdmInvitation::class;
$invitationId = $invitation->getID();
Expand Down Expand Up @@ -96,7 +101,7 @@ public function testInvitationCreation() {
$secondInvitation = $this->newTestedInstance();
$secondInvitation->add([
'entities_id' => $_SESSION['glpiactive_entity'],
'_useremails' => $email,
'users_id' => $user->getID(),
]);
$this->boolean($secondInvitation->isNewItem())->isFalse();

Expand Down
Loading

0 comments on commit e7d1cf6

Please sign in to comment.