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:
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { Loader2 } from 'lucide-react';
|
import { Loader2 } from 'lucide-react';
|
||||||
@@ -17,9 +17,18 @@ import { useAuthStore } from '@/lib/auth-store';
|
|||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
const { login, isLoading, error, clearError } = useAuthStore();
|
const { login, isLoading, error, clearError } = useAuthStore();
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
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 {
|
const {
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
@@ -45,6 +54,11 @@ export default function LoginPage() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
<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 && (
|
{error && (
|
||||||
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
|
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive" role="alert">
|
||||||
{error}
|
{error}
|
||||||
|
|||||||
55
apps/web/app/auth/callback/google/page.tsx
Normal file
55
apps/web/app/auth/callback/google/page.tsx
Normal 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ử lý đăng nhập Google...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
55
apps/web/app/auth/callback/zalo/page.tsx
Normal file
55
apps/web/app/auth/callback/zalo/page.tsx
Normal 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ử lý đăng nhập Zalo...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ import { create } from 'zustand';
|
|||||||
import { authApi, type TokenPair, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
|
import { authApi, type TokenPair, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
|
||||||
import { ApiError } from './api-client';
|
import { ApiError } from './api-client';
|
||||||
|
|
||||||
|
export type { TokenPair };
|
||||||
|
|
||||||
const TOKEN_KEY = 'goodgo_tokens';
|
const TOKEN_KEY = 'goodgo_tokens';
|
||||||
|
|
||||||
function persistTokens(tokens: TokenPair | null) {
|
function persistTokens(tokens: TokenPair | null) {
|
||||||
@@ -32,6 +34,7 @@ interface AuthState {
|
|||||||
|
|
||||||
login: (data: LoginPayload) => Promise<void>;
|
login: (data: LoginPayload) => Promise<void>;
|
||||||
register: (data: RegisterPayload) => Promise<void>;
|
register: (data: RegisterPayload) => Promise<void>;
|
||||||
|
handleOAuthCallback: (tokens: TokenPair) => Promise<void>;
|
||||||
logout: () => void;
|
logout: () => void;
|
||||||
refreshToken: () => Promise<boolean>;
|
refreshToken: () => Promise<boolean>;
|
||||||
fetchProfile: () => Promise<void>;
|
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: () => {
|
logout: () => {
|
||||||
persistTokens(null);
|
persistTokens(null);
|
||||||
set({ tokens: null, user: null, error: null });
|
set({ tokens: null, user: null, error: null });
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { NextResponse } from 'next/server';
|
import { NextResponse } from 'next/server';
|
||||||
import type { NextRequest } from 'next/server';
|
import type { NextRequest } from 'next/server';
|
||||||
|
|
||||||
const publicPaths = ['/login', '/register', '/search'];
|
const publicPaths = ['/login', '/register', '/search', '/auth/callback'];
|
||||||
|
|
||||||
const publicExactPaths = ['/'];
|
const publicExactPaths = ['/'];
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user