Skip to content

Commit

Permalink
WIP: Bitbucket provider (#280).
Browse files Browse the repository at this point in the history
  • Loading branch information
jimafisk committed Nov 13, 2024
1 parent fff52f8 commit c77170d
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 3 deletions.
22 changes: 19 additions & 3 deletions defaults/core/cms/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ if (provider === "gitea" || provider === "forgejo") {
authorization_endpoint = "/login/oauth/authorize";
access_token_endpoint = "/login/oauth/access_token";
}
if (provider === "bitbucket") {
//authorization_endpoint = "/rest/oauth2/latest/authorize";
//access_token_endpoint = "/rest/oauth2/latest/token";
authorization_endpoint = "/site/oauth2/authorize";
access_token_endpoint = "/site/oauth2/access_token";
}

const settings = {
provider: provider,
Expand Down Expand Up @@ -135,17 +141,27 @@ const requestAuthCode = async () => {

const requestAccessToken = async code => {
const { access_token_endpoint, server, redirectUrl, appId } = settings;
const params = new URLSearchParams({
client_id: appId,
code: code,
grant_type: 'authorization_code',
redirect_uri: redirectUrl,
code_verifier: codeVerifier
});
const response = await fetch(server + access_token_endpoint
/*
+ "?client_id=" + encodeURIComponent(appId)
+ "&code=" + encodeURIComponent(code)
+ "&grant_type=authorization_code"
+ "&redirect_uri=" + encodeURIComponent(redirectUrl)
+ "&code_verifier=" + encodeURIComponent(codeVerifier),
{
*/
,{
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
},
body: params.toString()
}
);
const tokens = await response.json();
Expand Down Expand Up @@ -178,4 +194,4 @@ const requestRefreshToken = async () => {
throw new Error(refreshedTokens.error_description);
}
tokenStore.set(refreshedTokens);
};
};
86 changes: 86 additions & 0 deletions defaults/core/cms/providers/bitbucket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { env } from '../../../generated/env.js';
import { makeUrl } from '../url_checker.js';
import evaluateRoute from '../route_eval.js';

const repoUrl = makeUrl(env.cms.repo);
const owner = repoUrl.pathname.split('/')[1];
const repo = repoUrl.pathname.split('/')[2];
const apiBaseUrl = `https://api.${repoUrl.host}/2.0/repositories`;
const branch = env.cms.branch;

const capitalizeFirstLetter = string => {
return string.charAt(0).toUpperCase() + string.slice(1);
}

/**
* @param {string} file
* @param {string} contents
* @param {string} action
*/
export async function commitBitbucket(commitList, shadowContent, action, encoding, user) {
// Keep track of current user and promise it's availability.
let currentUser;
const userAvailable = new Promise(resolve => {
user.subscribe(user => {
currentUser = user;
resolve();
});
});

await userAvailable;
if (!currentUser.isAuthenticated) {
throw new Error('Authentication required');
}

const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${currentUser.tokens.access_token}`,
};

for (const commitItem of commitList) {
//const url = `${apiBaseUrl}/${owner}/${repo}/src/${branch}/` + commitItem.file;
const url = `${apiBaseUrl}/${owner}/${repo}/src`;

const makeDataStr = base64Str => base64Str.split(',')[1];
let message = capitalizeFirstLetter(action) + ' ' + (commitList.length > 1 ? commitList.length + ' files' : commitList[0].file);
let content = encoding === "base64" ? makeDataStr(commitItem.contents) : btoa(unescape(encodeURIComponent(commitItem.contents)));

const payload = {
branch: branch,
message: message,
files: commitItem.file,
content: content,
};

let method = action === 'create' ? 'POST' : action === 'update' ? 'PUT' : action === 'delete' ? 'DELETE' : '';

const response = await fetch(url, {
method: method,
headers,
body: JSON.stringify(payload),
});
if (response.ok) {
if (action === 'create' || action === 'update') {
shadowContent?.onSave?.();
// Make sure saving single content file, not list of media items
if (commitList.length === 1 && commitList[0].file.lastIndexOf('.json') > 0) {
let evaluatedRoute = evaluateRoute(commitList[0]);
// Redirect only if new route is being created
if (evaluatedRoute !== location.pathname) {
history.pushState({
isNew: true,
route: evaluatedRoute
}, '', evaluatedRoute);
}
}
}
if (action === 'delete') {
shadowContent?.onDelete?.();
history.pushState(null, '', env.baseurl && !env.local ? env.baseurl : '/');
}
} else {
const { error, message } = await response.json();
throw new Error(`Publish failed: ${error || message}`);
}
};
}

0 comments on commit c77170d

Please sign in to comment.