feat / AEB-26 login page

This commit is contained in:
Timofey Syrokvashko
2025-09-01 11:34:30 +03:00
parent 38a31824bc
commit 65a63235e5
37 changed files with 1185 additions and 49 deletions

View File

@@ -0,0 +1,12 @@
'use client'
import { Toaster } from 'react-hot-toast'
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
<>
<Toaster />
{children}
</>
)
}

View File

@@ -1,7 +1,143 @@
import React from 'react'
'use client'
import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useRouter } from 'next/navigation'
import useUserStore from '@/app/store/userStore'
import Loader from '@/components/ui/Loader'
import { useForm } from '@/app/hooks/useForm'
import Button from '@/components/ui/Button'
import showToast from '@/components/ui/ShowToast'
import { signIn } from 'next-auth/react'
import TextInput from '@/components/ui/TextInput'
import RoleSelector from '@/components/selectors/RoleSelector'
const validationRules = {
login: { required: true },
password: { required: true },
}
const LoginPage = () => {
return <div> LoginPage</div>
const router = useRouter()
const { isAuthenticated } = useUserStore()
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
// проверяем логин
if (isAuthenticated) {
// распределяем
router.replace('/objects')
return
}
const timer = setTimeout(() => {
setIsLoading(false)
}, 300)
return () => clearTimeout(timer)
}, [isAuthenticated, router])
const { values, isVisible, handleChange, handleSubmit, togglePasswordVisibility } = useForm(
{
login: '',
password: '',
role: '',
},
validationRules,
async values => {
try {
const result = await signIn('credentials', {
login: values.login,
password: values.password,
redirect: false,
})
if (result?.error) {
showToast({ type: 'error', message: result.error })
return
}
showToast({ type: 'success', message: 'Авторизация успешна!' })
router.push('/objects')
} catch {
showToast({ type: 'error', message: 'Ошибка при входе в аккаунт' })
}
}
)
if (isLoading) {
return <Loader />
}
return (
<div className="relative flex h-screen flex-col items-center justify-center gap-8 py-8">
<div className="mb-4 flex items-center justify-center gap-4">
<Image
src="/icons/logo.svg"
alt="AerBIM Logo"
width={83}
height={57}
className="h-14 w-auto"
/>
<div className="flex flex-col items-start justify-center">
<span className="text-xl font-semibold">AerBIM Monitor</span>
<span className="text-blue text-lg">AMS HT Viewer</span>
</div>
</div>
<div className="bg-cards z-10 mx-4 flex w-full max-w-xl flex-col gap-4 rounded-2xl p-6 shadow-lg md:mx-8">
<form
className="flex flex-col items-center justify-between gap-8 md:flex-row md:gap-4"
onSubmit={handleSubmit}
>
<div className="flex w-full flex-col gap-4">
<h1 className="text-2xl font-bold">Авторизация</h1>
<TextInput
value={values.login}
name="login"
handleChange={handleChange}
placeholder="ivan_ivanov"
style="register"
label="Ваш логин"
/>
<TextInput
value={values.password}
name="password"
handleChange={handleChange}
placeholder="Не менее 8 символов"
style="register"
label="Ваш пароль"
isPassword={true}
isVisible={isVisible}
togglePasswordVisibility={togglePasswordVisibility}
/>
<RoleSelector
value={values.role}
name="role"
handleChange={handleChange}
label="Ваша роль"
placeholder="Выберите вашу роль"
/>
<div className="flex w-full items-center justify-center pt-6">
<Button
text="Войти"
className="bg-blue mt-3 flex w-full items-center justify-center py-4 text-base font-semibold text-white shadow-lg transition-all duration-200 hover:opacity-90"
type="submit"
/>
</div>
</div>
</form>
<p className="text-center text-base font-medium">
<span className="hover:text-blue transition-colors duration-200 hover:underline">
<Link href="/password-recovery">Забыли логин/пароль?</Link>
</span>
</p>
</div>
</div>
)
}
export default LoginPage

View File

View File

@@ -0,0 +1,5 @@
import NextAuth from 'next-auth'
import { authOptions } from '@/lib/auth'
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST }

View File

@@ -1,25 +1,37 @@
@import "tailwindcss";
@import 'tailwindcss';
:root {
--background: #ffffff;
--foreground: #171717;
--background: #0e111a;
--foreground: #ffffff;
}
/* @font-face {
font-family: '';
font-style: normal;
font-weight: 200 700;
font-display: swap;
src: url('') format('truetype');
} */
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-blue: #3193f5;
--color-cards: #161824;
/* --font-display: '', 'sans-serif'; */
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--background: #0e111a;
--foreground: #ededed;
}
}
html, body {
html,
body {
margin: 0;
padding: 0;
height: 100%;

View File

@@ -1,34 +1,22 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
import type { Metadata } from 'next'
import './globals.css'
import { Providers } from './providers/Providers'
export const metadata: Metadata = {
title: "Aerbim - 3D Building Sensor Dashboard",
description: "Aerbim является дашбордом для визуализации показаний датчиков в 3D модели здания",
};
title: 'Aerbim - 3D Building Sensor Dashboard',
description: 'Aerbim является дашбордом для визуализации показаний датчиков в 3D модели здания',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
children: React.ReactNode
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<body className="font-display flex min-h-screen flex-col">
<Providers>{children}</Providers>
</body>
</html>
);
)
}

View File

@@ -0,0 +1,57 @@
'use client'
import { useSession } from 'next-auth/react'
import { useEffect } from 'react'
import useUserStore from '../store/userStore'
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
const { data: session } = useSession()
const { setUser, setAuthenticated } = useUserStore()
useEffect(() => {
const fetchUserData = async () => {
if (!session?.accessToken) {
setUser(null)
setAuthenticated(false)
return
}
const API_URL = process.env.NEXT_PUBLIC_API_URL
try {
const response = await fetch(`${API_URL}/account/user/`, {
headers: {
Authorization: `Bearer ${session.accessToken}`,
'Content-Type': 'application/json',
},
})
if (!response.ok) {
const errorText = await response.text()
console.error('Error response:', errorText)
throw new Error(`Error fetching user data: ${response.status} ${errorText}`)
}
const userData = await response.json()
setUser({
id: userData.id,
name: userData.name || session.user.name || '',
surname: userData.surname || '',
email: userData.email || session.user.email || '',
image: userData.image,
account_type: userData.account_type,
login: userData.login,
uuid: userData.uuid,
})
setAuthenticated(true)
} catch (error) {
console.error('Error in fetchUserData:', error)
}
}
fetchUserData()
}, [session, setUser, setAuthenticated])
return <>{children}</>
}

View File

@@ -0,0 +1,29 @@
'use client'
import { SessionProvider } from 'next-auth/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { AuthProvider } from './AuthProvider'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
})
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SessionProvider
refetchInterval={0}
refetchOnWindowFocus={false}
refetchWhenOffline={false}
basePath="/api/auth"
>
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
</SessionProvider>
)
}

View File

@@ -26,9 +26,41 @@ export interface User {
email: string
account_type?: string
login: string
uuid?: string
}
export interface UserState {
isAuthenticated: boolean
user: User | null
}
export interface ButtonProps {
onClick?: () => void
className?: string
text?: string
leftIcon?: React.ReactNode
midIcon?: React.ReactNode
rightIcon?: React.ReactNode
type?: 'button' | 'submit' | 'reset'
disabled?: boolean
size?: 'sm' | 'md' | 'lg'
variant?: 'default' | 'text'
}
export interface TextInputProps {
value: string
handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
label?: string
placeholder?: string
name: string
type?: 'text' | 'email' | 'password' | 'datetime-local' | 'date'
className?: string
maxLength?: number
tooltip?: string | React.ReactNode
style: string
isPassword?: boolean
isVisible?: boolean
togglePasswordVisibility?: () => void
error?: string
min?: string
}