feat: Move to passport for authentication (#1934)

- Added `accountProvisioner`
- Move authentication to use passport strategies
- Make authentication more pluggable
- Change language of services -> providers

closes #1120
This commit is contained in:
Tom Moor
2021-03-11 10:02:22 -08:00
committed by GitHub
parent dc967be4fc
commit 5d6f68d399
33 changed files with 1104 additions and 725 deletions

View File

@@ -1,57 +1,45 @@
// @flow
import path from "path";
import Router from "koa-router";
import { reject } from "lodash";
import { find } from "lodash";
import { parseDomain, isCustomSubdomain } from "../../shared/utils/domains";
import { signin } from "../../shared/utils/routeHelpers";
import auth from "../middlewares/authentication";
import { Team } from "../models";
import { presentUser, presentTeam, presentPolicies } from "../presenters";
import { isCustomDomain } from "../utils/domains";
import { requireDirectory } from "../utils/fs";
const router = new Router();
let providers = [];
let services = [];
if (process.env.GOOGLE_CLIENT_ID) {
services.push({
id: "google",
name: "Google",
authUrl: signin("google"),
});
}
if (process.env.SLACK_KEY) {
services.push({
id: "slack",
name: "Slack",
authUrl: signin("slack"),
});
}
services.push({
id: "email",
name: "Email",
authUrl: "",
});
function filterServices(team) {
let output = services;
const providerNames = team
? team.authenticationProviders.map((provider) => provider.name)
: [];
if (team && !providerNames.includes("google")) {
output = reject(output, (service) => service.id === "google");
}
if (team && !providerNames.includes("slack")) {
output = reject(output, (service) => service.id === "slack");
}
if (!team || !team.guestSignin) {
output = reject(output, (service) => service.id === "email");
requireDirectory(path.join(__dirname, "..", "auth")).forEach(
([{ config }, id]) => {
if (config && config.enabled) {
providers.push({
id,
name: config.name,
authUrl: signin(id),
});
}
}
);
return output;
function filterProviders(team) {
return providers
.sort((provider) => (provider.id === "email" ? 1 : -1))
.filter((provider) => {
// guest sign-in is an exception as it does not have an authentication
// provider using passport, instead it exists as a boolean option on the team
if (provider.id === "email") {
return team && team.guestSignin;
}
return (
!team ||
find(team.authenticationProviders, { name: provider.id, enabled: true })
);
});
}
router.post("auth.config", async (ctx) => {
@@ -66,7 +54,7 @@ router.post("auth.config", async (ctx) => {
ctx.body = {
data: {
name: team.name,
services: filterServices(team),
providers: filterProviders(team),
},
};
return;
@@ -83,7 +71,7 @@ router.post("auth.config", async (ctx) => {
data: {
name: team.name,
hostname: ctx.request.hostname,
services: filterServices(team),
providers: filterProviders(team),
},
};
return;
@@ -108,7 +96,7 @@ router.post("auth.config", async (ctx) => {
data: {
name: team.name,
hostname: ctx.request.hostname,
services: filterServices(team),
providers: filterProviders(team),
},
};
return;
@@ -118,7 +106,7 @@ router.post("auth.config", async (ctx) => {
// Otherwise, we're requesting from the standard root signin page
ctx.body = {
data: {
services: filterServices(),
providers: filterProviders(),
},
};
});

View File

@@ -41,3 +41,149 @@ describe("#auth.info", () => {
expect(res.status).toEqual(401);
});
});
describe("#auth.config", () => {
it("should return available SSO providers", async () => {
const res = await server.post("/api/auth.config");
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(2);
expect(body.data.providers[0].name).toBe("Slack");
expect(body.data.providers[1].name).toBe("Google");
});
it("should return available providers for team subdomain", async () => {
process.env.URL = "http://localoutline.com";
await buildTeam({
guestSignin: false,
subdomain: "example",
authenticationProviders: [
{
name: "slack",
providerId: "123",
},
],
});
const res = await server.post("/api/auth.config", {
headers: { host: `example.localoutline.com` },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(1);
expect(body.data.providers[0].name).toBe("Slack");
});
it("should return available providers for team custom domain", async () => {
await buildTeam({
guestSignin: false,
domain: "docs.mycompany.com",
authenticationProviders: [
{
name: "slack",
providerId: "123",
},
],
});
const res = await server.post("/api/auth.config", {
headers: { host: "docs.mycompany.com" },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(1);
expect(body.data.providers[0].name).toBe("Slack");
});
it("should return email provider for team when guest signin enabled", async () => {
process.env.URL = "http://localoutline.com";
await buildTeam({
guestSignin: true,
subdomain: "example",
authenticationProviders: [
{
name: "slack",
providerId: "123",
},
],
});
const res = await server.post("/api/auth.config", {
headers: { host: "example.localoutline.com" },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(2);
expect(body.data.providers[0].name).toBe("Slack");
expect(body.data.providers[1].name).toBe("Email");
});
it("should not return provider when disabled", async () => {
process.env.URL = "http://localoutline.com";
await buildTeam({
guestSignin: false,
subdomain: "example",
authenticationProviders: [
{
name: "slack",
providerId: "123",
enabled: false,
},
],
});
const res = await server.post("/api/auth.config", {
headers: { host: "example.localoutline.com" },
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(0);
});
describe("self hosted", () => {
it("should return available providers for team", async () => {
process.env.DEPLOYMENT = "";
await buildTeam({
guestSignin: false,
authenticationProviders: [
{
name: "slack",
providerId: "123",
},
],
});
const res = await server.post("/api/auth.config");
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(1);
expect(body.data.providers[0].name).toBe("Slack");
});
it("should return email provider for team when guest signin enabled", async () => {
process.env.DEPLOYMENT = "";
await buildTeam({
guestSignin: true,
authenticationProviders: [
{
name: "slack",
providerId: "123",
},
],
});
const res = await server.post("/api/auth.config");
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.providers.length).toBe(2);
expect(body.data.providers[0].name).toBe("Slack");
expect(body.data.providers[1].name).toBe("Email");
});
});
});

12
server/auth/README.md Normal file
View File

@@ -0,0 +1,12 @@
# Authentication Providers
A new auth provider can be added with the addition of a single file in this
folder, and (optionally) a matching logo in `/app/components/AuthLogo/index.js`
that will appear on the signin button.
Auth providers generally use [Passport](http://www.passportjs.org/) strategies,
although they can use any custom logic if needed. See the `google` auth provider for the cleanest example of what is required some rules:
- The strategy name _must_ be lowercase
- The stragegy _must_ call the `accountProvisioner` command in the verify callback
- The auth file _must_ export a `config` object with `name` and `enabled` keys

View File

@@ -12,6 +12,11 @@ import { getUserForEmailSigninToken } from "../utils/jwt";
const router = new Router();
export const config = {
name: "Email",
enabled: true,
};
router.use(methodOverride());
router.use(validation());

View File

@@ -1,135 +1,100 @@
// @flow
import * as Sentry from "@sentry/node";
import { OAuth2Client } from "google-auth-library";
import invariant from "invariant";
import passport from "@outlinewiki/koa-passport";
import Router from "koa-router";
import { capitalize } from "lodash";
import Sequelize from "sequelize";
import teamCreator from "../commands/teamCreator";
import userCreator from "../commands/userCreator";
import { Strategy as GoogleStrategy } from "passport-google-oauth2";
import accountProvisioner from "../commands/accountProvisioner";
import env from "../env";
import {
GoogleWorkspaceRequiredError,
GoogleWorkspaceInvalidError,
} from "../errors";
import auth from "../middlewares/authentication";
import { User } from "../models";
import passportMiddleware from "../middlewares/passport";
import { StateStore } from "../utils/passport";
const router = new Router();
const client = new OAuth2Client(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
`${process.env.URL}/auth/google.callback`
);
const providerName = "google";
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const allowedDomainsEnv = process.env.GOOGLE_ALLOWED_DOMAINS;
const allowedDomains = allowedDomainsEnv ? allowedDomainsEnv.split(",") : [];
// start the oauth process and redirect user to Google
router.get("google", async (ctx) => {
// Generate the url that will be used for the consent dialog.
const authorizeUrl = client.generateAuthUrl({
access_type: "offline",
scope: [
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
],
prompt: "select_account consent",
});
ctx.redirect(authorizeUrl);
});
const scopes = [
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
];
// signin callback from Google
router.get("google.callback", auth({ required: false }), async (ctx) => {
const { code } = ctx.request.query;
ctx.assertPresent(code, "code is required");
const response = await client.getToken(code);
client.setCredentials(response.tokens);
export const config = {
name: "Google",
enabled: !!GOOGLE_CLIENT_ID,
};
const profile = await client.request({
url: "https://www.googleapis.com/oauth2/v1/userinfo",
});
if (!profile.data.hd) {
ctx.redirect("/?notice=google-hd");
return;
}
// allow all domains by default if the env is not set
const allowedDomains = allowedDomainsEnv && allowedDomainsEnv.split(",");
if (allowedDomains && !allowedDomains.includes(profile.data.hd)) {
ctx.redirect("/?notice=hd-not-allowed");
return;
}
const domain = profile.data.hd;
const subdomain = profile.data.hd.split(".")[0];
const teamName = capitalize(subdomain);
let result;
try {
result = await teamCreator({
name: teamName,
domain,
subdomain,
authenticationProvider: {
name: "google",
providerId: domain,
if (GOOGLE_CLIENT_ID) {
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: `${env.URL}/auth/google.callback`,
prompt: "select_account consent",
passReqToCallback: true,
store: new StateStore(),
scope: scopes,
},
});
} catch (err) {
if (err instanceof Sequelize.UniqueConstraintError) {
ctx.redirect(`/?notice=auth-error&error=team-exists`);
return;
}
}
async function (req, accessToken, refreshToken, profile, done) {
try {
const domain = profile._json.hd;
invariant(result, "Team creator result must exist");
const { team, isNewTeam, authenticationProvider } = result;
if (!domain) {
throw new GoogleWorkspaceRequiredError();
}
try {
const result = await userCreator({
name: profile.data.name,
email: profile.data.email,
isAdmin: isNewTeam,
avatarUrl: profile.data.picture,
teamId: team.id,
ip: ctx.request.ip,
authentication: {
authenticationProviderId: authenticationProvider.id,
providerId: profile.data.id,
accessToken: response.tokens.access_token,
refreshToken: response.tokens.refresh_token,
scopes: response.tokens.scope.split(" "),
},
});
if (allowedDomains.length && !allowedDomains.includes(domain)) {
throw new GoogleWorkspaceInvalidError();
}
const { user, isNewUser } = result;
const subdomain = domain.split(".")[0];
const teamName = capitalize(subdomain);
if (isNewTeam) {
await team.provisionFirstCollection(user.id);
}
// set cookies on response and redirect to team subdomain
ctx.signIn(user, team, "google", isNewUser);
} catch (err) {
if (err instanceof Sequelize.UniqueConstraintError) {
const exists = await User.findOne({
where: {
email: profile.data.email,
teamId: team.id,
},
});
if (exists) {
ctx.redirect(`${team.url}?notice=email-auth-required`);
} else {
if (process.env.SENTRY_DSN) {
Sentry.captureException(err);
} else {
console.error(err);
const result = await accountProvisioner({
ip: req.ip,
team: {
name: teamName,
domain,
subdomain,
},
user: {
name: profile.displayName,
email: profile.email,
avatarUrl: profile.picture,
},
authenticationProvider: {
name: providerName,
providerId: domain,
},
authentication: {
providerId: profile.id,
accessToken,
refreshToken,
scopes,
},
});
return done(null, result.user, result);
} catch (err) {
return done(err, null);
}
ctx.redirect(`${team.url}?notice=auth-error`);
}
)
);
return;
}
router.get("google", passport.authenticate(providerName));
throw err;
}
});
router.get(
"google.callback",
auth({ required: false }),
passportMiddleware(providerName)
);
}
export default router;

View File

@@ -1,5 +1,7 @@
// @flow
import passport from "@outlinewiki/koa-passport";
import addMonths from "date-fns/add_months";
import debug from "debug";
import Koa from "koa";
import bodyParser from "koa-body";
import Router from "koa-router";
@@ -7,17 +9,25 @@ import { AuthenticationError } from "../errors";
import auth from "../middlewares/authentication";
import validation from "../middlewares/validation";
import { Team } from "../models";
import { requireDirectory } from "../utils/fs";
import email from "./email";
import google from "./google";
import slack from "./slack";
const log = debug("server");
const app = new Koa();
const router = new Router();
router.use("/", slack.routes());
router.use("/", google.routes());
router.use("/", email.routes());
router.use(passport.initialize());
// dynamically load available authentication providers
requireDirectory(__dirname).forEach(([{ default: provider, config }]) => {
if (provider && provider.routes) {
if (!config) {
throw new Error("Auth providers must export a 'config' object");
}
router.use("/", provider.routes());
log(`loaded ${config.name} auth provider`);
}
});
router.get("/redirect", auth(), async (ctx) => {
const user = ctx.state.user;

View File

@@ -1,138 +1,164 @@
// @flow
import * as Sentry from "@sentry/node";
import addHours from "date-fns/add_hours";
import invariant from "invariant";
import passport from "@outlinewiki/koa-passport";
import Router from "koa-router";
import Sequelize from "sequelize";
import { slackAuth } from "../../shared/utils/routeHelpers";
import teamCreator from "../commands/teamCreator";
import userCreator from "../commands/userCreator";
import { Strategy as SlackStrategy } from "passport-slack-oauth2";
import accountProvisioner from "../commands/accountProvisioner";
import env from "../env";
import auth from "../middlewares/authentication";
import { Authentication, Collection, Integration, User, Team } from "../models";
import passportMiddleware from "../middlewares/passport";
import { Authentication, Collection, Integration, Team } from "../models";
import * as Slack from "../slack";
import { getCookieDomain } from "../utils/domains";
import { StateStore } from "../utils/passport";
const router = new Router();
const providerName = "slack";
const SLACK_CLIENT_ID = process.env.SLACK_KEY;
const SLACK_CLIENT_SECRET = process.env.SLACK_SECRET;
// start the oauth process and redirect user to Slack
router.get("slack", async (ctx) => {
const state = Math.random().toString(36).substring(7);
const scopes = [
"identity.email",
"identity.basic",
"identity.avatar",
"identity.team",
];
ctx.cookies.set("state", state, {
httpOnly: false,
expires: addHours(new Date(), 1),
domain: getCookieDomain(ctx.request.hostname),
});
ctx.redirect(slackAuth(state));
});
export const config = {
name: "Slack",
enabled: !!SLACK_CLIENT_ID,
};
// signin callback from Slack
router.get("slack.callback", auth({ required: false }), async (ctx) => {
const { code, error, state } = ctx.request.query;
ctx.assertPresent(code || error, "code is required");
ctx.assertPresent(state, "state is required");
if (state !== ctx.cookies.get("state")) {
ctx.redirect("/?notice=auth-error&error=state_mismatch");
return;
}
if (error) {
ctx.redirect(`/?notice=auth-error&error=${error}`);
return;
}
const data = await Slack.oauthAccess(code);
let result;
try {
result = await teamCreator({
name: data.team.name,
subdomain: data.team.domain,
avatarUrl: data.team.image_230,
authenticationProvider: {
name: "slack",
providerId: data.team.id,
},
});
} catch (err) {
if (err instanceof Sequelize.UniqueConstraintError) {
ctx.redirect(`/?notice=auth-error&error=team-exists`);
return;
}
throw err;
}
invariant(result, "Team creator result must exist");
const { authenticationProvider, team, isNewTeam } = result;
try {
const result = await userCreator({
name: data.user.name,
email: data.user.email,
isAdmin: isNewTeam,
avatarUrl: data.user.image_192,
teamId: team.id,
ip: ctx.request.ip,
authentication: {
authenticationProviderId: authenticationProvider.id,
providerId: data.user.id,
accessToken: data.access_token,
scopes: data.scope.split(","),
},
});
const { user, isNewUser } = result;
if (isNewTeam) {
await team.provisionFirstCollection(user.id);
}
// set cookies on response and redirect to team subdomain
ctx.signIn(user, team, "slack", isNewUser);
} catch (err) {
if (err instanceof Sequelize.UniqueConstraintError) {
const exists = await User.findOne({
where: {
email: data.user.email,
teamId: team.id,
},
});
if (exists) {
ctx.redirect(`${team.url}?notice=email-auth-required`);
} else {
if (process.env.SENTRY_DSN) {
Sentry.captureException(err);
} else {
console.error(err);
}
ctx.redirect(`${team.url}?notice=auth-error`);
}
return;
}
throw err;
}
});
router.get("slack.commands", auth({ required: false }), async (ctx) => {
const { code, state, error } = ctx.request.query;
const user = ctx.state.user;
ctx.assertPresent(code || error, "code is required");
if (error) {
ctx.redirect(`/settings/integrations/slack?error=${error}`);
return;
}
// 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 (state) {
if (SLACK_CLIENT_ID) {
const strategy = new SlackStrategy(
{
clientID: SLACK_CLIENT_ID,
clientSecret: SLACK_CLIENT_SECRET,
callbackURL: `${env.URL}/auth/slack.callback`,
passReqToCallback: true,
store: new StateStore(),
scope: scopes,
},
async function (req, accessToken, refreshToken, profile, done) {
try {
const team = await Team.findByPk(state);
const result = await accountProvisioner({
ip: req.ip,
team: {
name: profile.team.name,
subdomain: profile.team.domain,
avatarUrl: profile.team.image_230,
},
user: {
name: profile.user.name,
email: profile.user.email,
avatarUrl: profile.user.image_192,
},
authenticationProvider: {
name: providerName,
providerId: profile.team.id,
},
authentication: {
providerId: profile.user.id,
accessToken,
refreshToken,
scopes,
},
});
return done(null, result.user, result);
} catch (err) {
return done(err, null);
}
}
);
// For some reason the author made the strategy name capatilised, I don't know
// why but we need everything lowercase so we just monkey-patch it here.
strategy.name = providerName;
passport.use(strategy);
router.get("slack", passport.authenticate(providerName));
router.get(
"slack.callback",
auth({ required: false }),
passportMiddleware(providerName)
);
router.get("slack.commands", auth({ required: false }), async (ctx) => {
const { code, state, error } = ctx.request.query;
const user = ctx.state.user;
ctx.assertPresent(code || error, "code is required");
if (error) {
ctx.redirect(`/settings/integrations/slack?error=${error}`);
return;
}
// 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 (state) {
try {
const team = await Team.findByPk(state);
return ctx.redirect(
`${team.url}/auth${ctx.request.path}?${ctx.request.querystring}`
);
} catch (err) {
return ctx.redirect(
`/settings/integrations/slack?error=unauthenticated`
);
}
} else {
return ctx.redirect(
`/settings/integrations/slack?error=unauthenticated`
);
}
}
const endpoint = `${process.env.URL || ""}/auth/slack.commands`;
const data = await Slack.oauthAccess(code, endpoint);
const authentication = await Authentication.create({
service: "slack",
userId: user.id,
teamId: user.teamId,
token: data.access_token,
scopes: data.scope.split(","),
});
await Integration.create({
service: "slack",
type: "command",
userId: user.id,
teamId: user.teamId,
authenticationId: authentication.id,
settings: {
serviceTeamId: data.team_id,
},
});
ctx.redirect("/settings/integrations/slack");
});
router.get("slack.post", auth({ required: false }), async (ctx) => {
const { code, error, state } = ctx.request.query;
const user = ctx.state.user;
ctx.assertPresent(code || error, "code is required");
const collectionId = state;
ctx.assertUuid(collectionId, "collectionId must be an uuid");
if (error) {
ctx.redirect(`/settings/integrations/slack?error=${error}`);
return;
}
// this code block accounts for the root domain being unable to
// access authentcation for subdomains. We must forward to the
// appropriate subdomain to complete the oauth flow
if (!user) {
try {
const collection = await Collection.findByPk(state);
const team = await Team.findByPk(collection.teamId);
return ctx.redirect(
`${team.url}/auth${ctx.request.path}?${ctx.request.querystring}`
);
@@ -141,91 +167,36 @@ router.get("slack.commands", auth({ required: false }), async (ctx) => {
`/settings/integrations/slack?error=unauthenticated`
);
}
} else {
return ctx.redirect(`/settings/integrations/slack?error=unauthenticated`);
}
}
const endpoint = `${process.env.URL || ""}/auth/slack.commands`;
const data = await Slack.oauthAccess(code, endpoint);
const endpoint = `${process.env.URL || ""}/auth/slack.post`;
const data = await Slack.oauthAccess(code, endpoint);
const authentication = await Authentication.create({
service: "slack",
userId: user.id,
teamId: user.teamId,
token: data.access_token,
scopes: data.scope.split(","),
const authentication = await Authentication.create({
service: "slack",
userId: user.id,
teamId: user.teamId,
token: data.access_token,
scopes: data.scope.split(","),
});
await Integration.create({
service: "slack",
type: "post",
userId: user.id,
teamId: user.teamId,
authenticationId: authentication.id,
collectionId,
events: [],
settings: {
url: data.incoming_webhook.url,
channel: data.incoming_webhook.channel,
channelId: data.incoming_webhook.channel_id,
},
});
ctx.redirect("/settings/integrations/slack");
});
await Integration.create({
service: "slack",
type: "command",
userId: user.id,
teamId: user.teamId,
authenticationId: authentication.id,
settings: {
serviceTeamId: data.team_id,
},
});
ctx.redirect("/settings/integrations/slack");
});
router.get("slack.post", auth({ required: false }), async (ctx) => {
const { code, error, state } = ctx.request.query;
const user = ctx.state.user;
ctx.assertPresent(code || error, "code is required");
const collectionId = state;
ctx.assertUuid(collectionId, "collectionId must be an uuid");
if (error) {
ctx.redirect(`/settings/integrations/slack?error=${error}`);
return;
}
// this code block accounts for the root domain being unable to
// access authentcation for subdomains. We must forward to the
// appropriate subdomain to complete the oauth flow
if (!user) {
try {
const collection = await Collection.findByPk(state);
const team = await Team.findByPk(collection.teamId);
return ctx.redirect(
`${team.url}/auth${ctx.request.path}?${ctx.request.querystring}`
);
} catch (err) {
return ctx.redirect(`/settings/integrations/slack?error=unauthenticated`);
}
}
const endpoint = `${process.env.URL || ""}/auth/slack.post`;
const data = await Slack.oauthAccess(code, endpoint);
const authentication = await Authentication.create({
service: "slack",
userId: user.id,
teamId: user.teamId,
token: data.access_token,
scopes: data.scope.split(","),
});
await Integration.create({
service: "slack",
type: "post",
userId: user.id,
teamId: user.teamId,
authenticationId: authentication.id,
collectionId,
events: [],
settings: {
url: data.incoming_webhook.url,
channel: data.incoming_webhook.channel,
channelId: data.incoming_webhook.channel_id,
},
});
ctx.redirect("/settings/integrations/slack");
});
}
export default router;

View File

@@ -0,0 +1,119 @@
// @flow
import invariant from "invariant";
import Sequelize from "sequelize";
import {
AuthenticationError,
EmailAuthenticationRequiredError,
AuthenticationProviderDisabledError,
} from "../errors";
import { Team, User } from "../models";
import teamCreator from "./teamCreator";
import userCreator from "./userCreator";
type Props = {|
ip: string,
user: {|
name: string,
email: string,
avatarUrl?: string,
|},
team: {|
name: string,
domain?: string,
subdomain: string,
avatarUrl?: string,
|},
authenticationProvider: {|
name: string,
providerId: string,
|},
authentication: {|
providerId: string,
scopes: string[],
accessToken?: string,
refreshToken?: string,
|},
|};
export type AccountProvisionerResult = {|
user: User,
team: Team,
isNewTeam: boolean,
isNewUser: boolean,
|};
export default async function accountProvisioner({
ip,
user: userParams,
team: teamParams,
authenticationProvider: authenticationProviderParams,
authentication: authenticationParams,
}: Props): Promise<AccountProvisionerResult> {
let result;
try {
result = await teamCreator({
name: teamParams.name,
domain: teamParams.domain,
subdomain: teamParams.subdomain,
avatarUrl: teamParams.avatarUrl,
authenticationProvider: authenticationProviderParams,
});
} catch (err) {
throw new AuthenticationError(err.message);
}
invariant(result, "Team creator result must exist");
const { authenticationProvider, team, isNewTeam } = result;
if (!authenticationProvider.enabled) {
throw new AuthenticationProviderDisabledError();
}
try {
const result = await userCreator({
name: userParams.name,
email: userParams.email,
isAdmin: isNewTeam,
avatarUrl: userParams.avatarUrl,
teamId: team.id,
ip,
authentication: {
...authenticationParams,
authenticationProviderId: authenticationProvider.id,
},
});
const { isNewUser, user } = result;
if (isNewTeam) {
await team.provisionFirstCollection(user.id);
}
return {
user,
team,
isNewUser,
isNewTeam,
};
} catch (err) {
if (err instanceof Sequelize.UniqueConstraintError) {
const exists = await User.findOne({
where: {
email: userParams.email,
teamId: team.id,
},
});
if (exists) {
throw new EmailAuthenticationRequiredError(
"Email authentication required",
team.url
);
} else {
throw new AuthenticationError(err.message, team.url);
}
}
throw err;
}
}

View File

@@ -0,0 +1,182 @@
// @flow
import { Collection, UserAuthentication } from "../models";
import { buildUser, buildTeam } from "../test/factories";
import { flushdb } from "../test/support";
import accountProvisioner from "./accountProvisioner";
jest.mock("aws-sdk", () => {
const mS3 = { putObject: jest.fn().mockReturnThis(), promise: jest.fn() };
return {
S3: jest.fn(() => mS3),
Endpoint: jest.fn(),
};
});
beforeEach(() => flushdb());
describe("accountProvisioner", () => {
const ip = "127.0.0.1";
it("should create a new user and team", async () => {
const { user, team, isNewTeam, isNewUser } = await accountProvisioner({
ip,
user: {
name: "Jenny Tester",
email: "jenny@example.com",
avatarUrl: "https://example.com/avatar.png",
},
team: {
name: "New team",
avatarUrl: "https://example.com/avatar.png",
subdomain: "example",
},
authenticationProvider: {
name: "google",
providerId: "example.com",
},
authentication: {
providerId: "123456789",
accessToken: "123",
scopes: ["read"],
},
});
const authentications = await user.getAuthentications();
const auth = authentications[0];
expect(auth.accessToken).toEqual("123");
expect(auth.scopes.length).toEqual(1);
expect(auth.scopes[0]).toEqual("read");
expect(team.name).toEqual("New team");
expect(user.email).toEqual("jenny@example.com");
expect(isNewUser).toEqual(true);
expect(isNewTeam).toEqual(true);
const collectionCount = await Collection.count();
expect(collectionCount).toEqual(1);
});
it("should update exising user and authentication", async () => {
const existingTeam = await buildTeam();
const providers = await existingTeam.getAuthenticationProviders();
const authenticationProvider = providers[0];
const existing = await buildUser({ teamId: existingTeam.id });
const authentications = await existing.getAuthentications();
const authentication = authentications[0];
const newEmail = "test@example.com";
const { user } = await accountProvisioner({
ip,
user: {
name: existing.name,
email: newEmail,
avatarUrl: existing.avatarUrl,
},
team: {
name: existingTeam.name,
avatarUrl: existingTeam.avatarUrl,
subdomain: "example",
},
authenticationProvider: {
name: authenticationProvider.name,
providerId: authenticationProvider.providerId,
},
authentication: {
providerId: authentication.providerId,
accessToken: "123",
scopes: ["read"],
},
});
const auth = await UserAuthentication.findByPk(authentication.id);
expect(auth.accessToken).toEqual("123");
expect(auth.scopes.length).toEqual(1);
expect(auth.scopes[0]).toEqual("read");
expect(user.email).toEqual(newEmail);
const collectionCount = await Collection.count();
expect(collectionCount).toEqual(0);
});
it("should throw an error when authentication provider is disabled", async () => {
const existingTeam = await buildTeam();
const providers = await existingTeam.getAuthenticationProviders();
const authenticationProvider = providers[0];
await authenticationProvider.update({ enabled: false });
const existing = await buildUser({ teamId: existingTeam.id });
const authentications = await existing.getAuthentications();
const authentication = authentications[0];
let error;
try {
await accountProvisioner({
ip,
user: {
name: existing.name,
email: existing.email,
avatarUrl: existing.avatarUrl,
},
team: {
name: existingTeam.name,
avatarUrl: existingTeam.avatarUrl,
subdomain: "example",
},
authenticationProvider: {
name: authenticationProvider.name,
providerId: authenticationProvider.providerId,
},
authentication: {
providerId: authentication.providerId,
accessToken: "123",
scopes: ["read"],
},
});
} catch (err) {
error = err;
}
expect(error).toBeTruthy();
});
it("should create a new user in an existing team", async () => {
const team = await buildTeam();
const authenticationProviders = await team.getAuthenticationProviders();
const authenticationProvider = authenticationProviders[0];
const { user, isNewUser } = await accountProvisioner({
ip,
user: {
name: "Jenny Tester",
email: "jenny@example.com",
avatarUrl: "https://example.com/avatar.png",
},
team: {
name: team.name,
avatarUrl: team.avatarUrl,
subdomain: "example",
},
authenticationProvider: {
name: authenticationProvider.name,
providerId: authenticationProvider.providerId,
},
authentication: {
providerId: "123456789",
accessToken: "123",
scopes: ["read"],
},
});
const authentications = await user.getAuthentications();
const auth = authentications[0];
expect(auth.accessToken).toEqual("123");
expect(auth.scopes.length).toEqual(1);
expect(auth.scopes[0]).toEqual("read");
expect(user.email).toEqual("jenny@example.com");
expect(isNewUser).toEqual(true);
const collectionCount = await Collection.count();
expect(collectionCount).toEqual(0);
});
});

View File

@@ -1,10 +1,15 @@
// @flow
import httpErrors from "http-errors";
import env from "./env";
export function AuthenticationError(
message: string = "Invalid authentication"
message: string = "Invalid authentication",
redirectUrl: string = env.URL
) {
return httpErrors(401, message, { id: "authentication_required" });
return httpErrors(401, message, {
redirectUrl,
id: "authentication_required",
});
}
export function AuthorizationError(
@@ -57,3 +62,38 @@ export function FileImportError(
) {
return httpErrors(400, message, { id: "import_error" });
}
export function OAuthStateMismatchError(
message: string = "State returned in OAuth flow did not match"
) {
return httpErrors(400, message, { id: "state_mismatch" });
}
export function EmailAuthenticationRequiredError(
message: string = "User must authenticate with email",
redirectUrl: string = env.URL
) {
return httpErrors(400, message, { redirectUrl, id: "email_auth_required" });
}
export function GoogleWorkspaceRequiredError(
message: string = "Google Workspace is required to authenticate"
) {
return httpErrors(400, message, { id: "google_hd" });
}
export function GoogleWorkspaceInvalidError(
message: string = "Google Workspace is invalid"
) {
return httpErrors(400, message, { id: "hd_not_allowed" });
}
export function AuthenticationProviderDisabledError(
message: string = "Authentication method has been disabled by an admin",
redirectUrl: string = env.URL
) {
return httpErrors(400, message, {
redirectUrl,
id: "authentication_provider_disabled",
});
}

View File

@@ -0,0 +1,33 @@
// @flow
import passport from "@outlinewiki/koa-passport";
import type { AccountProvisionerResult } from "../commands/accountProvisioner";
import type { ContextWithAuthMiddleware } from "../types";
export default function createMiddleware(providerName: string) {
return function passportMiddleware(ctx: ContextWithAuthMiddleware) {
return passport.authorize(
providerName,
{ session: false },
(err, _, result: AccountProvisionerResult) => {
if (err) {
if (err.id) {
console.error(err);
const notice = err.id.replace(/_/g, "-");
return ctx.redirect(`${err.redirectUrl || "/"}?notice=${notice}`);
}
if (process.env.NODE_ENV === "development") {
throw err;
}
return ctx.redirect(`/?notice=auth-error`);
}
if (result.user.isSuspended) {
return ctx.redirect("/?notice=suspended");
}
ctx.signIn(result.user, result.team, providerName, result.isNewUser);
}
)(ctx);
};
}

View File

@@ -0,0 +1,19 @@
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.removeColumn("users", "slackData");
await queryInterface.removeColumn("teams", "slackData");
},
down: async (queryInterface, Sequelize) => {
await queryInterface.addColumn("teams", "slackData", {
type: 'JSONB',
allowNull: true,
});
await queryInterface.addColumn("users", "slackData", {
type: 'JSONB',
allowNull: true,
});
}
};

View File

@@ -10,6 +10,7 @@ import {
} from "../../shared/utils/domains";
import { ValidationError } from "../errors";
import { DataTypes, sequelize, Op } from "../sequelize";
import { generateAvatarUrl } from "../utils/avatars";
import { publicS3Endpoint, uploadToS3FromUrl } from "../utils/s3";
import Collection from "./Collection";
@@ -66,7 +67,6 @@ const Team = sequelize.define(
allowNull: false,
defaultValue: true,
},
slackData: DataTypes.JSONB,
},
{
paranoid: true,
@@ -85,7 +85,11 @@ const Team = sequelize.define(
},
logoUrl() {
return (
this.avatarUrl || (this.slackData ? this.slackData.image_88 : null)
this.avatarUrl ||
generateAvatarUrl({
id: this.id,
name: this.name,
})
);
},
},
@@ -164,17 +168,10 @@ Team.prototype.provisionFirstCollection = async function (userId) {
"Our Editor",
"What is Outline",
];
for (const title of onboardingDocs) {
const text = await readFile(
path.join(
__dirname,
"..",
"..",
"..",
"server",
"onboarding",
`${title}.md`
),
path.join(process.cwd(), "server", "onboarding", `${title}.md`),
"utf8"
);
const document = await Document.create({

View File

@@ -8,11 +8,10 @@ import { languages } from "../../shared/i18n";
import { ValidationError } from "../errors";
import { sendEmail } from "../mailer";
import { DataTypes, sequelize, encryptedFields } from "../sequelize";
import { DEFAULT_AVATAR_HOST } from "../utils/avatars";
import { publicS3Endpoint, uploadToS3FromUrl } from "../utils/s3";
import { Star, Team, Collection, NotificationSetting, ApiKey } from ".";
const DEFAULT_AVATAR_HOST = "https://tiley.herokuapp.com";
const User = sequelize.define(
"user",
{
@@ -28,7 +27,6 @@ const User = sequelize.define(
isAdmin: DataTypes.BOOLEAN,
service: { type: DataTypes.STRING, allowNull: true },
serviceId: { type: DataTypes.STRING, allowNull: true, unique: true },
slackData: DataTypes.JSONB,
jwtSecret: encryptedFields().vault("jwtSecret"),
lastActiveAt: DataTypes.DATE,
lastActiveIp: { type: DataTypes.STRING, allowNull: true },
@@ -210,7 +208,6 @@ const removeIdentifyingInfo = async (model, options) => {
model.avatarUrl = "";
model.serviceId = null;
model.username = null;
model.slackData = null;
model.lastActiveIp = null;
model.lastSignedInIp = null;

View File

@@ -6,9 +6,6 @@ it("presents a user", async () => {
id: "123",
name: "Test User",
username: "testuser",
slackData: {
image_192: "http://example.com/avatar.png",
},
});
expect(user).toMatchSnapshot();
@@ -19,7 +16,6 @@ it("presents a user without slack data", async () => {
id: "123",
name: "Test User",
username: "testuser",
slackData: null,
});
expect(user).toMatchSnapshot();

View File

@@ -1,27 +1,18 @@
// @flow
import path from "path";
import debug from "debug";
import fs from "fs-extra";
import { requireDirectory } from "../utils/fs";
const log = debug("services");
const services = {};
if (!process.env.SINGLE_RUN) {
fs.readdirSync(__dirname)
.filter(
(file) =>
file.indexOf(".") !== 0 &&
file !== path.basename(__filename) &&
!file.includes(".test")
)
.forEach((fileName) => {
const servicePath = path.join(__dirname, fileName);
const name = path.basename(servicePath.replace(/\.js$/, ""));
// $FlowIssue
const Service = require(servicePath).default;
requireDirectory(__dirname).forEach(([module, name]) => {
if (module && module.default) {
const Service = module.default;
services[name] = new Service();
log(`loaded ${name} service`);
});
}
});
}
export default services;

View File

@@ -4,6 +4,8 @@ require("dotenv").config({ silent: true });
// test environment variables
process.env.DATABASE_URL = process.env.DATABASE_URL_TEST;
process.env.NODE_ENV = "test";
process.env.GOOGLE_CLIENT_ID = "123";
process.env.SLACK_KEY = "123";
// This is needed for the relative manual mock to be picked up
jest.mock("../events");

View File

@@ -1,6 +1,6 @@
// @flow
import { type Context } from "koa";
import { User } from "./models";
import { User, Team } from "./models";
export type ContextWithState = {|
...$Exact<Context>,
@@ -10,3 +10,13 @@ export type ContextWithState = {|
authType: "app" | "api",
},
|};
export type ContextWithAuthMiddleware = {|
...$Exact<ContextWithState>,
signIn: (
user: User,
team: Team,
providerName: string,
isFirstSignin: boolean
) => void,
|};

View File

@@ -2,6 +2,8 @@
import crypto from "crypto";
import fetch from "isomorphic-fetch";
export const DEFAULT_AVATAR_HOST = "https://tiley.herokuapp.com";
export async function generateAvatarUrl({
id,
domain,
@@ -27,6 +29,6 @@ export async function generateAvatarUrl({
}
}
const tileyUrl = `https://tiley.herokuapp.com/avatar/${hashedId}/${name[0]}.png`;
const tileyUrl = `${DEFAULT_AVATAR_HOST}/avatar/${hashedId}/${name[0]}.png`;
return cbUrl && cbResponse && cbResponse.status === 200 ? cbUrl : tileyUrl;
}

22
server/utils/fs.js Normal file
View File

@@ -0,0 +1,22 @@
// @flow
import path from "path";
import fs from "fs-extra";
export function requireDirectory<T>(dirName: string): [T, string][] {
return fs
.readdirSync(dirName)
.filter(
(file) =>
file.indexOf(".") !== 0 &&
file.endsWith(".js") &&
file !== path.basename(__filename) &&
!file.includes(".test")
)
.map((fileName) => {
const filePath = path.join(dirName, fileName);
const name = path.basename(filePath.replace(/\.js$/, ""));
// $FlowIssue
return [require(filePath), name];
});
}

50
server/utils/passport.js Normal file
View File

@@ -0,0 +1,50 @@
// @flow
import addMinutes from "date-fns/add_minutes";
import subMinutes from "date-fns/sub_minutes";
import { type Request } from "koa";
import { OAuthStateMismatchError } from "../errors";
import { getCookieDomain } from "./domains";
export class StateStore {
key: string = "state";
store = (req: Request, callback: (err: ?Error, state?: string) => void) => {
const state = Math.random().toString(36).substring(7);
// $FlowFixMe
req.cookies.set(this.key, state, {
httpOnly: false,
expires: addMinutes(new Date(), 10),
domain: getCookieDomain(req.hostname),
});
callback(null, state);
};
verify = (
req: Request,
providedState: string,
callback: (err: ?Error, ?boolean) => void
) => {
// $FlowFixMe
const state = req.cookies.get(this.key);
if (!state) {
return callback(
new OAuthStateMismatchError("State not return in OAuth flow")
);
}
// $FlowFixMe
req.cookies.set(this.key, "", {
httpOnly: false,
expires: subMinutes(new Date(), 1),
domain: getCookieDomain(req.hostname),
});
if (state !== providedState) {
return callback(new OAuthStateMismatchError());
}
callback(null, true);
};
}