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: Add sign in/up info in auth URL generated by Passport #320

Merged
merged 11 commits into from
Sep 28, 2018
Merged
Show file tree
Hide file tree
Changes from 9 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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ KEYCLOAK_REDIRECT_URI=http://localhost:4000/auth
STRIPE_PUBLIC_API_KEY=ENTER_STRIPE_PUBLIC_KEY_HERE
OAUTH2_AUTH_URL=http://localhost:4444/oauth2/auth
OAUTH2_TOKEN_URL=http://hydra:4444/oauth2/token
HYDRA_ADMIN_URL=http://hydra:4445
OAUTH2_CLIENT_ID=reaction-next-starterkit
OAUTH2_CLIENT_SECRET=CHANGEME
OAUTH2_REDIRECT_URL=http://localhost:4000/callback
OAUTH2_IDP_HOST_URL=http://reaction.api.reaction.localhost:3000/
PASSPORT_SESSION_SECRET=CHANGEME
CANONICAL_URL=http://example.com
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"react-stripe-elements": "^2.0.1",
"react-tracking": "^5.2.1",
"reacto-form": "^0.0.2",
"request": "^2.88.0",
"styled-components": "^3.4.9"
},
"devDependencies": {
Expand Down Expand Up @@ -105,7 +106,6 @@
"jest-transform-graphql": "2.1.0",
"mocha": "^5.2.0",
"react-test-renderer": "^16.3.1",
"request": "^2.87.0",
"rimraf": "^2.6.2",
"snyk": "^1.73.0"
},
Expand Down
29 changes: 15 additions & 14 deletions src/components/AccountDropdown/AccountDropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { inject, observer } from "mobx-react";
import { withStyles } from "@material-ui/core/styles";
import IconButton from "@material-ui/core/IconButton";
import Button from "@material-ui/core/Button";
import ButtonBase from "@material-ui/core/ButtonBase";
import AccountIcon from "mdi-material-ui/Account";
import Popover from "@material-ui/core/Popover";
import ViewerInfo from "@reactioncommerce/components/ViewerInfo/v1";
Expand All @@ -25,6 +26,7 @@ const styles = (theme) => ({
class AccountDropdown extends Component {
static propTypes = {
authStore: PropTypes.object.isRequired,
viewer: PropTypes.object,
classes: PropTypes.object
};

Expand Down Expand Up @@ -83,12 +85,19 @@ class AccountDropdown extends Component {
render() {
const { classes, authStore } = this.props;
const { anchorElement } = this.state;
const { account } = authStore;

return (
<Fragment>
<IconButton color="inherit" onClick={this.toggleOpen}>
<AccountIcon />
</IconButton>
{ authStore.isAuthenticated ?
<ButtonBase onClick={this.toggleOpen}>
<ViewerInfo viewer={account} />
</ButtonBase>
:
<IconButton color="inherit" onClick={this.toggleOpen}>
<AccountIcon />
</IconButton>
}

<Popover
anchorEl={anchorElement}
Expand All @@ -102,26 +111,18 @@ class AccountDropdown extends Component {
<div className={classes.accountDropdown}>
{authStore.isAuthenticated ?
<Fragment>
<div className={classes.authContent}>
<ViewerInfo
viewer={{
firstName: authStore.account.name,
lastName: " "
}}
/>
</div>
<Button color="primary" fullWidth href="/logout" variant="raised">
<Button color="primary" fullWidth href={`/logout/${account._id}`} variant="raised">
Sign Out
</Button>
</Fragment>
:
<Fragment>
<div className={classes.authContent}>
<Button color="primary" fullWidth href="/auth2" variant="raised">
<Button color="primary" fullWidth href="/signin" variant="raised">
Sign In
</Button>
</div>
<Button color="primary" fullWidth href="/auth2">
<Button color="primary" fullWidth href="/signup">
Create Account
</Button>
</Fragment>
Expand Down
4 changes: 2 additions & 2 deletions src/components/Entry/Entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ export default class Entry extends Component {

static defaultProps = {
onLoginButtonClick() {
Router.pushRoute("/auth2");
Router.pushRoute("/signin");
},
onRegisterButtonClick() {
Router.pushRoute("/auth2");
Router.pushRoute("/signup");
},
setEmailOnAnonymousCart() {}
};
Expand Down
17 changes: 2 additions & 15 deletions src/components/Header/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { NavigationDesktop } from "components/NavigationDesktop";
import { NavigationMobile, NavigationToggleMobile } from "components/NavigationMobile";
import AccountDropdown from "components/AccountDropdown";
import ShopLogo from "@reactioncommerce/components/ShopLogo/v1";
import ViewerInfo from "@reactioncommerce/components/ViewerInfo/v1";
import Link from "components/Link";
import MiniCart from "components/MiniCart";

Expand Down Expand Up @@ -59,20 +58,8 @@ class Header extends Component {
this.props.uiStore.toggleMenuDrawerOpen();
};

// TODO: quick fix until we figure out the viewer name stuff.
// See https://github.com/reactioncommerce/reaction/issues/4646
get splitNames() {
const { viewer: { name } } = this.props;
const [firstName, lastName] = name.split(" ");

return {
firstName,
lastName
};
}

render() {
const { classes: { appBar, controls, toolbar, title }, shop, viewer } = this.props;
const { classes: { appBar, controls, toolbar, title }, shop } = this.props;

return (
<AppBar position="static" elevation={0} className={appBar}>
Expand All @@ -93,7 +80,7 @@ class Header extends Component {
</Hidden>
</div>

{viewer ? <ViewerInfo viewer={{ ...this.splitNames, ...viewer }} /> : <AccountDropdown />}
<AccountDropdown />
<MiniCart />
</Toolbar>
<NavigationMobile />
Expand Down
2 changes: 1 addition & 1 deletion src/containers/account/withViewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default function withViewer(Component) {
return (
<Query query={viewerQuery}>
{({ data }) => {
if (data && data.viewer) {
if (data) {
authStore.setAccount(data.viewer);
}

Expand Down
21 changes: 19 additions & 2 deletions src/lib/stores/AuthStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,26 @@ class AuthStore {
return false;
}

// TODO: Temporary workaround until name fields get added from GQL
// See https://github.com/reactioncommerce/reaction/issues/4646
splitNames(account) {
const { name } = account;
const [firstName, lastName] = name.split(" ");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mike probably from this?
Maybe something like const [firstName, lastName] = name && name.split(" ");

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay. Will push a fix


return {
firstName,
lastName
};
}

@action setAccount(account) {
this.accountId = account._id || null;
this.account = account;
if (account) {
this.accountId = account._id || null;
this.account = { ...this.splitNames(account), ...account };
} else {
this.accountId = null;
this.account = {};
}
}
}

Expand Down
38 changes: 30 additions & 8 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import cookieParser from "cookie-parser";
import express from "express";
import session from "express-session";
import nextApp from "next";
import request from "request";
import { useStaticRendering } from "mobx-react";
import logger from "lib/logger";
import passport from "passport";
Expand All @@ -12,6 +13,18 @@ import router from "./routes";

const app = nextApp({ dir: appPath, dev });
const routeHandler = router.getRequestHandler(app);
const decodeOpaqueId = (opaqueId) => {
if (opaqueId === undefined || opaqueId === null) return null;
const unencoded = Buffer.from(opaqueId, "base64").toString("utf8");
const [namespace, id] = unencoded.split(":");
return { namespace, id };
};

// This is needed to allow custom parameters (e.g loginActions) to be included
// when requesting authorization. This is setup to allow only loginAction to pass through
OAuth2Strategy.prototype.authorizationParams = function (options = {}) {
return { loginAction: options.loginAction };
};

useStaticRendering(true);

Expand Down Expand Up @@ -46,21 +59,30 @@ app
server.use(passport.session());
server.use(cookieParser());

// This endpoint initializes the OAuth2 request
server.get("/auth2", (req, res, next) => {
if (!req.user) req.session.redirectTo = req.get("Referer");
server.get("/signin", (req, res, next) => {
req.session.redirectTo = req.get("Referer");
next(); // eslint-disable-line promise/no-callback-in-promise
}, passport.authenticate("oauth2", { loginAction: "signin" }));

server.get("/signup", (req, res, next) => {
req.session.redirectTo = req.get("Referer");
next(); // eslint-disable-line promise/no-callback-in-promise
}, passport.authenticate("oauth2"));
}, passport.authenticate("oauth2", { loginAction: "signup" }));

// This endpoint handles OAuth2 requests (exchanges code for token)
server.get("/callback", passport.authenticate("oauth2"), (req, res) => {
// After success, redirect to the page we came from originally
res.redirect(req.session.redirectTo);
res.redirect(req.session.redirectTo || "/");
});

server.get("/logout", (req, res) => {
req.logout();
res.redirect(req.get("Referer"));
server.get("/logout/:userId", (req, res) => {
const { id } = decodeOpaqueId(req.params.userId);
request(`${process.env.OAUTH2_IDP_HOST_URL}logout?userId=${id}`, (error) => {
if (!error) {
req.logout();
res.redirect(req.get("Referer") || "/");
}
});
});

// Setup next routes
Expand Down
Loading