Login mit jwt

This commit is contained in:
klaas 2024-09-29 02:53:40 +02:00
parent 550a69688d
commit 11e825c64f
10 changed files with 111 additions and 46 deletions

View File

@ -7,12 +7,6 @@
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);

View File

@ -1,4 +1,5 @@
import Counter from "@/components/Counter";
import Login from "@/components/Login";
export default function Home() {
@ -6,6 +7,7 @@ export default function Home() {
return (<div >
<h1 className="text-7xl font-bold underline">My first Next App</h1>
<Login />
< Counter />

View File

@ -1,7 +1,7 @@
import React from 'react'
import Link from "next/link";
type response = {
type res = {
message: string;
game: spiel;
}
@ -20,8 +20,7 @@ async function spiel({params}:{params:{id:number}}) {
const response = await fetch("http://localhost:2006/spiele/"+params.id);
const data:response[] = await response.json();
console.log(data);
const data:res = await response.json();
const game: spiel = data.game;
return (
<div>

View File

@ -15,7 +15,7 @@ type spiel = {
async function spiele() {
const response = await fetch("http://localhost:2006/spiele");
const data:response[] = await response.json();
const data:response = await response.json();
return (
<div>

View File

@ -1,24 +1,65 @@
import React from 'react'
'use client';
import { useState } from 'react';
import axios from 'axios';
import Cookies from 'js-cookie';
export default function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:2006/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email,
password,
}),
});
if (response.ok) {
const data= await response.json();
console.log('Login successful:', data.token);
// Speichere das JWT im Cookie
Cookies.set('token', data.token);
}else{
console.error('Login failed:', response.statusText);
}
// Weiterleitung zur geschützten Route
} catch (error) {
console.error('Login error:', error);
alert(JSON.stringify({
email,
password,
}));
alert(error);
}
};
function Login() {
return (
<div>
<form>
<label>
Username
<input type="text" name="username" />
</label>
<label>
Password
<input type="password" name="password" />
</label>
<h1>Login</h1>
<form onSubmit={handleLogin}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="E-Mail"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Passwort"
/>
<button type="submit">Login</button>
</form>
<script>
console.log("Login")
</script>
</div>
)
);
}
export default Login

19
app/middleware.ts Normal file
View File

@ -0,0 +1,19 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(req: NextRequest) {
const token = req.cookies.get('token')?.value;
const loginUrl = new URL('/login', req.url);
// Wenn kein Token vorhanden ist, leite zur Login-Seite um
if (!token) {
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
// Definiere, für welche Routen das Middleware gelten soll
export const config = {
matcher: ['/protected'],
};

View File

@ -9,18 +9,21 @@
"lint": "next lint"
},
"dependencies": {
"axios": "^1.7.7",
"js-cookie": "^3.0.5",
"next": "14.2.13",
"react": "^18",
"react-dom": "^18",
"next": "14.2.13"
"react-dom": "^18"
},
"devDependencies": {
"typescript": "^5",
"@types/js-cookie": "^3.0.6",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.2.13",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^8",
"eslint-config-next": "14.2.13"
"typescript": "^5"
}
}

View File

@ -5,6 +5,15 @@ const authRoutes = require("./routes/auth");
const memberRoutes = require("./routes/members");
const spieleRoutes = require("./routes/spiele");
const bodyParser = require("body-parser");
const cors = require("cors");
// CORS für alle Routen aktivieren
app.use(
cors({
origin: "http://localhost:3000", // Ersetze dies durch deine Next.js URL
credentials: true, // Falls du Cookies oder Auth-Headers verwendest
})
);
// Middleware
app.use(express.json());

View File

@ -47,6 +47,7 @@ const registerUser = async (req, res) => {
// Loginfunktion
const loginUser = async (req, res) => {
const { email, password } = req.body;
console.log(email, password);
try {
// Überprüfen, ob der Benutzer existiert
const user = await pool.query("SELECT * FROM Users WHERE email = $1", [
@ -84,16 +85,12 @@ const updateUser = async (req, res) => {
"UPDATE users SET username = $1, password = $2, email = $3, role = $4 WHERE id = $5 RETURNING *",
[username, password, email, role, id]
);
res
.status(200)
.json({
res.status(200).json({
message: "Benutzerdaten aktualisiert",
user: updateUser.rows[0],
});
} catch (err) {
res
.status(500)
.json({
res.status(500).json({
message: "Fehler beim Aktualisieren der Benutzerdaten",
error: err.message,
});

View File

@ -11,6 +11,7 @@
"description": "",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.0",
"jsonwebtoken": "^9.0.2",