mirror of
https://github.com/outline/outline.git
synced 2026-11-28 00:09:58 +03:00
exchange code for access_token and persist
This commit is contained in:
1 parent
a9612f1e61
commit
97e4c2dfd6
6 files changed
+189
-4
No files matched your search
@@ -0,0 +1,102 @@
|
||||
import Router from "koa-router";
|
||||
import { IntegrationService, IntegrationType } from "@shared/types";
|
||||
import { parseDomain } from "@shared/utils/domains";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import { transaction } from "@server/middlewares/transaction";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { Integration, IntegrationAuthentication, Team } from "@server/models";
|
||||
import { APIContext } from "@server/types";
|
||||
import { NotionOAuth } from "../oauth";
|
||||
import * as T from "./schema";
|
||||
import { NotionUtils } from "plugins/notion/shared/NotionUtils";
|
||||
|
||||
const router = new Router();
|
||||
|
||||
router.get(
|
||||
"notion.callback",
|
||||
auth({ optional: true }),
|
||||
validate(T.NotionCallbackSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.NotionCallbackReq>) => {
|
||||
const { code, state, error } = ctx.input.query;
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
|
||||
if (error) {
|
||||
ctx.redirect(NotionUtils.errorUrl(error));
|
||||
return;
|
||||
}
|
||||
|
||||
let parsedState;
|
||||
try {
|
||||
parsedState = NotionUtils.parseState(state);
|
||||
} catch {
|
||||
ctx.redirect(NotionUtils.errorUrl("invalid_state"));
|
||||
return;
|
||||
}
|
||||
|
||||
const { teamId } = parsedState;
|
||||
|
||||
// This code block accounts for the root domain being unable to access authentication for subdomains.
|
||||
// We must forward to the appropriate subdomain to complete the oauth flow
|
||||
if (!user) {
|
||||
if (teamId) {
|
||||
try {
|
||||
const team = await Team.findByPk(teamId, {
|
||||
rejectOnEmpty: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
return parseDomain(ctx.host).teamSubdomain === team.subdomain
|
||||
? ctx.redirect("/")
|
||||
: ctx.redirectOnClient(
|
||||
NotionUtils.callbackUrl({
|
||||
baseUrl: team.url,
|
||||
params: ctx.request.querystring,
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
Logger.error(`Error fetching team for teamId: ${teamId}!`, err);
|
||||
return ctx.redirect(NotionUtils.errorUrl("unauthenticated"));
|
||||
}
|
||||
} else {
|
||||
return ctx.redirect(NotionUtils.errorUrl("unauthenticated"));
|
||||
}
|
||||
}
|
||||
|
||||
// validation middleware ensures that code is non-null at this point.
|
||||
const data = await NotionOAuth.oauthAccess(code!);
|
||||
|
||||
const authentication = await IntegrationAuthentication.create(
|
||||
{
|
||||
service: IntegrationService.Notion,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
token: data.access_token,
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await Integration.create(
|
||||
{
|
||||
service: IntegrationService.Notion,
|
||||
type: IntegrationType.Import,
|
||||
userId: user.id,
|
||||
teamId: user.teamId,
|
||||
authenticationId: authentication.id,
|
||||
settings: {
|
||||
externalWorkspace: {
|
||||
id: data.workspace_id,
|
||||
name: data.workspace_name ?? undefined,
|
||||
iconUrl: data.workspace_icon ?? undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
ctx.redirect(NotionUtils.settingsUrl);
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,17 @@
|
||||
import isEmpty from "lodash/isEmpty";
|
||||
import { z } from "zod";
|
||||
import { BaseSchema } from "@server/routes/api/schema";
|
||||
|
||||
export const NotionCallbackSchema = BaseSchema.extend({
|
||||
query: z
|
||||
.object({
|
||||
code: z.string().nullish(),
|
||||
state: z.string(),
|
||||
error: z.string().nullish(),
|
||||
})
|
||||
.refine((req) => !(isEmpty(req.code) && isEmpty(req.error)), {
|
||||
message: "one of code or error is required",
|
||||
}),
|
||||
});
|
||||
|
||||
export type NotionCallbackReq = z.infer<typeof NotionCallbackSchema>;
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Hook, PluginManager } from "@server/utils/PluginManager";
|
||||
import config from "../plugin.json";
|
||||
import router from "./api/notion";
|
||||
import env from "./env";
|
||||
|
||||
const enabled = !!env.NOTION_CLIENT_ID && !!env.NOTION_CLIENT_SECRET;
|
||||
|
||||
if (enabled) {
|
||||
PluginManager.add([
|
||||
{
|
||||
...config,
|
||||
type: Hook.API,
|
||||
value: router,
|
||||
},
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from "zod";
|
||||
import fetch from "@server/utils/fetch";
|
||||
import { NotionUtils } from "../shared/NotionUtils";
|
||||
import env from "./env";
|
||||
|
||||
export class NotionOAuth {
|
||||
private static tokenUrl = "https://api.notion.com/v1/oauth/token";
|
||||
private static credentials = Buffer.from(
|
||||
`${env.NOTION_CLIENT_ID}:${env.NOTION_CLIENT_SECRET}`
|
||||
).toString("base64");
|
||||
|
||||
private static resSchema = z.object({
|
||||
access_token: z.string(),
|
||||
bot_id: z.string(),
|
||||
workspace_id: z.string(),
|
||||
workspace_name: z.string().nullish(),
|
||||
workspace_icon: z.string().url().nullish(),
|
||||
});
|
||||
|
||||
static async oauthAccess(code: string) {
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Basic ${this.credentials}`,
|
||||
};
|
||||
const body = {
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: NotionUtils.callbackUrl(),
|
||||
};
|
||||
|
||||
const res = await fetch(this.tokenUrl, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
return this.resSchema.parse(await res.json());
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
import queryString from "query-string";
|
||||
import env from "@shared/env";
|
||||
import { settingsPath } from "@shared/utils/routeHelpers";
|
||||
|
||||
export type OAuthState = {
|
||||
teamId: string;
|
||||
};
|
||||
|
||||
export class NotionUtils {
|
||||
// private static clientId = "eda3ac5b-39fa-4d79-a99d-b70bc5ded123";
|
||||
private static clientId = env.NOTION_CLIENT_ID;
|
||||
private static clientSecret = env.NOTION_CLIENT_SECRET;
|
||||
private static authBaseUrl = "https://api.notion.com/v1/oauth/authorize";
|
||||
static settingsUrl = settingsPath("import");
|
||||
|
||||
static parseState(state: string): OAuthState {
|
||||
return JSON.parse(state);
|
||||
}
|
||||
|
||||
static errorUrl(error: string) {
|
||||
const params = {
|
||||
type: "notion",
|
||||
error,
|
||||
};
|
||||
return `${this.settingsUrl}?${queryString.stringify(params)}`;
|
||||
}
|
||||
|
||||
static callbackUrl(
|
||||
{ baseUrl, params }: { baseUrl: string; params?: string } = {
|
||||
// baseUrl: `${env.URL}`,
|
||||
@@ -29,7 +36,7 @@ export class NotionUtils {
|
||||
|
||||
static authUrl({ state }: { state: OAuthState }) {
|
||||
const params = {
|
||||
client_id: this.clientId,
|
||||
client_id: env.NOTION_CLIENT_ID,
|
||||
redirect_uri: this.callbackUrl(),
|
||||
state: JSON.stringify(state),
|
||||
response_type: "code",
|
||||
|
||||
@@ -86,6 +86,7 @@ export enum IntegrationType {
|
||||
Analytics = "analytics",
|
||||
/** An integration that maps an Outline user to an external service. */
|
||||
LinkedAccount = "linkedAccount",
|
||||
Import = "import",
|
||||
}
|
||||
|
||||
export enum IntegrationService {
|
||||
@@ -96,6 +97,7 @@ export enum IntegrationService {
|
||||
Matomo = "matomo",
|
||||
Umami = "umami",
|
||||
GitHub = "github",
|
||||
Notion = "notion",
|
||||
}
|
||||
|
||||
export type UserCreatableIntegrationService = Extract<
|
||||
@@ -157,6 +159,7 @@ export type IntegrationSettings<T> = T extends IntegrationType.Embed
|
||||
| { serviceTeamId: string }
|
||||
| { measurementId: string }
|
||||
| { slack: { serviceTeamId: string; serviceUserId: string } }
|
||||
| { externalWorkspace: { id: string; name?: string; iconUrl?: string } }
|
||||
| undefined;
|
||||
|
||||
export enum UserPreference {
|
||||
|
||||
Reference in new issue
Block a user