forked from wdw21/songbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
255 lines (227 loc) · 8.78 KB
/
common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import {createOAuthUserAuth} from "@octokit/auth-app";
import {Octokit} from "@octokit/rest";
import {RequestError} from "@octokit/request-error";
import util from "util";
import {graphql} from "@octokit/graphql";
import crypto from "crypto";
import {oauthAuthorizationUrl} from "@octokit/oauth-authorization-url";
const USER_AGENT="songbook/0.1.0";
const OAUTH_APP_SECRET = process.env.OAUTH_APP_SECRET;
export const OAUTH_CLIENT_ID = process.env.OAUTH_CLIENT_ID;
export const BASE_URL = process.env.BASE_URL;
export const EDITOR_DOMAIN = process.env.EDITOR_DOMAIN;
export const EDITOR_PATH = process.env.EDITOR_PATH;
export const PARENT_DOMAIN = process.env.PARENT_DOMAIN;
export const EDITOR_BASE_URL = EDITOR_DOMAIN + EDITOR_PATH
export const CHANGES_BASE_URL = BASE_URL + "/changes";
export const REDIRECT_BASE_URL = BASE_URL + "/redirect";
export const CONFIG_BASE_URL = BASE_URL + "/config";
export const MAIN_BRANCH_NAME="songeditor-main";
export async function getFileFromBranch(octokit, user, branchName) {
let diff = await octokit.rest.repos.compareCommitsWithBasehead({
owner: 'wdw21',
repo: 'songbook',
basehead: `main...${user}:songbook:${branchName}`
});
return diff.data.files.length>0 ? diff.data.files[0].filename : null;
}
export function htmlPrefix(res) {
res.write(`<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" lang="pl-PL">
<head>
<meta charset="UTF-8">
<title>Edytor piosenek</title>
<script>
function deleteBranch(user, branch) {
if (confirm("Czy na pewno chcesz skasować zmianę: '" +branch + "'?")) {
let url='${BASE_URL}/users/' + user + '/changes/' + branch;
fetch(url, {method:'DELETE'})
.then(() => window.location.reload());
}
}
</script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="/editor.css" rel="stylesheet">
</head>
<body>
<div>
<a href="${EDITOR_DOMAIN}">[Piosenki]</a>
<a href="/users/me/changes:new">[Nowa]</a>
<a href="/changes">[Inne rozpoczęte edycje]</a>
</div>
`);
}
export function htmlSuffix(res) {
res.write(`
</body>
</html>`);
res.end();
}
function fullUrl(req) {
return new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
}
function stripProtocol(s) {
return s.replace("http://", "").replace("https://","");
}
function getBackUrl(req, backUrl) {
if (backUrl) {
console.log("Using back URL", backUrl);
return backUrl;
}
const u = fullUrl(req);
if (req.method=='GET' && !stripProtocol(u.href).startsWith(stripProtocol(REDIRECT_BASE_URL))) {
console.log("Using back URL based on req: ", u.href);
return u.href;
}
console.log("Using the default back URL:" + CHANGES_BASE_URL);
return CHANGES_BASE_URL;
}
export function clearCookiesAndAuthRedirect(res, backUrl) {
const state = crypto.randomUUID();
res.clearCookie("session", {domain: PARENT_DOMAIN});
res.cookie("state", state);
res.cookie("redirectUrl", backUrl);
const {url} =
oauthAuthorizationUrl({
clientType: "oauth-app",
clientId: OAUTH_CLIENT_ID,
redirectUrl: REDIRECT_BASE_URL,
scopes: ["public_repo"],
state: state,
});
res.redirect(url);
}
export async function newUserOctokit(req,res, backUrl) {
let access_token = req.cookies.session ? req.cookies.session.access_token
: null;
let authuser = req.cookies.session ? req.cookies.session.user : null;
// console.log("access token from cookie: ", access_token)
if (!access_token || !authuser) {
//TODO(ptab): Compare secret with the cookie.
const authData = {
clientId: OAUTH_CLIENT_ID,
clientSecret: OAUTH_APP_SECRET,
code: req.query.code,
state: req.query.state,
redirectUrl: REDIRECT_BASE_URL,
log: console,
};
const auth = await createOAuthUserAuth(authData);
try {
const {token} = await auth();
access_token = token;
} catch (e) {
console.log("Catched error(1):", e);
console.log("Catched error(2):", e.status, e instanceof RequestError);
clearCookiesAndAuthRedirect(res, getBackUrl(req, backUrl));
return {octkokit: null,authuser:null,user:null,mygraphql:null};
}
const octokit = new Octokit({
userAgent: USER_AGENT,
auth: access_token,
log: console,
});
const authenticated = await octokit.rest.users.getAuthenticated();
authuser = authenticated.data.login;
console.log(util.inspect(authenticated, false, null, false));
res.cookie("session", {
"access_token": access_token,
"user": authuser},
{ maxAge: 3*24*60*60*1000, httpOnly: true, sameSite:'none', secure: true, domain: PARENT_DOMAIN });
res.cookie("new", "false", { maxAge: 31536000});
}
const usr = (!req.params.user || req.params.user === 'me') ? authuser : req.params.user;
console.log('Acting as user:', usr);
return {
octokit: new Octokit({
userAgent: USER_AGENT,
auth: access_token,
log: console,
}),
mygraphql: graphql.defaults({
headers: {
"Authorization": "bearer " + access_token
},
}),
authuser: authuser,
user: usr
}
}
export async function fetchBranch(octokit, user, branchName) {
try {
console.log("fetchingBranch", user, branchName)
return await octokit.rest.repos.getBranch(
{owner: user, repo: 'songbook', 'branch': branchName});
} catch (e) {
if (e instanceof RequestError && e.status===404) {
console.log("fetchBranch returning null (due to 404)")
return null;
}
console.log("Rethrowing e", JSON.stringify(e))
throw e;
}
}
export async function prepareMainBranch(octokit, user) {
let branch = await fetchBranch(octokit, user, MAIN_BRANCH_NAME);
if (!branch) {
// let originBranch = await fetchBranch(octokit, 'wdw21', 'main');
// console.log(util.inspect(originBranch, false, null, false));
// We use really old commit as (originBranch.data.commit.sha) was sometimes not pulled from the repository.
await octokit.rest.git.createRef({owner: user, repo: 'songbook', "ref": "refs/heads/" + MAIN_BRANCH_NAME, "sha": 'c21af496c93eecd96902d8ee01c994b9ec2e8157'});
const res = await octokit.request('POST /repos/{owner}/{repo}/pulls', {
owner: user,
repo: 'songbook',
title: 'Automated creation of songbook-main branch.',
body: 'Should get automatically merged.',
head: 'wdw21:songbook:main',
base: MAIN_BRANCH_NAME
})
console.log("Creating pull request", JSON.stringify(res));
const merge = await octokit.request('PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge', {
owner: user,
repo: 'songbook',
pull_number: res.data.number
})
console.log("Merging", JSON.stringify(merge));
}
await octokit.rest.repos.mergeUpstream({owner: user, repo: 'songbook', 'branch': MAIN_BRANCH_NAME});
return fetchBranch(octokit, user, MAIN_BRANCH_NAME);
}
export async function prepareBranch(octokit, user, branchName) {
console.log("prepareBranch")
let branch = await fetchBranch(octokit, user, branchName);
if (branch) {
return branch;
}
let mainBranch = await prepareMainBranch(octokit, user);
console.log("prepareBranch (main): ", JSON.stringify(mainBranch));
await octokit.rest.git.createRef({owner: user, repo: 'songbook', "ref": "refs/heads/" + branchName, "sha": mainBranch.data.commit.sha});
return fetchBranch(octokit, user, branchName);
}
export function editorLink(user, branchName, file, autocommit, maybeNew) {
let url = new URL(EDITOR_BASE_URL);
url.searchParams.set('baseUrl', BASE_URL);
url.searchParams.set('branch', branchName);
url.searchParams.set('file', file);
url.searchParams.set('user', user);
if (autocommit) {
url.searchParams.set('commitOnLoad', 'true');
}
if (maybeNew) {
url.searchParams.set('new', 'maybe');
}
return url.href;
}
export function HandleError(e, res) {
console.log("HttpError", e);
if (!res.headersSent && e instanceof RequestError && e.status===401) {
// HttpError RequestError [HttpError]: Bad credentials
res.redirect('/auth');
return;
}
if (!res.responsesSent) {
res.send(`<hr/><detail><summery>Error</summery><pre>`);
// res.send(util.inspect(e, false, null, false));
res.end(`</pre></detail></body></html>`);
}
}