Netlify auth (#194)
This commit is contained in:
@ -1,29 +1,34 @@
|
||||
import LocalForage from 'localforage';
|
||||
import MediaProxy from '../../valueObjects/MediaProxy';
|
||||
import { Base64 } from 'js-base64';
|
||||
import _ from 'lodash';
|
||||
import { SIMPLE, EDITORIAL_WORKFLOW, status } from '../../constants/publishModes';
|
||||
|
||||
const API_ROOT = 'https://api.github.com';
|
||||
import LocalForage from "localforage";
|
||||
import { Base64 } from "js-base64";
|
||||
import _ from "lodash";
|
||||
import MediaProxy from "../../valueObjects/MediaProxy";
|
||||
import { SIMPLE, EDITORIAL_WORKFLOW, status } from "../../constants/publishModes";
|
||||
|
||||
export default class API {
|
||||
constructor(token, repo, branch) {
|
||||
this.token = token;
|
||||
this.repo = repo;
|
||||
this.branch = branch;
|
||||
constructor(config) {
|
||||
this.api_root = config.api_root || "https://api.github.com";
|
||||
this.token = config.token || false;
|
||||
this.branch = config.branch || "master";
|
||||
this.repo = config.repo || "";
|
||||
this.repoURL = `/repos/${ this.repo }`;
|
||||
}
|
||||
|
||||
user() {
|
||||
return this.request('/user');
|
||||
return this.request("/user");
|
||||
}
|
||||
|
||||
requestHeaders(headers = {}) {
|
||||
return {
|
||||
Authorization: `token ${ this.token }`,
|
||||
'Content-Type': 'application/json',
|
||||
const baseHeader = {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
};
|
||||
|
||||
if (this.token) {
|
||||
baseHeader.Authorization = `token ${ this.token }`;
|
||||
return baseHeader;
|
||||
}
|
||||
|
||||
return baseHeader;
|
||||
}
|
||||
|
||||
parseJsonResponse(response) {
|
||||
@ -44,16 +49,16 @@ export default class API {
|
||||
}
|
||||
}
|
||||
if (params.length) {
|
||||
path += `?${ params.join('&') }`;
|
||||
path += `?${ params.join("&") }`;
|
||||
}
|
||||
return API_ROOT + path;
|
||||
return this.api_root + path;
|
||||
}
|
||||
|
||||
request(path, options = {}) {
|
||||
const headers = this.requestHeaders(options.headers || {});
|
||||
const url = this.urlFor(path, options);
|
||||
return fetch(url, { ...options, headers }).then((response) => {
|
||||
const contentType = response.headers.get('Content-Type');
|
||||
const contentType = response.headers.get("Content-Type");
|
||||
if (contentType && contentType.match(/json/)) {
|
||||
return this.parseJsonResponse(response);
|
||||
}
|
||||
@ -64,27 +69,28 @@ export default class API {
|
||||
|
||||
checkMetadataRef() {
|
||||
return this.request(`${ this.repoURL }/git/refs/meta/_netlify_cms?${ Date.now() }`, {
|
||||
cache: 'no-store',
|
||||
cache: "no-store",
|
||||
})
|
||||
.then(response => response.object)
|
||||
.catch((error) => {
|
||||
// Meta ref doesn't exist
|
||||
const readme = {
|
||||
raw: '# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.',
|
||||
raw: "# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.",
|
||||
};
|
||||
|
||||
return this.uploadBlob(readme)
|
||||
.then(item => this.request(`${ this.repoURL }/git/trees`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ tree: [{ path: 'README.md', mode: '100644', type: 'blob', sha: item.sha }] }),
|
||||
method: "POST",
|
||||
body: JSON.stringify({ tree: [{ path: "README.md", mode: "100644", type: "blob", sha: item.sha }] }),
|
||||
}))
|
||||
.then(tree => this.commit('First Commit', tree))
|
||||
.then(response => this.createRef('meta', '_netlify_cms', response.sha))
|
||||
.then(tree => this.commit("First Commit", tree))
|
||||
.then(response => this.createRef("meta", "_netlify_cms", response.sha))
|
||||
.then(response => response.object);
|
||||
});
|
||||
}
|
||||
|
||||
storeMetadata(key, data) {
|
||||
console.log('Trying to store Metadata');
|
||||
return this.checkMetadataRef()
|
||||
.then((branchData) => {
|
||||
const fileTree = {
|
||||
@ -96,9 +102,9 @@ export default class API {
|
||||
};
|
||||
|
||||
return this.uploadBlob(fileTree[`${ key }.json`])
|
||||
.then(item => this.updateTree(branchData.sha, '/', fileTree))
|
||||
.then(item => this.updateTree(branchData.sha, "/", fileTree))
|
||||
.then(changeTree => this.commit(`Updating “${ key }” metadata`, changeTree))
|
||||
.then(response => this.patchRef('meta', '_netlify_cms', response.sha))
|
||||
.then(response => this.patchRef("meta", "_netlify_cms", response.sha))
|
||||
.then(() => {
|
||||
LocalForage.setItem(`gh.meta.${ key }`, {
|
||||
expires: Date.now() + 300000, // In 5 minutes
|
||||
@ -114,9 +120,9 @@ export default class API {
|
||||
if (cached && cached.expires > Date.now()) { return cached.data; }
|
||||
console.log("%c Checking for MetaData files", "line-height: 30px;text-align: center;font-weight: bold"); // eslint-disable-line
|
||||
return this.request(`${ this.repoURL }/contents/${ key }.json`, {
|
||||
params: { ref: 'refs/meta/_netlify_cms' },
|
||||
headers: { Accept: 'application/vnd.github.VERSION.raw' },
|
||||
cache: 'no-store',
|
||||
params: { ref: "refs/meta/_netlify_cms" },
|
||||
headers: { Accept: "application/vnd.github.VERSION.raw" },
|
||||
cache: "no-store",
|
||||
})
|
||||
.then(response => JSON.parse(response))
|
||||
.catch(error => console.log("%c %s does not have metadata", "line-height: 30px;text-align: center;font-weight: bold", key)); // eslint-disable-line
|
||||
@ -129,7 +135,7 @@ export default class API {
|
||||
if (cached) { return cached; }
|
||||
|
||||
return this.request(`${ this.repoURL }/contents/${ path }`, {
|
||||
headers: { Accept: 'application/vnd.github.VERSION.raw' },
|
||||
headers: { Accept: "application/vnd.github.VERSION.raw" },
|
||||
params: { ref: branch },
|
||||
cache: false,
|
||||
}).then((result) => {
|
||||
@ -155,9 +161,7 @@ export default class API {
|
||||
return this.readFile(data.objects.entry, null, data.branch);
|
||||
})
|
||||
.then(fileData => ({ metaData, fileData }))
|
||||
.catch((error) => {
|
||||
return null;
|
||||
});
|
||||
.catch(error => null);
|
||||
return unpublishedPromise;
|
||||
}
|
||||
|
||||
@ -178,7 +182,7 @@ export default class API {
|
||||
files.forEach((file) => {
|
||||
if (file.uploaded) { return; }
|
||||
uploadPromises.push(this.uploadBlob(file));
|
||||
parts = file.path.split('/').filter(part => part);
|
||||
parts = file.path.split("/").filter(part => part);
|
||||
filename = parts.pop();
|
||||
subtree = fileTree;
|
||||
while (part = parts.shift()) {
|
||||
@ -191,7 +195,7 @@ export default class API {
|
||||
return Promise.all(uploadPromises).then(() => {
|
||||
if (!options.mode || (options.mode && options.mode === SIMPLE)) {
|
||||
return this.getBranch()
|
||||
.then(branchData => this.updateTree(branchData.commit.sha, '/', fileTree))
|
||||
.then(branchData => this.updateTree(branchData.commit.sha, "/", fileTree))
|
||||
.then(changeTree => this.commit(options.commitMessage, changeTree))
|
||||
.then(response => this.patchBranch(this.branch, response.sha));
|
||||
} else if (options.mode && options.mode === EDITORIAL_WORKFLOW) {
|
||||
@ -212,16 +216,13 @@ export default class API {
|
||||
const branchName = `cms/${ contentKey }`;
|
||||
|
||||
return this.getBranch()
|
||||
.then(branchData => this.updateTree(branchData.commit.sha, '/', fileTree))
|
||||
.then(branchData => this.updateTree(branchData.commit.sha, "/", fileTree))
|
||||
.then(changeTree => this.commit(options.commitMessage, changeTree))
|
||||
.then(commitResponse => this.createBranch(branchName, commitResponse.sha))
|
||||
.then(branchResponse => this.createPR(options.commitMessage, branchName))
|
||||
.then((prResponse) => {
|
||||
return this.user().then((user) => {
|
||||
return user.name ? user.name : user.login;
|
||||
})
|
||||
.then(prResponse => this.user().then(user => user.name ? user.name : user.login)
|
||||
.then(username => this.storeMetadata(contentKey, {
|
||||
type: 'PR',
|
||||
type: "PR",
|
||||
pr: {
|
||||
number: prResponse.number,
|
||||
head: prResponse.head && prResponse.head.sha,
|
||||
@ -237,19 +238,16 @@ export default class API {
|
||||
files: filesList,
|
||||
},
|
||||
timeStamp: new Date().toISOString(),
|
||||
}));
|
||||
});
|
||||
})));
|
||||
} else {
|
||||
// Entry is already on editorial review workflow - just update metadata and commit to existing branch
|
||||
return this.getBranch(branchName)
|
||||
.then(branchData => this.updateTree(branchData.commit.sha, '/', fileTree))
|
||||
.then(branchData => this.updateTree(branchData.commit.sha, "/", fileTree))
|
||||
.then(changeTree => this.commit(options.commitMessage, changeTree))
|
||||
.then((response) => {
|
||||
const contentKey = entry.slug;
|
||||
const branchName = `cms/${ contentKey }`;
|
||||
return this.user().then((user) => {
|
||||
return user.name ? user.name : user.login;
|
||||
})
|
||||
return this.user().then(user => user.name ? user.name : user.login)
|
||||
.then(username => this.retrieveMetadata(contentKey))
|
||||
.then((metadata) => {
|
||||
let files = metadata.objects && metadata.objects.files || [];
|
||||
@ -275,12 +273,10 @@ export default class API {
|
||||
updateUnpublishedEntryStatus(collection, slug, status) {
|
||||
const contentKey = slug;
|
||||
return this.retrieveMetadata(contentKey)
|
||||
.then((metadata) => {
|
||||
return {
|
||||
...metadata,
|
||||
status,
|
||||
};
|
||||
})
|
||||
.then(metadata => ({
|
||||
...metadata,
|
||||
status,
|
||||
}))
|
||||
.then(updatedMetadata => this.storeMetadata(contentKey, updatedMetadata));
|
||||
}
|
||||
|
||||
@ -297,21 +293,21 @@ export default class API {
|
||||
|
||||
createRef(type, name, sha) {
|
||||
return this.request(`${ this.repoURL }/git/refs`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ref: `refs/${ type }/${ name }`, sha }),
|
||||
});
|
||||
}
|
||||
|
||||
patchRef(type, name, sha) {
|
||||
return this.request(`${ this.repoURL }/git/refs/${ type }/${ name }`, {
|
||||
method: 'PATCH',
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ sha }),
|
||||
});
|
||||
}
|
||||
|
||||
deleteRef(type, name, sha) {
|
||||
return this.request(`${ this.repoURL }/git/refs/${ type }/${ name }`, {
|
||||
method: 'DELETE',
|
||||
method: "DELETE",
|
||||
});
|
||||
}
|
||||
|
||||
@ -320,30 +316,30 @@ export default class API {
|
||||
}
|
||||
|
||||
createBranch(branchName, sha) {
|
||||
return this.createRef('heads', branchName, sha);
|
||||
return this.createRef("heads", branchName, sha);
|
||||
}
|
||||
|
||||
patchBranch(branchName, sha) {
|
||||
return this.patchRef('heads', branchName, sha);
|
||||
return this.patchRef("heads", branchName, sha);
|
||||
}
|
||||
|
||||
deleteBranch(branchName) {
|
||||
return this.deleteRef('heads', branchName);
|
||||
return this.deleteRef("heads", branchName);
|
||||
}
|
||||
|
||||
createPR(title, head, base = 'master') {
|
||||
const body = 'Automatically generated by Netlify CMS';
|
||||
createPR(title, head, base = "master") {
|
||||
const body = "Automatically generated by Netlify CMS";
|
||||
return this.request(`${ this.repoURL }/pulls`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
body: JSON.stringify({ title, body, head, base }),
|
||||
});
|
||||
}
|
||||
|
||||
mergePR(headSha, number) {
|
||||
return this.request(`${ this.repoURL }/pulls/${ number }/merge`, {
|
||||
method: 'PUT',
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
commit_message: 'Automatically generated. Merged on Netlify CMS.',
|
||||
commit_message: "Automatically generated. Merged on Netlify CMS.",
|
||||
sha: headSha,
|
||||
}),
|
||||
});
|
||||
@ -362,19 +358,17 @@ export default class API {
|
||||
uploadBlob(item) {
|
||||
const content = item instanceof MediaProxy ? item.toBase64() : this.toBase64(item.raw);
|
||||
|
||||
return content.then((contentBase64) => {
|
||||
return this.request(`${ this.repoURL }/git/blobs`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
content: contentBase64,
|
||||
encoding: 'base64',
|
||||
}),
|
||||
}).then((response) => {
|
||||
item.sha = response.sha;
|
||||
item.uploaded = true;
|
||||
return item;
|
||||
});
|
||||
});
|
||||
return content.then(contentBase64 => this.request(`${ this.repoURL }/git/blobs`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
content: contentBase64,
|
||||
encoding: "base64",
|
||||
}),
|
||||
}).then((response) => {
|
||||
item.sha = response.sha;
|
||||
item.uploaded = true;
|
||||
return item;
|
||||
}));
|
||||
}
|
||||
|
||||
updateTree(sha, path, fileTree) {
|
||||
@ -402,19 +396,15 @@ export default class API {
|
||||
if (added[filename]) { continue; }
|
||||
updates.push(
|
||||
fileOrDir.file ?
|
||||
{ path: filename, mode: '100644', type: 'blob', sha: fileOrDir.sha } :
|
||||
{ path: filename, mode: "100644", type: "blob", sha: fileOrDir.sha } :
|
||||
this.updateTree(null, filename, fileOrDir)
|
||||
);
|
||||
}
|
||||
return Promise.all(updates)
|
||||
.then((updates) => {
|
||||
return this.request(`${ this.repoURL }/git/trees`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ base_tree: sha, tree: updates }),
|
||||
});
|
||||
}).then((response) => {
|
||||
return { path, mode: '040000', type: 'tree', sha: response.sha, parentSha: sha };
|
||||
});
|
||||
.then(updates => this.request(`${ this.repoURL }/git/trees`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ base_tree: sha, tree: updates }),
|
||||
})).then(response => ({ path, mode: "040000", type: "tree", sha: response.sha, parentSha: sha }));
|
||||
});
|
||||
}
|
||||
|
||||
@ -422,7 +412,7 @@ export default class API {
|
||||
const tree = changeTree.sha;
|
||||
const parents = changeTree.parentSha ? [changeTree.parentSha] : [];
|
||||
return this.request(`${ this.repoURL }/git/commits`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
body: JSON.stringify({ message, tree, parents }),
|
||||
});
|
||||
}
|
||||
|
@ -2,7 +2,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.button {
|
||||
|
@ -1,17 +1,19 @@
|
||||
import semaphore from 'semaphore';
|
||||
import AuthenticationPage from './AuthenticationPage';
|
||||
import API from './API';
|
||||
import semaphore from "semaphore";
|
||||
import AuthenticationPage from "./AuthenticationPage";
|
||||
import API from "./API";
|
||||
|
||||
const MAX_CONCURRENT_DOWNLOADS = 10;
|
||||
|
||||
export default class GitHub {
|
||||
constructor(config) {
|
||||
constructor(config, proxied = false) {
|
||||
this.config = config;
|
||||
if (config.getIn(['backend', 'repo']) == null) {
|
||||
throw new Error('The GitHub backend needs a "repo" in the backend configuration.');
|
||||
|
||||
if (!proxied && config.getIn(["backend", "repo"]) == null) {
|
||||
throw new Error("The GitHub backend needs a \"repo\" in the backend configuration.");
|
||||
}
|
||||
this.repo = config.getIn(['backend', 'repo']);
|
||||
this.branch = config.getIn(['backend', 'branch']) || 'master';
|
||||
|
||||
this.repo = config.getIn(["backend", "repo"], "");
|
||||
this.branch = config.getIn(["backend", "branch"], "master");
|
||||
}
|
||||
|
||||
authComponent() {
|
||||
@ -19,11 +21,11 @@ export default class GitHub {
|
||||
}
|
||||
|
||||
setUser(user) {
|
||||
this.api = new API(user.token, this.repo, this.branch || 'master');
|
||||
this.api = new API({ token: user.token, branch: this.branch, repo: this.repo });
|
||||
}
|
||||
|
||||
authenticate(state) {
|
||||
this.api = new API(state.token, this.repo, this.branch || 'master');
|
||||
this.api = new API({ token: state.token, branch: this.branch, repo: this.repo });
|
||||
return this.api.user().then((user) => {
|
||||
user.token = state.token;
|
||||
return user;
|
||||
@ -31,14 +33,14 @@ export default class GitHub {
|
||||
}
|
||||
|
||||
entriesByFolder(collection) {
|
||||
return this.api.listFiles(collection.get('folder'))
|
||||
return this.api.listFiles(collection.get("folder"))
|
||||
.then(this.fetchFiles);
|
||||
}
|
||||
|
||||
entriesByFiles(collection) {
|
||||
const files = collection.get('files').map(collectionFile => ({
|
||||
path: collectionFile.get('file'),
|
||||
label: collectionFile.get('label'),
|
||||
const files = collection.get("files").map(collectionFile => ({
|
||||
path: collectionFile.get("file"),
|
||||
label: collectionFile.get("label"),
|
||||
}));
|
||||
return this.fetchFiles(files);
|
||||
}
|
||||
@ -78,7 +80,7 @@ export default class GitHub {
|
||||
const promises = [];
|
||||
branches.map((branch) => {
|
||||
promises.push(new Promise((resolve, reject) => {
|
||||
const slug = branch.ref.split('refs/heads/cms/').pop();
|
||||
const slug = branch.ref.split("refs/heads/cms/").pop();
|
||||
return sem.take(() => this.api.readUnpublishedBranchFile(slug).then((data) => {
|
||||
if (data === null || data === undefined) {
|
||||
resolve(null);
|
||||
@ -102,7 +104,7 @@ export default class GitHub {
|
||||
return Promise.all(promises);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.message === 'Not Found') {
|
||||
if (error.message === "Not Found") {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
return error;
|
||||
|
Reference in New Issue
Block a user