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; --foreground: #171717;
} }
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body { body {
color: var(--foreground); color: var(--foreground);

View File

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

View File

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

View File

@ -15,7 +15,7 @@ type spiel = {
async function spiele() { async function spiele() {
const response = await fetch("http://localhost:2006/spiele"); const response = await fetch("http://localhost:2006/spiele");
const data:response[] = await response.json(); const data:response = await response.json();
return ( return (
<div> <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 ( return (
<div> <div>
<form> <h1>Login</h1>
<label> <form onSubmit={handleLogin}>
Username <input
<input type="text" name="username" /> type="email"
</label> value={email}
<label> onChange={(e) => setEmail(e.target.value)}
Password placeholder="E-Mail"
<input type="password" name="password" /> />
</label> <input
<button type="submit">Login</button> type="password"
</form> value={password}
<script> onChange={(e) => setPassword(e.target.value)}
console.log("Login") placeholder="Passwort"
</script> />
<button type="submit">Login</button>
</form>
</div> </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" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"axios": "^1.7.7",
"js-cookie": "^3.0.5",
"next": "14.2.13",
"react": "^18", "react": "^18",
"react-dom": "^18", "react-dom": "^18"
"next": "14.2.13"
}, },
"devDependencies": { "devDependencies": {
"typescript": "^5", "@types/js-cookie": "^3.0.6",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^18", "@types/react": "^18",
"@types/react-dom": "^18", "@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.2.13",
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.1",
"eslint": "^8", "typescript": "^5"
"eslint-config-next": "14.2.13"
} }
} }

View File

@ -5,6 +5,15 @@ const authRoutes = require("./routes/auth");
const memberRoutes = require("./routes/members"); const memberRoutes = require("./routes/members");
const spieleRoutes = require("./routes/spiele"); const spieleRoutes = require("./routes/spiele");
const bodyParser = require("body-parser"); 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 // Middleware
app.use(express.json()); app.use(express.json());

View File

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

View File

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