mirror of
https://github.com/CommunitySolidServer/CommunitySolidServer.git
synced 2024-10-03 14:55:10 +00:00
feat: Simplify setup to be more in line with IDP behaviour
This commit is contained in:
parent
129d3c0ef1
commit
9577791472
@ -14,14 +14,31 @@
|
|||||||
"args_responseWriter": { "@id": "urn:solid-server:default:ResponseWriter" },
|
"args_responseWriter": { "@id": "urn:solid-server:default:ResponseWriter" },
|
||||||
"args_operationHandler": {
|
"args_operationHandler": {
|
||||||
"@type": "SetupHttpHandler",
|
"@type": "SetupHttpHandler",
|
||||||
"args_initializer": { "@id": "urn:solid-server:default:RootInitializer" },
|
"args_handler": {
|
||||||
"args_registrationManager": { "@id": "urn:solid-server:default:SetupRegistrationManager" },
|
"@type": "SetupHandler",
|
||||||
|
"args_initializer": { "@id": "urn:solid-server:default:RootInitializer" },
|
||||||
|
"args_registrationManager": { "@id": "urn:solid-server:default:SetupRegistrationManager" }
|
||||||
|
},
|
||||||
"args_converter": { "@id": "urn:solid-server:default:RepresentationConverter" },
|
"args_converter": { "@id": "urn:solid-server:default:RepresentationConverter" },
|
||||||
"args_storageKey": "setupCompleted-2.0",
|
"args_storageKey": "setupCompleted-2.0",
|
||||||
"args_storage": { "@id": "urn:solid-server:default:SetupStorage" },
|
"args_storage": { "@id": "urn:solid-server:default:SetupStorage" },
|
||||||
"args_viewTemplate": "@css:templates/setup/index.html.ejs",
|
"args_templateEngine": {
|
||||||
"args_responseTemplate": "@css:templates/setup/response.html.ejs",
|
"comment": "Renders the specific page and embeds it into the main HTML body.",
|
||||||
"args_errorHandler": { "@id": "urn:solid-server:default:ErrorHandler" }
|
"@type": "ChainedTemplateEngine",
|
||||||
|
"renderedName": "htmlBody",
|
||||||
|
"engines": [
|
||||||
|
{
|
||||||
|
"comment": "Renders the main setup template.",
|
||||||
|
"@type": "EjsTemplateEngine",
|
||||||
|
"template": "@css:templates/setup/index.html.ejs"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"comment": "Will embed the result of the first engine into the main HTML template.",
|
||||||
|
"@type": "EjsTemplateEngine",
|
||||||
|
"template": "@css:templates/main.html.ejs"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
@ -185,6 +185,7 @@ export * from './init/final/Finalizable';
|
|||||||
export * from './init/final/ParallelFinalizer';
|
export * from './init/final/ParallelFinalizer';
|
||||||
|
|
||||||
// Init/Setup
|
// Init/Setup
|
||||||
|
export * from './init/setup/SetupHandler';
|
||||||
export * from './init/setup/SetupHttpHandler';
|
export * from './init/setup/SetupHttpHandler';
|
||||||
|
|
||||||
// Init/Cli
|
// Init/Cli
|
||||||
|
83
src/init/setup/SetupHandler.ts
Normal file
83
src/init/setup/SetupHandler.ts
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
import { BasicRepresentation } from '../../http/representation/BasicRepresentation';
|
||||||
|
import type { Representation } from '../../http/representation/Representation';
|
||||||
|
import { BaseInteractionHandler } from '../../identity/interaction/BaseInteractionHandler';
|
||||||
|
import type { RegistrationManager } from '../../identity/interaction/email-password/util/RegistrationManager';
|
||||||
|
import type { InteractionHandlerInput } from '../../identity/interaction/InteractionHandler';
|
||||||
|
import { getLoggerFor } from '../../logging/LogUtil';
|
||||||
|
import { APPLICATION_JSON } from '../../util/ContentTypes';
|
||||||
|
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
|
||||||
|
import { readJsonStream } from '../../util/StreamUtil';
|
||||||
|
import type { Initializer } from '../Initializer';
|
||||||
|
|
||||||
|
export interface SetupHandlerArgs {
|
||||||
|
/**
|
||||||
|
* Used for registering a pod during setup.
|
||||||
|
*/
|
||||||
|
registrationManager?: RegistrationManager;
|
||||||
|
/**
|
||||||
|
* Initializer to call in case no registration procedure needs to happen.
|
||||||
|
* This Initializer should make sure the necessary resources are there so the server can work correctly.
|
||||||
|
*/
|
||||||
|
initializer?: Initializer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On POST requests, runs an initializer and/or performs a registration step, both optional.
|
||||||
|
*/
|
||||||
|
export class SetupHandler extends BaseInteractionHandler {
|
||||||
|
protected readonly logger = getLoggerFor(this);
|
||||||
|
|
||||||
|
private readonly registrationManager?: RegistrationManager;
|
||||||
|
private readonly initializer?: Initializer;
|
||||||
|
|
||||||
|
public constructor(args: SetupHandlerArgs) {
|
||||||
|
super({});
|
||||||
|
this.registrationManager = args.registrationManager;
|
||||||
|
this.initializer = args.initializer;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async handlePost({ operation }: InteractionHandlerInput): Promise<Representation> {
|
||||||
|
const json = operation.body.isEmpty ? {} : await readJsonStream(operation.body.data);
|
||||||
|
|
||||||
|
const output: Record<string, any> = { initialize: false, registration: false };
|
||||||
|
if (json.registration) {
|
||||||
|
Object.assign(output, await this.register(json));
|
||||||
|
output.registration = true;
|
||||||
|
} else if (json.initialize) {
|
||||||
|
// We only want to initialize if no registration happened
|
||||||
|
await this.initialize();
|
||||||
|
output.initialize = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.debug(`Output: ${JSON.stringify(output)}`);
|
||||||
|
|
||||||
|
return new BasicRepresentation(JSON.stringify(output), APPLICATION_JSON);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call the initializer.
|
||||||
|
* Errors if no initializer was defined.
|
||||||
|
*/
|
||||||
|
private async initialize(): Promise<void> {
|
||||||
|
if (!this.initializer) {
|
||||||
|
throw new NotImplementedHttpError('This server is not configured with a setup initializer.');
|
||||||
|
}
|
||||||
|
await this.initializer.handleSafe();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a user based on the given input.
|
||||||
|
* Errors if no registration manager is defined.
|
||||||
|
*/
|
||||||
|
private async register(json: NodeJS.Dict<any>): Promise<Record<string, any>> {
|
||||||
|
if (!this.registrationManager) {
|
||||||
|
throw new NotImplementedHttpError('This server is not configured to support registration during setup.');
|
||||||
|
}
|
||||||
|
// Validate the input JSON
|
||||||
|
const validated = this.registrationManager.validateInput(json, true);
|
||||||
|
this.logger.debug(`Validated input: ${JSON.stringify(validated)}`);
|
||||||
|
|
||||||
|
// Register and/or create a pod as requested. Potentially does nothing if all booleans are false.
|
||||||
|
return this.registrationManager.register(validated, true);
|
||||||
|
}
|
||||||
|
}
|
@ -1,55 +1,26 @@
|
|||||||
import type { Operation } from '../../http/Operation';
|
import type { Operation } from '../../http/Operation';
|
||||||
import type { ErrorHandler } from '../../http/output/error/ErrorHandler';
|
import { OkResponseDescription } from '../../http/output/response/OkResponseDescription';
|
||||||
import { ResponseDescription } from '../../http/output/response/ResponseDescription';
|
import type { ResponseDescription } from '../../http/output/response/ResponseDescription';
|
||||||
import { BasicRepresentation } from '../../http/representation/BasicRepresentation';
|
import { BasicRepresentation } from '../../http/representation/BasicRepresentation';
|
||||||
import type { RegistrationParams,
|
import type { InteractionHandler } from '../../identity/interaction/InteractionHandler';
|
||||||
RegistrationManager } from '../../identity/interaction/email-password/util/RegistrationManager';
|
|
||||||
import { getLoggerFor } from '../../logging/LogUtil';
|
import { getLoggerFor } from '../../logging/LogUtil';
|
||||||
import type { OperationHttpHandlerInput } from '../../server/OperationHttpHandler';
|
import type { OperationHttpHandlerInput } from '../../server/OperationHttpHandler';
|
||||||
import { OperationHttpHandler } from '../../server/OperationHttpHandler';
|
import { OperationHttpHandler } from '../../server/OperationHttpHandler';
|
||||||
import type { RepresentationConverter } from '../../storage/conversion/RepresentationConverter';
|
import type { RepresentationConverter } from '../../storage/conversion/RepresentationConverter';
|
||||||
import type { KeyValueStorage } from '../../storage/keyvalue/KeyValueStorage';
|
import type { KeyValueStorage } from '../../storage/keyvalue/KeyValueStorage';
|
||||||
import { APPLICATION_JSON, TEXT_HTML } from '../../util/ContentTypes';
|
import { APPLICATION_JSON, TEXT_HTML } from '../../util/ContentTypes';
|
||||||
import { createErrorMessage } from '../../util/errors/ErrorUtil';
|
|
||||||
import { HttpError } from '../../util/errors/HttpError';
|
|
||||||
import { InternalServerError } from '../../util/errors/InternalServerError';
|
|
||||||
import { MethodNotAllowedHttpError } from '../../util/errors/MethodNotAllowedHttpError';
|
import { MethodNotAllowedHttpError } from '../../util/errors/MethodNotAllowedHttpError';
|
||||||
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
|
import type { TemplateEngine } from '../../util/templates/TemplateEngine';
|
||||||
import { addTemplateMetadata } from '../../util/ResourceUtil';
|
|
||||||
import { readJsonStream } from '../../util/StreamUtil';
|
|
||||||
import type { Initializer } from '../Initializer';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Input parameters expected in calls to the handler.
|
|
||||||
* Will be sent to the RegistrationManager for validation and registration.
|
|
||||||
* The reason this is a flat object and does not have a specific field for all the registration parameters
|
|
||||||
* is so we can also support form data.
|
|
||||||
*/
|
|
||||||
export interface SetupInput extends Record<string, any>{
|
|
||||||
/**
|
|
||||||
* Indicates if the initializer should be executed. Ignored if `registration` is true.
|
|
||||||
*/
|
|
||||||
initialize?: boolean;
|
|
||||||
/**
|
|
||||||
* Indicates if the registration procedure should be done for IDP registration and/or pod provisioning.
|
|
||||||
*/
|
|
||||||
registration?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SetupHttpHandlerArgs {
|
export interface SetupHttpHandlerArgs {
|
||||||
/**
|
/**
|
||||||
* Used for registering a pod during setup.
|
* Used for converting the input data.
|
||||||
*/
|
|
||||||
registrationManager?: RegistrationManager;
|
|
||||||
/**
|
|
||||||
* Initializer to call in case no registration procedure needs to happen.
|
|
||||||
* This Initializer should make sure the necessary resources are there so the server can work correctly.
|
|
||||||
*/
|
|
||||||
initializer?: Initializer;
|
|
||||||
/**
|
|
||||||
* Used for content negotiation.
|
|
||||||
*/
|
*/
|
||||||
converter: RepresentationConverter;
|
converter: RepresentationConverter;
|
||||||
|
/**
|
||||||
|
* Handles the requests.
|
||||||
|
*/
|
||||||
|
handler: InteractionHandler;
|
||||||
/**
|
/**
|
||||||
* Key that is used to store the boolean in the storage indicating setup is finished.
|
* Key that is used to store the boolean in the storage indicating setup is finished.
|
||||||
*/
|
*/
|
||||||
@ -59,17 +30,9 @@ export interface SetupHttpHandlerArgs {
|
|||||||
*/
|
*/
|
||||||
storage: KeyValueStorage<string, boolean>;
|
storage: KeyValueStorage<string, boolean>;
|
||||||
/**
|
/**
|
||||||
* Template to use for GET requests.
|
* Renders the main view.
|
||||||
*/
|
*/
|
||||||
viewTemplate: string;
|
templateEngine: TemplateEngine;
|
||||||
/**
|
|
||||||
* Template to show when setup was completed successfully.
|
|
||||||
*/
|
|
||||||
responseTemplate: string;
|
|
||||||
/**
|
|
||||||
* Used for converting output errors.
|
|
||||||
*/
|
|
||||||
errorHandler: ErrorHandler;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -78,128 +41,68 @@ export interface SetupHttpHandlerArgs {
|
|||||||
* this to prevent accidentally running unsafe servers.
|
* this to prevent accidentally running unsafe servers.
|
||||||
*
|
*
|
||||||
* GET requests will return the view template which should contain the setup information for the user.
|
* GET requests will return the view template which should contain the setup information for the user.
|
||||||
* POST requests will run an initializer and/or perform a registration step, both optional.
|
* POST requests will be sent to the InteractionHandler.
|
||||||
* After successfully completing a POST request this handler will disable itself and become unreachable.
|
* After successfully completing a POST request this handler will disable itself and become unreachable.
|
||||||
* All other methods will be rejected.
|
* All other methods will be rejected.
|
||||||
*/
|
*/
|
||||||
export class SetupHttpHandler extends OperationHttpHandler {
|
export class SetupHttpHandler extends OperationHttpHandler {
|
||||||
protected readonly logger = getLoggerFor(this);
|
protected readonly logger = getLoggerFor(this);
|
||||||
|
|
||||||
private readonly registrationManager?: RegistrationManager;
|
private readonly handler: InteractionHandler;
|
||||||
private readonly initializer?: Initializer;
|
|
||||||
private readonly converter: RepresentationConverter;
|
private readonly converter: RepresentationConverter;
|
||||||
private readonly storageKey: string;
|
private readonly storageKey: string;
|
||||||
private readonly storage: KeyValueStorage<string, boolean>;
|
private readonly storage: KeyValueStorage<string, boolean>;
|
||||||
private readonly viewTemplate: string;
|
private readonly templateEngine: TemplateEngine;
|
||||||
private readonly responseTemplate: string;
|
|
||||||
private readonly errorHandler: ErrorHandler;
|
|
||||||
|
|
||||||
private finished: boolean;
|
|
||||||
|
|
||||||
public constructor(args: SetupHttpHandlerArgs) {
|
public constructor(args: SetupHttpHandlerArgs) {
|
||||||
super();
|
super();
|
||||||
this.finished = false;
|
|
||||||
|
|
||||||
this.registrationManager = args.registrationManager;
|
this.handler = args.handler;
|
||||||
this.initializer = args.initializer;
|
|
||||||
this.converter = args.converter;
|
this.converter = args.converter;
|
||||||
this.storageKey = args.storageKey;
|
this.storageKey = args.storageKey;
|
||||||
this.storage = args.storage;
|
this.storage = args.storage;
|
||||||
this.viewTemplate = args.viewTemplate;
|
this.templateEngine = args.templateEngine;
|
||||||
this.responseTemplate = args.responseTemplate;
|
|
||||||
this.errorHandler = args.errorHandler;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async handle({ operation }: OperationHttpHandlerInput): Promise<ResponseDescription> {
|
public async handle({ operation }: OperationHttpHandlerInput): Promise<ResponseDescription> {
|
||||||
let json: Record<string, any>;
|
switch (operation.method) {
|
||||||
let template: string;
|
case 'GET': return this.handleGet(operation);
|
||||||
let success = false;
|
case 'POST': return this.handlePost(operation);
|
||||||
let statusCode = 200;
|
default: throw new MethodNotAllowedHttpError();
|
||||||
try {
|
|
||||||
({ json, template } = await this.getJsonResult(operation));
|
|
||||||
success = true;
|
|
||||||
} catch (err: unknown) {
|
|
||||||
// We want to show the errors on the original page in case of HTML interactions, so we can't just throw them here
|
|
||||||
const error = HttpError.isInstance(err) ? err : new InternalServerError(createErrorMessage(err));
|
|
||||||
({ statusCode } = error);
|
|
||||||
this.logger.warn(error.message);
|
|
||||||
const response = await this.errorHandler.handleSafe({ error, preferences: { type: { [APPLICATION_JSON]: 1 }}});
|
|
||||||
json = await readJsonStream(response.data!);
|
|
||||||
template = this.viewTemplate;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert the response JSON to the required format
|
|
||||||
const representation = new BasicRepresentation(JSON.stringify(json), operation.target, APPLICATION_JSON);
|
|
||||||
addTemplateMetadata(representation.metadata, template, TEXT_HTML);
|
|
||||||
const result = await this.converter.handleSafe(
|
|
||||||
{ representation, identifier: operation.target, preferences: operation.preferences },
|
|
||||||
);
|
|
||||||
|
|
||||||
// Make sure this setup handler is never used again after a successful POST request
|
|
||||||
if (success && operation.method === 'POST') {
|
|
||||||
this.finished = true;
|
|
||||||
await this.storage.set(this.storageKey, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ResponseDescription(statusCode, result.metadata, result.data);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a JSON object representing the result of executing the given operation,
|
* Returns the HTML representation of the setup page.
|
||||||
* together with the template it should be applied to.
|
|
||||||
*/
|
*/
|
||||||
private async getJsonResult(operation: Operation): Promise<{ json: Record<string, any>; template: string }> {
|
private async handleGet(operation: Operation): Promise<ResponseDescription> {
|
||||||
if (operation.method === 'GET') {
|
const result = await this.templateEngine.render({});
|
||||||
// Return the initial setup page
|
const representation = new BasicRepresentation(result, operation.target, TEXT_HTML);
|
||||||
return { json: {}, template: this.viewTemplate };
|
return new OkResponseDescription(representation.metadata, representation.data);
|
||||||
}
|
}
|
||||||
if (operation.method !== 'POST') {
|
|
||||||
throw new MethodNotAllowedHttpError();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Registration manager expects JSON data
|
/**
|
||||||
let json: SetupInput = {};
|
* Converts the input data to JSON and calls the setup handler.
|
||||||
if (!operation.body.isEmpty) {
|
* On success `true` will be written to the storage key.
|
||||||
|
*/
|
||||||
|
private async handlePost(operation: Operation): Promise<ResponseDescription> {
|
||||||
|
// Convert input data to JSON
|
||||||
|
// Allows us to still support form data
|
||||||
|
if (operation.body.metadata.contentType) {
|
||||||
const args = {
|
const args = {
|
||||||
representation: operation.body,
|
representation: operation.body,
|
||||||
preferences: { type: { [APPLICATION_JSON]: 1 }},
|
preferences: { type: { [APPLICATION_JSON]: 1 }},
|
||||||
identifier: operation.target,
|
identifier: operation.target,
|
||||||
};
|
};
|
||||||
const converted = await this.converter.handleSafe(args);
|
operation = {
|
||||||
json = await readJsonStream(converted.data);
|
...operation,
|
||||||
this.logger.debug(`Input JSON: ${JSON.stringify(json)}`);
|
body: await this.converter.handleSafe(args),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// We want to initialize after the input has been validated, but before (potentially) writing a pod
|
const representation = await this.handler.handleSafe({ operation });
|
||||||
// since that might overwrite the initializer result
|
await this.storage.set(this.storageKey, true);
|
||||||
if (json.initialize && !json.registration) {
|
|
||||||
if (!this.initializer) {
|
|
||||||
throw new NotImplementedHttpError('This server is not configured with a setup initializer.');
|
|
||||||
}
|
|
||||||
await this.initializer.handleSafe();
|
|
||||||
}
|
|
||||||
|
|
||||||
let output: Record<string, any> = {};
|
return new OkResponseDescription(representation.metadata, representation.data);
|
||||||
// We only call the RegistrationManager when getting registration input.
|
|
||||||
// This way it is also possible to set up a server without requiring registration parameters.
|
|
||||||
let validated: RegistrationParams | undefined;
|
|
||||||
if (json.registration) {
|
|
||||||
if (!this.registrationManager) {
|
|
||||||
throw new NotImplementedHttpError('This server is not configured to support registration during setup.');
|
|
||||||
}
|
|
||||||
// Validate the input JSON
|
|
||||||
validated = this.registrationManager.validateInput(json, true);
|
|
||||||
this.logger.debug(`Validated input: ${JSON.stringify(validated)}`);
|
|
||||||
|
|
||||||
// Register and/or create a pod as requested. Potentially does nothing if all booleans are false.
|
|
||||||
output = await this.registrationManager.register(validated, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add extra setup metadata
|
|
||||||
output.initialize = Boolean(json.initialize);
|
|
||||||
output.registration = Boolean(json.registration);
|
|
||||||
this.logger.debug(`Output: ${JSON.stringify(output)}`);
|
|
||||||
|
|
||||||
return { json: output, template: this.responseTemplate };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,72 +1,45 @@
|
|||||||
<h1>Set up your Solid server</h1>
|
<div id="input-partial">
|
||||||
<p>
|
<%- include('./input-partial.html.ejs') %>
|
||||||
Your Solid server needs a <strong>one-time setup</strong>
|
</div>
|
||||||
so it acts exactly the way you want.
|
<div id="response-partial">
|
||||||
</p>
|
<h1 id="public">Server setup complete</h1>
|
||||||
|
<p>
|
||||||
|
Congratulations!
|
||||||
|
Your Solid server is now ready to use.
|
||||||
|
<br>
|
||||||
|
You can now visit its <a href="./">homepage</a>.
|
||||||
|
</p>
|
||||||
|
|
||||||
<form method="post" id="mainForm">
|
<div id="response-initialize">
|
||||||
<% const safePrefilled = locals.prefilled || {}; %>
|
<h2>Root Pod</h2>
|
||||||
|
<p>
|
||||||
|
<strong>Warning: the root Pod is publicly accessible.</strong>
|
||||||
|
<br>
|
||||||
|
Prevent public write and control access to the root
|
||||||
|
by modifying its <a href=".acl">ACL document</a>.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<% if (locals.message) { %>
|
<div id="response-registration">
|
||||||
<p class="error"><%= message %></p>
|
<%- include('../identity/email-password/register-response-partial.html.ejs', { idpIndex: '' }) %>
|
||||||
<% } %>
|
</div>
|
||||||
<fieldset>
|
</div>
|
||||||
<legend>Accounts on this server</legend>
|
|
||||||
<ol>
|
|
||||||
<li class="checkbox">
|
|
||||||
<label>
|
|
||||||
<input type="checkbox" checked disabled>
|
|
||||||
Enable account registration.
|
|
||||||
</label>
|
|
||||||
<p>
|
|
||||||
You can disable account registration
|
|
||||||
by <a href="https://github.com/solid/community-server/blob/main/config/identity/README.md">changing the configuration</a>.
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
<li class="checkbox">
|
|
||||||
<label>
|
|
||||||
<input type="checkbox" id="registration" name="registration">
|
|
||||||
Sign me up for an account.
|
|
||||||
</label>
|
|
||||||
<p>
|
|
||||||
Any existing root Pod will be disabled.
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
<li class="checkbox" id="initializeForm">
|
|
||||||
<label>
|
|
||||||
<input type="checkbox" id="initialize" name="initialize">
|
|
||||||
Expose a public root Pod.
|
|
||||||
</label>
|
|
||||||
<p>
|
|
||||||
By default, the public has read and write access to the root Pod.
|
|
||||||
<br>
|
|
||||||
You typically only want to choose this
|
|
||||||
for rapid testing and development.
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
</ol>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<fieldset id="registrationForm">
|
|
||||||
<legend>Sign up</legend>
|
|
||||||
<%-
|
|
||||||
include('../identity/email-password/register-partial.html.ejs', {
|
|
||||||
allowRoot: true,
|
|
||||||
})
|
|
||||||
%>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<p class="actions"><button type="submit">Complete setup</button></p>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- Show or hide the account creation form when needed -->
|
|
||||||
<script>
|
<script>
|
||||||
[
|
function updateResponse(json) {
|
||||||
'registration', 'registrationForm', 'initializeForm',
|
// Swap visibility
|
||||||
].forEach(registerElement);
|
setVisibility('input-partial', false);
|
||||||
|
setVisibility('response-partial', true);
|
||||||
|
|
||||||
Object.assign(visibilityConditions, {
|
setVisibility('response-initialize', json.initialize);
|
||||||
registrationForm: () => elements.registration.checked,
|
|
||||||
initializeForm: () => !elements.registration.checked,
|
setVisibility('response-registration', json.registration);
|
||||||
});
|
if (json.registration) {
|
||||||
|
updateResponseFields(json);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setVisibility('response-partial', false);
|
||||||
|
|
||||||
|
addPostListener('mainForm', 'error', '', updateResponse);
|
||||||
</script>
|
</script>
|
||||||
|
69
templates/setup/input-partial.html.ejs
Normal file
69
templates/setup/input-partial.html.ejs
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
<h1>Set up your Solid server</h1>
|
||||||
|
<p>
|
||||||
|
Your Solid server needs a <strong>one-time setup</strong>
|
||||||
|
so it acts exactly the way you want.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<form method="post" id="mainForm">
|
||||||
|
<p class="error" id="error"></p>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>Accounts on this server</legend>
|
||||||
|
<ol>
|
||||||
|
<li class="checkbox">
|
||||||
|
<label>
|
||||||
|
<input type="checkbox" checked disabled>
|
||||||
|
Enable account registration.
|
||||||
|
</label>
|
||||||
|
<p>
|
||||||
|
You can disable account registration
|
||||||
|
by <a href="https://github.com/solid/community-server/blob/main/config/identity/README.md">changing the configuration</a>.
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
<li class="checkbox">
|
||||||
|
<label>
|
||||||
|
<input type="checkbox" id="registration" name="registration">
|
||||||
|
Sign me up for an account.
|
||||||
|
</label>
|
||||||
|
<p>
|
||||||
|
Any existing root Pod will be disabled.
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
<li class="checkbox" id="initializeForm">
|
||||||
|
<label>
|
||||||
|
<input type="checkbox" id="initialize" name="initialize">
|
||||||
|
Expose a public root Pod.
|
||||||
|
</label>
|
||||||
|
<p>
|
||||||
|
By default, the public has read and write access to the root Pod.
|
||||||
|
<br>
|
||||||
|
You typically only want to choose this
|
||||||
|
for rapid testing and development.
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset id="registrationForm">
|
||||||
|
<legend>Sign up</legend>
|
||||||
|
<%-
|
||||||
|
include('../identity/email-password/register-partial.html.ejs', {
|
||||||
|
allowRoot: true,
|
||||||
|
})
|
||||||
|
%>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<p class="actions"><button type="submit">Complete setup</button></p>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<!-- Show or hide the account creation form when needed -->
|
||||||
|
<script>
|
||||||
|
[
|
||||||
|
'registration', 'registrationForm', 'initializeForm',
|
||||||
|
].forEach(registerElement);
|
||||||
|
|
||||||
|
Object.assign(visibilityConditions, {
|
||||||
|
registrationForm: () => elements.registration.checked,
|
||||||
|
initializeForm: () => !elements.registration.checked,
|
||||||
|
});
|
||||||
|
</script>
|
@ -1,54 +0,0 @@
|
|||||||
<h1 id="public">Server setup complete</h1>
|
|
||||||
<p>
|
|
||||||
Congratulations!
|
|
||||||
Your Solid server is now ready to use.
|
|
||||||
<br>
|
|
||||||
You can now visit its <a href="./">homepage</a>.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<% if (initialize && !registration) { %>
|
|
||||||
<h2>Root Pod</h2>
|
|
||||||
<p>
|
|
||||||
<strong>Warning: the root Pod is publicly accessible.</strong>
|
|
||||||
<br>
|
|
||||||
Prevent public write and control access to the root
|
|
||||||
by modifying its <a href=".acl">ACL document</a>.
|
|
||||||
</p>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (registration) { %>
|
|
||||||
<% if (createPod) { %>
|
|
||||||
<h2>Your new Pod</h2>
|
|
||||||
<p>
|
|
||||||
Your new Pod is located at <a href="<%= podBaseUrl %>" class="link"><%= podBaseUrl %></a>.
|
|
||||||
<br>
|
|
||||||
You can store your documents and data there.
|
|
||||||
</p>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (createWebId) { %>
|
|
||||||
<h2>Your new WebID</h2>
|
|
||||||
<p>
|
|
||||||
Your new WebID is <a href="<%= webId %>" class="link"><%= webId %></a>.
|
|
||||||
<br>
|
|
||||||
You can use this identifier to interact with Solid pods and apps.
|
|
||||||
</p>
|
|
||||||
<% } %>
|
|
||||||
|
|
||||||
<% if (register) { %>
|
|
||||||
<h2>Your new account</h2>
|
|
||||||
<p>
|
|
||||||
Via your email address <em><%= email %></em>,
|
|
||||||
this server lets you log in to Solid apps
|
|
||||||
with your WebID <a href="<%= webId %>" class="link"><%= webId %></a>
|
|
||||||
</p>
|
|
||||||
<% if (!createWebId) { %>
|
|
||||||
<p>
|
|
||||||
You will need to add the triple
|
|
||||||
<code><%= `<${webId}> <http://www.w3.org/ns/solid/terms#oidcIssuer> <${oidcIssuer}>.`%></code>
|
|
||||||
to your existing WebID document <em><%= webId %></em>
|
|
||||||
to indicate that you trust this server as a login provider.
|
|
||||||
</p>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
||||||
<% } %>
|
|
@ -33,21 +33,24 @@ describe('A Solid server with setup', (): void => {
|
|||||||
it('catches all requests.', async(): Promise<void> => {
|
it('catches all requests.', async(): Promise<void> => {
|
||||||
let res = await fetch(baseUrl, { method: 'GET', headers: { accept: 'text/html' }});
|
let res = await fetch(baseUrl, { method: 'GET', headers: { accept: 'text/html' }});
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.url).toBe(setupUrl);
|
||||||
await expect(res.text()).resolves.toContain('Set up your Solid server');
|
await expect(res.text()).resolves.toContain('Set up your Solid server');
|
||||||
|
|
||||||
res = await fetch(joinUrl(baseUrl, '/random/path/'), { method: 'GET', headers: { accept: 'text/html' }});
|
res = await fetch(joinUrl(baseUrl, '/random/path/'), { method: 'GET', headers: { accept: 'text/html' }});
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.url).toBe(setupUrl);
|
||||||
await expect(res.text()).resolves.toContain('Set up your Solid server');
|
await expect(res.text()).resolves.toContain('Set up your Solid server');
|
||||||
|
|
||||||
res = await fetch(joinUrl(baseUrl, '/random/path/'), { method: 'PUT', headers: { accept: 'text/html' }});
|
res = await fetch(joinUrl(baseUrl, '/random/path/'), { method: 'PUT' });
|
||||||
expect(res.status).toBe(405);
|
expect(res.status).toBe(405);
|
||||||
await expect(res.text()).resolves.toContain('Set up your Solid server');
|
expect(res.url).toBe(setupUrl);
|
||||||
|
await expect(res.json()).resolves.toEqual(expect.objectContaining({ name: 'MethodNotAllowedHttpError' }));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('can create a server that disables root but allows registration.', async(): Promise<void> => {
|
it('can create a server that disables root but allows registration.', async(): Promise<void> => {
|
||||||
let res = await fetch(setupUrl, { method: 'POST', headers: { accept: 'text/html' }});
|
let res = await fetch(setupUrl, { method: 'POST' });
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
await expect(res.text()).resolves.toContain('Server setup complete');
|
await expect(res.json()).resolves.toEqual({ initialize: false, registration: false });
|
||||||
|
|
||||||
// Root access disabled
|
// Root access disabled
|
||||||
res = await fetch(baseUrl);
|
res = await fetch(baseUrl);
|
||||||
@ -57,7 +60,7 @@ describe('A Solid server with setup', (): void => {
|
|||||||
const registerParams = { email, podName, password, confirmPassword: password, createWebId: true };
|
const registerParams = { email, podName, password, confirmPassword: password, createWebId: true };
|
||||||
res = await fetch(joinUrl(baseUrl, 'idp/register/'), {
|
res = await fetch(joinUrl(baseUrl, 'idp/register/'), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { accept: 'text/html', 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify(registerParams),
|
body: JSON.stringify(registerParams),
|
||||||
});
|
});
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
@ -70,11 +73,11 @@ describe('A Solid server with setup', (): void => {
|
|||||||
it('can create a server with a public root.', async(): Promise<void> => {
|
it('can create a server with a public root.', async(): Promise<void> => {
|
||||||
let res = await fetch(setupUrl, {
|
let res = await fetch(setupUrl, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { accept: 'text/html', 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify({ initialize: true }),
|
body: JSON.stringify({ initialize: true }),
|
||||||
});
|
});
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
await expect(res.text()).resolves.toContain('Server setup complete');
|
await expect(res.json()).resolves.toEqual({ initialize: true, registration: false });
|
||||||
|
|
||||||
// Root access enabled
|
// Root access enabled
|
||||||
res = await fetch(baseUrl);
|
res = await fetch(baseUrl);
|
||||||
@ -85,7 +88,7 @@ describe('A Solid server with setup', (): void => {
|
|||||||
const registerParams = { email, podName, password, confirmPassword: password, createWebId: true, rootPod: true };
|
const registerParams = { email, podName, password, confirmPassword: password, createWebId: true, rootPod: true };
|
||||||
res = await fetch(joinUrl(baseUrl, 'idp/register/'), {
|
res = await fetch(joinUrl(baseUrl, 'idp/register/'), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { accept: 'text/html', 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify(registerParams),
|
body: JSON.stringify(registerParams),
|
||||||
});
|
});
|
||||||
expect(res.status).toBe(500);
|
expect(res.status).toBe(500);
|
||||||
@ -95,11 +98,19 @@ describe('A Solid server with setup', (): void => {
|
|||||||
const registerParams = { email, podName, password, confirmPassword: password, createWebId: true, rootPod: true };
|
const registerParams = { email, podName, password, confirmPassword: password, createWebId: true, rootPod: true };
|
||||||
let res = await fetch(setupUrl, {
|
let res = await fetch(setupUrl, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { accept: 'text/html', 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify({ registration: true, initialize: true, ...registerParams }),
|
body: JSON.stringify({ registration: true, initialize: true, ...registerParams }),
|
||||||
});
|
});
|
||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
await expect(res.text()).resolves.toContain('Server setup complete');
|
const json = await res.json();
|
||||||
|
expect(json).toEqual(expect.objectContaining({
|
||||||
|
registration: true,
|
||||||
|
initialize: false,
|
||||||
|
oidcIssuer: baseUrl,
|
||||||
|
webId: `${baseUrl}profile/card#me`,
|
||||||
|
email,
|
||||||
|
podBaseUrl: baseUrl,
|
||||||
|
}));
|
||||||
|
|
||||||
// Root profile created
|
// Root profile created
|
||||||
res = await fetch(joinUrl(baseUrl, '/profile/card'));
|
res = await fetch(joinUrl(baseUrl, '/profile/card'));
|
||||||
@ -109,7 +120,7 @@ describe('A Solid server with setup', (): void => {
|
|||||||
// Pod root is not accessible even though initialize was set to true
|
// Pod root is not accessible even though initialize was set to true
|
||||||
res = await fetch(joinUrl(baseUrl, 'resource'), {
|
res = await fetch(joinUrl(baseUrl, 'resource'), {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { accept: 'text/html', 'content-type': 'text/plain' },
|
headers: { 'content-type': 'text/plain' },
|
||||||
body: 'random data',
|
body: 'random data',
|
||||||
});
|
});
|
||||||
expect(res.status).toBe(401);
|
expect(res.status).toBe(401);
|
||||||
|
88
test/unit/init/setup/SetupHandler.test.ts
Normal file
88
test/unit/init/setup/SetupHandler.test.ts
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
import type { Operation } from '../../../../src/http/Operation';
|
||||||
|
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
|
||||||
|
import type { RegistrationResponse,
|
||||||
|
RegistrationManager } from '../../../../src/identity/interaction/email-password/util/RegistrationManager';
|
||||||
|
import type { Initializer } from '../../../../src/init/Initializer';
|
||||||
|
import { SetupHandler } from '../../../../src/init/setup/SetupHandler';
|
||||||
|
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
|
||||||
|
import { readJsonStream } from '../../../../src/util/StreamUtil';
|
||||||
|
|
||||||
|
describe('A SetupHandler', (): void => {
|
||||||
|
let operation: Operation;
|
||||||
|
let details: RegistrationResponse;
|
||||||
|
let registrationManager: jest.Mocked<RegistrationManager>;
|
||||||
|
let initializer: jest.Mocked<Initializer>;
|
||||||
|
let handler: SetupHandler;
|
||||||
|
|
||||||
|
beforeEach(async(): Promise<void> => {
|
||||||
|
operation = {
|
||||||
|
method: 'POST',
|
||||||
|
target: { path: 'http://example.com/setup' },
|
||||||
|
preferences: {},
|
||||||
|
body: new BasicRepresentation(),
|
||||||
|
};
|
||||||
|
|
||||||
|
initializer = {
|
||||||
|
handleSafe: jest.fn(),
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
details = {
|
||||||
|
email: 'alice@test.email',
|
||||||
|
createWebId: true,
|
||||||
|
register: true,
|
||||||
|
createPod: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
registrationManager = {
|
||||||
|
validateInput: jest.fn((input): any => input),
|
||||||
|
register: jest.fn().mockResolvedValue(details),
|
||||||
|
} as any;
|
||||||
|
|
||||||
|
handler = new SetupHandler({ registrationManager, initializer });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('error if no Initializer is defined and initialization is requested.', async(): Promise<void> => {
|
||||||
|
handler = new SetupHandler({});
|
||||||
|
operation.body = new BasicRepresentation(JSON.stringify({ initialize: true }), 'application/json');
|
||||||
|
await expect(handler.handle({ operation })).rejects.toThrow(NotImplementedHttpError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('error if no RegistrationManager is defined and registration is requested.', async(): Promise<void> => {
|
||||||
|
handler = new SetupHandler({});
|
||||||
|
operation.body = new BasicRepresentation(JSON.stringify({ registration: true }), 'application/json');
|
||||||
|
await expect(handler.handle({ operation })).rejects.toThrow(NotImplementedHttpError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls the Initializer when requested.', async(): Promise<void> => {
|
||||||
|
operation.body = new BasicRepresentation(JSON.stringify({ initialize: true }), 'application/json');
|
||||||
|
const result = await handler.handle({ operation });
|
||||||
|
await expect(readJsonStream(result.data)).resolves.toEqual({ initialize: true, registration: false });
|
||||||
|
expect(result.metadata.contentType).toBe('application/json');
|
||||||
|
expect(initializer.handleSafe).toHaveBeenCalledTimes(1);
|
||||||
|
expect(registrationManager.validateInput).toHaveBeenCalledTimes(0);
|
||||||
|
expect(registrationManager.register).toHaveBeenCalledTimes(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls the RegistrationManager when requested.', async(): Promise<void> => {
|
||||||
|
const body = { registration: true, email: 'test@example.com' };
|
||||||
|
operation.body = new BasicRepresentation(JSON.stringify(body), 'application/json');
|
||||||
|
const result = await handler.handle({ operation });
|
||||||
|
await expect(readJsonStream(result.data)).resolves.toEqual({ initialize: false, registration: true, ...details });
|
||||||
|
expect(result.metadata.contentType).toBe('application/json');
|
||||||
|
expect(initializer.handleSafe).toHaveBeenCalledTimes(0);
|
||||||
|
expect(registrationManager.validateInput).toHaveBeenCalledTimes(1);
|
||||||
|
expect(registrationManager.register).toHaveBeenCalledTimes(1);
|
||||||
|
expect(registrationManager.validateInput).toHaveBeenLastCalledWith(body, true);
|
||||||
|
expect(registrationManager.register).toHaveBeenLastCalledWith(body, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults to an empty JSON body if no data is provided.', async(): Promise<void> => {
|
||||||
|
operation.body = new BasicRepresentation();
|
||||||
|
const result = await handler.handle({ operation });
|
||||||
|
await expect(readJsonStream(result.data)).resolves.toEqual({ initialize: false, registration: false });
|
||||||
|
expect(result.metadata.contentType).toBe('application/json');
|
||||||
|
expect(initializer.handleSafe).toHaveBeenCalledTimes(0);
|
||||||
|
expect(registrationManager.validateInput).toHaveBeenCalledTimes(0);
|
||||||
|
expect(registrationManager.register).toHaveBeenCalledTimes(0);
|
||||||
|
});
|
||||||
|
});
|
@ -1,13 +1,8 @@
|
|||||||
import type { Operation } from '../../../../src/http/Operation';
|
import type { Operation } from '../../../../src/http/Operation';
|
||||||
import type { ErrorHandler, ErrorHandlerArgs } from '../../../../src/http/output/error/ErrorHandler';
|
|
||||||
import type { ResponseDescription } from '../../../../src/http/output/response/ResponseDescription';
|
|
||||||
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
|
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
|
||||||
import type { Representation } from '../../../../src/http/representation/Representation';
|
import type { Representation } from '../../../../src/http/representation/Representation';
|
||||||
import { RepresentationMetadata } from '../../../../src/http/representation/RepresentationMetadata';
|
import { RepresentationMetadata } from '../../../../src/http/representation/RepresentationMetadata';
|
||||||
import type { RegistrationManager,
|
import type { InteractionHandler } from '../../../../src/identity/interaction/InteractionHandler';
|
||||||
RegistrationResponse } from '../../../../src/identity/interaction/email-password/util/RegistrationManager';
|
|
||||||
import type { Initializer } from '../../../../src/init/Initializer';
|
|
||||||
import type { SetupInput } from '../../../../src/init/setup/SetupHttpHandler';
|
|
||||||
import { SetupHttpHandler } from '../../../../src/init/setup/SetupHttpHandler';
|
import { SetupHttpHandler } from '../../../../src/init/setup/SetupHttpHandler';
|
||||||
import type { HttpRequest } from '../../../../src/server/HttpRequest';
|
import type { HttpRequest } from '../../../../src/server/HttpRequest';
|
||||||
import type { HttpResponse } from '../../../../src/server/HttpResponse';
|
import type { HttpResponse } from '../../../../src/server/HttpResponse';
|
||||||
@ -15,25 +10,20 @@ import { getBestPreference } from '../../../../src/storage/conversion/Conversion
|
|||||||
import type { RepresentationConverterArgs,
|
import type { RepresentationConverterArgs,
|
||||||
RepresentationConverter } from '../../../../src/storage/conversion/RepresentationConverter';
|
RepresentationConverter } from '../../../../src/storage/conversion/RepresentationConverter';
|
||||||
import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage';
|
import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage';
|
||||||
import { APPLICATION_JSON } from '../../../../src/util/ContentTypes';
|
import { APPLICATION_JSON, APPLICATION_X_WWW_FORM_URLENCODED } from '../../../../src/util/ContentTypes';
|
||||||
import type { HttpError } from '../../../../src/util/errors/HttpError';
|
|
||||||
import { InternalServerError } from '../../../../src/util/errors/InternalServerError';
|
|
||||||
import { MethodNotAllowedHttpError } from '../../../../src/util/errors/MethodNotAllowedHttpError';
|
import { MethodNotAllowedHttpError } from '../../../../src/util/errors/MethodNotAllowedHttpError';
|
||||||
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
|
import { readableToString } from '../../../../src/util/StreamUtil';
|
||||||
import { guardedStreamFrom, readableToString } from '../../../../src/util/StreamUtil';
|
import type { TemplateEngine } from '../../../../src/util/templates/TemplateEngine';
|
||||||
import { CONTENT_TYPE, SOLID_META } from '../../../../src/util/Vocabularies';
|
import { CONTENT_TYPE } from '../../../../src/util/Vocabularies';
|
||||||
|
|
||||||
describe('A SetupHttpHandler', (): void => {
|
describe('A SetupHttpHandler', (): void => {
|
||||||
let request: HttpRequest;
|
const request: HttpRequest = {} as any;
|
||||||
const response: HttpResponse = {} as any;
|
const response: HttpResponse = {} as any;
|
||||||
let operation: Operation;
|
let operation: Operation;
|
||||||
const viewTemplate = '/templates/view';
|
|
||||||
const responseTemplate = '/templates/response';
|
|
||||||
const storageKey = 'completed';
|
const storageKey = 'completed';
|
||||||
let details: RegistrationResponse;
|
let representation: Representation;
|
||||||
let errorHandler: jest.Mocked<ErrorHandler>;
|
let interactionHandler: jest.Mocked<InteractionHandler>;
|
||||||
let registrationManager: jest.Mocked<RegistrationManager>;
|
let templateEngine: jest.Mocked<TemplateEngine>;
|
||||||
let initializer: jest.Mocked<Initializer>;
|
|
||||||
let converter: jest.Mocked<RepresentationConverter>;
|
let converter: jest.Mocked<RepresentationConverter>;
|
||||||
let storage: jest.Mocked<KeyValueStorage<string, any>>;
|
let storage: jest.Mocked<KeyValueStorage<string, any>>;
|
||||||
let handler: SetupHttpHandler;
|
let handler: SetupHttpHandler;
|
||||||
@ -41,32 +31,15 @@ describe('A SetupHttpHandler', (): void => {
|
|||||||
beforeEach(async(): Promise<void> => {
|
beforeEach(async(): Promise<void> => {
|
||||||
operation = {
|
operation = {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
target: { path: 'http://test.com/setup' },
|
target: { path: 'http://example.com/setup' },
|
||||||
preferences: { type: { 'text/html': 1 }},
|
preferences: {},
|
||||||
body: new BasicRepresentation(),
|
body: new BasicRepresentation(),
|
||||||
};
|
};
|
||||||
|
|
||||||
errorHandler = { handleSafe: jest.fn(({ error }: ErrorHandlerArgs): ResponseDescription => ({
|
templateEngine = {
|
||||||
statusCode: 400,
|
render: jest.fn().mockReturnValue(Promise.resolve('<html>')),
|
||||||
data: guardedStreamFrom(`{ "name": "${error.name}", "message": "${error.message}" }`),
|
|
||||||
})) } as any;
|
|
||||||
|
|
||||||
initializer = {
|
|
||||||
handleSafe: jest.fn(),
|
|
||||||
} as any;
|
|
||||||
|
|
||||||
details = {
|
|
||||||
email: 'alice@test.email',
|
|
||||||
createWebId: true,
|
|
||||||
register: true,
|
|
||||||
createPod: true,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
registrationManager = {
|
|
||||||
validateInput: jest.fn((input): any => input),
|
|
||||||
register: jest.fn().mockResolvedValue(details),
|
|
||||||
} as any;
|
|
||||||
|
|
||||||
converter = {
|
converter = {
|
||||||
handleSafe: jest.fn((input: RepresentationConverterArgs): Representation => {
|
handleSafe: jest.fn((input: RepresentationConverterArgs): Representation => {
|
||||||
// Just find the best match;
|
// Just find the best match;
|
||||||
@ -76,148 +49,71 @@ describe('A SetupHttpHandler', (): void => {
|
|||||||
}),
|
}),
|
||||||
} as any;
|
} as any;
|
||||||
|
|
||||||
|
representation = new BasicRepresentation();
|
||||||
|
interactionHandler = {
|
||||||
|
handleSafe: jest.fn().mockResolvedValue(representation),
|
||||||
|
} as any;
|
||||||
|
|
||||||
storage = new Map<string, any>() as any;
|
storage = new Map<string, any>() as any;
|
||||||
|
|
||||||
handler = new SetupHttpHandler({
|
handler = new SetupHttpHandler({
|
||||||
initializer,
|
|
||||||
registrationManager,
|
|
||||||
converter,
|
converter,
|
||||||
storageKey,
|
storageKey,
|
||||||
storage,
|
storage,
|
||||||
viewTemplate,
|
handler: interactionHandler,
|
||||||
responseTemplate,
|
templateEngine,
|
||||||
errorHandler,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Since all tests check similar things, the test functionality is generalized in here
|
it('only accepts GET and POST operations.', async(): Promise<void> => {
|
||||||
async function testPost(input: SetupInput, error?: HttpError): Promise<void> {
|
operation = {
|
||||||
operation.method = 'POST';
|
method: 'DELETE',
|
||||||
const initialize = Boolean(input.initialize);
|
target: { path: 'http://example.com/setup' },
|
||||||
const registration = Boolean(input.registration);
|
preferences: {},
|
||||||
const requestBody = { initialize, registration };
|
body: new BasicRepresentation(),
|
||||||
if (Object.keys(input).length > 0) {
|
};
|
||||||
operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json');
|
await expect(handler.handle({ operation, request, response })).rejects.toThrow(MethodNotAllowedHttpError);
|
||||||
}
|
});
|
||||||
|
|
||||||
|
it('calls the template engine for GET requests.', async(): Promise<void> => {
|
||||||
const result = await handler.handle({ operation, request, response });
|
const result = await handler.handle({ operation, request, response });
|
||||||
expect(result).toBeDefined();
|
expect(result.data).toBeDefined();
|
||||||
expect(initializer.handleSafe).toHaveBeenCalledTimes(!error && initialize ? 1 : 0);
|
await expect(readableToString(result.data!)).resolves.toBe('<html>');
|
||||||
expect(registrationManager.validateInput).toHaveBeenCalledTimes(!error && registration ? 1 : 0);
|
|
||||||
expect(registrationManager.register).toHaveBeenCalledTimes(!error && registration ? 1 : 0);
|
|
||||||
let expectedResult: any = { initialize, registration };
|
|
||||||
if (error) {
|
|
||||||
expectedResult = { name: error.name, message: error.message };
|
|
||||||
} else if (registration) {
|
|
||||||
Object.assign(expectedResult, details);
|
|
||||||
}
|
|
||||||
expect(JSON.parse(await readableToString(result.data!))).toEqual(expectedResult);
|
|
||||||
expect(result.statusCode).toBe(error?.statusCode ?? 200);
|
|
||||||
expect(result.metadata?.contentType).toBe('text/html');
|
expect(result.metadata?.contentType).toBe('text/html');
|
||||||
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(error ? viewTemplate : responseTemplate);
|
|
||||||
|
|
||||||
if (!error && registration) {
|
|
||||||
expect(registrationManager.validateInput).toHaveBeenLastCalledWith(requestBody, true);
|
|
||||||
expect(registrationManager.register).toHaveBeenLastCalledWith(requestBody, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
it('returns the view template on GET requests.', async(): Promise<void> => {
|
|
||||||
const result = await handler.handle({ operation, request, response });
|
|
||||||
expect(result).toBeDefined();
|
|
||||||
expect(JSON.parse(await readableToString(result.data!))).toEqual({});
|
|
||||||
expect(result.statusCode).toBe(200);
|
|
||||||
expect(result.metadata?.contentType).toBe('text/html');
|
|
||||||
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(viewTemplate);
|
|
||||||
|
|
||||||
// Setup is still enabled since this was a GET request
|
// Setup is still enabled since this was a GET request
|
||||||
expect(storage.get(storageKey)).toBeUndefined();
|
expect(storage.get(storageKey)).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('simply disables the handler if no setup is requested.', async(): Promise<void> => {
|
it('returns the handler result as 200 response.', async(): Promise<void> => {
|
||||||
await expect(testPost({ initialize: false, registration: false })).resolves.toBeUndefined();
|
operation.method = 'POST';
|
||||||
|
const result = await handler.handle({ operation, request, response });
|
||||||
|
expect(result.statusCode).toBe(200);
|
||||||
|
expect(result.data).toBe(representation.data);
|
||||||
|
expect(result.metadata).toBe(representation.metadata);
|
||||||
|
expect(interactionHandler.handleSafe).toHaveBeenCalledTimes(1);
|
||||||
|
expect(interactionHandler.handleSafe).toHaveBeenLastCalledWith({ operation });
|
||||||
|
|
||||||
// Handler is now disabled due to successful POST
|
// Handler is now disabled due to successful POST
|
||||||
expect(storage.get(storageKey)).toBe(true);
|
expect(storage.get(storageKey)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('defaults to an empty body if there is none.', async(): Promise<void> => {
|
it('converts input bodies to JSON.', async(): Promise<void> => {
|
||||||
await expect(testPost({})).resolves.toBeUndefined();
|
operation.method = 'POST';
|
||||||
});
|
operation.body.metadata.contentType = APPLICATION_X_WWW_FORM_URLENCODED;
|
||||||
|
|
||||||
it('calls the initializer when requested.', async(): Promise<void> => {
|
|
||||||
await expect(testPost({ initialize: true, registration: false })).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls the registrationManager when requested.', async(): Promise<void> => {
|
|
||||||
await expect(testPost({ initialize: false, registration: true })).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('converts non-HTTP errors to internal errors.', async(): Promise<void> => {
|
|
||||||
converter.handleSafe.mockRejectedValueOnce(new Error('bad data'));
|
|
||||||
const error = new InternalServerError('bad data');
|
|
||||||
await expect(testPost({ initialize: true, registration: false }, error)).resolves.toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('errors on non-GET/POST requests.', async(): Promise<void> => {
|
|
||||||
operation.method = 'PUT';
|
|
||||||
const requestBody = { initialize: true, registration: true };
|
|
||||||
operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json');
|
|
||||||
const error = new MethodNotAllowedHttpError();
|
|
||||||
|
|
||||||
const result = await handler.handle({ operation, request, response });
|
const result = await handler.handle({ operation, request, response });
|
||||||
expect(result).toBeDefined();
|
expect(result.statusCode).toBe(200);
|
||||||
expect(initializer.handleSafe).toHaveBeenCalledTimes(0);
|
expect(result.data).toBe(representation.data);
|
||||||
expect(registrationManager.register).toHaveBeenCalledTimes(0);
|
expect(result.metadata).toBe(representation.metadata);
|
||||||
expect(errorHandler.handleSafe).toHaveBeenCalledTimes(1);
|
expect(interactionHandler.handleSafe).toHaveBeenCalledTimes(1);
|
||||||
expect(errorHandler.handleSafe).toHaveBeenLastCalledWith({ error, preferences: { type: { [APPLICATION_JSON]: 1 }}});
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
|
const { body, ...partialOperation } = operation;
|
||||||
|
expect(interactionHandler.handleSafe).toHaveBeenLastCalledWith(
|
||||||
|
{ operation: expect.objectContaining(partialOperation) },
|
||||||
|
);
|
||||||
|
expect(interactionHandler.handleSafe.mock.calls[0][0].operation.body.metadata.contentType).toBe(APPLICATION_JSON);
|
||||||
|
|
||||||
expect(JSON.parse(await readableToString(result.data!))).toEqual({ name: error.name, message: error.message });
|
// Handler is now disabled due to successful POST
|
||||||
expect(result.statusCode).toBe(405);
|
expect(storage.get(storageKey)).toBe(true);
|
||||||
expect(result.metadata?.contentType).toBe('text/html');
|
|
||||||
expect(result.metadata?.get(SOLID_META.template)?.value).toBe(viewTemplate);
|
|
||||||
|
|
||||||
// Setup is not disabled since there was an error
|
|
||||||
expect(storage.get(storageKey)).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('errors when attempting registration when no RegistrationManager is defined.', async(): Promise<void> => {
|
|
||||||
handler = new SetupHttpHandler({
|
|
||||||
errorHandler,
|
|
||||||
initializer,
|
|
||||||
converter,
|
|
||||||
storageKey,
|
|
||||||
storage,
|
|
||||||
viewTemplate,
|
|
||||||
responseTemplate,
|
|
||||||
});
|
|
||||||
operation.method = 'POST';
|
|
||||||
const requestBody = { initialize: false, registration: true };
|
|
||||||
operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json');
|
|
||||||
const error = new NotImplementedHttpError('This server is not configured to support registration during setup.');
|
|
||||||
await expect(testPost({ initialize: false, registration: true }, error)).resolves.toBeUndefined();
|
|
||||||
|
|
||||||
// Setup is not disabled since there was an error
|
|
||||||
expect(storage.get(storageKey)).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('errors when attempting initialization when no Initializer is defined.', async(): Promise<void> => {
|
|
||||||
handler = new SetupHttpHandler({
|
|
||||||
errorHandler,
|
|
||||||
registrationManager,
|
|
||||||
converter,
|
|
||||||
storageKey,
|
|
||||||
storage,
|
|
||||||
viewTemplate,
|
|
||||||
responseTemplate,
|
|
||||||
});
|
|
||||||
operation.method = 'POST';
|
|
||||||
const requestBody = { initialize: true, registration: false };
|
|
||||||
operation.body = new BasicRepresentation(JSON.stringify(requestBody), 'application/json');
|
|
||||||
const error = new NotImplementedHttpError('This server is not configured with a setup initializer.');
|
|
||||||
await expect(testPost({ initialize: true, registration: false }, error)).resolves.toBeUndefined();
|
|
||||||
|
|
||||||
// Setup is not disabled since there was an error
|
|
||||||
expect(storage.get(storageKey)).toBeUndefined();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
Loading…
x
Reference in New Issue
Block a user