add registration and session logic
This commit is contained in:
Generated
+3
-2
@@ -10,11 +10,13 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tailwindcss/postcss": "^4.1.17",
|
"@tailwindcss/postcss": "^4.1.17",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"jose": "^6.1.2",
|
||||||
"next": "16.0.3",
|
"next": "16.0.3",
|
||||||
"next-auth": "5.0.0-beta.30",
|
"next-auth": "5.0.0-beta.30",
|
||||||
"react": "19.2.0",
|
"react": "19.2.0",
|
||||||
"react-dom": "19.2.0",
|
"react-dom": "19.2.0",
|
||||||
"tailwindcss": "^4.1.17"
|
"tailwindcss": "^4.1.17",
|
||||||
|
"zod": "^4.1.13"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
@@ -7013,7 +7015,6 @@
|
|||||||
"version": "4.1.13",
|
"version": "4.1.13",
|
||||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.1.13.tgz",
|
"resolved": "https://registry.npmjs.org/zod/-/zod-4.1.13.tgz",
|
||||||
"integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==",
|
"integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"url": "https://github.com/sponsors/colinhacks"
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
|
|||||||
+3
-1
@@ -11,11 +11,13 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tailwindcss/postcss": "^4.1.17",
|
"@tailwindcss/postcss": "^4.1.17",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"jose": "^6.1.2",
|
||||||
"next": "16.0.3",
|
"next": "16.0.3",
|
||||||
"next-auth": "5.0.0-beta.30",
|
"next-auth": "5.0.0-beta.30",
|
||||||
"react": "19.2.0",
|
"react": "19.2.0",
|
||||||
"react-dom": "19.2.0",
|
"react-dom": "19.2.0",
|
||||||
"tailwindcss": "^4.1.17"
|
"tailwindcss": "^4.1.17",
|
||||||
|
"zod": "^4.1.13"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^20",
|
"@types/node": "^20",
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
'use server'
|
||||||
|
|
||||||
|
import { SignupFormSchema, FormState } from '@/app/lib/definitions'
|
||||||
|
import { createSession, deleteSession } from '@/app/lib/session'
|
||||||
|
import { redirect } from 'next/navigation'
|
||||||
|
|
||||||
|
export async function logout() {
|
||||||
|
await deleteSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authorization(
|
||||||
|
state: string | undefined,
|
||||||
|
formData: FormData,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
console.log(formData);
|
||||||
|
} catch (error) {
|
||||||
|
if (error) {
|
||||||
|
return 'Something went wrong.';
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function registration(
|
||||||
|
state: string | undefined,
|
||||||
|
formData: FormData,
|
||||||
|
) {
|
||||||
|
const validatedFields = SignupFormSchema.safeParse({
|
||||||
|
name: formData.get('full_name'),
|
||||||
|
email: formData.get('email'),
|
||||||
|
password: formData.get('password'),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!validatedFields.success) {
|
||||||
|
return 'Something went wrong from valid.';
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { name, email, password } = validatedFields.data;
|
||||||
|
const response = await fetch('http://localhost:8080/api/auth/register', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ fullName: name, email, password }),
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let parsed = await response.json();
|
||||||
|
await createSession(parsed.token);
|
||||||
|
} catch (error) {
|
||||||
|
if (error) {
|
||||||
|
return 'Something went wrong. error';
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
redirect('/pages/dashboard');
|
||||||
|
}
|
||||||
@@ -19,10 +19,8 @@ export async function testConnect() {
|
|||||||
const response = await fetch('http://localhost:8080/api/auth/register', {
|
const response = await fetch('http://localhost:8080/api/auth/register', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
"firstName": "Serg",
|
"fullName": "Vladislav Sergevich",
|
||||||
"secondName": "Fedorovich",
|
"email": "s2@e.ru",
|
||||||
"lastName": "Tankan",
|
|
||||||
"email": "gggpetst2test@e.ru",
|
|
||||||
"password": "1121231412"
|
"password": "1121231412"
|
||||||
}),
|
}),
|
||||||
headers: {
|
headers: {
|
||||||
@@ -39,31 +37,3 @@ export async function testConnect() {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function authenticate(
|
|
||||||
prevState: string | undefined,
|
|
||||||
formData: FormData,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
console.log(formData);
|
|
||||||
} catch (error) {
|
|
||||||
if (error) {
|
|
||||||
return 'Something went wrong.';
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function registration(
|
|
||||||
prevState: string | undefined,
|
|
||||||
formData: FormData,
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
console.log(formData);
|
|
||||||
} catch (error) {
|
|
||||||
if (error) {
|
|
||||||
return 'Something went wrong.';
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import * as z from 'zod'
|
||||||
|
|
||||||
|
export const SignupFormSchema = z.object({
|
||||||
|
name: z
|
||||||
|
.string()
|
||||||
|
.min(2, { error: 'Name must be at least 2 characters long.' })
|
||||||
|
.trim(),
|
||||||
|
email: z.email({ error: 'Please enter a valid email.' }).trim(),
|
||||||
|
password: z
|
||||||
|
.string()
|
||||||
|
.min(5, { error: 'Be at least 5 characters long' })
|
||||||
|
.regex(/[a-zA-Z]/, { error: 'Contain at least one letter.' })
|
||||||
|
.regex(/[0-9]/, { error: 'Contain at least one number.' })
|
||||||
|
.trim(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type FormState =
|
||||||
|
| {
|
||||||
|
errors?: {
|
||||||
|
name?: string[]
|
||||||
|
email?: string[]
|
||||||
|
password?: string[]
|
||||||
|
}
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
| undefined
|
||||||
|
|
||||||
|
export type FormAction = (
|
||||||
|
state: FormState,
|
||||||
|
formData: FormData
|
||||||
|
) => Promise<FormState>
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import 'server-only'
|
||||||
|
import { cookies } from 'next/headers'
|
||||||
|
import { SignJWT, jwtVerify } from 'jose'
|
||||||
|
/* import { SessionPayload } from '@/app/lib/definitions' */
|
||||||
|
|
||||||
|
const secretKey = process.env.SESSION_SECRET
|
||||||
|
const encodedKey = new TextEncoder().encode(secretKey)
|
||||||
|
|
||||||
|
export async function encrypt(payload: any) {
|
||||||
|
return new SignJWT(payload)
|
||||||
|
.setProtectedHeader({ alg: 'HS256' })
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime('7d')
|
||||||
|
.sign(encodedKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function decrypt(session: string | undefined = '') {
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(session, encodedKey, {
|
||||||
|
algorithms: ['HS256'],
|
||||||
|
})
|
||||||
|
return payload
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Failed to verify session')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createSession(userId: string) {
|
||||||
|
const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
const session = await encrypt({ userId, expiresAt })
|
||||||
|
const cookieStore = await cookies()
|
||||||
|
|
||||||
|
cookieStore.set('session', session, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
expires: expiresAt,
|
||||||
|
sameSite: 'lax',
|
||||||
|
path: '/',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteSession() {
|
||||||
|
const cookieStore = await cookies()
|
||||||
|
cookieStore.delete('session')
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import 'server-only'
|
||||||
|
import { cookies } from 'next/headers'
|
||||||
|
import { decrypt } from '@/app/lib/session'
|
||||||
|
|
||||||
|
export async function updateSession() {
|
||||||
|
const session = (await cookies()).get('session')?.value
|
||||||
|
const payload = await decrypt(session)
|
||||||
|
|
||||||
|
if (!session || !payload) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
|
||||||
|
const cookieStore = await cookies()
|
||||||
|
cookieStore.set('session', session, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
expires: expires,
|
||||||
|
sameSite: 'lax',
|
||||||
|
path: '/',
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { testConnect } from '@/app/api/action';
|
import { testConnect } from '@/app/lib/action';
|
||||||
|
|
||||||
async function clickHandler() {
|
async function clickHandler() {
|
||||||
testConnect();
|
testConnect();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useRef } from 'react';
|
import { useState, useRef } from 'react';
|
||||||
import { fetchFruits } from '@/app/api/action';
|
import { fetchFruits } from '@/app/lib/action';
|
||||||
import { useClickOutside } from '@/app/hooks/useClickOutside';
|
import { useClickOutside } from '@/app/hooks/useClickOutside';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
import styles from '@/app/styles/login.module.scss'
|
import styles from '@/app/styles/login.module.scss'
|
||||||
import { useActionState } from 'react';
|
import { useActionState } from 'react';
|
||||||
import { authenticate } from '@/app/api/action';
|
import { authorization } from '@/app/actions/auth';
|
||||||
|
|
||||||
export default function LoginForm() {
|
export default function LoginForm() {
|
||||||
const [errorMessage, formAction, isPending] = useActionState(
|
const [errorMessage, formAction, isPending] = useActionState(
|
||||||
authenticate,
|
authorization,
|
||||||
undefined,
|
undefined,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import styles from '@/app/styles/login.module.scss';
|
import styles from '@/app/styles/login.module.scss';
|
||||||
import { useActionState } from 'react';
|
import { useActionState } from 'react';
|
||||||
import { registration } from '@/app/api/action';
|
import { registration } from '@/app/actions/auth';
|
||||||
|
|
||||||
export default function RegisterForm() {
|
export default function RegisterForm() {
|
||||||
const [errorMessage, formAction, isPending] = useActionState(
|
const [errorMessage, formAction, isPending] = useActionState(
|
||||||
@@ -23,7 +23,7 @@ export default function RegisterForm() {
|
|||||||
<div className={`${styles['form-row']}`}>
|
<div className={`${styles['form-row']}`}>
|
||||||
<div className={`${styles['form-group']}`}>
|
<div className={`${styles['form-group']}`}>
|
||||||
<label className={`${styles['form-label']} ${styles['required']}`}>Email адрес</label>
|
<label className={`${styles['form-label']} ${styles['required']}`}>Email адрес</label>
|
||||||
<input type="password" id="email" name="email" className={`${styles['form-input']}`} placeholder="ivan@example.com" />
|
<input type="text" id="email" name="email" className={`${styles['form-input']}`} placeholder="ivan@example.com" />
|
||||||
</div>
|
</div>
|
||||||
<div className={`${styles['form-group']}`}>
|
<div className={`${styles['form-group']}`}>
|
||||||
<label className={`${styles['form-label']}`}>Телефон</label>
|
<label className={`${styles['form-label']}`}>Телефон</label>
|
||||||
|
|||||||
+18
-4
@@ -1,11 +1,25 @@
|
|||||||
import { NextResponse, NextRequest } from 'next/server';
|
import { NextResponse, NextRequest } from 'next/server';
|
||||||
|
import { cookies } from 'next/headers'
|
||||||
|
import { decrypt } from '@/app/lib/session';
|
||||||
|
|
||||||
const isLogin = true;
|
const protectedRoutes = ['/pages']
|
||||||
|
const publicRoutes = ['/login', '/register', '/']
|
||||||
|
|
||||||
export function proxy(request: NextRequest) {
|
export default async function proxy(request: NextRequest) {
|
||||||
if (request.nextUrl.pathname !== '/login' && !isLogin) {
|
const path = request.nextUrl.pathname;
|
||||||
return NextResponse.redirect(new URL('/login', request.url));
|
const isProtectedRoute = protectedRoutes.includes(path.slice(0, 6));
|
||||||
|
const isPublicRoute = publicRoutes.includes(path);
|
||||||
|
|
||||||
|
const cookie = (await cookies()).get('session')?.value;
|
||||||
|
console.log("cookie");
|
||||||
|
console.log(!!cookie);
|
||||||
|
const session = await decrypt(cookie);
|
||||||
|
|
||||||
|
if (isProtectedRoute && !session?.userId) {
|
||||||
|
return NextResponse.redirect(new URL('/login', request.nextUrl))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
|
|||||||
Reference in New Issue
Block a user