chore: Migrate authentication to new tables (#1929)
This work provides a foundation for a more pluggable authentication system such as the one outlined in #1317. closes #1317
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
// @flow
|
||||
import subMinutes from "date-fns/sub_minutes";
|
||||
import Router from "koa-router";
|
||||
import { find } from "lodash";
|
||||
import { AuthorizationError } from "../errors";
|
||||
import mailer from "../mailer";
|
||||
import auth from "../middlewares/authentication";
|
||||
@@ -19,23 +20,27 @@ router.post("email", async (ctx) => {
|
||||
|
||||
ctx.assertEmail(email, "email is required");
|
||||
|
||||
const user = await User.findOne({
|
||||
const user = await User.scope("withAuthentications").findOne({
|
||||
where: { email: email.toLowerCase() },
|
||||
});
|
||||
|
||||
if (user) {
|
||||
const team = await Team.findByPk(user.teamId);
|
||||
const team = await Team.scope("withAuthenticationProviders").findByPk(
|
||||
user.teamId
|
||||
);
|
||||
if (!team) {
|
||||
ctx.redirect(`/?notice=auth-error`);
|
||||
return;
|
||||
}
|
||||
|
||||
// If the user matches an email address associated with an SSO
|
||||
// signin then just forward them directly to that service's
|
||||
// login page
|
||||
if (user.service && user.service !== "email") {
|
||||
// provider then just forward them directly to that sign-in page
|
||||
if (user.authentications.length) {
|
||||
const authProvider = find(team.authenticationProviders, {
|
||||
id: user.authentications[0].authenticationProviderId,
|
||||
});
|
||||
ctx.body = {
|
||||
redirect: `${team.url}/auth/${user.service}`,
|
||||
redirect: `${team.url}/auth/${authProvider.name}`,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -87,11 +92,7 @@ router.get("email.callback", auth({ required: false }), async (ctx) => {
|
||||
throw new AuthorizationError();
|
||||
}
|
||||
|
||||
if (!user.service) {
|
||||
user.service = "email";
|
||||
user.lastActiveAt = new Date();
|
||||
await user.save();
|
||||
}
|
||||
await user.update({ lastActiveAt: new Date() });
|
||||
|
||||
// set cookies on response and redirect to team subdomain
|
||||
ctx.signIn(user, team, "email", false);
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// @flow
|
||||
import crypto from "crypto";
|
||||
import * as Sentry from "@sentry/node";
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import invariant from "invariant";
|
||||
import Router from "koa-router";
|
||||
import { capitalize } from "lodash";
|
||||
import Sequelize from "sequelize";
|
||||
import teamCreator from "../commands/teamCreator";
|
||||
import userCreator from "../commands/userCreator";
|
||||
import auth from "../middlewares/authentication";
|
||||
import { User, Team } from "../models";
|
||||
|
||||
const Op = Sequelize.Op;
|
||||
import { User } from "../models";
|
||||
|
||||
const router = new Router();
|
||||
const client = new OAuth2Client(
|
||||
@@ -55,90 +55,60 @@ router.get("google.callback", auth({ required: false }), async (ctx) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const googleId = profile.data.hd;
|
||||
const hostname = profile.data.hd.split(".")[0];
|
||||
const teamName = capitalize(hostname);
|
||||
const domain = profile.data.hd;
|
||||
const subdomain = profile.data.hd.split(".")[0];
|
||||
const teamName = capitalize(subdomain);
|
||||
|
||||
// attempt to get logo from Clearbit API. If one doesn't exist then
|
||||
// fall back to using tiley to generate a placeholder logo
|
||||
const hash = crypto.createHash("sha256");
|
||||
hash.update(googleId);
|
||||
const hashedGoogleId = hash.digest("hex");
|
||||
const cbUrl = `https://logo.clearbit.com/${profile.data.hd}`;
|
||||
const tileyUrl = `https://tiley.herokuapp.com/avatar/${hashedGoogleId}/${teamName[0]}.png`;
|
||||
const cbResponse = await fetch(cbUrl);
|
||||
const avatarUrl = cbResponse.status === 200 ? cbUrl : tileyUrl;
|
||||
|
||||
let team, isFirstUser;
|
||||
let result;
|
||||
try {
|
||||
[team, isFirstUser] = await Team.findOrCreate({
|
||||
where: {
|
||||
googleId,
|
||||
},
|
||||
defaults: {
|
||||
name: teamName,
|
||||
avatarUrl,
|
||||
result = await teamCreator({
|
||||
name: teamName,
|
||||
domain,
|
||||
subdomain,
|
||||
authenticationProvider: {
|
||||
name: "google",
|
||||
providerId: domain,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof Sequelize.UniqueConstraintError) {
|
||||
ctx.redirect(`/?notice=auth-error`);
|
||||
ctx.redirect(`/?notice=auth-error&error=team-exists`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
invariant(team, "Team must exist");
|
||||
|
||||
invariant(result, "Team creator result must exist");
|
||||
const { team, isNewTeam, authenticationProvider } = result;
|
||||
|
||||
try {
|
||||
const [user, isFirstSignin] = await User.findOrCreate({
|
||||
where: {
|
||||
[Op.or]: [
|
||||
{
|
||||
service: "google",
|
||||
serviceId: profile.data.id,
|
||||
},
|
||||
{
|
||||
service: { [Op.eq]: null },
|
||||
email: profile.data.email,
|
||||
},
|
||||
],
|
||||
teamId: team.id,
|
||||
},
|
||||
defaults: {
|
||||
service: "google",
|
||||
serviceId: profile.data.id,
|
||||
name: profile.data.name,
|
||||
email: profile.data.email,
|
||||
isAdmin: isFirstUser,
|
||||
avatarUrl: profile.data.picture,
|
||||
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(" "),
|
||||
},
|
||||
});
|
||||
|
||||
// update the user with fresh details if they just accepted an invite
|
||||
if (!user.serviceId || !user.service) {
|
||||
await user.update({
|
||||
service: "google",
|
||||
serviceId: profile.data.id,
|
||||
avatarUrl: profile.data.picture,
|
||||
});
|
||||
}
|
||||
const { user, isNewUser } = result;
|
||||
|
||||
// update email address if it's changed in Google
|
||||
if (!isFirstSignin && profile.data.email !== user.email) {
|
||||
await user.update({ email: profile.data.email });
|
||||
}
|
||||
|
||||
if (isFirstUser) {
|
||||
if (isNewTeam) {
|
||||
await team.provisionFirstCollection(user.id);
|
||||
await team.provisionSubdomain(hostname);
|
||||
}
|
||||
|
||||
// set cookies on response and redirect to team subdomain
|
||||
ctx.signIn(user, team, "google", isFirstSignin);
|
||||
ctx.signIn(user, team, "google", isNewUser);
|
||||
} catch (err) {
|
||||
if (err instanceof Sequelize.UniqueConstraintError) {
|
||||
const exists = await User.findOne({
|
||||
where: {
|
||||
service: "email",
|
||||
email: profile.data.email,
|
||||
teamId: team.id,
|
||||
},
|
||||
@@ -147,6 +117,11 @@ router.get("google.callback", auth({ required: false }), async (ctx) => {
|
||||
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`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
// @flow
|
||||
import * as Sentry from "@sentry/node";
|
||||
import addHours from "date-fns/add_hours";
|
||||
import invariant from "invariant";
|
||||
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 auth from "../middlewares/authentication";
|
||||
import { Authentication, Collection, Integration, User, Team } from "../models";
|
||||
import * as Slack from "../slack";
|
||||
import { getCookieDomain } from "../utils/domains";
|
||||
|
||||
const Op = Sequelize.Op;
|
||||
const router = new Router();
|
||||
|
||||
// start the oauth process and redirect user to Slack
|
||||
@@ -41,76 +43,56 @@ router.get("slack.callback", auth({ required: false }), async (ctx) => {
|
||||
|
||||
const data = await Slack.oauthAccess(code);
|
||||
|
||||
let team, isFirstUser;
|
||||
let result;
|
||||
try {
|
||||
[team, isFirstUser] = await Team.findOrCreate({
|
||||
where: {
|
||||
slackId: data.team.id,
|
||||
},
|
||||
defaults: {
|
||||
name: data.team.name,
|
||||
avatarUrl: data.team.image_88,
|
||||
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`);
|
||||
ctx.redirect(`/?notice=auth-error&error=team-exists`);
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
invariant(team, "Team must exist");
|
||||
|
||||
invariant(result, "Team creator result must exist");
|
||||
const { authenticationProvider, team, isNewTeam } = result;
|
||||
|
||||
try {
|
||||
const [user, isFirstSignin] = await User.findOrCreate({
|
||||
where: {
|
||||
[Op.or]: [
|
||||
{
|
||||
service: "slack",
|
||||
serviceId: data.user.id,
|
||||
},
|
||||
{
|
||||
service: { [Op.eq]: null },
|
||||
email: data.user.email,
|
||||
},
|
||||
],
|
||||
teamId: team.id,
|
||||
},
|
||||
defaults: {
|
||||
service: "slack",
|
||||
serviceId: data.user.id,
|
||||
name: data.user.name,
|
||||
email: data.user.email,
|
||||
isAdmin: isFirstUser,
|
||||
avatarUrl: data.user.image_192,
|
||||
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(","),
|
||||
},
|
||||
});
|
||||
|
||||
// update the user with fresh details if they just accepted an invite
|
||||
if (!user.serviceId || !user.service) {
|
||||
await user.update({
|
||||
service: "slack",
|
||||
serviceId: data.user.id,
|
||||
avatarUrl: data.user.image_192,
|
||||
});
|
||||
}
|
||||
const { user, isNewUser } = result;
|
||||
|
||||
// update email address if it's changed in Slack
|
||||
if (!isFirstSignin && data.user.email !== user.email) {
|
||||
await user.update({ email: data.user.email });
|
||||
}
|
||||
|
||||
if (isFirstUser) {
|
||||
if (isNewTeam) {
|
||||
await team.provisionFirstCollection(user.id);
|
||||
await team.provisionSubdomain(data.team.domain);
|
||||
}
|
||||
|
||||
// set cookies on response and redirect to team subdomain
|
||||
ctx.signIn(user, team, "slack", isFirstSignin);
|
||||
ctx.signIn(user, team, "slack", isNewUser);
|
||||
} catch (err) {
|
||||
if (err instanceof Sequelize.UniqueConstraintError) {
|
||||
const exists = await User.findOne({
|
||||
where: {
|
||||
service: "email",
|
||||
email: data.user.email,
|
||||
teamId: team.id,
|
||||
},
|
||||
@@ -119,6 +101,11 @@ router.get("slack.callback", auth({ required: false }), async (ctx) => {
|
||||
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`);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user