Login and working api with simple chat
This commit is contained in:
+56
-13
@@ -12,7 +12,10 @@ export async function POST(req: NextRequest) {
|
||||
);
|
||||
|
||||
if (user_.rows.length > 0) {
|
||||
return NextResponse.json({ message: "Username already used" }, { status: StatusCodes.CONFLICT });
|
||||
return NextResponse.json(
|
||||
{ message: "Username already used" },
|
||||
{ status: StatusCodes.CONFLICT }
|
||||
);
|
||||
}
|
||||
|
||||
const user_email = await pool.query(
|
||||
@@ -21,16 +24,53 @@ export async function POST(req: NextRequest) {
|
||||
);
|
||||
|
||||
if (user_email.rows.length > 0) {
|
||||
return NextResponse.json({ message: "Email already used" }, { status: StatusCodes.CONFLICT });
|
||||
return NextResponse.json(
|
||||
{ message: "Email already used" },
|
||||
{ status: StatusCodes.CONFLICT }
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: Hash the password
|
||||
const result = await pool.query("INSERT INTO users (username, email, password_hash) VALUES ($1, $2, $3) RETURNING id;", [username, email, password]);
|
||||
const result = await pool.query(
|
||||
"INSERT INTO users (username, email, password_hash) VALUES ($1, $2, $3) RETURNING id;",
|
||||
[username, email, password]
|
||||
);
|
||||
const token = crypto.randomUUID();
|
||||
|
||||
CLIENT_AUTH_TOKENS[token] = parseInt(result.rows[0].id);
|
||||
|
||||
return NextResponse.json({ message: "ok", token, user_id: result.rows[0].id });
|
||||
return NextResponse.json({
|
||||
message: "ok",
|
||||
token,
|
||||
user_id: result.rows[0].id,
|
||||
});
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
const { username, password } = await req.json();
|
||||
|
||||
if (!username || !password)
|
||||
return NextResponse.json(
|
||||
{ message: "Body must have username and password" },
|
||||
{ status: StatusCodes.BAD_REQUEST }
|
||||
);
|
||||
|
||||
const user = await pool.query(
|
||||
"SELECT id, username, email FROM users WHERE password_hash = $2 AND username = $1 OR email = $1;",
|
||||
[username, password]
|
||||
);
|
||||
|
||||
if (user.rowCount === 0)
|
||||
return NextResponse.json(
|
||||
{ message: "Invalid credentials" },
|
||||
{ status: StatusCodes.UNAUTHORIZED }
|
||||
);
|
||||
|
||||
const token = crypto.randomUUID();
|
||||
|
||||
CLIENT_AUTH_TOKENS[token] = parseInt(user.rows[0].id);
|
||||
|
||||
return NextResponse.json({ message: "ok", token });
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
@@ -39,12 +79,18 @@ export async function GET(req: NextRequest) {
|
||||
const token = url.searchParams.get("token");
|
||||
|
||||
if (!query_id && !token)
|
||||
return NextResponse.json({ message: "Query arg should be token or id" }, { status: StatusCodes.BAD_REQUEST });
|
||||
return NextResponse.json(
|
||||
{ message: "Query arg should be token or id" },
|
||||
{ status: StatusCodes.BAD_REQUEST }
|
||||
);
|
||||
else {
|
||||
const id = query_id ? query_id : token ? CLIENT_AUTH_TOKENS[token] : null;
|
||||
|
||||
if (!id)
|
||||
return NextResponse.json({ message: "Invalid token" }, { status: StatusCodes.NOT_FOUND });
|
||||
return NextResponse.json(
|
||||
{ message: "Invalid token" },
|
||||
{ status: StatusCodes.NOT_FOUND }
|
||||
);
|
||||
|
||||
const user = await pool.query(
|
||||
"SELECT id, username, email FROM users WHERE id = $1;",
|
||||
@@ -57,13 +103,10 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
let { username } = await req.json();
|
||||
|
||||
await pool.query(
|
||||
"DELETE FROM users WHERE username = $1;",
|
||||
[username]
|
||||
);
|
||||
|
||||
|
||||
await pool.query("DELETE FROM users WHERE username = $1;", [username]);
|
||||
|
||||
return NextResponse.json({ message: "ok" });
|
||||
}
|
||||
|
||||
initDb();
|
||||
initDb();
|
||||
|
||||
+36
-3
@@ -1,7 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import axios from "axios";
|
||||
import { useState } from "react";
|
||||
import Cookies from "js-cookie";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function Login() {
|
||||
return <div>
|
||||
<Input />
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
|
||||
return (
|
||||
<div className="h-screen flex items-center">
|
||||
<div className="w-md mx-auto p-7 rounded-2xl flex flex-col gap-4 bg-neutral-900">
|
||||
<h1 className="mx-auto text-3xl">Login</h1>
|
||||
<span>
|
||||
Username
|
||||
<Input onChange={(e) => setUsername(e.target.value)} />
|
||||
</span>
|
||||
<span>
|
||||
Password
|
||||
<Input onChange={(e) => setPassword(e.target.value)} />
|
||||
</span>
|
||||
|
||||
<Button
|
||||
className="mt-4"
|
||||
onClick={async () => {
|
||||
const res = await axios.put("/api/user", { username, password });
|
||||
Cookies.set("token", (res.data as any).token);
|
||||
redirect("/");
|
||||
}}
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,60 +5,68 @@ import { useParams } from "next/navigation";
|
||||
import MessageBox from "@/components/MessageBox";
|
||||
import AppSidebar from "@/components/Sidebar";
|
||||
import Message from "@/types/message";
|
||||
import getUser from "@/hooks/get-user";
|
||||
import useUser, { User } from "@/hooks/get-user";
|
||||
import Cookies from "js-cookie";
|
||||
import axios from "axios";
|
||||
import { StringMap } from "@/types/typeUtils";
|
||||
|
||||
export default function Server() {
|
||||
const { id: ip } = useParams<{ id: string }>();
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const user = getUser();
|
||||
const { user, loading } = useUser();
|
||||
const [userList, setUserList] = useState<StringMap<User>>({});
|
||||
|
||||
useEffect(() => {
|
||||
if (!ip || !user) return;
|
||||
if (!ip || !user || loading) return;
|
||||
|
||||
async function auth() {
|
||||
const server_auth = ((await axios.post('http://localhost:3000/api/auth', {
|
||||
server_ip: ip === 'localhost' ? '127.0.0.1' : ip,
|
||||
session_token: Cookies.get('token'),
|
||||
})).data as any).token;
|
||||
const server_auth = (
|
||||
(
|
||||
await axios.post("http://localhost:3000/api/auth", {
|
||||
server_ip: ip === "localhost" ? "127.0.0.1" : ip,
|
||||
session_token: Cookies.get("token"),
|
||||
})
|
||||
).data as any
|
||||
).token;
|
||||
|
||||
// Open the WebSocket connection
|
||||
const ws = new WebSocket(`ws://${ip}:7080`);
|
||||
wsRef.current = ws;
|
||||
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log("Connected to WebSocket:", ip);
|
||||
ws.send(JSON.stringify({
|
||||
version: '0.0.1',
|
||||
auth_token: server_auth,
|
||||
last_message: 0
|
||||
}))
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
version: "0.0.1",
|
||||
auth_token: server_auth,
|
||||
last_message: 0,
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
ws.onmessage = (m) => {
|
||||
const data = JSON.parse(m.data);
|
||||
console.log("Message received:", data);
|
||||
|
||||
switch (data.type) {
|
||||
case 'authenticated':
|
||||
case "authenticated":
|
||||
setMessages(data.params.messages);
|
||||
|
||||
case 'message_create':
|
||||
|
||||
case "message_create":
|
||||
// setMessages([...messages, data.params]);
|
||||
setMessages((prev) => [...prev, data.params]);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
ws.onerror = (err) => {
|
||||
console.error("WebSocket error:", err);
|
||||
};
|
||||
|
||||
|
||||
ws.onclose = () => {
|
||||
console.log("WebSocket closed:", ip);
|
||||
};
|
||||
|
||||
|
||||
// Cleanup on unmount or id change
|
||||
return () => {
|
||||
ws.close();
|
||||
@@ -66,7 +74,11 @@ export default function Server() {
|
||||
}
|
||||
|
||||
auth();
|
||||
}, [ip]);
|
||||
setUserList((prev) => {
|
||||
prev[user.id] = user;
|
||||
return prev;
|
||||
});
|
||||
}, [ip, user, loading]);
|
||||
|
||||
return (
|
||||
<AppSidebar
|
||||
@@ -82,17 +94,20 @@ export default function Server() {
|
||||
}}
|
||||
>
|
||||
<MessageBox
|
||||
messages={messages.filter(m => m.channel_id === 'general').toReversed()}
|
||||
userList={userList}
|
||||
messages={messages
|
||||
.filter((m) => m.channel_id === "general")
|
||||
.toReversed()}
|
||||
sendMessage={(message) => {
|
||||
wsRef.current?.send(JSON.stringify(
|
||||
{
|
||||
type: 'send_message',
|
||||
wsRef.current?.send(
|
||||
JSON.stringify({
|
||||
type: "send_message",
|
||||
params: {
|
||||
channel_id: 'general',
|
||||
contents: message
|
||||
}
|
||||
}
|
||||
));
|
||||
channel_id: "general",
|
||||
contents: message,
|
||||
},
|
||||
})
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</AppSidebar>
|
||||
|
||||
Reference in New Issue
Block a user