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

(FE, CLI) Add discord invite code workflow #288

Merged
merged 6 commits into from Aug 25, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 6 additions & 5 deletions packages/cli/src/bin/index.ts
Expand Up @@ -17,12 +17,13 @@ if (parseFloat(nodeVersion) >= 10.0) {

const hasDiscordInveite = args && args[0]?.includes("--")

const isDefaultCommand = (args.length === 0 || true) || ["open", "."].some((x) => args && args[0] === x);

if(["version", "--version"].includes(args[0])) {
const commandArgs = args ? args.filter((a) => !a.startsWith("-")) : [];
const isDefaultCommand = (commandArgs.length === 0) || ["open", "."].some((x) => args && args[0] === x);
const isHelpArg = helpArgs.includes(args[0]);
if(["version", "--version", "-v"].includes(args[0])) {
// Do nothing since version gets printed for every command
} else {
if (isDefaultCommand) {
if (isDefaultCommand && !isHelpArg) {
// console.log("Choose a command to run");
// new EntryCommand().help();

Expand All @@ -45,7 +46,7 @@ if (parseFloat(nodeVersion) >= 10.0) {

execSync(`${getRecorderDistCommand()} --crusher-cli-path=${eval("__dirname") + "/index.js"} ${customFlags} --no-sandbox`, {stdio: "inherit"});
});
} else if(helpArgs.includes(args[0])) {
} else if(isHelpArg) {
new EntryCommand().help();
} else {
new EntryCommand().run();
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/index.ts
@@ -1,4 +1,4 @@
import { Command } from "commander";
import { Command, program } from "commander";
import * as packgeJSON from "../../package.json";
import fs from "fs";
import path from "path";
Expand Down
25 changes: 17 additions & 8 deletions packages/cli/src/utils/hooks.ts
Expand Up @@ -20,16 +20,17 @@ const secretInviteCode = "crush"
*/
const checkForDiscord = async()=>{
const isCodeInCommandLine = process.argv.some((e)=>{
return e.includes("--") || e === secretInviteCode
return e.includes("--code=") && !["help", "--help", "-h"].includes(e)
})
const hasLoginFlag = process.argv.some((e) => e.includes("--login"));


if(isUserLoggedIn() || isCodeInCommandLine) return;

if(!isCodeInCommandLine){
if(!isCodeInCommandLine && !hasLoginFlag){
await cli.log(chalk.green(`New to crusher?`))

await cli.log(`Get access code - ${chalk.green("https://discord.com/")}`)
await cli.log(`Get access code - ${chalk.green("https://discord.gg/sWbWNYWv")}`)
await cli.log(`1.) Get access code on home screen`)
await cli.log(`2.) Run command with access code`)

Expand All @@ -40,28 +41,36 @@ const checkForDiscord = async()=>{
}
}

const parseDiscordFlag = (flag: string) => {
if(!flag) return null;
return flag.split("--code=")[1];
};

const waitForUserLogin = async (): Promise<string> => {
await checkForDiscord();

// ask for discord code here?
const discordCode = process.argv.find((i)=>{
return i.includes("--") || i===secretInviteCode
});

const discordCode = parseDiscordFlag(process.argv.find((i)=>{
return i.includes("--code=");
}));


const loginKey = await axios
.get(resolveBackendServerUrl("/cli/get.key"))
.then((res) => {
return res.data.loginKey;
});
const loginUrl = resolveFrontendServerUrl(`/login_sucessful?lK=${loginKey}&inviteCode=${discordCode}`);

await cli.log(
"Login or create an account to create/sync tests⚡⚡. Opening a browser to sync test.\nOr open this link:"
);
await cli.log(`${resolveFrontendServerUrl(`/login_sucessful?lK=${loginKey}&code=${discordCode}`)} \n`);
await cli.log(`${loginUrl} \n`);
await cli.action.start("Waiting for login");

await cli
.open(`${resolveFrontendServerUrl(`/login_sucessful?lK=${loginKey}&code=${discordCode}`)}`)
.open(loginUrl)
.catch((err) => {
console.error(err);
});
Expand Down
6 changes: 6 additions & 0 deletions packages/crusher-app/src/hooks/tempTest.tsx
Expand Up @@ -12,6 +12,7 @@ import { cliLoginUserKeyAtom } from "@store/atoms/global/cliToken";
import { backendRequest } from "@utils/common/backendRequest";
import { resolvePathToBackendURI } from "@utils/common/url";
import { RequestMethod } from "@types/RequestOptions";
import { inviteCodeUserKeyAtom } from "@store/atoms/global/inviteCode";

export const useLoadTempData = () => {
const [, setTempTest] = useAtom(tempTestAtom);
Expand All @@ -21,6 +22,7 @@ export const useLoadTempData = () => {
const [, setGithubToken] = useAtom(githubTokenAtom);
const [, setLoginKey] = useAtom(cliLoginUserKeyAtom);
const [, setProjectToRedirect] = useAtom(tempProjectAtom);
const [, setInviteCode] = useAtom(inviteCodeUserKeyAtom);

const { asPath } = useRouter();

Expand All @@ -35,6 +37,7 @@ export const useLoadTempData = () => {

const githubToken = urlQuery.get("github_token");
const loginKey = urlQuery.get("lK");
const inviteCode = urlQuery.get("inviteCode");

setTempTestName(tempTestName);
setTempTest(tempTestId);
Expand All @@ -50,6 +53,9 @@ export const useLoadTempData = () => {
console.error("Request failed");
});
}
if(!!inviteCode) {
setInviteCode(inviteCode);
}
if (githubToken) {
setGithubToken(githubToken);
}
Expand Down
15 changes: 15 additions & 0 deletions packages/crusher-app/src/store/atoms/global/inviteCode.ts
@@ -0,0 +1,15 @@
import { atom } from "jotai";

const LOCAL_STORAGE_KEY = "inviteCodeUserKeyAtom";
const primitiveInviteCodeUserKeyAtom = atom<string | null>(typeof window !== "undefined" ? localStorage.getItem(LOCAL_STORAGE_KEY) ?? null : null);

export const inviteCodeUserKeyAtom = atom(
(get) => get(primitiveInviteCodeUserKeyAtom),
(_get, set, newValue: any) => {
set(primitiveInviteCodeUserKeyAtom, newValue);
if(newValue == null) {
window.localStorage.removeItem(LOCAL_STORAGE_KEY);
}
window.localStorage.setItem(LOCAL_STORAGE_KEY, newValue);
},
);
4 changes: 4 additions & 0 deletions packages/crusher-app/src/utils/common/validationUtils.ts
Expand Up @@ -18,3 +18,7 @@ export const validateName = (name: string) => {
}
return true;
};

export const validateSessionInviteCode = (inviteCode: string) => {
return inviteCode && inviteCode.startsWith("CRU-");
};
14 changes: 9 additions & 5 deletions packages/crusher-app/src/utils/core/external.ts
Expand Up @@ -24,11 +24,15 @@ const getGithubOAuthURLLegacy = (alreadyAuthorized = false) => {
return githubUrl.toString();
};

export const getGithubLoginURL = () => {
const url = new URL("https://github.com/login/oauth/authorize");
url.searchParams.append("client_id", CLIENT_ID);
url.searchParams.append("state", `${btoa(JSON.stringify({ type: "auth" }))}`);

export const getGithubLoginURL = (inviteType, inviteCode, sessionInviteCode) => {
const url = new URL(resolvePathToBackendURI("/users/actions/auth.github"));
if(inviteCode && inviteType) {
url.searchParams.append("inviteCode", inviteCode);
url.searchParams.append("inviteType", inviteType);
}
if(sessionInviteCode) {
url.searchParams.append("sessionInviteCode", sessionInviteCode);
}
return url.toString();
};

Expand Down
Expand Up @@ -5,11 +5,11 @@ import { css } from "@emotion/react";
@Note - Wrong implementation of the loading state.
It should be implemented in the parent component.
*/
export function FormInput({ type, data, onChange, placeholder, autoComplete, onBlur, onKeyDown, onReturn }: any) {
export function FormInput({ type, data, onChange, placeholder, autoComplete, onBlur, onKeyDown, onReturn, className }: any) {
return (
<div>
<Input
className="md-20 bg"
className={`${className} md-20 bg`}
autoComplete={autoComplete}
value={data.value}
placeholder={placeholder}
Expand Down
3 changes: 2 additions & 1 deletion packages/crusher-app/src_ee/ui/containers/auth/login.tsx
Expand Up @@ -41,6 +41,7 @@ export const GithubSVG = function (props) {

export default function Login({ loginWithEmailHandler }) {
const router = useRouter();
const { query } = router;

return (
<div css={containerCSS}>
Expand Down Expand Up @@ -88,7 +89,7 @@ export default function Login({ loginWithEmailHandler }) {

<div css={overlayContainer} className={"mt-48 pb-60"}>
<div className={" mb-42"}>
<Link href={getGithubLoginURL()}>
<Link href={getGithubLoginURL(query?.inviteType?.toString(), query?.inviteCode?.toString(), null)}>
<Button className={"flex items-center justify-center"} css={githubButtonCSS}>
<GithubSVG />{" "}
<Text className={"ml-10"} fontSize={14} weight={700}>
Expand Down
13 changes: 9 additions & 4 deletions packages/crusher-app/src_ee/ui/containers/auth/signup.tsx
Expand Up @@ -153,6 +153,8 @@ import Link from "next/link";
import { getGithubLoginURL } from "@utils/core/external";
import { LoginNavBar } from "@ui/containers/common/login/navbar";
import React from "react";
import { useAtom } from "jotai";
import { inviteCodeUserKeyAtom } from "@store/atoms/global/inviteCode";
const RocketImage = (props) => (
<img
{...props}
Expand Down Expand Up @@ -186,7 +188,12 @@ export const GithubSVG = function (props) {

export default function SignupInitial({ loginWithEmailHandler }) {
const router = useRouter();

const { query } = router;
const [sessionInviteCode, setSessionInviteCode] = useAtom(inviteCodeUserKeyAtom);
const handleGithub = () => {
if(!sessionInviteCode) { alert("Invite code needed to signup"); return; }
window.location.href = getGithubLoginURL(query?.inviteType?.toString(), query?.inviteCode?.toString(), sessionInviteCode)
};
return (
<div css={containerCSS}>
<div className="pt-28">
Expand Down Expand Up @@ -233,14 +240,12 @@ export default function SignupInitial({ loginWithEmailHandler }) {

<div css={overlayContainer} className={"mt-48 pb-60"}>
<div className={" mb-42"}>
<Link href={getGithubLoginURL()}>
<Button className={"flex items-center justify-center"} css={githubButtonCSS}>
<Button onClick={handleGithub} className={"flex items-center justify-center"} css={githubButtonCSS}>
<GithubSVG />{" "}
<Text className={"ml-10"} fontSize={14} weight={700}>
Signup with Github
</Text>
</Button>
</Link>

{/* <Button
onClick={loginWithEmailHandler}
Expand Down
46 changes: 40 additions & 6 deletions packages/crusher-app/src_ee/ui/containers/auth/signup_email.tsx
Expand Up @@ -5,18 +5,20 @@ import { Text } from "dyson/src/components/atoms/text/Text";
import { useRouter } from "next/router";
import React, { useCallback, useState } from "react";
import { loadUserDataAndRedirect } from "@hooks/user";
import { validateEmail, validatePassword, validateName } from "@utils/common/validationUtils";
import { validateEmail, validatePassword, validateName, validateSessionInviteCode } from "@utils/common/validationUtils";
import { SubmitButton } from "./components/SubmitButton";
import { FormInput } from "./components/FormInput";

import { LoginNavBar } from "@ui/containers/common/login/navbar";
import { backendRequest } from "@utils/common/backendRequest";
import { RequestMethod } from "@types/RequestOptions";
import { inviteCodeUserKeyAtom } from "@store/atoms/global/inviteCode";
import { useAtom } from "jotai";

const registerUser = (name: string, email: string, password: string, inviteType: string | null = null, inviteCode: string | null = null) => {
const registerUser = (name: string, email: string, password: string, discordInviteCode: string, inviteType: string | null = null, inviteCode: string | null = null) => {
return backendRequest("/users/actions/signup", {
method: RequestMethod.POST,
payload: { email, password, name: name, lastName: "", inviteReferral: inviteType && inviteCode ? { code: inviteCode, type: inviteType } : null },
payload: { email, password, name: name, lastName: "", discordInviteCode: discordInviteCode, inviteReferral: inviteType && inviteCode ? { code: inviteCode, type: inviteType } : null },
});
};

Expand All @@ -28,6 +30,15 @@ export default function Signup_email({ loginWithEmailHandler }) {
const [email, setEmail] = useState({ value: "", error: "" });
const [password, setPassword] = useState({ value: "", error: "" });
const [name, setName] = useState({ value: "", error: "" });
const [sessionInviteCode, setSessionInviteCode] = useAtom(inviteCodeUserKeyAtom);

const [discordInviteCode, setDiscordInviteCode] = React.useState({value: "", error: ""});

React.useEffect(() => {
if(sessionInviteCode) {
setDiscordInviteCode({value: sessionInviteCode, error: ""});
}
}, [sessionInviteCode]);
const [loading, setLoading] = useState(false);

const emailChange = useCallback(
Expand All @@ -48,11 +59,16 @@ export default function Signup_email({ loginWithEmailHandler }) {
},
[name],
);
const inviteCodeChange = useCallback((e) => {
setDiscordInviteCode({...discordInviteCode, value: e.target.value});
}, [discordInviteCode]);

const verifyInfo = (completeVerify = false) => {
const shouldValidateEmail = completeVerify || email.value;
const shouldValidatePassword = completeVerify || password.value;
const shouldValidateName = completeVerify || name.value;
const shouldValidateInvitecode = completeVerify || discordInviteCode.value;

if (!validateEmail(email.value) && shouldValidateEmail) {
setEmail({ ...email, error: "Please enter valid email" });
} else setEmail({ ...email, error: "" });
Expand All @@ -64,16 +80,23 @@ export default function Signup_email({ loginWithEmailHandler }) {
if (!validateName(name.value) && shouldValidateName) {
setName({ ...name, error: "Please enter a valid name" });
} else setName({ ...name, error: "" });

if(!validateSessionInviteCode(discordInviteCode.value) && shouldValidateInvitecode) {
setDiscordInviteCode({...discordInviteCode, error: "Please enter correct invite code."})
} else {
setName({ ...name, error: ""});
}
};

const signupUser = async () => {
verifyInfo(true);

if (!validateEmail(email.value) || !validatePassword(password.value) || !validateName(email.value)) return;
if (!validateEmail(email.value) || !validatePassword(password.value) || !validateName(email.value) || !validateSessionInviteCode(discordInviteCode.value)) return;
setLoading(true);
try {
const data = await registerUser(name.value, email.value, password.value, query?.inviteType?.toString(), query?.inviteCode?.toString());
const data = await registerUser(name.value, email.value, password.value, discordInviteCode.value, query?.inviteType?.toString(), query?.inviteCode?.toString());
setData(data.systemInfo);
setSessionInviteCode(null);
} catch (e: any) {
console.error(e);
alert(e.message === "USER_EMAIL_NOT_AVAILABLE" ? "User already registered" : "Some error occurred while registering");
Expand Down Expand Up @@ -155,13 +178,24 @@ export default function Signup_email({ loginWithEmailHandler }) {
<FormInput
type={"password"}
data={password}
onReturn={signupUser.bind(this)}
onChange={passwordChange}
onEnter={signupOnEnter}
autoComplete={"new-password"}
placeholder={"Enter password"}
onBlur={verifyInfo.bind(this, false)}
/>
<FormInput
type={"text"}
data={discordInviteCode}
onReturn={signupUser.bind(this)}
onChange={inviteCodeChange}
onEnter={signupOnEnter}
placeholder={"Enter invite code"}
onBlur={verifyInfo.bind(this, false)}
/>
<div css={css`display: flex; justify-content: flex-end;`}>
<a href="https://discord.gg/sWbWNYWv" target="__blank" css={css`:hover { opacity: 0.8 }`}>Don't have any? Get one</a>
</div>
</div>

<SubmitButton text="Create an account" onSubmit={signupUser} loading={loading} />
Expand Down
Expand Up @@ -13,7 +13,7 @@ class CLIController {
@Get("/cli/get.key")
async getUniqueLoginKey() {
const key = uuidv4() + Date.now();
await this.redisManager.set(key, JSON.stringify({ userId: null, teamId: null }), { expiry: { type: "s", value: 5 * 60 } });
await this.redisManager.set(key, JSON.stringify({ userId: null, teamId: null }), { expiry: { type: "s", value: 60 * 60 } });
return { loginKey: key };
}

Expand Down
Expand Up @@ -128,7 +128,7 @@ class IntegrationsController {

// @TODO: Clean "cannot set headers after they are sent" error
@Get("/integrations/:project_id/github/actions/callback")
async connectGithubAccount(@QueryParams() params, @Req() req: any, @Res() res: any) {
async connectGithubAccount(@QueryParams() params: any, @Req() req: any, @Res() res: any) {
const { code, state: encodedState } = params;
const githubService = new GithubService();
const tokenInfo = await githubService.parseGithubAccessToken(code);
Expand All @@ -138,7 +138,7 @@ class IntegrationsController {
const userInfo = await githubService.getUserInfo((tokenInfo as any).token);
const githubRegisteredUser = await this.userService.getUserByGithubUserId(`${userInfo.id}`);

if (true || !githubRegisteredUser) {
if (!githubRegisteredUser) {
const userRecord = await this.userAuthService.authUser(
{
name: userInfo.name || userInfo.userName,
Expand All @@ -148,6 +148,7 @@ class IntegrationsController {
req,
res,
state.inviteType ? encodedState : null,
state.sessionInviteCode ? state.sessionInviteCode : null
);

await this.userService.setGithubUserId(`${userInfo.id}`, userRecord.userId);
Expand All @@ -157,6 +158,7 @@ class IntegrationsController {
return res.redirect(resolvePathToFrontendURI("/?github_token=" + (tokenInfo as any).token));
}

// @TODO: Use proper util functions here
const redirectUrl = new URL(process.env.FRONTEND_URL ? process.env.FRONTEND_URL : "http://localhost:3000/");
redirectUrl.searchParams.append("token", (tokenInfo as any).token);
res.redirect(redirectUrl.toString());
Expand Down