fix: ghToken in session now

This commit is contained in:
Andras Bacsai
2022-02-18 15:29:32 +01:00
parent 2ce64ac213
commit 906a63b6b5
8 changed files with 37 additions and 39 deletions

1
src/app.d.ts vendored
View File

@@ -18,6 +18,7 @@ interface SessionData {
isAdmin?: boolean; isAdmin?: boolean;
expires?: string | null; expires?: string | null;
gitlabToken?: string | null; gitlabToken?: string | null;
ghToken?: string | null;
} }
type DateTimeFormatOptions = { type DateTimeFormatOptions = {

View File

@@ -17,7 +17,7 @@ export const handle = handleSession(
let response; let response;
try { try {
let gitlabToken = event.locals.cookies.gitlabToken; let gitlabToken = event.locals.cookies.gitlabToken;
let ghToken = event.locals.cookies.ghToken;
if (event.locals.cookies['kit.session']) { if (event.locals.cookies['kit.session']) {
const { permission, teamId, userId } = await getUserDetails(event, false); const { permission, teamId, userId } = await getUserDetails(event, false);
const newSession = { const newSession = {
@@ -26,7 +26,8 @@ export const handle = handleSession(
permission, permission,
isAdmin: permission === 'admin' || permission === 'owner', isAdmin: permission === 'admin' || permission === 'owner',
expires: event.locals.session.data.expires, expires: event.locals.session.data.expires,
gitlabToken: gitlabToken gitlabToken,
ghToken
}; };
if (JSON.stringify(event.locals.session.data) !== JSON.stringify(newSession)) { if (JSON.stringify(event.locals.session.data) !== JSON.stringify(newSession)) {

View File

@@ -17,7 +17,7 @@
const endpoint = `/applications/${params.id}.json`; const endpoint = `/applications/${params.id}.json`;
const res = await fetch(endpoint); const res = await fetch(endpoint);
if (res.ok) { if (res.ok) {
const { application, githubToken, ghToken, isRunning, appId } = await res.json(); const { application, isRunning, appId } = await res.json();
if (!application || Object.entries(application).length === 0) { if (!application || Object.entries(application).length === 0) {
return { return {
status: 302, status: 302,
@@ -42,8 +42,6 @@
}, },
stuff: { stuff: {
isRunning, isRunning,
ghToken,
githubToken,
application, application,
appId appId
} }

View File

@@ -1,13 +1,11 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
export let githubToken;
export let application; export let application;
import { page } from '$app/stores'; import { page, session } from '$app/stores';
import { get, post } from '$lib/api'; import { get, post } from '$lib/api';
import { getGithubToken } from '$lib/components/common'; import { errorNotification } from '$lib/form';
import { enhance, errorNotification } from '$lib/form';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
const { id } = $page.params; const { id } = $page.params;
@@ -30,19 +28,16 @@
branch: undefined branch: undefined
}; };
let showSave = false; let showSave = false;
let token = null;
async function loadRepositoriesByPage(page = 0) { async function loadRepositoriesByPage(page = 0) {
try { try {
return await get(`${apiUrl}/installation/repositories?per_page=100&page=${page}`, { return await get(`${apiUrl}/installation/repositories?per_page=100&page=${page}`, {
Authorization: `token ${token}` Authorization: `token ${$session.ghToken}`
}); });
} catch ({ error }) { } catch ({ error }) {
return errorNotification(error); return errorNotification(error);
} }
} }
async function loadRepositories() { async function loadRepositories() {
token = await getGithubToken({ apiUrl, githubToken, application });
let page = 1; let page = 1;
let reposCount = 0; let reposCount = 0;
const loadedRepos = await loadRepositoriesByPage(); const loadedRepos = await loadRepositoriesByPage();
@@ -63,7 +58,7 @@
selected.projectId = repositories.find((repo) => repo.full_name === selected.repository).id; selected.projectId = repositories.find((repo) => repo.full_name === selected.repository).id;
try { try {
branches = await get(`${apiUrl}/repos/${selected.repository}/branches`, { branches = await get(`${apiUrl}/repos/${selected.repository}/branches`, {
Authorization: `token ${token}` Authorization: `token ${$session.ghToken}`
}); });
return; return;
} catch ({ error }) { } catch ({ error }) {

View File

@@ -1,7 +1,7 @@
<script context="module" lang="ts"> <script context="module" lang="ts">
import type { Load } from '@sveltejs/kit'; import type { Load } from '@sveltejs/kit';
export const load: Load = async ({ fetch, params, url, stuff }) => { export const load: Load = async ({ fetch, params, url, stuff }) => {
const { application, ghToken } = stuff; const { application } = stuff;
if (application?.buildPack && !url.searchParams.get('from')) { if (application?.buildPack && !url.searchParams.get('from')) {
return { return {
status: 302, status: 302,
@@ -14,8 +14,7 @@
return { return {
props: { props: {
...(await res.json()), ...(await res.json()),
application, application
ghToken
} }
}; };
} }
@@ -43,7 +42,6 @@
export let projectId; export let projectId;
export let repository; export let repository;
export let branch; export let branch;
export let ghToken;
export let type; export let type;
export let application; export let application;
@@ -96,7 +94,7 @@
} }
} else if (type === 'github') { } else if (type === 'github') {
const files = await get(`${apiUrl}/repos/${repository}/contents?ref=${branch}`, { const files = await get(`${apiUrl}/repos/${repository}/contents?ref=${branch}`, {
Authorization: `Bearer ${ghToken}`, Authorization: `Bearer ${$session.ghToken || ghToken}`,
Accept: 'application/vnd.github.v2.json' Accept: 'application/vnd.github.v2.json'
}); });
const packageJson = files.find( const packageJson = files.find(
@@ -113,7 +111,7 @@
foundConfig.buildPack = 'docker'; foundConfig.buildPack = 'docker';
} else if (packageJson) { } else if (packageJson) {
const data = await get(`${packageJson.git_url}`, { const data = await get(`${packageJson.git_url}`, {
Authorization: `Bearer ${ghToken}`, Authorization: `Bearer ${$session.ghToken}`,
Accept: 'application/vnd.github.v2.raw' Accept: 'application/vnd.github.v2.raw'
}); });
const json = JSON.parse(data) || {}; const json = JSON.parse(data) || {};

View File

@@ -1,7 +1,7 @@
<script context="module" lang="ts"> <script context="module" lang="ts">
import type { Load } from '@sveltejs/kit'; import type { Load } from '@sveltejs/kit';
export const load: Load = async ({ params, url, stuff }) => { export const load: Load = async ({ params, url, stuff }) => {
const { application, githubToken, appId } = stuff; const { application, appId } = stuff;
if (application?.branch && application?.repository && !url.searchParams.get('from')) { if (application?.branch && application?.repository && !url.searchParams.get('from')) {
return { return {
status: 302, status: 302,
@@ -10,7 +10,6 @@
} }
return { return {
props: { props: {
githubToken,
application, application,
appId appId
} }
@@ -20,7 +19,6 @@
<script lang="ts"> <script lang="ts">
export let application; export let application;
export let githubToken;
export let appId; export let appId;
import GithubRepositories from './_GithubRepositories.svelte'; import GithubRepositories from './_GithubRepositories.svelte';
import GitlabRepositories from './_GitlabRepositories.svelte'; import GitlabRepositories from './_GitlabRepositories.svelte';
@@ -31,7 +29,7 @@
</div> </div>
<div class="flex flex-wrap justify-center"> <div class="flex flex-wrap justify-center">
{#if application.gitSource.type === 'github'} {#if application.gitSource.type === 'github'}
<GithubRepositories {application} {githubToken} /> <GithubRepositories {application} />
{:else if application.gitSource.type === 'gitlab'} {:else if application.gitSource.type === 'gitlab'}
<GitlabRepositories {application} {appId} /> <GitlabRepositories {application} {appId} />
{/if} {/if}

View File

@@ -14,34 +14,41 @@ export const get: RequestHandler = async (event) => {
let githubToken = null; let githubToken = null;
let ghToken = null; let ghToken = null;
let isRunning = false; let isRunning = false;
const { id } = event.params; const { id } = event.params;
try { try {
const application = await db.getApplication({ id, teamId }); const application = await db.getApplication({ id, teamId });
const { gitSource } = application; const { gitSource } = application;
if (gitSource?.type === 'github' && gitSource?.githubApp) { if (gitSource?.type === 'github' && gitSource?.githubApp) {
const payload = { if (!event.locals.session.data.ghToken) {
iat: Math.round(new Date().getTime() / 1000), const payload = {
exp: Math.round(new Date().getTime() / 1000 + 60), iat: Math.round(new Date().getTime() / 1000),
iss: gitSource.githubApp.appId exp: Math.round(new Date().getTime() / 1000 + 600),
}; iss: gitSource.githubApp.appId
githubToken = jsonwebtoken.sign(payload, gitSource.githubApp.privateKey, { };
algorithm: 'RS256' githubToken = jsonwebtoken.sign(payload, gitSource.githubApp.privateKey, {
}); algorithm: 'RS256'
ghToken = await getGithubToken({ apiUrl: gitSource.apiUrl, application, githubToken }); });
ghToken = await getGithubToken({ apiUrl: gitSource.apiUrl, application, githubToken });
}
} }
if (application.destinationDockerId) { if (application.destinationDockerId) {
isRunning = await checkContainer(application.destinationDocker.engine, id); isRunning = await checkContainer(application.destinationDocker.engine, id);
} }
return { const payload = {
body: { body: {
isRunning, isRunning,
ghToken,
githubToken,
application, application,
appId appId
} },
headers: {}
}; };
if (ghToken) {
payload.headers = {
'set-cookie': [`ghToken=${ghToken}; HttpOnly; Path=/; Max-Age=15778800;`]
};
}
return payload;
} catch (error) { } catch (error) {
console.log(error); console.log(error);
return ErrorHandler(error); return ErrorHandler(error);

View File

@@ -42,7 +42,7 @@
import Explainer from '$lib/components/Explainer.svelte'; import Explainer from '$lib/components/Explainer.svelte';
import Setting from '$lib/components/Setting.svelte'; import Setting from '$lib/components/Setting.svelte';
import type Prisma from '@prisma/client'; import type Prisma from '@prisma/client';
import { getDomain, notNodeDeployments, staticDeployments } from '$lib/components/common'; import { notNodeDeployments, staticDeployments } from '$lib/components/common';
import { toast } from '@zerodevx/svelte-toast'; import { toast } from '@zerodevx/svelte-toast';
import { post } from '$lib/api'; import { post } from '$lib/api';
const { id } = $page.params; const { id } = $page.params;