Skip to content

Commit

Permalink
remove logs and update tsconfig
Browse files Browse the repository at this point in the history
  • Loading branch information
bluebeel committed Dec 7, 2020
1 parent 8d2110c commit 65e4fe5
Show file tree
Hide file tree
Showing 8 changed files with 138 additions and 35 deletions.
52 changes: 42 additions & 10 deletions src/auth/create-oauth-callback.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import querystring from 'querystring';
import querystring from "querystring";

import type { NextApiRequest, NextApiResponse } from 'next';
import type { NextApiRequest, NextApiResponse } from "next";

import {AuthConfig} from '../types';
import { AuthConfig } from "../types";

import ShopifyError, { ErrorResponse } from "./errors";
import validateHmac from './validate-hmac';
import validateHmac from "./validate-hmac";
//import { setCookie } from '../helpers/cookies';
import cookie from "cookie";

export default function createOAuthCallback(config: AuthConfig) {
return async function oAuthCallback(req: NextApiRequest,res: NextApiResponse) {
return async function oAuthCallback(
req: NextApiRequest,
res: NextApiResponse
) {
const query = req.query as Record<string, string>;
const { code, hmac, shop, state: nonce } = query;
const { apiKey, secret, afterAuth } = config;
Expand Down Expand Up @@ -52,13 +57,13 @@ export default function createOAuthCallback(config: AuthConfig) {
const accessTokenResponse = await fetch(
`https://${shop}/admin/oauth/access_token`,
{
method: 'POST',
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(accessTokenQuery).toString(),
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(accessTokenQuery).toString(),
},
body: accessTokenQuery,
},
}
);

if (!accessTokenResponse.ok) {
Expand All @@ -77,9 +82,36 @@ export default function createOAuthCallback(config: AuthConfig) {
associated_user: associatedUser,
} = accessTokenData;

res.setHeader("Set-Cookie", [
cookie.serialize("shopOrigin", String(shop), {
secure: true,
httpOnly: false,
sameSite: "none",
path: "/",
}),
cookie.serialize("shopifyToken", String(accessToken), {
secure: true,
httpOnly: false,
sameSite: "none",
path: "/",
}),
cookie.serialize("shopifyAssociatedUser", JSON.stringify(associatedUser), {
secure: true,
httpOnly: false,
sameSite: "none",
path: "/",
}),
]);

if (afterAuth) {
await afterAuth({ shopOrigin: shop, shopifyToken: accessToken, shopifyScope: associatedUserScope, shopifyAssociatedUser: associatedUser, req, res })
await afterAuth({
shopOrigin: shop,
shopifyToken: accessToken,
shopifyScope: associatedUserScope,
shopifyAssociatedUser: associatedUser,
req,
res,
});
}
};
}
4 changes: 2 additions & 2 deletions src/auth/create-oauth-start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {OAuthStartOptions} from '../types';
import ShopifyError, { ErrorResponse } from "./errors";
import oAuthQueryString from './oauth-query-string';
import { DEFAULT_ACCESS_MODE, DEFAULT_MYSHOPIFY_DOMAIN, TOP_LEVEL_OAUTH_COOKIE_NAME } from "./index";
import {setCookie} from "../helpers/cookies";
import {destroyCookie} from "../helpers/cookies";

export default function createOAuthStart(
options: OAuthStartOptions,
Expand Down Expand Up @@ -37,7 +37,7 @@ export default function createOAuthStart(
return;
}

setCookie({res,name: TOP_LEVEL_OAUTH_COOKIE_NAME, value: ''});
destroyCookie({ res, name: TOP_LEVEL_OAUTH_COOKIE_NAME });


const formattedQueryString = oAuthQueryString(req, res, options, callbackPath);
Expand Down
9 changes: 7 additions & 2 deletions src/auth/redirection-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ type RedirectionParams = {
export default function redirectionScript({
origin,
redirectTo,
apiKey,
apiKey
}: RedirectionParams) {
return `
<script src="https://unpkg.com/@shopify/app-bridge@^1"></script> <script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
// If the current window is the 'child', change the parent's URL with postMessage
if (window.top === window.self) {
// If the current window is the 'parent', change the URL by setting location.href
window.location.href = "${redirectTo}";
} else {
// If the current window is the 'child', change the parent's URL with postMessage
var AppBridge = window['app-bridge'];
var createApp = AppBridge.default;
var Redirect = AppBridge.actions.Redirect;
Expand All @@ -22,6 +26,7 @@ export default function redirectionScript({
});
var redirect = Redirect.create(app);
redirect.dispatch(Redirect.Action.REMOTE, "${redirectTo}");
}
});
</script>
`;
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ export * from "./auth";
export * from "./types";

export { default as verifyRequest } from "./verify-request";

export { default as authenticateShopifyPage } from "./requireAuthentication";
52 changes: 52 additions & 0 deletions src/requireAuthentication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {
GetServerSidePropsContext,
} from "next";
import { parseCookies } from "nookies";
import verifyRequest from "./verify-request/verify-request";

// Overwrite ServerResponse to allow `shopOrigin`
interface GetServerSideShopifyPropsContext extends GetServerSidePropsContext {
shopOrigin?: string;
}


export type GetServerSideProps<
P extends { [key: string]: any } = { [key: string]: any }
> = (context: GetServerSideShopifyPropsContext) => Promise<{ props: P }>;

const authenticateShopifyPage = async (
getServerSidePropsInner: GetServerSideProps = async () => ({ props: {} })
) => {
const getServerSideProps: GetServerSideProps = async (ctx) => {
const pathname = new URL(ctx.resolvedUrl).pathname;

const authRoute = "/api/shopify/auth";
const fallbackRoute = "/login";
const verifyTokenUrl = `${process.env.HOST}/api/shopify/verify-token`;
const cookies = parseCookies(ctx);
const shopOrigin = ctx.query.shop ?? cookies.shopOrigin;

if (pathname !== fallbackRoute) {
await verifyRequest({
query: ctx.query,
cookies,
res: ctx.res,
options: { authRoute, fallbackRoute, verifyTokenUrl },
});
}

ctx.shopOrigin = shopOrigin as string;

const result = await getServerSidePropsInner(ctx);

return {
props: {
shopOrigin,
...result.props,
},
};
};
return getServerSideProps;
};

export default authenticateShopifyPage;
8 changes: 4 additions & 4 deletions src/verify-request/utilities.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Routes } from "./types";
import { ServerResponse } from "http";
import { setCookie } from "../helpers/cookies";
import { destroyCookie } from "../helpers/cookies";

export function redirectToAuth({
shop,
Expand All @@ -19,7 +19,7 @@ export function redirectToAuth({
}

export function clearSession({ res }: { res?: ServerResponse }) {
setCookie({ res, name: "shopSettingsId", value: "" });
setCookie({ res, name: "shopOrigin", value: "" });
setCookie({ res, name: "shopifyToken", value: "" });
destroyCookie({ res, name: "shopSettingsId" });
destroyCookie({ res, name: "shopOrigin" });
destroyCookie({ res, name: "shopifyToken" });
}
29 changes: 16 additions & 13 deletions src/verify-request/verify-request.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { ServerResponse } from "http";

import {loginAgainIfDifferentShop} from './login-again-if-different-shop';
import {verifyToken} from './verify-token';
import {Options, Routes} from './types';
import { loginAgainIfDifferentShop } from "./login-again-if-different-shop";
import { verifyToken } from "./verify-token";
import { Options, Routes } from "./types";

export default async function verifyRequest({
query,
cookies,
res,
options,
}: {
query: Record<string, string | string[]>;
query,
cookies,
res,
options,
}: {
query: Record<string, string | string[] | undefined>;
cookies: Record<string, string>;
res?: ServerResponse;
options: Options;
Expand All @@ -21,8 +21,6 @@ export default async function verifyRequest({
};

const shopFromQuery = Array.isArray(query.shop) ? query.shop[0] : query.shop;
console.log("lib", cookies)
console.log("shop", shopFromQuery)
if (shopFromQuery && cookies.shopOrigin) {
if (shopFromQuery !== cookies.shopOrigin) {
// go through login process if different shops
Expand All @@ -33,6 +31,11 @@ export default async function verifyRequest({
const shopifyToken = cookies.shopifyToken;
const shopOrigin = shopFromQuery ?? cookies.shopOrigin;

await verifyToken({ shopOrigin, shopifyToken, res, routes, verifyTokenUrl: options.verifyTokenUrl });

await verifyToken({
shopOrigin,
shopifyToken,
res,
routes,
verifyTokenUrl: options.verifyTokenUrl,
});
}
17 changes: 13 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"noUnusedLocals": true,
"importHelpers": true,
"lib": [
"dom",
"dom.iterable",
"es2015",
"es2016",
"es2017",
"es2018",
"esnext.asynciterable"
],
"rootDir": "src",
"outDir": "dist",
"sourceMap": true,
"sourceMap": false,
"strict": true,
"lib": ["dom"],
"esModuleInterop": true,
"declaration": true,
"declarationMap": true,
"skipLibCheck": true
"skipLibCheck": true,
"downlevelIteration": true,
},
"exclude": ["node_modules", "dist"]
}

0 comments on commit 65e4fe5

Please sign in to comment.