mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-21 18:01:36 +03:00
7b443d4b63
no issue The `config` service has been a source of confusion when writing with modern Ember patterns because it's use of the deprecated `ProxyMixin` forced all property access/setting to go via `.get()` and `.set()` whereas the rest of the system has mostly (there are a few other uses of ProxyObjects remaining) eliminated the use of the non-native get/set methods. - removed use of `ProxyMixin` in the `config` service by grabbing the API response after fetching and using `Object.defineProperty()` to add native getters/setters that pass through to a tracked object holding the API response data. Ember's autotracking automatically works across the native getters/setters so we can then use the service as if it was any other native object - updated all code to use `config.{attrName}` directly for getting/setting instead of `.get()` and `.set()` - removed unnecessary async around `config.availableTimezones` which wasn't making any async calls
63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
import Service, {inject as service} from '@ember/service';
|
|
import fetch from 'fetch';
|
|
import validator from 'validator';
|
|
|
|
export default class FrontendService extends Service {
|
|
@service settings;
|
|
@service config;
|
|
@service ajax;
|
|
|
|
_hasLoggedIn = false;
|
|
_lastPassword = null;
|
|
|
|
get hasPasswordChanged() {
|
|
return this._lastPassword !== this.settings.password;
|
|
}
|
|
|
|
getUrl(path) {
|
|
const siteUrl = new URL(this.config.blogUrl);
|
|
const subdir = siteUrl.pathname.endsWith('/') ? siteUrl.pathname : `${siteUrl.pathname}/`;
|
|
const fullPath = `${subdir}${path.replace(/^\//, '')}`;
|
|
|
|
return `${siteUrl.origin}${fullPath}`;
|
|
}
|
|
|
|
async loginIfNeeded() {
|
|
if (this.settings.isPrivate && (this.hasPasswordChanged || !this._hasLoggedIn)) {
|
|
const privateLoginUrl = this.getUrl('/private/?r=%2F');
|
|
this._lastPassword = this.settings.password;
|
|
|
|
return fetch(privateLoginUrl, {
|
|
method: 'POST',
|
|
mode: 'cors',
|
|
redirect: 'manual',
|
|
credentials: 'include',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
},
|
|
body: `password=${this._lastPassword}`
|
|
}).then(() => {
|
|
this._hasLoggedIn = true;
|
|
}).catch((e) => {
|
|
// Safari will error when x-site tracking is prevented and frontend/admin are separate
|
|
// we don't want to break anything else in that case so make it look like it succeeded
|
|
console.error(e); // eslint-disable-line
|
|
return true;
|
|
});
|
|
}
|
|
}
|
|
|
|
async fetch(urlOrPath, options) {
|
|
await this.loginIfNeeded();
|
|
let frontendUrl = urlOrPath;
|
|
if (!validator.isURL(urlOrPath)) {
|
|
frontendUrl = this.getUrl(urlOrPath);
|
|
}
|
|
return fetch(frontendUrl, {
|
|
mode: 'cors',
|
|
credentials: 'include',
|
|
...options
|
|
});
|
|
}
|
|
}
|