add auth, logout
This commit is contained in:
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev -p 2999",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "eslint"
|
"lint": "eslint"
|
||||||
|
|||||||
+57
-7
@@ -1,25 +1,70 @@
|
|||||||
'use server'
|
'use server'
|
||||||
|
|
||||||
import { SignupFormSchema, FormState } from '@/app/lib/definitions'
|
import { SignupFormSchema, loginFormSchema } from '@/app/lib/definitions';
|
||||||
import { createSession, deleteSession } from '@/app/lib/session'
|
import { createSession, deleteSession, getSessionToken } from '@/app/lib/session';
|
||||||
import { redirect } from 'next/navigation'
|
import { redirect } from 'next/navigation'
|
||||||
|
|
||||||
export async function logout() {
|
export async function logout() {
|
||||||
await deleteSession()
|
const token = await getSessionToken();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fetch('http://localhost:8080/api/auth/logout', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json",
|
||||||
|
"Authorization": `Bearer ${token}`,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
await deleteSession();
|
||||||
|
redirect('/login');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function authorization(
|
export async function authorization(
|
||||||
state: string | undefined,
|
state: string | undefined,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
) {
|
) {
|
||||||
|
const validatedFields = loginFormSchema.safeParse({
|
||||||
|
email: formData.get('email'),
|
||||||
|
password: formData.get('password'),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!validatedFields.success) {
|
||||||
|
return 'error';
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(formData);
|
const { email, password } = validatedFields.data;
|
||||||
|
const response = await fetch('http://localhost:8080/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
email: email,
|
||||||
|
password: password
|
||||||
|
}),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (response.ok) {
|
||||||
|
let parsed = await response.json();
|
||||||
|
await createSession(parsed.token);
|
||||||
|
} else {
|
||||||
|
throw new Error('Something went wrong. from server');
|
||||||
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error) {
|
if (error) {
|
||||||
return 'Something went wrong.';
|
return 'Something went wrong. from server';
|
||||||
}
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
redirect('/pages/dashboard');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function registration(
|
export async function registration(
|
||||||
@@ -59,8 +104,13 @@ export async function registration(
|
|||||||
"Accept": "application/json"
|
"Accept": "application/json"
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let parsed = await response.json();
|
|
||||||
await createSession(parsed.token);
|
if (response.ok) {
|
||||||
|
let parsed = await response.json();
|
||||||
|
await createSession(parsed.token);
|
||||||
|
} else {
|
||||||
|
throw new Error('Something went wrong. from server');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error) {
|
if (error) {
|
||||||
const errors: Record<string, string> = {}
|
const errors: Record<string, string> = {}
|
||||||
|
|||||||
+27
-15
@@ -1,5 +1,21 @@
|
|||||||
import * as z from 'zod'
|
import * as z from 'zod'
|
||||||
|
|
||||||
|
export type FormState =
|
||||||
|
| {
|
||||||
|
errors?: {
|
||||||
|
name?: string[]
|
||||||
|
email?: string[]
|
||||||
|
password?: string[]
|
||||||
|
}
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
| undefined
|
||||||
|
|
||||||
|
export type FormAction = (
|
||||||
|
state: FormState,
|
||||||
|
formData: FormData
|
||||||
|
) => Promise<FormState>
|
||||||
|
|
||||||
export const SignupFormSchema = z
|
export const SignupFormSchema = z
|
||||||
.object({
|
.object({
|
||||||
full_name: z
|
full_name: z
|
||||||
@@ -21,18 +37,14 @@ export const SignupFormSchema = z
|
|||||||
path: ['confirm_password'],
|
path: ['confirm_password'],
|
||||||
});
|
});
|
||||||
|
|
||||||
export type FormState =
|
export const loginFormSchema = z
|
||||||
| {
|
.object({
|
||||||
errors?: {
|
email: z
|
||||||
name?: string[]
|
.string()
|
||||||
email?: string[]
|
.min(1, { error: 'Email must be not empty' })
|
||||||
password?: string[]
|
.trim(),
|
||||||
}
|
password: z
|
||||||
message?: string
|
.string()
|
||||||
}
|
.min(1, { error: 'Password must be not empty' })
|
||||||
| undefined
|
.trim(),
|
||||||
|
})
|
||||||
export type FormAction = (
|
|
||||||
state: FormState,
|
|
||||||
formData: FormData
|
|
||||||
) => Promise<FormState>
|
|
||||||
+23
-4
@@ -25,10 +25,10 @@ export async function decrypt(session: string | undefined = '') {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createSession(userId: string) {
|
export async function createSession(token: string) {
|
||||||
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||||
const session = await encrypt({ userId, expiresAt })
|
const session = await encrypt({ token, expiresAt });
|
||||||
const cookieStore = await cookies()
|
const cookieStore = await cookies();
|
||||||
|
|
||||||
cookieStore.set('session', session, {
|
cookieStore.set('session', session, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
@@ -39,6 +39,25 @@ export async function createSession(userId: string) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getSessionToken(): Promise<string | null> {
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const sessionCookie = cookieStore.get('session')?.value;
|
||||||
|
|
||||||
|
if (!sessionCookie) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await decrypt(sessionCookie);
|
||||||
|
|
||||||
|
if (payload && typeof payload === 'object' && 'token' in payload) {
|
||||||
|
return payload.token as string;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export async function deleteSession() {
|
export async function deleteSession() {
|
||||||
const cookieStore = await cookies()
|
const cookieStore = await cookies()
|
||||||
cookieStore.delete('session')
|
cookieStore.delete('session')
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import clsx from 'clsx';
|
|||||||
import styles from './ui.module.scss'
|
import styles from './ui.module.scss'
|
||||||
import Logo from '@/app/ui/logo';
|
import Logo from '@/app/ui/logo';
|
||||||
import DropDownList from '@/app/ui/nav-link-dropdown';
|
import DropDownList from '@/app/ui/nav-link-dropdown';
|
||||||
|
import { logout } from '@/app/actions/auth';
|
||||||
|
|
||||||
const links = [
|
const links = [
|
||||||
{
|
{
|
||||||
@@ -42,12 +43,7 @@ const links = [
|
|||||||
name: 'API',
|
name: 'API',
|
||||||
href: '/pages/page1',
|
href: '/pages/page1',
|
||||||
img: 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0L19.2 12l-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
|
img: 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0L19.2 12l-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
|
||||||
},
|
}
|
||||||
{
|
|
||||||
name: 'Выход',
|
|
||||||
href: '/pages/page1',
|
|
||||||
img: 'M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z'
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
export default function NavLinks() {
|
export default function NavLinks() {
|
||||||
@@ -95,6 +91,20 @@ export default function NavLinks() {
|
|||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
<Link
|
||||||
|
key='Выход'
|
||||||
|
href='/login'
|
||||||
|
className={`flex ${styles['nav-link']}`}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
logout();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"></path>
|
||||||
|
</svg>
|
||||||
|
<p className="hidden md:block">Выход</p>
|
||||||
|
</Link>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+1
-1
@@ -15,7 +15,7 @@ export default async function proxy(request: NextRequest) {
|
|||||||
console.log(!!cookie);
|
console.log(!!cookie);
|
||||||
const session = await decrypt(cookie);
|
const session = await decrypt(cookie);
|
||||||
|
|
||||||
if (isProtectedRoute && !session?.userId) {
|
if (isProtectedRoute && !session?.token) {
|
||||||
return NextResponse.redirect(new URL('/login', request.nextUrl))
|
return NextResponse.redirect(new URL('/login', request.nextUrl))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user