Skip to content

Commit

Permalink
Enable/Disable User
Browse files Browse the repository at this point in the history
  • Loading branch information
lcharette committed Dec 28, 2024
1 parent d3dbc2a commit 59142c9
Show file tree
Hide file tree
Showing 9 changed files with 214 additions and 84 deletions.
1 change: 1 addition & 0 deletions packages/sprinkle-admin/app/assets/composables/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export { useUserApi } from './useUserApi'
export { useUserCreateApi } from './useUserCreateApi'
export { useUserDeleteApi } from './useUserDeleteApi'
export { useUserEditApi } from './useUserEditApi'
export { useUserUpdateApi } from './useUserUpdateApi'
49 changes: 49 additions & 0 deletions packages/sprinkle-admin/app/assets/composables/useUserUpdateApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { ref } from 'vue'
import axios from 'axios'
import { Severity, type AlertInterface } from '@userfrosting/sprinkle-core/interfaces'
import type { ApiResponse } from '../interfaces'

// TODO : Add validation
// 'schema://requests/user/edit-field.yaml'

/**
* API Composable
*/
export function useUserUpdateApi() {
const apiLoading = ref<Boolean>(false)
const apiError = ref<AlertInterface | null>(null)

async function submitUserUpdate(user_name: string, fieldName: string, fieldValue: any) {
apiLoading.value = true
apiError.value = null

// Assign the field name and value to the payload
const payload: Record<string, any> = {}
payload[fieldName] = fieldValue

return axios
.put<ApiResponse>('/api/users/u/' + user_name + '/' + fieldName, payload)
.then((response) => {
return {
message: response.data.message
}
})
.catch((err) => {
apiError.value = {
...{
description: 'An error as occurred',
style: Severity.Danger,
closeBtn: true
},
...err.response.data
}

throw apiError.value
})
.finally(() => {
apiLoading.value = false
})
}

return { submitUserUpdate, apiLoading, apiError }
}
6 changes: 6 additions & 0 deletions packages/sprinkle-admin/app/assets/interfaces/ApiResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* Interfaces - What the API expects and what it returns
*/
export interface ApiResponse {
message: string
}
1 change: 1 addition & 0 deletions packages/sprinkle-admin/app/assets/interfaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export type { UserApi } from './UserApi'
export type { UserCreateForm, UserCreateResponse } from './UserCreateApi'
export type { UserDeleteResponse } from './UserDeleteApi'
export type { UserEditForm, UserEditResponse } from './UserEditApi'
export type { ApiResponse } from './ApiResponse'
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,21 @@
use Illuminate\Support\Collection;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use UserFrosting\Alert\AlertStream;
use UserFrosting\Config\Config;
use UserFrosting\Fortress\RequestSchema;
use UserFrosting\Fortress\RequestSchema\RequestSchemaInterface;
use UserFrosting\Fortress\Transformer\RequestDataTransformer;
use UserFrosting\Fortress\Validator\ServerSideValidator;
use UserFrosting\I18n\Translator;
use UserFrosting\Sprinkle\Account\Authenticate\Authenticator;
use UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface;
use UserFrosting\Sprinkle\Account\Database\Models\User;
use UserFrosting\Sprinkle\Account\Exceptions\AccountException;
use UserFrosting\Sprinkle\Account\Exceptions\ForbiddenException;
use UserFrosting\Sprinkle\Account\Log\UserActivityLogger;
use UserFrosting\Sprinkle\Admin\Exceptions\MissingRequiredParamException;
use UserFrosting\Sprinkle\Core\Exceptions\ValidationException;
use UserFrosting\Support\Message\UserMessage;

/**
* Processes the request to update a specific field for an existing user.
Expand All @@ -51,7 +53,7 @@ class UserUpdateFieldAction
* Inject dependencies.
*/
public function __construct(
protected AlertStream $alert,
protected Translator $translator,
protected Authenticator $authenticator,
protected Config $config,
protected Connection $db,
Expand All @@ -76,8 +78,10 @@ public function __invoke(
Request $request,
Response $response
): Response {
$this->handle($user, $field, $request);
$payload = json_encode([], JSON_THROW_ON_ERROR);
$message = $this->handle($user, $field, $request);
$payload = json_encode([
'message' => $this->translator->translate($message->message, $message->parameters),
], JSON_THROW_ON_ERROR);
$response->getBody()->write($payload);

return $response->withHeader('Content-Type', 'application/json');
Expand All @@ -89,12 +93,14 @@ public function __invoke(
* @param UserInterface $user
* @param string $fieldName
* @param Request $request
*
* @return UserMessage The message to display to the user.
*/
protected function handle(
UserInterface $user,
string $fieldName,
Request $request
): void {
): UserMessage {
// Access-controlled resource - check that current User has permission
// to edit the specified field for this user
$this->validateAccess($user, $fieldName);
Expand Down Expand Up @@ -189,24 +195,21 @@ protected function handle(
]);
});

// Add success messages
// Return success messages
$message = new UserMessage();
$message->parameters = ['user_name' => $user->user_name];

if ($fieldName === 'flag_enabled' && $fieldValue === '1') {
$this->alert->addMessage('success', 'ENABLE_SUCCESSFUL', [
'user_name' => $user->user_name,
]);
$message->message = 'ENABLE_SUCCESSFUL';
} elseif ($fieldName === 'flag_enabled') {
$this->alert->addMessage('success', 'DISABLE_SUCCESSFUL', [
'user_name' => $user->user_name,
]);
$message->message = 'DISABLE_SUCCESSFUL';
} elseif ($fieldName == 'flag_verified') {
$this->alert->addMessage('success', 'MANUALLY_ACTIVATED', [
'user_name' => $user->user_name,
]);
$message->message = 'MANUALLY_ACTIVATED';
} else {
$this->alert->addMessage('success', 'DETAILS_UPDATED', [
'user_name' => $user->user_name,
]);
$message->message = 'DETAILS_UPDATED';
}

return $message;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
namespace UserFrosting\Sprinkle\Admin\Tests\Controller\User;

use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use UserFrosting\Alert\AlertStream;
use UserFrosting\Config\Config;
use UserFrosting\Sprinkle\Account\Database\Models\Role;
use UserFrosting\Sprinkle\Account\Database\Models\User;
Expand Down Expand Up @@ -121,15 +120,10 @@ public function testPostForPassword(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertResponseStatus(200, $response);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('success', array_reverse($messages)[0]['type']);
$this->assertSame('Account details updated for user <strong>' . $userToEdit->user_name . '</strong>', array_reverse($messages)[0]['message']);
$this->assertJsonResponse([
'message' => 'Account details updated for user <strong>' . $userToEdit->user_name . '</strong>',
], $response);
}

public function testPostForPasswordWithoutConfirmation(): void
Expand Down Expand Up @@ -167,15 +161,10 @@ public function testPostForEnabled(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertResponseStatus(200, $response);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('success', array_reverse($messages)[0]['type']);
$this->assertSame('Account for user <strong>' . $user->user_name . '</strong> has been successfully enabled.', array_reverse($messages)[0]['message']);
$this->assertJsonResponse([
'message' => 'Account for user <strong>' . $user->user_name . '</strong> has been successfully enabled.',
], $response);
}

public function testPostForDisabled(): void
Expand All @@ -194,15 +183,10 @@ public function testPostForDisabled(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertResponseStatus(200, $response);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('success', array_reverse($messages)[0]['type']);
$this->assertSame('Account for user <strong>' . $userToEdit->user_name . '</strong> has been successfully disabled.', array_reverse($messages)[0]['message']);
$this->assertJsonResponse([
'message' => 'Account for user <strong>' . $userToEdit->user_name . '</strong> has been successfully disabled.',
], $response);
}

public function testPostForVerified(): void
Expand All @@ -217,15 +201,10 @@ public function testPostForVerified(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertResponseStatus(200, $response);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('success', array_reverse($messages)[0]['type']);
$this->assertSame($user->user_name . "'s account has been manually activated", array_reverse($messages)[0]['message']);
$this->assertJsonResponse([
'message' => $user->user_name . "'s account has been manually activated",
], $response);
}

public function testPostForRole(): void
Expand Down Expand Up @@ -255,19 +234,14 @@ public function testPostForRole(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertResponseStatus(200, $response);
$this->assertJsonResponse([
'message' => 'Account details updated for user <strong>' . $user->user_name . '</strong>',
], $response);

// Make sure the user has the new roles.
$user->refresh();
$this->assertCount(2, $user->roles);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('success', array_reverse($messages)[0]['type']);
$this->assertSame('Account details updated for user <strong>' . $user->user_name . '</strong>', array_reverse($messages)[0]['message']);
}

public function testPostForRemovingRoles(): void
Expand All @@ -283,19 +257,14 @@ public function testPostForRemovingRoles(): void
$response = $this->handleRequest($request);

// Assert response status & body
$this->assertJsonResponse([], $response);
$this->assertResponseStatus(200, $response);
$this->assertJsonResponse([
'message' => 'Account details updated for user <strong>' . $user->user_name . '</strong>',
], $response);

// Make sure the user has the new roles.
$user->refresh();
$this->assertCount(0, $user->roles);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('success', array_reverse($messages)[0]['type']);
$this->assertSame('Account details updated for user <strong>' . $user->user_name . '</strong>', array_reverse($messages)[0]['message']);
}

public function testPageForFailedValidation(): void
Expand All @@ -316,12 +285,6 @@ public function testPageForFailedValidation(): void
// Assert response status & body
$this->assertJsonResponse('Invalid email address.', $response, 'description');
$this->assertResponseStatus(400, $response);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('danger', array_reverse($messages)[0]['type']);
}

public function testPageForFailedToEditMasterUser(): void
Expand All @@ -346,12 +309,6 @@ public function testPageForFailedToEditMasterUser(): void
// Assert response status & body
$this->assertJsonResponse('Access Denied', $response, 'title');
$this->assertResponseStatus(403, $response);

// Test message
/** @var AlertStream */
$ms = $this->ci->get(AlertStream::class);
$messages = $ms->getAndClearMessages();
$this->assertSame('danger', array_reverse($messages)[0]['type']);
}

public function testPostForDisableMasterUser(): void
Expand Down
Loading

0 comments on commit 59142c9

Please sign in to comment.