Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: OAuth for Backstage #2

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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