Skip to content

Commit

Permalink
feat: OAuth for Backstage
Browse files Browse the repository at this point in the history
Signed-off-by: Andrea Falzetti <[email protected]>
  • Loading branch information
loujaybee authored and andreafalzetti committed Jul 14, 2021
1 parent 5238afe commit 890cd5c
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 17 deletions.
6 changes: 6 additions & 0 deletions .changeset/angry-spies-approve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@backstage/plugin-scaffolder': patch
'@backstage/plugin-scaffolder-backend': patch
---

Use GitHub OAuth in Scaffolder
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export function createPublishGithubAction(options: {
}

const client = new Octokit({
auth: token,
auth: ctx.token ?? token,
baseUrl: integrationConfig.config.apiBaseUrl,
previews: ['nebula-preview'],
});
Expand Down Expand Up @@ -250,9 +250,15 @@ export function createPublishGithubAction(options: {
const remoteUrl = newRepo.clone_url;
const repoContentsUrl = `${newRepo.html_url}/blob/${defaultBranch}`;

const authenticatedUser = await client.users.getAuthenticated();

const gitAuthorInfo = {
name: config.getOptionalString('scaffolder.defaultAuthor.name'),
email: config.getOptionalString('scaffolder.defaultAuthor.email'),
name:
authenticatedUser?.data?.name ??
config.getOptionalString('scaffolder.defaultAuthor.name'),
email:
authenticatedUser?.data?.email ??
config.getOptionalString('scaffolder.defaultAuthor.email'),
};

await initRepoAndPush({
Expand All @@ -261,7 +267,7 @@ export function createPublishGithubAction(options: {
defaultBranch,
auth: {
username: 'x-access-token',
password: token,
password: ctx.token ?? token,
},
logger: ctx.logger,
gitAuthorInfo,
Expand Down
4 changes: 2 additions & 2 deletions plugins/scaffolder/api-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export interface ScaffolderApi {
): Promise<TemplateParameterSchema>;
// (undocumented)
listActions(): Promise<ListActionsResponse>;
scaffold(templateName: string, values: Record<string, any>): Promise<string>;
scaffold(templateName: string, values: Record<string, any>, githubAccessToken?: string): Promise<string>;
// (undocumented)
streamLogs({
taskId,
Expand Down Expand Up @@ -114,7 +114,7 @@ export class ScaffolderClient implements ScaffolderApi {
): Promise<TemplateParameterSchema>;
// (undocumented)
listActions(): Promise<ListActionsResponse>;
scaffold(templateName: string, values: Record<string, any>): Promise<string>;
scaffold(templateName: string, values: Record<string, any>, githubAccessToken: string): Promise<string>;
// (undocumented)
streamLogs({
taskId,
Expand Down
10 changes: 8 additions & 2 deletions plugins/scaffolder/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,13 @@ export interface ScaffolderApi {
*
* @param templateName Name of the Template entity for the scaffolder to use. New project is going to be created out of this template.
* @param values Parameters for the template, e.g. name, description
* @param [githubAccessToken] GitHub User access token
*/
scaffold(templateName: string, values: Record<string, any>): Promise<string>;
scaffold(
templateName: string,
values: Record<string, any>,
githubAccessToken?: string,
): Promise<string>;

getTask(taskId: string): Promise<ScaffolderTask>;

Expand Down Expand Up @@ -153,8 +158,9 @@ export class ScaffolderClient implements ScaffolderApi {
async scaffold(
templateName: string,
values: Record<string, any>,
githubAccessToken: string,
): Promise<string> {
const token = await this.identityApi.getIdToken();
const token = githubAccessToken ?? (await this.identityApi.getIdToken());
const url = `${await this.discoveryApi.getBaseUrl('scaffolder')}/v2/tasks`;
const response = await fetch(url, {
method: 'POST',
Expand Down
45 changes: 36 additions & 9 deletions plugins/scaffolder/src/components/TemplatePage/TemplatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,16 @@
import { JsonObject, JsonValue } from '@backstage/config';
import { LinearProgress } from '@material-ui/core';
import { FormValidation, IChangeEvent } from '@rjsf/core';
import React, { useCallback, useState } from 'react';
import {
githubAuthApiRef,
ApiHolder,
configApiRef,
errorApiRef,
useApi,
useApiHolder,
useRouteRef,
} from '@backstage/core-plugin-api';
import React, { useCallback, useState, useEffect } from 'react';
import { generatePath, Navigate, useNavigate } from 'react-router';
import { useParams } from 'react-router-dom';
import { useAsync } from 'react-use';
Expand All @@ -32,13 +41,6 @@ import {
Lifecycle,
Page,
} from '@backstage/core-components';
import {
ApiHolder,
errorApiRef,
useApi,
useApiHolder,
useRouteRef,
} from '@backstage/core-plugin-api';

const useTemplateParameterSchema = (templateName: string) => {
const scaffolderApi = useApi(scaffolderApiRef);
Expand Down Expand Up @@ -113,6 +115,7 @@ export const TemplatePage = ({
}: {
customFieldExtensions?: FieldExtensionOptions[];
}) => {
const configApi = useApi(configApiRef);
const apiHolder = useApiHolder();
const errorApi = useApi(errorApiRef);
const scaffolderApi = useApi(scaffolderApiRef);
Expand All @@ -127,9 +130,33 @@ export const TemplatePage = ({
[setFormState],
);

const [githubAccessToken, setGithubAccessToken] = useState('');
const githubAuth = useApi(githubAuthApiRef);

const githubConfig = configApi.getOptionalConfig('auth.providers.github');

useEffect(() => {
const fetchGithubUserInfo = async () => {
const accessToken = await githubAuth.getAccessToken([
'repo',
'user',
'workflow',
]);
setGithubAccessToken(accessToken);
};

if (githubConfig && !githubAccessToken) {
fetchGithubUserInfo();
}
});

const handleCreate = async () => {
try {
const id = await scaffolderApi.scaffold(templateName, formState);
const id = await scaffolderApi.scaffold(
templateName,
formState,
githubAccessToken,
);

navigate(generatePath(`${rootLink()}/tasks/:taskId`, { taskId: id }));
} catch (e) {
Expand Down

0 comments on commit 890cd5c

Please sign in to comment.