Skip to content

OpenStock is an open-source alternative to expensive market platforms. Track real-time prices, set personalized alerts, and explore detailed company insights — built openly, for everyone, forever free.

feat(profile): profile page with details, sign-in methods and password change

ravixalgorithmebefb7254657
diff --git a/app/(root)/profile/page.tsx b/app/(root)/profile/page.tsx
new file mode 100644
index 0000000..a4ed1ad
--- /dev/null
+++ b/app/(root)/profile/page.tsx
@@ -0,0 +1,103 @@
+import { headers } from "next/headers";
+import { redirect } from "next/navigation";
+import { Bell, KeyRound, ShieldCheck, Star } from "lucide-react";
+import Panel from "@/components/Panel";
+import ProfileForm from "@/components/profile/ProfileForm";
+import PasswordForm from "@/components/profile/PasswordForm";
+import ConnectProviderButton from "@/components/profile/ConnectProviderButton";
+import { auth, getSession } from "@/lib/better-auth/auth";
+import { getUserWatchlist } from "@/lib/actions/watchlist.actions";
+import { getUserAlerts } from "@/lib/actions/alert.actions";
+
+export const metadata = { title: 'Profile | OpenStock' };
+
+const PROVIDERS = [
+ { id: 'credential', label: 'Email and password', configured: true },
+ { id: 'google', label: 'Google', configured: !!process.env.GOOGLE_CLIENT_ID },
+ { id: 'github', label: 'GitHub', configured: !!process.env.GITHUB_CLIENT_ID },
+] as const;
+
+export default async function ProfilePage() {
+ const session = await getSession();
+ if (!session?.user) redirect('/sign-in');
+ const { user } = session;
+
+ const [accounts, watchlist, alerts] = await Promise.all([
+ auth.api.listUserAccounts({ headers: await headers() }).catch(() => []),
+ getUserWatchlist(user.id),
+ getUserAlerts(user.id),
+ ]);
+ const linked = new Set(accounts.map((a: { providerId: string }) => a.providerId));
+ const activeAlerts = alerts.filter((a: { triggered?: boolean }) => !a.triggered).length;
+ const memberSince = new Date(user.createdAt).toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
+
+ const stats = [
+ { label: 'Watching', value: watchlist.length, icon: Star },
+ { label: 'Active alerts', value: activeAlerts, icon: Bell },
+ { label: 'Sign-in methods', value: linked.size, icon: ShieldCheck },
+ ];
+
+ return (
+ <>
+ <section className="hatch">
+ <div className="card flex flex-wrap items-center gap-4 p-5">
+ <span className="grid size-14 flex-none place-items-center rounded-full bg-brand-soft text-[22px] font-bold text-brand-ink">
+ {user.name?.[0]?.toUpperCase() ?? '?'}
+ </span>
+ <div className="min-w-0 flex-1">
+ <h1 className="truncate text-[22px] font-bold tracking-[-0.03em]">{user.name}</h1>
+ <p className="truncate text-faint">{user.email} · member since {memberSince}</p>
+ </div>
+ </div>
+ <div className="bento mt-[3px]">
+ {stats.map(({ label, value, icon: Icon }) => (
+ <div key={label} className="bento-tile col-span-4 gap-2.5 max-lg:col-span-12">
+ <div className="bento-head"><span className="bento-ico"><Icon /></span>{label}</div>
+ <p className="bento-value text-[26px]">{value}</p>
+ </div>
+ ))}
+ </div>
+ </section>
+
+ <div className="grid items-start gap-3 xl:grid-cols-[minmax(0,1fr)_minmax(320px,420px)]">
+ <Panel title="Details" sub="Your name and what your welcome email is tailored to">
+ <ProfileForm
+ initial={{
+ name: user.name,
+ country: user.country ?? 'US',
+ investmentGoals: user.investmentGoals ?? 'Growth',
+ riskTolerance: user.riskTolerance ?? 'Medium',
+ preferredIndustry: user.preferredIndustry ?? 'Technology',
+ }}
+ />
+ </Panel>
+
+ <div className="flex min-w-0 flex-col gap-3">
+ <Panel title="Sign-in methods" sub="Ways you can get into this account">
+ <ul className="row-list">
+ {PROVIDERS.filter((p) => p.configured || linked.has(p.id)).map((p) => (
+ <li key={p.id} className="flex items-center gap-3 px-3.5 py-3">
+ <span className="bento-ico"><KeyRound /></span>
+ <span className="flex-1 font-semibold">{p.label}</span>
+ {linked.has(p.id) ? (
+ <span className="pill is-up">Connected</span>
+ ) : p.id === 'credential' ? (
+ <span className="pill">Not set</span>
+ ) : (
+ <ConnectProviderButton provider={p.id} />
+ )}
+ </li>
+ ))}
+ </ul>
+ </Panel>
+
+ {linked.has('credential') && (
+ <Panel title="Password" sub="Changing it signs out your other devices">
+ <PasswordForm />
+ </Panel>
+ )}
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/components/profile/ConnectProviderButton.tsx b/components/profile/ConnectProviderButton.tsx
new file mode 100644
index 0000000..905a547
--- /dev/null
+++ b/components/profile/ConnectProviderButton.tsx
@@ -0,0 +1,26 @@
+'use client';
+
+import { useState } from "react";
+import { toast } from "sonner";
+import { connectProvider } from "@/lib/actions/profile.actions";
+
+export default function ConnectProviderButton({ provider }: { provider: 'google' | 'github' }) {
+ const [pending, setPending] = useState(false);
+
+ const onClick = async () => {
+ setPending(true);
+ const result = await connectProvider(provider);
+ if (result.success && result.url) {
+ window.location.href = result.url;
+ return;
+ }
+ setPending(false);
+ toast.error('Couldn’t connect', { description: result.error });
+ };
+
+ return (
+ <button type="button" onClick={onClick} disabled={pending} className="btn btn-ghost h-8 px-3 text-[13px]">
+ {pending ? 'Redirecting' : 'Connect'}
+ </button>
+ );
+}
diff --git a/components/profile/PasswordForm.tsx b/components/profile/PasswordForm.tsx
new file mode 100644
index 0000000..58c3360
--- /dev/null
+++ b/components/profile/PasswordForm.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import InputField from "@/components/forms/InputField";
+import PasswordRequirements from "@/components/forms/PasswordRequirements";
+import { PASSWORD_VALIDATION } from "@/lib/constants";
+import { changePassword } from "@/lib/actions/profile.actions";
+
+type PasswordInput = { currentPassword: string; newPassword: string };
+
+export default function PasswordForm() {
+ const { register, handleSubmit, watch, reset, formState: { errors, isSubmitting } } = useForm<PasswordInput>({
+ defaultValues: { currentPassword: '', newPassword: '' },
+ mode: 'onBlur',
+ });
+
+ const onSubmit = async (values: PasswordInput) => {
+ const result = await changePassword(values);
+ if (!result.success) {
+ toast.error('Password not changed', { description: result.error });
+ return;
+ }
+ toast.success('Password changed', { description: 'Other devices were signed out.' });
+ reset();
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4 p-4">
+ <InputField
+ name="currentPassword"
+ label="Current password"
+ placeholder="Your current password"
+ type="password"
+ register={register}
+ error={errors.currentPassword}
+ validation={{ required: 'Enter your current password' }}
+ />
+ <div className="flex flex-col gap-2">
+ <InputField
+ name="newPassword"
+ label="New password"
+ placeholder="At least 8 characters"
+ type="password"
+ register={register}
+ error={errors.newPassword}
+ validation={PASSWORD_VALIDATION}
+ />
+ <PasswordRequirements password={watch('newPassword') ?? ''} />
+ </div>
+ <button type="submit" disabled={isSubmitting} className="btn btn-ghost self-start">
+ {isSubmitting ? 'Changing' : 'Change password'}
+ </button>
+ </form>
+ );
+}
diff --git a/components/profile/ProfileForm.tsx b/components/profile/ProfileForm.tsx
new file mode 100644
index 0000000..819af64
--- /dev/null
+++ b/components/profile/ProfileForm.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { useForm } from "react-hook-form";
+import { useRouter } from "next/navigation";
+import { toast } from "sonner";
+import InputField from "@/components/forms/InputField";
+import ChoiceChips from "@/components/forms/ChoiceChips";
+import { CountrySelectField } from "@/components/forms/CountrySelectField";
+import { INVESTMENT_GOALS, PREFERRED_INDUSTRIES, RISK_TOLERANCE_OPTIONS } from "@/lib/constants";
+import { updateProfile, type ProfileInput } from "@/lib/actions/profile.actions";
+
+export default function ProfileForm({ initial }: { initial: ProfileInput }) {
+ const router = useRouter();
+ const { register, control, handleSubmit, formState: { errors, isSubmitting, isDirty }, reset } = useForm<ProfileInput>({
+ defaultValues: initial,
+ mode: 'onBlur',
+ });
+
+ const onSubmit = async (values: ProfileInput) => {
+ const result = await updateProfile(values);
+ if (!result.success) {
+ toast.error('Couldn’t save', { description: result.error });
+ return;
+ }
+ toast.success('Profile saved');
+ reset(values);
+ router.refresh();
+ };
+
+ return (
+ <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-5 p-4">
+ <InputField
+ name="name"
+ label="Name"
+ placeholder="Your name"
+ register={register}
+ error={errors.name}
+ validation={{ required: 'Name is required', minLength: { value: 2, message: 'At least 2 characters' } }}
+ />
+ <CountrySelectField name="country" label="Country" control={control} error={errors.country} required />
+ <ChoiceChips name="investmentGoals" label="Investment goal" options={INVESTMENT_GOALS} control={control} />
+ <ChoiceChips name="riskTolerance" label="Risk tolerance" options={RISK_TOLERANCE_OPTIONS} control={control} />
+ <ChoiceChips name="preferredIndustry" label="Preferred industry" options={PREFERRED_INDUSTRIES} control={control} />
+ <div className="flex items-center gap-3 pt-1">
+ <button type="submit" disabled={isSubmitting || !isDirty} className="btn btn-primary">
+ {isSubmitting ? 'Saving' : 'Save changes'}
+ </button>
+ {!isDirty && <span className="text-[13px] text-faint">Up to date</span>}
+ </div>
+ </form>
+ );
+}
diff --git a/lib/actions/profile.actions.ts b/lib/actions/profile.actions.ts
new file mode 100644
index 0000000..8a82193
--- /dev/null
+++ b/lib/actions/profile.actions.ts
@@ -0,0 +1,72 @@
+'use server';
+
+import { headers } from "next/headers";
+import { revalidatePath } from "next/cache";
+import { auth } from "@/lib/better-auth/auth";
+import { INVESTMENT_GOALS, PREFERRED_INDUSTRIES, RISK_TOLERANCE_OPTIONS } from "@/lib/constants";
+
+export type ProfileInput = {
+ name: string;
+ country: string;
+ investmentGoals: string;
+ riskTolerance: string;
+ preferredIndustry: string;
+};
+
+const isOption = (options: readonly { value: string }[], value: string) => options.some((o) => o.value === value);
+
+// Every call acts on the signed-in user's own session; nothing here takes a user id from the client.
+export async function updateProfile(input: ProfileInput) {
+ const name = input.name.trim();
+ if (name.length < 2 || name.length > 80) return { success: false, error: 'Name must be 2 to 80 characters.' };
+ if (!/^[A-Z]{2}$/.test(input.country)) return { success: false, error: 'Pick a country.' };
+ if (!isOption(INVESTMENT_GOALS, input.investmentGoals)
+ || !isOption(RISK_TOLERANCE_OPTIONS, input.riskTolerance)
+ || !isOption(PREFERRED_INDUSTRIES, input.preferredIndustry)) {
+ return { success: false, error: 'Pick one option in each group.' };
+ }
+
+ try {
+ await auth.api.updateUser({
+ headers: await headers(),
+ body: {
+ name,
+ country: input.country,
+ investmentGoals: input.investmentGoals,
+ riskTolerance: input.riskTolerance,
+ preferredIndustry: input.preferredIndustry,
+ },
+ });
+ revalidatePath('/', 'layout');
+ return { success: true };
+ } catch (e) {
+ console.error('Profile update failed', e);
+ return { success: false, error: 'Couldn’t save your profile.' };
+ }
+}
+
+export async function changePassword({ currentPassword, newPassword }: { currentPassword: string; newPassword: string }) {
+ try {
+ await auth.api.changePassword({
+ headers: await headers(),
+ body: { currentPassword, newPassword, revokeOtherSessions: true },
+ });
+ return { success: true };
+ } catch (e) {
+ console.error('Password change failed', e);
+ return { success: false, error: 'Current password is incorrect, or the new one is too short.' };
+ }
+}
+
+export async function connectProvider(provider: 'google' | 'github') {
+ try {
+ const { url } = await auth.api.linkSocialAccount({
+ headers: await headers(),
+ body: { provider, callbackURL: '/profile' },
+ });
+ return { success: true, url };
+ } catch (e) {
+ console.error('Account linking failed', e);
+ return { success: false, error: `${provider === 'google' ? 'Google' : 'GitHub'} isn’t available right now.` };
+ }
+}