login page

This commit is contained in:
2025-05-19 11:54:30 +03:00
parent 695c29ab62
commit b91bd87555
12 changed files with 457 additions and 14 deletions

View File

@@ -53,6 +53,12 @@ MIDDLEWARE = [
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),

View File

@@ -0,0 +1,57 @@
'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import AccountSidebar from '@/components/AccountSidebar'
import Loader from '@/components/ui/Loader'
import { RiUser3Line } from 'react-icons/ri'
import { CgNotes } from 'react-icons/cg'
import { FaStar } from 'react-icons/fa6'
import useUserStore from '@/app/store/userStore'
export default function AccountLayout({
children,
}: {
children: React.ReactNode
}) {
const [isLoading, setIsLoading] = useState(true)
const router = useRouter()
const { isAuthenticated, user } = useUserStore()
useEffect(() => {
if (!isAuthenticated || !user) {
router.replace('/login')
return
}
const timer = setTimeout(() => {
setIsLoading(false)
}, 300)
return () => clearTimeout(timer)
}, [isAuthenticated, user, router])
if (!isAuthenticated || !user || isLoading) {
return <Loader />
}
const userNavigation = [
{ name: 'Профиль', href: '/account', icon: RiUser3Line },
{ name: 'Мои маршруты', href: '/account/routes', icon: CgNotes },
]
return (
<div className="min-h-full">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="flex flex-col md:flex-row gap-6">
<div className="w-full md:w-64 flex-shrink-0">
<div className="sticky top-8">
<AccountSidebar user={user} navigation={userNavigation} />
</div>
</div>
<main className="flex-1 min-w-0">{children}</main>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,114 @@
import React from 'react'
import { useForm } from '@/app/hooks/useForm'
import Button from '@/components/ui/Button'
// import LoginButton from '@/app/components/ui/LoginButton'
import { HiOutlineEye, HiOutlineEyeOff } from 'react-icons/hi'
import showToast from '@/components/ui/Toast'
import { useRouter } from 'next/navigation'
import { signIn } from 'next-auth/react'
// import PasswordRecovery from '@/app/components/ui/PasswordRecovery'
const validationRules = {
email: { required: true },
password: { required: true, minLength: 8 },
}
const ClientView = () => {
const router = useRouter()
const {
values,
isVisible,
handleChange,
handleSubmit,
togglePasswordVisibility,
} = useForm(
{
email: '',
password: '',
},
validationRules,
async (values) => {
try {
const result = await signIn('credentials', {
email: values.email,
password: values.password,
redirect: false,
})
if (result?.error) {
showToast({ type: 'error', message: result.error })
return
}
showToast({ type: 'success', message: 'Авторизация успешна!' })
router.push('/account')
} catch {
showToast({ type: 'error', message: 'Ошибка при входе в аккаунт' })
}
}
)
return (
<>
<form className="flex flex-col gap-1" onSubmit={handleSubmit}>
<div className="mb-2">
<label className="block mb-2 text-gray-700" htmlFor="email">
Ваш email:
</label>
<input
type="email"
id="email"
placeholder="my_email@gmail.com"
value={values.email}
onChange={handleChange}
className="w-full px-3 py-2 border text-black rounded-xl focus:outline-none focus:ring-2 focus:ring-mainblocks"
autoComplete="true"
/>
</div>
<div className="mb-4">
<label className="block mb-2 text-gray-700" htmlFor="email">
Ваш пароль:
</label>
<div className="relative">
<input
type={isVisible ? 'text' : 'password'}
id="password"
placeholder="Пароль"
value={values.password}
onChange={handleChange}
className="w-full px-3 py-2 border text-black rounded-xl focus:outline-none focus:ring-2 focus:ring-mainblocks"
autoComplete="true"
/>
<button
type="button"
onClick={() => togglePasswordVisibility()}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
>
{isVisible ? <HiOutlineEye /> : <HiOutlineEyeOff />}
</button>
</div>
</div>
{/* <div className="flex flex-row-reverse text-sm justify-between pb-2">
<PasswordRecovery />
</div> */}
<Button
text="Войти"
className="flex items-center justify-center bg-black rounded-2xl text-white text-base font-semibold py-3"
type="submit"
/>
</form>
<div className="flex items-center gap-4">
<div className="flex-1 border-t border-gray-300" />
<p className="shrink-0 px-2 text-gray-700">Или</p>
<div className="flex-1 border-t border-gray-300" />
</div>
{/* <LoginButton /> */}
</>
)
}
export default ClientView

View File

@@ -1,7 +1,60 @@
import React from 'react'
'use client'
const page = () => {
return <div>page</div>
import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import Loader from '@/components/ui/Loader'
import useUserStore from '@/app/store/userStore'
import ClientView from './ClientView'
const LoginPage = () => {
const router = useRouter()
const { isAuthenticated } = useUserStore()
const [isClient, setIsClient] = useState(true)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
// проверяем логин
if (isAuthenticated) {
// распределяем
if (isClient) {
router.replace('/account')
}
return
}
const timer = setTimeout(() => {
setIsLoading(false)
}, 300)
return () => clearTimeout(timer)
}, [isAuthenticated, router, isClient])
if (isLoading) {
return <Loader />
}
return (
<div className="flex items-center justify-center py-8 ">
<div className="flex w-full max-w-xl flex-col gap-4 bg-white rounded-2xl shadow-lg p-6">
<div className="flex flex-col items-center py-4">
<h1 className="text-2xl font-medium pb-1">Рады видеть Вас снова!</h1>
<p className="text-base font-medium text-center">
Пожалуйста, авторизуйтесь, чтобы продолжить
</p>
</div>
<ClientView />
<p className="text-center text-base font-medium">
Впервые у нас?{' '}
<span className="text-orange/70 hover:underline">
<Link href="/register">Зарегистрироваться</Link>
</span>
</p>
</div>
</div>
)
}
export default page
export default LoginPage

View File

@@ -1,7 +0,0 @@
import React from 'react'
const page = () => {
return <div>page</div>
}
export default page

View File

@@ -15,9 +15,7 @@ const RegisterPage = () => {
// проверяем логин
if (isAuthenticated) {
// распределяем
if (!isClient) {
router.replace('/admin')
} else {
if (isClient) {
router.replace('/account')
}
return

View File

@@ -1,4 +1,5 @@
import { StaticImageData } from 'next/image'
import { IconType } from 'react-icons'
export interface TextInputProps {
value: string
@@ -121,3 +122,14 @@ export interface PhoneInputProps {
className?: string
operatorsInfo?: boolean
}
export interface NavigationItem {
name: string
href: string
icon: IconType
}
export interface AccountSidebarProps {
user: User
navigation: NavigationItem[]
}

View File

@@ -0,0 +1,110 @@
'use client'
import React from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { usePathname } from 'next/navigation'
import { AccountSidebarProps } from '@/app/types'
import Logout from './Logout'
import noPhoto from '../public/images/noPhoto.png'
const AccountSidebar: React.FC<AccountSidebarProps> = ({
user,
navigation,
}) => {
const pathname = usePathname()
if (!user) {
return null
}
const navigationItems = navigation
const getAccountTypeStyles = (accountType: string) => {
switch (accountType.toLowerCase()) {
case 'free':
return 'bg-gray-400 text-white'
case 'pro':
return 'bg-orage/70 text-white'
case 'premium':
return 'bg-blue-300'
default:
return 'bg-gray-200'
}
}
return (
<div className="space-y-3">
<div className="flex items-center space-x-4 w-full bg-white rounded-2xl shadow p-4">
<div className="flex items-center justify-center">
{user.image ? (
<Image
src={user.image}
alt="Profile"
height={84}
width={84}
className="rounded-2xl w-full md:w-[84px] aspect-square object-cover"
priority
/>
) : (
<Image
src={noPhoto}
alt="Фотографии пока что нет"
height={84}
width={84}
priority
className="rounded-2xl w-full md:w-[84px] aspect-square object-cover"
/>
)}
</div>
<div className="space-y-1">
<p className="text-xl font-bold">{user.name || 'Пользователь'}</p>
<p className="text-sm font-medium text-gray-500">
ID: {user.uuid || 'Not available'}
</p>
{user.account_type && (
<Link
href="payments/"
className={`${getAccountTypeStyles(
user.account_type
)} flex items-center justify-center py-1 px-3 text-sm rounded-lg`}
>
{user.account_type.charAt(0).toUpperCase() +
user.account_type.slice(1)}
</Link>
)}
</div>
</div>
<div className="w-full md:w-64 bg-white rounded-2xl shadow p-2">
<nav className="space-y-2">
{navigationItems.map((item) => {
const isActive = pathname === item.href
return (
<Link
key={item.name}
href={item.href}
className={`${
isActive
? 'bg-mainblocks text-white'
: 'text-gray-600 hover:bg-gray-100'
} flex items-center p-4 text-sm font-medium rounded-lg transition-colors`}
>
<item.icon
className={`mr-3 h-5 w-5 ${
isActive ? 'text-white' : 'text-gray-400'
}`}
/>
{item.name}
</Link>
)
})}
</nav>
</div>
<div className="w-full md:w-64 bg-white rounded-2xl shadow p-2">
<Logout />
</div>
</div>
)
}
export default AccountSidebar

View File

@@ -0,0 +1,43 @@
import React from 'react'
import { useRouter } from 'next/navigation'
import { signOut } from 'next-auth/react'
import Button from './ui/Button'
import { IoExitOutline } from 'react-icons/io5'
import useUserStore from '@/app/store/userStore'
const Logout = () => {
const API_URL = process.env.NEXT_PUBLIC_API_URL
const router = useRouter()
const handleLogout = async () => {
try {
// бекенд чистит куки
await fetch(`${API_URL}/logout`, {
method: 'POST',
credentials: 'include',
})
// чистим стор
useUserStore.getState().logout()
// если логин был гугловый
await signOut({ redirect: false })
// редирект
router.push('/')
router.refresh() // обновляем страницу чтобы обновить стейты
} catch (error) {
console.error('Logout error:', error)
}
}
return (
<Button
text="Выйти из аккаунта"
className="w-full text-sm font-medium text-gray-600 hover:bg-gray-100 px-4 py-4 flex items-center rounded-lg transition-colors"
onClick={handleLogout}
/>
)
}
export default Logout

View File

@@ -0,0 +1,21 @@
import React from 'react'
const Loader = () => {
return (
<div className="flex items-center justify-center p-8">
<div className="relative w-12 h-12">
{/* пульсирующие круги */}
<div className="absolute inset-0 rounded-full bg-orange/20 animate-ping"></div>
<div
className="absolute inset-2 rounded-full bg-orange/40 animate-ping"
style={{ animationDelay: '0.2s' }}
></div>
<div className="absolute inset-4 rounded-full bg-orange animate-pulse"></div>
{/* бегущий блик */}
<div className="absolute inset-0 rounded-full bg-gradient-to-r from-transparent via-white/20 to-transparent animate-shimmer"></div>
</div>
</div>
)
}
export default Loader

View File

@@ -0,0 +1,36 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { jwtDecode } from 'jwt-decode'
interface JWTPayload {
exp?: number
}
export function middleware(request: NextRequest) {
const accessToken = request.cookies.get('accessToken')?.value
const refreshToken = request.cookies.get('refreshToken')?.value
const isAuthPage = request.nextUrl.pathname.startsWith('/account')
if (isAuthPage && (!accessToken || !refreshToken)) {
return NextResponse.redirect(new URL('/login', request.url))
}
if (isAuthPage && accessToken) {
try {
const decoded = jwtDecode<JWTPayload>(accessToken)
if (decoded.exp && decoded.exp < Date.now() / 1000) {
return NextResponse.redirect(new URL('/login', request.url))
}
} catch (error) {
console.error('Token decode error:', error)
return NextResponse.redirect(new URL('/login', request.url))
}
}
return NextResponse.next()
}
export const config = {
matcher: ['/account/:path*'],
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 504 KiB