Skip to content

Commit

Permalink
feat: allow login flow after selecting repositories to add to insight…
Browse files Browse the repository at this point in the history
… page (close #1132) (#1184)
  • Loading branch information
a0m0rajab authored Jun 26, 2023
1 parent 65a5ddf commit 21aaa0b
Show file tree
Hide file tree
Showing 8 changed files with 71 additions and 45 deletions.
11 changes: 10 additions & 1 deletion components/molecules/AuthSection/auth-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,16 @@ const AuthSection: React.FC = ({}) => {
<Text className="group-hover:text-light-orange-10">Settings</Text>
</Link>,
<span
onClick={async () => await signOut()}
onClick={async () => {
const pageHref = window.location.href;
const searchParams = new URLSearchParams(pageHref.substring(pageHref.indexOf("?")));
if (searchParams.has("login")){
searchParams.delete("login");
router.replace(`${pageHref.substring(0, pageHref.indexOf("?"))}?${searchParams.toString()}`);
}

await signOut();
}}
key="authorized"
className="flex items-center px-4 py-2 text-lg transition rounded-md cursor-pointer group gap-x-3 hover:bg-light-orange-3"
>
Expand Down
2 changes: 0 additions & 2 deletions components/molecules/RepoRow/repo-row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,6 @@ const RepoRow = ({ repo, topic, userPage, selected, handleOnSelectRepo }: RepoPr
<Checkbox
checked={selected ? true : false}
onCheckedChange={handleSelectCheckbox}
disabled={!user}
title={!user ? "Connect to GitHub" : ""}
className={`${user && "border-orange-500 hover:bg-orange-600"}`}
/>
{/* Column: Repository Name */}
Expand Down
25 changes: 18 additions & 7 deletions components/organisms/InsightPage/InsightPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import RepositoriesCart from "components/organisms/RepositoriesCart/repositories
import RepositoryCartItem from "components/molecules/ReposoitoryCartItem/repository-cart-item";
import RepoNotIndexed from "components/organisms/Repositories/repository-not-indexed";
import DeleteInsightPageModal from "./DeleteInsightPageModal";
import useRepositories from "lib/hooks/api/useRepositories";

import useSupabaseAuth from "lib/hooks/useSupabaseAuth";
import { getAvatarById, getAvatarByUsername } from "lib/utils/github";
Expand Down Expand Up @@ -41,10 +42,19 @@ const InsightPage = ({ edit, insight, pageRepos }: InsightPageProps) => {
const { sessionToken, providerToken } = useSupabaseAuth();
const { toast } = useToast();
const router = useRouter();
let receivedData = [];
if (router.query.selectedRepos) {
receivedData = JSON.parse(router.query.selectedRepos as string);
}
const pageHref = router.asPath;
const [reposIds, setReposIds] = useState<number[]>([]);
const { data: repoListData } = useRepositories(reposIds);

useEffect(() => {
const searchParams = new URLSearchParams(pageHref.substring(pageHref.indexOf("?")));
if (router.query.selectedRepos) {
setRepos(JSON.parse(router.query.selectedRepos as string) || []);
} else if (searchParams.has("selectedReposIDs")) {
setReposIds(JSON.parse(searchParams.get("selectedReposIDs") as string) || []);
setRepos(repoListData);
}
}, [repoListData, router.query.selectedRepos, pageHref]);

const { data, addMember, deleteMember, updateMember } = useInsightMembers(insight?.id || 0);

Expand All @@ -60,6 +70,7 @@ const InsightPage = ({ edit, insight, pageRepos }: InsightPageProps) => {
insight_id: Number(insight?.id),
email: String(insight?.user.email),
id: String(insight?.user.id),

name: String(insight?.user.name || insight?.user.login),
avatarUrl: getAvatarByUsername(String(insight?.user.login)),
access: "owner",
Expand All @@ -72,7 +83,7 @@ const InsightPage = ({ edit, insight, pageRepos }: InsightPageProps) => {
const [name, setName] = useState(insight?.name || "");
const [isNameValid, setIsNameValid] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [repos, setRepos] = useState<DbRepo[]>(receivedData);
const [repos, setRepos] = useState<DbRepo[]>([]);
const [repoHistory, setRepoHistory] = useState<DbRepo[]>([]);
const [addRepoError, setAddRepoError] = useState<RepoLookupError>(RepoLookupError.Initial);
const [isPublic, setIsPublic] = useState(!!insight?.is_public);
Expand Down Expand Up @@ -104,7 +115,7 @@ const InsightPage = ({ edit, insight, pageRepos }: InsightPageProps) => {
repoName: repoName,
totalPrs,
avatar: getAvatarByUsername(repoOwner, 60),
handleRemoveItem: () => {},
handleRemoveItem: () => { },
};
});

Expand Down Expand Up @@ -238,7 +249,7 @@ const InsightPage = ({ edit, insight, pageRepos }: InsightPageProps) => {
setRepoHistory((historyRepos) => {
return historyRepos.filter((repo) => `${repo.full_name}` !== repoAdded);
});
} catch (e) {}
} catch (e) { }
};

const handleRemoveRepository = (id: string) => {
Expand Down
28 changes: 16 additions & 12 deletions components/organisms/Repositories/repositories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const Repositories = ({ repositories }: RepositoriesProps): JSX.Element => {
isError: repoListIsError,
isLoading: repoListIsLoading,
setPage,
setLimit,
setLimit
} = useRepositories(repositories, range);
const filteredRepoNotIndexed = selectedFilter && !repoListIsLoading && !repoListIsError && repoListData.length === 0;
const [selectedRepos, setSelectedRepos] = useState<DbRepo[]>([]);
Expand All @@ -55,7 +55,13 @@ const Repositories = ({ repositories }: RepositoriesProps): JSX.Element => {
"/hub/insights/new"
);
} else {
signIn({ provider: "github" });
const reposIds = selectedRepos.map((repo) => repo.id);
signIn({
provider: "github",
options: {
redirectTo: `${window.location.origin}/hub/insights/new?selectedReposIDs=${JSON.stringify(reposIds)}&login=true&`,
},
});
}
};

Expand Down Expand Up @@ -97,26 +103,24 @@ const Repositories = ({ repositories }: RepositoriesProps): JSX.Element => {
<div className="lg:min-w-[1150px]">
<div className="flex justify-between gap-2 px-6 py-4 md:hidden bg-light-slate-3">
<div className="flex-1">
<TableTitle>Repositories</TableTitle>
<TableTitle> Repository </TableTitle>
</div>
<div className="flex-1">
<TableTitle>Pr Overview</TableTitle>
<TableTitle> Pr Overview </TableTitle>
</div>
</div>
<div className="hidden gap-2 px-6 py-4 md:flex bg-light-slate-3">
<div className={clsx(classNames.cols.checkbox)}>
<Checkbox
onCheckedChange={handleOnSelectAllChecked}
disabled={!user}
title={!user ? "Connect to GitHub" : ""}
className={`${user && "border-orange-500 hover:bg-orange-600"}`}
/>
</div>
<div className={clsx(classNames.cols.repository)}>
<TableTitle>Repository</TableTitle>
<TableTitle> Repository </TableTitle>
</div>
<div className={clsx(classNames.cols.activity)}>
<TableTitle>Activity</TableTitle>
<TableTitle >Activity</TableTitle>
</div>
<div className={clsx(classNames.cols.prOverview)}>
<TableTitle>PR Overview</TableTitle>
Expand All @@ -125,10 +129,10 @@ const Repositories = ({ repositories }: RepositoriesProps): JSX.Element => {
<TableTitle>PR Velocity</TableTitle>
</div>
<div className={clsx(classNames.cols.spam)}>
<TableTitle>SPAM</TableTitle>
<TableTitle >SPAM</TableTitle>
</div>
<div className={clsx(classNames.cols.contributors, "hidden lg:flex")}>
<TableTitle>Contributors</TableTitle>
<TableTitle >Contributors</TableTitle>
</div>
<div className={clsx(classNames.cols.last30days, "hidden lg:flex")}>
<TableTitle>Last 30 Days</TableTitle>
Expand All @@ -139,7 +143,7 @@ const Repositories = ({ repositories }: RepositoriesProps): JSX.Element => {
<div className="flex justify-between p-3 px-6 border-b-2 text-light-slate-11">
<div>{selectedRepos.length} Repositories selected</div>
<Button onClick={handleOnAddtoInsights} variant="primary">
Add to Insight Page
Add to Insight Page
</Button>
</div>
)}
Expand All @@ -164,7 +168,7 @@ const Repositories = ({ repositories }: RepositoriesProps): JSX.Element => {
{ name: "20 per page", value: "20" },
{ name: "30 per page", value: "30" },
{ name: "40 per page", value: "40" },
{ name: "50 per page", value: "50" },
{ name: "50 per page", value: "50" }
]}
className="!w-36 ml-auto md:hidden overflow-x-hidden"
onChange={function (limit: string): void {
Expand Down
2 changes: 2 additions & 0 deletions layouts/private-wrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const PrivateWrapper = ({ isPrivateRoute = false, children }: PrivateWrapperProp
const router = useRouter();

async function checkSession() {
if (router.asPath?.includes("login")) return;

const isValid = await authSession();

if (!isValid) {
Expand Down
5 changes: 3 additions & 2 deletions lib/hooks/useSupabaseAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,14 @@ const useSupabaseAuth = (loadSession = false) => {
}, []);

return {
signIn: (data: SignInWithOAuthCredentials) =>
signIn: (data: SignInWithOAuthCredentials) => {
supabase.auth.signInWithOAuth({
...data,
options: data.options ?? {
redirectTo: process.env.NEXT_PUBLIC_BASE_URL ?? "/",
},
}),
});
},
signOut: () => supabase.auth.signOut(),
user,
sessionToken,
Expand Down
35 changes: 18 additions & 17 deletions lib/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,26 @@ interface AppStore extends GlobalStateInterface {
setHasReports: (hasReports: boolean) => void;
}

const store = create<AppStore>()((set) => ({
...initialState,
setWaitlisted: () => set((state) => ({ ...state, waitlisted: true })),
onboardUser: () => set((state) => ({ ...state, onboarded: true })),
setSession: ({
onboarded,
waitlisted,
insightRepoLimit
}: {
const store = create<AppStore>()(
(set) => ({
...initialState,
setWaitlisted: () => set((state) => ({ ...state, waitlisted: true })),
onboardUser: () => set((state) => ({ ...state, onboarded: true })),
setSession: ({
onboarded,
waitlisted,
insightRepoLimit
}: {
onboarded: boolean;
waitlisted: boolean;
insightRepoLimit: number;
}) => set((state) => ({ ...state, onboarded, waitlisted, insightRepoLimit })),
updateRange: (range: number) => set((state) => ({ ...state, range })),
setUser: (user: User | null) => set((state) => ({ ...state, user })),
setSessionToken: (sessionToken?: string | null) => set((state) => ({ ...state, sessionToken })),
setProviderToken: (providerToken?: string | null) => set((state) => ({ ...state, providerToken })),
setUserId: (userId?: number | null) => set((state) => ({ ...state, userId })),
setHasReports: (hasReports: boolean) => set((state) => ({ ...state, hasReports }))
}));
updateRange: (range: number) => set((state) => ({ ...state, range })),
setUser: (user: User | null) => set((state) => ({ ...state, user })),
setSessionToken: (sessionToken?: string | null) => set((state) => ({ ...state, sessionToken })),
setProviderToken: (providerToken?: string | null) => set((state) => ({ ...state, providerToken })),
setUserId: (userId?: number | null) => set((state) => ({ ...state, userId })),
setHasReports: (hasReports: boolean) => set((state) => ({ ...state, hasReports })),
}));

export default store;
export default store;
8 changes: 4 additions & 4 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createMiddlewareSupabaseClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
const res = NextResponse.next();
Expand All @@ -10,13 +10,13 @@ export async function middleware(req: NextRequest) {
const {
data: { session },
} = await supabase.auth.getSession();

// Check auth condition
if (session?.user) {
if (session?.user || req.nextUrl.searchParams.has("login")) {
// Authentication successful, forward request to protected route.
return res;
}

// Auth condition not met, redirect to home page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/javascript/dashboard/filter/recent";
Expand Down

0 comments on commit 21aaa0b

Please sign in to comment.