feat(web): add OAuth callback pages and auth flow for Google/Zalo

- Add /auth/callback/google and /auth/callback/zalo pages that extract
  tokens from query params and persist them via the auth store
- Add handleOAuthCallback method to Zustand auth store
- Update middleware to allow /auth/callback/* as public routes
- Show OAuth error messages on login page when redirected back

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 02:21:48 +07:00
parent dafed32e11
commit bfdd2f7cfa
5 changed files with 142 additions and 2 deletions

View File

@@ -2,7 +2,7 @@
import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2 } from 'lucide-react';
@@ -17,9 +17,18 @@ import { useAuthStore } from '@/lib/auth-store';
export default function LoginPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { login, isLoading, error, clearError } = useAuthStore();
const [showPassword, setShowPassword] = useState(false);
const oauthError = searchParams.get('error');
const oauthErrorMessage =
oauthError === 'oauth_failed'
? 'Đăng nhập bằng mạng xã hội thất bại. Vui lòng thử lại.'
: oauthError
? decodeURIComponent(oauthError)
: null;
const {
register,
handleSubmit,
@@ -45,6 +54,11 @@ export default function LoginPage() {
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
{oauthErrorMessage && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
{oauthErrorMessage}
</div>
)}
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
{error}

View File

@@ -0,0 +1,55 @@
'use client';
import { useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { useAuthStore } from '@/lib/auth-store';
export default function GoogleCallbackPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { handleOAuthCallback } = useAuthStore();
const processed = useRef(false);
useEffect(() => {
if (processed.current) return;
processed.current = true;
const accessToken = searchParams.get('accessToken');
const refreshToken = searchParams.get('refreshToken');
const expiresIn = searchParams.get('expiresIn');
const error = searchParams.get('error');
if (error) {
router.replace(`/login?error=${encodeURIComponent(error)}`);
return;
}
if (!accessToken || !refreshToken) {
router.replace('/login?error=oauth_failed');
return;
}
handleOAuthCallback({
accessToken,
refreshToken,
expiresIn: expiresIn ? Number(expiresIn) : 900,
})
.then(() => {
const redirect = searchParams.get('redirect') || '/dashboard';
router.replace(redirect);
})
.catch(() => {
router.replace('/login?error=oauth_failed');
});
}, [searchParams, handleOAuthCallback, router]);
return (
<div className="flex min-h-screen items-center justify-center">
<div className="text-center">
<Loader2 className="mx-auto h-8 w-8 animate-spin text-primary" />
<p className="mt-4 text-sm text-muted-foreground">Đang xử đăng nhập Google...</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,55 @@
'use client';
import { useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { useAuthStore } from '@/lib/auth-store';
export default function ZaloCallbackPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { handleOAuthCallback } = useAuthStore();
const processed = useRef(false);
useEffect(() => {
if (processed.current) return;
processed.current = true;
const accessToken = searchParams.get('accessToken');
const refreshToken = searchParams.get('refreshToken');
const expiresIn = searchParams.get('expiresIn');
const error = searchParams.get('error');
if (error) {
router.replace(`/login?error=${encodeURIComponent(error)}`);
return;
}
if (!accessToken || !refreshToken) {
router.replace('/login?error=oauth_failed');
return;
}
handleOAuthCallback({
accessToken,
refreshToken,
expiresIn: expiresIn ? Number(expiresIn) : 900,
})
.then(() => {
const redirect = searchParams.get('redirect') || '/dashboard';
router.replace(redirect);
})
.catch(() => {
router.replace('/login?error=oauth_failed');
});
}, [searchParams, handleOAuthCallback, router]);
return (
<div className="flex min-h-screen items-center justify-center">
<div className="text-center">
<Loader2 className="mx-auto h-8 w-8 animate-spin text-primary" />
<p className="mt-4 text-sm text-muted-foreground">Đang xử đăng nhập Zalo...</p>
</div>
</div>
);
}

View File

@@ -2,6 +2,8 @@ import { create } from 'zustand';
import { authApi, type TokenPair, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
import { ApiError } from './api-client';
export type { TokenPair };
const TOKEN_KEY = 'goodgo_tokens';
function persistTokens(tokens: TokenPair | null) {
@@ -32,6 +34,7 @@ interface AuthState {
login: (data: LoginPayload) => Promise<void>;
register: (data: RegisterPayload) => Promise<void>;
handleOAuthCallback: (tokens: TokenPair) => Promise<void>;
logout: () => void;
refreshToken: () => Promise<boolean>;
fetchProfile: () => Promise<void>;
@@ -73,6 +76,19 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}
},
handleOAuthCallback: async (tokens) => {
set({ isLoading: true, error: null });
try {
persistTokens(tokens);
set({ tokens, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng nhập OAuth thất bại';
set({ isLoading: false, error: message });
throw e;
}
},
logout: () => {
persistTokens(null);
set({ tokens: null, user: null, error: null });

View File

@@ -1,7 +1,7 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const publicPaths = ['/login', '/register', '/search'];
const publicPaths = ['/login', '/register', '/search', '/auth/callback'];
const publicExactPaths = ['/'];