Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: logging in from video page (#1082)

Ameer Al Ashhab252fcde51d63
diff --git a/apps/web/app/(org)/login/form.tsx b/apps/web/app/(org)/login/form.tsx
index 0601ded15..3e1370b41 100644
--- a/apps/web/app/(org)/login/form.tsx
+++ b/apps/web/app/(org)/login/form.tsx
@@ -157,7 +157,7 @@ export function LoginForm() {
</motion.p>
</motion.div>
<MotionLink layout="position" className="flex mx-auto size-fit" href="/">
- <MotionLogoBadge layout="position" className="w-[72px] h-[72px]" />
+ <MotionLogoBadge layout="position" className="size-12" />
</MotionLink>
<motion.div
layout="position"
@@ -459,18 +459,16 @@ const NormalLogin = ({
className="flex flex-col gap-3 justify-center items-center"
>
{!oauthError && (
- <>
- <MotionButton
- variant="gray"
- type="button"
- className="flex gap-2 justify-center items-center w-full text-sm"
- onClick={handleGoogleSignIn}
- disabled={loading}
- >
- <Image src="/google.svg" alt="Google" width={16} height={16} />
- Login with Google
- </MotionButton>
- </>
+ <MotionButton
+ variant="gray"
+ type="button"
+ className="flex gap-2 justify-center items-center w-full text-sm"
+ onClick={handleGoogleSignIn}
+ disabled={loading}
+ >
+ <Image src="/google.svg" alt="Google" width={16} height={16} />
+ Login with Google
+ </MotionButton>
)}
{oauthError && (
@@ -481,8 +479,7 @@ const NormalLogin = ({
/>
<p className="text-xs leading-5 text-gray-50">
It looks like you've previously used this email to sign up via
- email login. Please enter your email below to receive a sign in
- link.
+ email login. Please enter your email.
</p>
</div>
)}
diff --git a/apps/web/app/(org)/verify-otp/form.tsx b/apps/web/app/(org)/verify-otp/form.tsx
index f2effe76c..4c7ff058a 100644
--- a/apps/web/app/(org)/verify-otp/form.tsx
+++ b/apps/web/app/(org)/verify-otp/form.tsx
@@ -156,19 +156,19 @@ export function VerifyOTPForm({
</Link>
<Link className="flex mx-auto size-fit" href="/">
- <LogoBadge className="w-[72px] h-[72px]" />
+ <LogoBadge className="size-12" />
</Link>
<div className="flex flex-col justify-center items-center my-7 text-center">
- <h1 className="text-2xl font-semibold text-gray-12">
+ <h1 className="text-xl font-semibold text-gray-12">
Enter verification code
</h1>
- <p className="text-[16px] text-gray-10 mt-2">
+ <p className="text-sm text-gray-10">
We sent a 6-digit code to {email}
</p>
</div>
- <div className="flex gap-2 justify-center mb-6">
+ <div className="flex flex-1 gap-2 justify-between mb-5">
{code.map((digit, index) => (
<input
key={index.toString()}
@@ -191,7 +191,7 @@ export function VerifyOTPForm({
.replace(/\D/g, "");
handleChange(0, pastedData);
}}
- className="w-12 h-14 text-xl font-semibold text-center rounded-lg border transition-all bg-gray-1 border-gray-5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
+ className="flex-1 h-[52px] text-xl font-semibold text-center rounded-lg border transition-all bg-gray-1 border-gray-5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
disabled={handleVerify.isPending || handleVerify.isSuccess}
/>
))}
@@ -221,7 +221,7 @@ export function VerifyOTPForm({
</div>
<p className="mt-6 text-xs text-center text-gray-9">
- By verifying your email, you acknowledge that you have both read and
+ By entering your email, you acknowledge that you have both read and
agree to Cap's{" "}
<Link
href="/terms"
diff --git a/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx b/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx
index dc35c6710..44809d4b0 100644
--- a/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx
+++ b/apps/web/app/s/[videoId]/_components/AuthOverlay.tsx
@@ -1,11 +1,13 @@
import { NODE_ENV } from "@cap/env";
import { Button, Dialog, DialogContent, Input, LogoBadge } from "@cap/ui";
-import { faEnvelope } from "@fortawesome/free-solid-svg-icons";
+import { faArrowLeft, faEnvelope } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import Image from "next/image";
+import { AnimatePresence } from "framer-motion";
+import Link from "next/link";
import { signIn } from "next-auth/react";
-import { useState } from "react";
+import { useId, useState } from "react";
import { toast } from "sonner";
+import OtpForm from "./OtpForm";
interface AuthOverlayProps {
isOpen: boolean;
@@ -19,156 +21,177 @@ export const AuthOverlay: React.FC<AuthOverlayProps> = ({
const [email, setEmail] = useState("");
const [loading, setLoading] = useState(false);
const [emailSent, setEmailSent] = useState(false);
+ const [step, setStep] = useState(1);
+ const [code, setCode] = useState(["", "", "", "", "", ""]);
- const handleGoogleSignIn = () => {
- signIn("google");
- };
+ const [lastResendTime, setLastResendTime] = useState<number | null>(null);
+ const emailId = useId();
return (
<Dialog open={isOpen} onOpenChange={onClose}>
- <DialogContent className="w-[90vw] sm:max-w-md p-6 rounded-xl">
+ <DialogContent className="w-[90vw] bg-gray-3 relative sm:max-w-md p-6 rounded-xl">
+ {emailSent && (
+ <div
+ onClick={() => {
+ setEmailSent(false);
+ setEmail("");
+ setLoading(false);
+ setStep(1);
+ setCode(["", "", "", "", "", ""]);
+ setLastResendTime(null);
+ }}
+ className="absolute top-5 left-5 cursor-pointer z-20 flex gap-2 items-center py-1.5 px-3 text-gray-12 bg-transparent border border-gray-4 rounded-full hover:bg-gray-1 transition-colors duration-300"
+ >
+ <FontAwesomeIcon className="w-2" icon={faArrowLeft} />
+ <p className="text-xs">Back</p>
+ </div>
+ )}
<div className="space-y-6">
- <LogoBadge className="w-auto h-12" />
+ <LogoBadge className="mx-auto w-auto h-12" />
- <div className="text-left">
- <h1 className="text-xl font-semibold">Sign in to comment</h1>
- <p className="text-lg text-gray-9">Join the conversation.</p>
+ <div className="text-center">
+ <h1 className="text-xl font-semibold">
+ {step === 1 ? "Sign in to comment" : "Email sent"}
+ </h1>
+ <p className="text-base text-gray-9">
+ {step === 1
+ ? "Join the conversation."
+ : "We sent a 6-digit code to your email."}
+ </p>
</div>
- <div className="flex flex-col space-y-3">
- {NODE_ENV === "development" && (
- <>
- <Button
- variant="primary"
- onClick={handleGoogleSignIn}
- disabled={loading}
- >
- <Image
- src="/google.svg"
- alt="Google"
- className="mr-1 size-4"
- width={16}
- height={16}
- />
- Continue with Google
- </Button>
- <div className="flex gap-4 items-center my-4">
- <span className="flex-1 h-px bg-gray-5" />
- <p className="text-sm text-center text-gray-8">OR</p>
- <span className="flex-1 h-px bg-gray-5" />
- </div>
- </>
+ <div className="flex flex-col">
+ <AnimatePresence> </AnimatePresence>
+ {step === 1 ? (
+ <StepOne
+ email={email}
+ emailSent={emailSent}
+ setEmail={setEmail}
+ loading={loading}
+ setEmailSent={setEmailSent}
+ setLoading={setLoading}
+ setStep={setStep}
+ setLastResendTime={setLastResendTime}
+ emailId={emailId}
+ />
+ ) : (
+ <OtpForm
+ email={email}
+ code={code}
+ setCode={setCode}
+ onClose={onClose}
+ step={step}
+ lastResendTime={lastResendTime}
+ setLastResendTime={setLastResendTime}
+ />
)}
-
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- if (!email) return;
-
- setLoading(true);
- signIn("email", {
- email,
- redirect: false,
- })
- .then((res) => {
- setLoading(false);
- if (res?.ok && !res?.error) {
- setEmail("");
- setEmailSent(true);
- toast.success("Email sent - check your inbox!");
- } else {
- toast.error("Error sending email - try again?");
- }
- })
- .catch(() => {
- setEmailSent(false);
- setLoading(false);
- toast.error("Error sending email - try again?");
- });
- }}
- className="flex flex-col space-y-3"
- >
- <div>
- <Input
- id="email"
- name="email"
- autoFocus
- type="email"
- placeholder={emailSent ? "" : "[email protected]"}
- autoComplete="email"
- required
- value={email}
- disabled={emailSent}
- onChange={(e) => {
- setEmail(e.target.value);
- }}
- />
- {NODE_ENV === "development" && (
- <div className="flex justify-center items-center px-6 py-3 mt-3 bg-red-600 rounded-xl">
- <p className="text-lg text-white">
- <span className="font-medium text-white">
- Development mode:
- </span>{" "}
- Auth URL will be logged to your dev console.
- </p>
- </div>
- )}
- </div>
- <Button
- variant="primary"
- type="submit"
- icon={
- <FontAwesomeIcon className="mr-1 size-4" icon={faEnvelope} />
- }
- disabled={loading || emailSent}
+ <p className="mt-6 text-xs text-center text-gray-9">
+ By entering your email, you acknowledge that you have both read
+ and agree to Cap's{" "}
+ <Link
+ href="/terms"
+ target="_blank"
+ className="text-xs font-semibold text-gray-12 hover:text-blue-300"
>
- {emailSent
- ? NODE_ENV === "development"
- ? "Email sent to your terminal"
- : "Email sent to your inbox"
- : "Continue with Email"}
- </Button>
- <p className="pt-2 text-xs text-center text-gray-12">
- By typing your email and clicking continue, you acknowledge that
- you have both read and agree to Cap's{" "}
- <a
- href="/terms"
- target="_blank"
- className="text-xs font-semibold text-gray-12 hover:text-blue-300"
- rel="noopener"
- >
- Terms of Service
- </a>{" "}
- and{" "}
- <a
- href="/privacy"
- target="_blank"
- className="text-xs font-semibold text-gray-12 hover:text-blue-300"
- rel="noopener"
- >
- Privacy Policy
- </a>
- .
- </p>
- </form>
- </div>
-
- {emailSent && (
- <div>
- <button
- className="mt-5 text-sm underline text-gray-1 hover:text-black"
- onClick={() => {
- setEmailSent(false);
- setEmail("");
- setLoading(false);
- }}
+ Terms of Service
+ </Link>{" "}
+ and{" "}
+ <Link
+ href="/privacy"
+ target="_blank"
+ className="text-xs font-semibold text-gray-12 hover:text-blue-300"
>
- Click to restart sign in process.
- </button>
- </div>
- )}
+ Privacy Policy
+ </Link>
+ .
+ </p>
+ </div>
</div>
</DialogContent>
</Dialog>
);
};
+
+const StepOne = ({
+ email,
+ emailSent,
+ setEmail,
+ loading,
+ setEmailSent,
+ setLoading,
+ setStep,
+ setLastResendTime,
+ emailId,
+}: {
+ email: string;
+ emailSent: boolean;
+ setEmail: (email: string) => void;
+ loading: boolean;
+ setEmailSent: (emailSent: boolean) => void;
+ setLoading: (loading: boolean) => void;
+ setStep: (step: number) => void;
+ setLastResendTime: (time: number | null) => void;
+ emailId: string;
+}) => {
+ return (
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (!email) return;
+
+ setLoading(true);
+ signIn("email", {
+ email,
+ redirect: false,
+ })
+ .then((res) => {
+ setLoading(false);
+ if (res?.ok && !res?.error) {
+ setEmail("");
+ setEmailSent(true);
+ setStep(2);
+ setLastResendTime(Date.now());
+ toast.success("Email sent - check your inbox!");
+ } else {
+ toast.error("Error sending email - try again?");
+ }
+ })
+ .catch(() => {
+ setEmailSent(false);
+ setLoading(false);
+ toast.error("Error sending email - try again?");
+ });
+ }}
+ className="flex flex-col gap-3"
+ >
+ <div>
+ <Input
+ id={emailId}
+ name="email"
+ autoFocus
+ type="email"
+ placeholder={emailSent ? "" : "[email protected]"}
+ autoComplete="email"
+ required
+ value={email}
+ disabled={emailSent}
+ onChange={(e) => {
+ setEmail(e.target.value);
+ }}
+ />
+ </div>
+ <Button
+ variant="dark"
+ type="submit"
+ icon={<FontAwesomeIcon className="mr-1 size-4" icon={faEnvelope} />}
+ disabled={loading || emailSent}
+ >
+ {emailSent
+ ? NODE_ENV === "development"
+ ? "Email sent to your terminal"
+ : "Email sent to your inbox"
+ : "Continue with Email"}
+ </Button>
+ </form>
+ );
+};
diff --git a/apps/web/app/s/[videoId]/_components/OtpForm.tsx b/apps/web/app/s/[videoId]/_components/OtpForm.tsx
new file mode 100644
index 000000000..56d3855c3
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/OtpForm.tsx
@@ -0,0 +1,203 @@
+import { Button } from "@cap/ui";
+import { useMutation } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { signIn } from "next-auth/react";
+import { useEffect, useRef } from "react";
+import { toast } from "sonner";
+
+const OtpForm = ({
+ email,
+ step,
+ onClose,
+ code,
+ setCode,
+ lastResendTime,
+ setLastResendTime,
+}: {
+ email: string;
+ step: number;
+ onClose: () => void;
+ code: string[];
+ setCode: (code: string[]) => void;
+ lastResendTime: number | null;
+ setLastResendTime: (time: number | null) => void;
+}) => {
+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
+ const router = useRouter();
+
+ useEffect(() => {
+ if (step === 2) {
+ inputRefs.current[0]?.focus();
+ }
+ }, [step]);
+
+ const handleOTPChange = (index: number, value: string) => {
+ if (value.length > 1) {
+ const pastedCode = value.slice(0, 6).split("");
+ const newCode = [...code];
+ pastedCode.forEach((digit, i) => {
+ if (index + i < 6) {
+ newCode[index + i] = digit;
+ }
+ });
+ setCode(newCode);
+
+ const nextEmptyIndex = newCode.findIndex((digit) => digit === "");
+ if (nextEmptyIndex !== -1) {
+ inputRefs.current[nextEmptyIndex]?.focus();
+ } else {
+ inputRefs.current[5]?.focus();
+ }
+
+ if (index + value.length >= 5) handleVerify.mutate(undefined);
+ } else {
+ const newCode = [...code];
+ newCode[index] = value;
+ setCode(newCode);
+
+ if (value && index < 5) {
+ inputRefs.current[index + 1]?.focus();
+ }
+ }
+ };
+
+ const handleOTPKeyDown = (
+ index: number,
+ e: React.KeyboardEvent<HTMLInputElement>,
+ ) => {
+ if (e.key === "Backspace" && !code[index] && index > 0) {
+ inputRefs.current[index - 1]?.focus();
+ }
+ };
+
+ const handleVerify = useMutation({
+ mutationFn: async () => {
+ const otpCode = code.join("");
+ if (otpCode.length !== 6) throw "Please enter a complete 6-digit code";
+
+ const res = await fetch(
+ `/api/auth/callback/email?email=${encodeURIComponent(email)}&token=${encodeURIComponent(otpCode)}&callbackUrl=${encodeURIComponent("/login-success")}`,
+ );
+
+ if (!res.url.includes("/login-success")) {
+ setCode(["", "", "", "", "", ""]);
+ inputRefs.current[0]?.focus();
+ throw "Invalid code. Please try again.";
+ }
+ },
+ onSuccess: () => {
+ router.refresh();
+ toast.success("Sign in successful!");
+ onClose();
+ },
+ onError: (e) => {
+ if (typeof e === "string") {
+ toast.error(e);
+ } else {
+ toast.error("An error occurred. Please try again.");
+ }
+ },
+ });
+
+ const handleResend = useMutation({
+ mutationFn: async () => {
+ // Check client-side rate limiting
+ if (lastResendTime) {
+ const timeSinceLastRequest = Date.now() - lastResendTime;
+ const waitTime = 30000; // 30 seconds
+ if (timeSinceLastRequest < waitTime) {
+ const remainingSeconds = Math.ceil(
+ (waitTime - timeSinceLastRequest) / 1000,
+ );
+ throw `Please wait ${remainingSeconds} seconds before requesting a new code`;
+ }
+ }
+
+ const result = await signIn("email", {
+ email,
+ redirect: false,
+ });
+
+ if (result?.error) {
+ throw "Please wait 30 seconds before requesting a new code";
+ }
+ },
+ onSuccess: () => {
+ toast.success("A new code has been sent to your email!");
+ setCode(["", "", "", "", "", ""]);
+ inputRefs.current[0]?.focus();
+ setLastResendTime(Date.now());
+ },
+ onError: (e) => {
+ if (typeof e === "string") {
+ toast.error(e);
+ } else {
+ toast.error("An error occurred. Please try again.");
+ }
+ },
+ });
+
+ const isVerifying = handleVerify.isPending || handleVerify.isSuccess;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-1 gap-2 justify-between">
+ {code.map((digit, index) => (
+ <input
+ key={index.toString()}
+ ref={(el) => {
+ inputRefs.current[index] = el;
+ }}
+ type="text"
+ inputMode="numeric"
+ pattern="[0-9]*"
+ maxLength={1}
+ value={digit}
+ onChange={(e) =>
+ handleOTPChange(index, e.target.value.replace(/\D/g, ""))
+ }
+ onKeyDown={(e) => handleOTPKeyDown(index, e)}
+ onPaste={(e) => {
+ e.preventDefault();
+ const pastedData = e.clipboardData
+ .getData("text")
+ .replace(/\D/g, "");
+ handleOTPChange(0, pastedData);
+ }}
+ className="flex-1 h-[52px] text-lg font-semibold text-center rounded-lg border transition-all bg-gray-1 border-gray-5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
+ disabled={isVerifying}
+ />
+ ))}
+ </div>
+
+ <Button
+ variant="dark"
+ className="w-full"
+ spinner={isVerifying}
+ onClick={() => {
+ handleVerify.mutate(undefined);
+ }}
+ disabled={code.some((digit) => !digit) || isVerifying}
+ >
+ {isVerifying ? "Verifying..." : "Verify Code"}
+ </Button>
+
+ <div className="text-center">
+ <button
+ type="button"
+ onClick={() => {
+ handleResend.mutate(undefined);
+ }}
+ disabled={handleResend.isPending}
+ className="text-sm underline transition-colors text-gray-10 hover:text-gray-12"
+ >
+ {handleResend.isPending
+ ? "Sending..."
+ : "Didn't receive the code? Resend"}
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export default OtpForm;