2022-01-21 22:25:47 +03:00
|
|
|
import Service, {inject as service} from '@ember/service';
|
2021-10-28 15:59:41 +03:00
|
|
|
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() {
|
2022-10-07 16:23:21 +03:00
|
|
|
return this._lastPassword !== this.settings.password;
|
2021-10-28 15:59:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
getUrl(path) {
|
2022-10-07 17:24:03 +03:00
|
|
|
const siteUrl = new URL(this.config.blogUrl);
|
2021-10-28 15:59:41 +03:00
|
|
|
const subdir = siteUrl.pathname.endsWith('/') ? siteUrl.pathname : `${siteUrl.pathname}/`;
|
|
|
|
const fullPath = `${subdir}${path.replace(/^\//, '')}`;
|
|
|
|
|
|
|
|
return `${siteUrl.origin}${fullPath}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
async loginIfNeeded() {
|
2022-10-07 16:23:21 +03:00
|
|
|
if (this.settings.isPrivate && (this.hasPasswordChanged || !this._hasLoggedIn)) {
|
2021-10-28 15:59:41 +03:00
|
|
|
const privateLoginUrl = this.getUrl('/private/?r=%2F');
|
2022-10-07 16:23:21 +03:00
|
|
|
this._lastPassword = this.settings.password;
|
2021-11-09 18:38:48 +03:00
|
|
|
|
2021-10-28 15:59:41 +03:00
|
|
|
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;
|
2021-11-09 18:38:48 +03:00
|
|
|
}).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;
|
2021-10-28 15:59:41 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|