Ghost/ghost/admin/app/controllers/setup.js

155 lines
5.2 KiB
JavaScript
Raw Normal View History

import classic from 'ember-classic-decorator';
import {inject as service} from '@ember/service';
/* eslint-disable camelcase, ghost/ember/alias-model-in-controller */
import Controller, {inject as controller} from '@ember/controller';
import ValidationEngine from 'ghost-admin/mixins/validation-engine';
import {action} from '@ember/object';
import {htmlSafe} from '@ember/template';
Fixed hosting management screen not loading after sign-in process (#15763) refs https://github.com/TryGhost/Team/issues/2110 - dynamically defined properties on the config service did not have autotracking set up properly if they were accessed in any way before the property was defined, this caused problems in a number of areas because we have both "unauthed" and "authed" sets of config and when not logged in we had parts of the app checking for authed config properties that don't exist until after sign-in and subsequent config re-fetch - renamed `config` service to `configManager` and updated to only contain methods for fetching config data - added a `config` instance initializer that sets up a `TrackedObject` instance with some custom properties/methods and registers it on `config:main` - uses application instance initializer rather than a standard initializer because standard initializers are only called once when setting up the test suite so we'd end up with config leaking across tests - added an `@inject` decorator that when used takes the property name and injects whatever is registered at `${propertyName}:main`, this allows us to use dependency injection for any object rather than just services or controllers - using `application.inject()` in the initializer was initially used but that only works for objects that extend from `EmberObject`, the injections weren't available in native-class glimmer components so this decorator keeps the injection syntax consistent - swapped all `@service config` uses to `@inject config`
2022-11-03 14:14:36 +03:00
import {inject} from 'ghost-admin/decorators/inject';
import {isInvalidError} from 'ember-ajax/errors';
import {isVersionMismatchError} from 'ghost-admin/services/ajax';
import {task} from 'ember-concurrency';
@classic
export default class SetupController extends Controller.extend(ValidationEngine) {
@controller application;
@service ajax;
@service ghostPaths;
@service notifications;
@service router;
@service session;
Fixed hosting management screen not loading after sign-in process (#15763) refs https://github.com/TryGhost/Team/issues/2110 - dynamically defined properties on the config service did not have autotracking set up properly if they were accessed in any way before the property was defined, this caused problems in a number of areas because we have both "unauthed" and "authed" sets of config and when not logged in we had parts of the app checking for authed config properties that don't exist until after sign-in and subsequent config re-fetch - renamed `config` service to `configManager` and updated to only contain methods for fetching config data - added a `config` instance initializer that sets up a `TrackedObject` instance with some custom properties/methods and registers it on `config:main` - uses application instance initializer rather than a standard initializer because standard initializers are only called once when setting up the test suite so we'd end up with config leaking across tests - added an `@inject` decorator that when used takes the property name and injects whatever is registered at `${propertyName}:main`, this allows us to use dependency injection for any object rather than just services or controllers - using `application.inject()` in the initializer was initially used but that only works for objects that extend from `EmberObject`, the injections weren't available in native-class glimmer components so this decorator keeps the injection syntax consistent - swapped all `@service config` uses to `@inject config`
2022-11-03 14:14:36 +03:00
@inject config;
// ValidationEngine settings
validationType = 'setup';
blogCreated = false;
blogTitle = null;
email = '';
flowErrors = '';
name = null;
password = null;
@action
setup() {
this.setupTask.perform();
}
@action
preValidate(model) {
// Only triggers validation if a value has been entered, preventing empty errors on focusOut
if (this.get(model)) {
return this.validate({property: model});
}
}
@task(function* () {
return yield this._passwordSetup();
})
setupTask;
@task(function* (authStrategy, authentication) {
// we don't want to redirect after sign-in during setup
this.session.skipAuthSuccessHandler = true;
try {
yield this.session.authenticate(authStrategy, ...authentication);
this.errors.remove('session');
return true;
} catch (error) {
if (error && error.payload && error.payload.errors) {
if (isVersionMismatchError(error)) {
return this.notifications.showAPIError(error);
}
error.payload.errors.forEach((err) => {
err.message = htmlSafe(err.message);
});
this.set('flowErrors', error.payload.errors[0].message.string);
} else {
// Connection errors don't return proper status message, only req.body
this.notifications.showAlert('There was a problem on the server.', {type: 'error', key: 'session.authenticate.failed'});
}
return false;
}
})
authenticate;
_passwordSetup() {
let setupProperties = ['blogTitle', 'name', 'email', 'password'];
let data = this.getProperties(setupProperties);
let method = this.blogCreated ? 'put' : 'post';
this.set('flowErrors', '');
this.hasValidated.addObjects(setupProperties);
return this.validate().then(() => {
let authUrl = this.get('ghostPaths.url').api('authentication', 'setup');
return this.ajax[method](authUrl, {
data: {
setup: [{
name: data.name,
email: data.email,
password: data.password,
blogTitle: data.blogTitle
}]
}
}).then((result) => {
Fixed hosting management screen not loading after sign-in process (#15763) refs https://github.com/TryGhost/Team/issues/2110 - dynamically defined properties on the config service did not have autotracking set up properly if they were accessed in any way before the property was defined, this caused problems in a number of areas because we have both "unauthed" and "authed" sets of config and when not logged in we had parts of the app checking for authed config properties that don't exist until after sign-in and subsequent config re-fetch - renamed `config` service to `configManager` and updated to only contain methods for fetching config data - added a `config` instance initializer that sets up a `TrackedObject` instance with some custom properties/methods and registers it on `config:main` - uses application instance initializer rather than a standard initializer because standard initializers are only called once when setting up the test suite so we'd end up with config leaking across tests - added an `@inject` decorator that when used takes the property name and injects whatever is registered at `${propertyName}:main`, this allows us to use dependency injection for any object rather than just services or controllers - using `application.inject()` in the initializer was initially used but that only works for objects that extend from `EmberObject`, the injections weren't available in native-class glimmer components so this decorator keeps the injection syntax consistent - swapped all `@service config` uses to `@inject config`
2022-11-03 14:14:36 +03:00
this.config.blogTitle = data.blogTitle;
// don't try to login again if we are already logged in
if (this.get('session.isAuthenticated')) {
return this._afterAuthentication(result);
}
// Don't call the success handler, otherwise we will be redirected to admin
this.session.skipAuthSuccessHandler = true;
return this.session.authenticate('authenticator:cookie', data.email, data.password).then(() => {
this.set('blogCreated', true);
Improved authentication timing in setup flow https://github.com/TryGhost/Admin/pull/2286 - `session.authenticate()` returns from it's promise as soon as the authenticate request is completed but it was assumed that it returned after the `session.handleAuthentication()` promise was also completed. A side-effect of that was that depending on network timing, the setup flow could transition to the dashboard before we had loaded all of the necessary user, config, and settings requests - normally that's not a problem because `handleAuthentication()` kicks off a transition once authentication is fully complete, in the setup flow we're handling the transition manually so need a way to manage the full async flow from outside of the session service - it didn't show up as a problem previously because the setup flow transitioned to a third setup screen that didn't require all of the post-auth data to exist - moved the async parts of `session.handleAuthentication()` into a task and updated to return the currently running task instance if one was already running - lets code that is relying on the full authentication flow to have completed call `await this.session.handleAuthentication()` without causing a double-load of the post-auth API requests - updated setup flow - removed manual `session.populateUser()` call as that was a workaround for the async timing issue and caused a double-fetch of the current user API endpoint - added an `await this.session.handleAuthentication()` call to the manual post-auth handler so we don't transition until the full auth flow is complete
2022-03-10 14:53:30 +03:00
return this._afterAuthentication(result);
}).catch((error) => {
this._handleAuthenticationError(error);
});
}).catch((error) => {
this._handleSaveError(error);
});
}).catch(() => {
2022-03-08 23:23:49 +03:00
this.set('flowErrors', 'Please fill out every field correctly to set up your site.');
});
}
_handleSaveError(resp) {
if (isInvalidError(resp)) {
let [error] = resp.payload.errors;
this.set('flowErrors', [error.message, error.context].join(' '));
} else {
this.notifications.showAPIError(resp, {key: 'setup.blog-details'});
}
}
_handleAuthenticationError(error) {
if (error && error.payload && error.payload.errors) {
let [apiError] = error.payload.errors;
this.set('flowErrors', [apiError.message, apiError.context].join(' '));
} else {
// Connection errors don't return proper status message, only req.body
this.notifications.showAlert('There was a problem on the server.', {type: 'error', key: 'setup.authenticate.failed'});
}
}
async _afterAuthentication() {
Improved authentication timing in setup flow https://github.com/TryGhost/Admin/pull/2286 - `session.authenticate()` returns from it's promise as soon as the authenticate request is completed but it was assumed that it returned after the `session.handleAuthentication()` promise was also completed. A side-effect of that was that depending on network timing, the setup flow could transition to the dashboard before we had loaded all of the necessary user, config, and settings requests - normally that's not a problem because `handleAuthentication()` kicks off a transition once authentication is fully complete, in the setup flow we're handling the transition manually so need a way to manage the full async flow from outside of the session service - it didn't show up as a problem previously because the setup flow transitioned to a third setup screen that didn't require all of the post-auth data to exist - moved the async parts of `session.handleAuthentication()` into a task and updated to return the currently running task instance if one was already running - lets code that is relying on the full authentication flow to have completed call `await this.session.handleAuthentication()` without causing a double-load of the post-auth API requests - updated setup flow - removed manual `session.populateUser()` call as that was a workaround for the async timing issue and caused a double-fetch of the current user API endpoint - added an `await this.session.handleAuthentication()` call to the manual post-auth handler so we don't transition until the full auth flow is complete
2022-03-10 14:53:30 +03:00
await this.session.handleAuthentication();
return this.router.transitionTo('setup.done');
}
}