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

[Web UI] Refresh tokens when GraphQL request produces 401 #1976

Merged
merged 2 commits into from
Sep 12, 2018
Merged
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
71 changes: 52 additions & 19 deletions dashboard/src/apollo/authLink.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,67 @@ import { when } from "/utils/promise";
import { UnauthorizedError } from "/errors/FetchError";
import QueryAbortedError from "/errors/QueryAbortedError";

import flagTokens from "/mutations/flagTokens";
import refreshTokens from "/mutations/refreshTokens";

const EXPIRY_THRESHOLD_MS = 13 * 60 * 1000;
const MAX_REFRESHES = 3;

const authLink = ({ getClient }) =>
new ApolloLink(
(operation, forward) =>
new Observable(observer => {
let sub;
refreshTokens(getClient(), {
notBefore: new Date(Date.now() + EXPIRY_THRESHOLD_MS).toISOString(),
})
.then(
({ data }) => {
operation.setContext({
headers: {
Authorization: `Bearer ${
data.refreshTokens.auth.accessToken
}`,
},
});
sub = forward(operation).subscribe(observer);
},
when(UnauthorizedError, error => {
throw new QueryAbortedError(error);
}),
)
.catch(observer.error.bind(observer));

const fetchToken = (attempts = 0) => {
const forceRefresh = attempts > 0;

refreshTokens(getClient(), {
notBefore: forceRefresh
? null
: new Date(Date.now() + EXPIRY_THRESHOLD_MS).toISOString(),
})
.then(
({ data }) => {
const { auth } = data.refreshTokens;

operation.setContext({
headers: {
Authorization: `Bearer ${auth.accessToken}`,
},
});

const nextObserver = {
next: observer.next.bind(observer),
complete: observer.complete.bind(observer),

// If chain results in an unauthorized error being thrown,
// either attempt to create a new access token or flag the
// auth token pair as invalid and throw query aborted err.
error: err => {
if (err instanceof UnauthorizedError) {
if (attempts < MAX_REFRESHES && !auth.invalid) {
sub.unsubscribe();
fetchToken(attempts + 1);
} else {
flagTokens(getClient());
observer.error(new QueryAbortedError(err));
}
} else {
observer.error(err);
}
},
};
sub = forward(operation).subscribe(nextObserver);
},
when(UnauthorizedError, error => {
throw new QueryAbortedError(error);
}),
)
.catch(observer.error.bind(observer));
};

fetchToken();

return () => {
if (sub) {
Expand Down
12 changes: 12 additions & 0 deletions dashboard/src/apollo/resolvers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ export default {
handleTokens(cache, "InvalidateTokensMutation"),
);
},

flagTokens: (_, vars, { cache }) => {
const data = {
auth: {
__typename: "Auth",
invalid: true,
},
};
cache.writeData({ data });

return null;
},
},
},
};
13 changes: 13 additions & 0 deletions dashboard/src/apollo/schema/client.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,25 @@ extend type Query {
}

extend type Mutation {
#
# Authentication

"Create new authorization tokens."
createTokens(username: String!, password: String!): Boolean

"Create new authorization tokens using refresh token."
refreshTokens(notBefore: DateTime): RefreshTokensPayload!

"Invalidates authorization tokens."
invalidateTokens: Boolean

"Flags authorization tokens as invalid."
flagTokens: Boolean

#
# Last Environment

"Stores given pair as user's last visited environment."
setLastEnvironment(organization: String!, environment: String!): Boolean
}

Expand Down
16 changes: 13 additions & 3 deletions dashboard/src/apollo/schema/combined.graphql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const Branding = createStyledComponent({
});

const Headline = createStyledComponent({
component: Typography,
component: "div",
styles: theme => ({
marginBottom: theme.spacing.unit * 3,
}),
Expand All @@ -46,7 +46,6 @@ const Container = createStyledComponent({

class SignInView extends React.Component {
static propTypes = {
classes: PropTypes.object.isRequired,
client: PropTypes.object.isRequired,
fullScreen: PropTypes.bool,
TransitionComponent: PropTypes.func,
Expand Down Expand Up @@ -85,7 +84,6 @@ class SignInView extends React.Component {

render() {
const {
classes,
fullScreen,
TransitionComponent,
onSuccess,
Expand Down
3 changes: 2 additions & 1 deletion dashboard/src/components/util/DefaultRedirect.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const query = gql`
query DefaultRedirectQuery {
auth @client {
accessToken
invalid
}
}
`;
Expand All @@ -20,7 +21,7 @@ class DefaultRedirect extends React.PureComponent {
};

render() {
if (!this.props.data.auth.accessToken) {
if (!this.props.data.auth.accessToken || this.props.data.auth.invalid) {
return <SigninRedirect />;
}
return <LastEnvironmentRedirect />;
Expand Down
22 changes: 11 additions & 11 deletions dashboard/src/components/util/LastEnvironmentRedirect.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import React from "react";
import PropTypes from "prop-types";
import { compose } from "recompose";
import { Redirect, withRouter } from "react-router-dom";
import { graphql, Query } from "react-apollo";
import { redirectKey } from "/constants/queryParams";
import gql from "graphql-tag";

import Query from "/components/util/Query";

const primaryQuery = gql`
query LastEnvironmentQuery {
lastEnvironment @client {
Expand All @@ -30,15 +30,12 @@ const fallbackQuery = gql`

class LastEnvironmentRedirect extends React.PureComponent {
static propTypes = {
// from graphql HOC
data: PropTypes.object.isRequired,

// from withRouter HOC
location: PropTypes.object.isRequired,
};

renderFallback = ({ data, loading }) => {
if (loading) {
renderFallback = ({ data, aborted, loading }) => {
if (loading || aborted) {
return null;
}

Expand All @@ -55,8 +52,8 @@ class LastEnvironmentRedirect extends React.PureComponent {
return <Redirect to={`/${firstOrg.name}/${firstEnv.name}`} />;
};

render() {
const { location, data } = this.props;
renderRedirect = ({ data }) => {
const { location } = this.props;

// 1. if 'redirect-to' query parameter is present use given path.
const queryParams = new URLSearchParams(location.search);
Expand All @@ -78,8 +75,11 @@ class LastEnvironmentRedirect extends React.PureComponent {
lastEnvironment.environment,
].join("/");
return <Redirect to={nextPath} />;
};

render() {
return <Query query={primaryQuery}>{this.renderRedirect}</Query>;
}
}

const enhance = compose(graphql(primaryQuery), withRouter);
export default enhance(LastEnvironmentRedirect);
export default withRouter(LastEnvironmentRedirect);
4 changes: 3 additions & 1 deletion dashboard/src/components/util/UnauthenticatedRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,17 @@ class UnauthenticatedRoute extends React.PureComponent {

render() {
const { data, ...props } = this.props;
const authenticated = data.auth.accessToken && !data.auth.invalid;

return <ConditionalRoute {...props} active={!data.auth.accessToken} />;
return <ConditionalRoute {...props} active={!authenticated} />;
}
}

export default graphql(gql`
query UnauthenticatedRouteQuery {
auth @client {
accessToken
invalid
}
}
`)(UnauthenticatedRoute);
9 changes: 9 additions & 0 deletions dashboard/src/mutations/flagTokens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import gql from "graphql-tag";

const mutation = gql`
mutation FlagTokensMutation {
flagTokens @client
}
`;

export default client => client.mutate({ mutation });