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

Office Hours Khoury OAuth Implementation #683

Draft
wants to merge 15 commits into
base: master
Choose a base branch
from
Draft
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
28 changes: 23 additions & 5 deletions packages/api-client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
CreateAlertResponse,
CreateQuestionParams,
CreateQuestionResponse,
DateRangeType,
DesktopNotifBody,
DesktopNotifPartial,
GetAlertsResponse,
Expand All @@ -15,10 +14,7 @@ import {
GetQueueResponse,
GetReleaseNotesResponse,
GetSelfEnrollResponse,
ListInsightsResponse,
ListQuestionsResponse,
SemesterPartial,
SubmitCourseParams,
TACheckinTimesResponse,
TACheckoutResponse,
TAUpdateStatusResponse,
Expand All @@ -28,6 +24,14 @@ import {
UpdateQuestionParams,
UpdateQuestionResponse,
UpdateQueueParams,
ListInsightsResponse,
DateRangeType,
SubmitCourseParams,
SemesterPartial,
OAuthAccessTokensResponse,
OAuthAccessTokensRequest,
AccessToken,
RefreshToken,
} from "@koh/common";
import Axios, { AxiosInstance, Method } from "axios";
import { plainToClass } from "class-transformer";
Expand Down Expand Up @@ -235,7 +239,21 @@ class APIClient {
this.req("PATCH", `/api/v1/alerts/${alertId}`);
},
};

oauth = {
tokens: async (
param: OAuthAccessTokensRequest
): Promise<OAuthAccessTokensResponse> =>
this.req(
"POST",
`/api/v1/oauth/tokens`,
OAuthAccessTokensResponse,
param
),
renewToken: async (param: RefreshToken): Promise<AccessToken> =>
this.req("POST", "/api/v1/oauth/tokens/refresh", AccessToken, param),
userInfo: async (param: AccessToken): Promise<void> =>
this.req("POST", `/api/v1/oauth/user`, undefined, param),
};
constructor(baseURL = "") {
this.axios = Axios.create({ baseURL: baseURL });
}
Expand Down
32 changes: 32 additions & 0 deletions packages/app/components/OAuth/OAuthErrorPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React, { ReactElement } from "react";
import styled from "styled-components";
import { Button } from "antd";
import Router from "next/router";

const Container = styled.div`
height: 80vh;
display: flex;
justify-content: center;
align-items: center;
`;

const ContentContainer = styled.div`
text-align: center;
`;

export default function OAuthErrorPage(): ReactElement {
return (
<Container>
<ContentContainer>
<h3> An error occurred while trying to login. Please try again. </h3>
<Button
onClick={() => {
Router.push("/login");
}}
>
Back Home
</Button>
</ContentContainer>
</Container>
);
}
8 changes: 3 additions & 5 deletions packages/app/components/Settings/SettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,9 @@ const ProfilePicButton = styled(Button)`
export default function SettingsPage({
defaultPage,
}: SettingsPageProps): ReactElement {
const {
data: profile,
error,
mutate,
} = useSWR(`api/v1/profile`, async () => API.profile.index());
const { data: profile, error, mutate } = useSWR(`api/v1/profile`, async () =>
API.profile.index()
);

const [currentSettings, setCurrentSettings] = useState(
defaultPage || SettingsOptions.PROFILE
Expand Down
9 changes: 4 additions & 5 deletions packages/app/components/Today/TACheckinButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,10 @@ export default function TACheckinButton({
);
}

const [checkoutModalInfo, setCheckoutModalInfo] =
useState<{
canClearQueue: boolean;
nextOfficeHourTime?: Date;
}>(EMPTY_CHECKOUT_INFO);
const [checkoutModalInfo, setCheckoutModalInfo] = useState<{
canClearQueue: boolean;
nextOfficeHourTime?: Date;
}>(EMPTY_CHECKOUT_INFO);
const closeModal = () => setCheckoutModalInfo(EMPTY_CHECKOUT_INFO);

return (
Expand Down
1 change: 1 addition & 0 deletions packages/app/hooks/useDefaultCourseRedirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export function useDefaultCourseRedirect(): boolean {
const [defaultCourse] = useLocalStorage("defaultCourse", null);
if (profile && profile.courses.length > 0) {
/// defaultCourse can get out-of-sync with the user's actual registered course (dropped class etc)
// TODO: Change from !!defaultCourse to defaultCourse
const isUserInDefaultCourse =
!!defaultCourse &&
profile.courses.some((c) => c.course.id === defaultCourse?.id);
Expand Down
7 changes: 5 additions & 2 deletions packages/app/hooks/useDraftQuestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ interface UseDraftQuestionResult {
deleteDraftQuestion: () => void;
}
export function useDraftQuestion(): UseDraftQuestionResult {
const [draftQuestion, setDraftQuestion, deleteDraftQuestion] =
useLocalStorage("draftQuestion", null);
const [
draftQuestion,
setDraftQuestion,
deleteDraftQuestion,
] = useLocalStorage("draftQuestion", null);
return {
draftQuestion,
setDraftQuestion,
Expand Down
6 changes: 1 addition & 5 deletions packages/app/hooks/useQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,7 @@ export function useQueue(qid: number, onUpdate?: OnUpdate): UseQueueReturn {
)
);

const {
data: queue,
error: queueError,
mutate: mutateQueue,
} = useSWR(
const { data: queue, error: queueError, mutate: mutateQueue } = useSWR(
key,
useCallback(async () => API.queues.get(Number(qid)), [qid]),
{
Expand Down
23 changes: 23 additions & 0 deletions packages/app/hooks/useSaveStateChallenge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export interface OAuthStateChallenge {
state: string;
challenge: string;
}

/**
*
* @param stateLength How long the state value should be
* @param hashLength How long the plaintext value of the challenge should be
* @returns The pair of the state and challenge plaintext value
*/
export function useSaveStateChallenge(
stateLength: number,
hashLength: number
): OAuthStateChallenge {
const state = Math.random().toString(20).substr(2, stateLength);
const challenge = Math.random().toString(20).substr(2, hashLength);

return {
state,
challenge,
};
}
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"next-compose-plugins": "^2.2.0",
"next-offline": "^5.0.2",
"next-transpile-modules": "^3.3.0",
"node-forge": "^0.10.0",
"platform": "^1.3.6",
"react": "16.13.1",
"react-big-calendar": "^0.24.6",
Expand Down
3 changes: 2 additions & 1 deletion packages/app/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import * as Sentry from "@sentry/node";
if (process.env.NODE_ENV === "production" && typeof window !== "undefined") {
Sentry.init({
enabled: process.env.NODE_ENV === "production",
dsn: "https://[email protected]/5557379",
dsn:
"https://[email protected]/5557379",
tracesSampleRate: 0.2,
});
}
Expand Down
60 changes: 59 additions & 1 deletion packages/app/pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ import { useDefaultCourseRedirect } from "../hooks/useDefaultCourseRedirect";
import { User } from "@koh/common";
import Router from "next/router";
import { useProfile } from "../hooks/useProfile";
import { useSaveStateChallenge } from "../hooks/useSaveStateChallenge";
import {
KHOURY_ADMIN_OAUTH_URL,
OAUTH_CLIENT_ID,
OAUTH_REDIRECT_URI,
OAUTH_SCOPES,
} from "@koh/common";

let forge = require("node-forge");
const isWindow = typeof window !== "undefined";

const Container = styled.div`
height: 80vh;
Expand All @@ -16,6 +26,38 @@ const Container = styled.div`
const ContentContainer = styled.div`
text-align: center;
`;
/**
* Opens a new window that directs a user to the Khoury OAuth login page and passes in
* the Office Hour client properties used for verification.
*/
function openKhouryOAuthLoginPage() {
let stateVal = "";
let codeVal = "";
if (isWindow) {
stateVal = window.localStorage.getItem("state");
codeVal = window.localStorage.getItem("challenge");
}
let md = forge.md.sha256.create();
md.update(codeVal);
const hashedCodeChallenge: string = md.digest().toHex();
const windowReference = window.open(
Copy link
Collaborator

Choose a reason for hiding this comment

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

Feel free to change it whenever we re-visit this, but can this be a string literal?

KHOURY_ADMIN_OAUTH_URL +
"/login?response_type=code&client_id=" +
OAUTH_CLIENT_ID +
"&redirect_uri=" +
OAUTH_REDIRECT_URI +
"&" +
OAUTH_SCOPES +
"&state=" +
stateVal +
"&challenge=" +
hashedCodeChallenge,
"_blank"
);
if (window.focus) {
windowReference.focus();
}
}

export default function Login(): ReactElement {
const profile: User = useProfile();
Expand All @@ -24,12 +66,28 @@ export default function Login(): ReactElement {
Router.push("/nocourses");
}

const stateChallengeLocalStorage = useSaveStateChallenge(6, 6);
const localState = stateChallengeLocalStorage.state;
const localChallenge = stateChallengeLocalStorage.challenge;

if (
isWindow &&
window.localStorage.getItem("state") === null &&
window.localStorage.getItem("challenge") === null
) {
window.localStorage.setItem("state", localState);
window.localStorage.setItem("challenge", localChallenge);
}
return (
<Container>
<ContentContainer>
<h1>You are currently not logged in</h1>
<p>Click the button below to login via Khoury Admin</p>
<Button href="https://admin.khoury.northeastern.edu/teaching/officehourslogin/">
<Button
onClick={() => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

i dont think you have to wrap this function in a lambda, you can just pass it in as data

openKhouryOAuthLoginPage();
}}
>
Log in via Khoury Admin
</Button>
</ContentContainer>
Expand Down
72 changes: 72 additions & 0 deletions packages/app/pages/oauth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { API } from "@koh/api-client";
import { useRouter } from "next/router";
import { ReactElement, useState } from "react";
import { StandardPageContainer } from "../components/common/PageContainer";
import Router from "next/router";
import { OAuthAccessTokensRequest } from "@koh/common";
import { Spin } from "antd";
import OAuthErrorPage from "../components/OAuth/OAuthErrorPage";

const isWindow = typeof window !== "undefined";

async function signUserIn(request: OAuthAccessTokensRequest): Promise<boolean> {
let tokens;
try {
tokens = await API.oauth.tokens(request);
} catch (err) {
return false;
}
let params = {
access: tokens.access,
};
const userLoginResult = await API.oauth
.userInfo(params)
.then(() => {
return true;
})
.catch(() => {
return false;
});
return userLoginResult;
}

export default function OAuth(): ReactElement {
const router = useRouter();
const state = router.query.state;
const authCode = router.query.code;
let [hasError, setHasError] = useState(false);

let tokensRequestBody: OAuthAccessTokensRequest;

if (state && authCode && isWindow) {
const storedState = window.localStorage.getItem("state");
const storedChallenge = window.localStorage.getItem("challenge");
if (storedState != state) {
// if the states are not equal then a CRSF attack may be happening so do not continue with OAuth sign in and return to login
// also, may want to notify khoury admin page. An error also could have happened so that is another possibility.
Router.push("/login");
} else {
tokensRequestBody = {
code: authCode as string,
verifier: storedChallenge,
};
signUserIn(tokensRequestBody)
.then((result) => {
if (result) {
Router.push("/nocourses");
} else {
setHasError(true);
}
})
.catch(() => {
setHasError(true);
});
}
}

return (
<StandardPageContainer>
{hasError ? <OAuthErrorPage /> : <Spin style={{ margin: "10% 45%" }} />}
</StandardPageContainer>
);
}
Loading