generated from lucien/api-template
add: added homepage
This commit is contained in:
parent
1f24907c80
commit
4ea8c9f2b3
11 changed files with 239 additions and 68 deletions
46
back/api/auth.js
Normal file
46
back/api/auth.js
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
const express = require('express');
|
||||||
|
const sha256 = require("sha256");
|
||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
const { getConnection, getUserByUsername, addUser, getUser } = require('../libs/mysql');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.post('/login', async (req, res) => {
|
||||||
|
const { username, password } = req.body;
|
||||||
|
const connection = await getConnection();
|
||||||
|
const users = await getUserByUsername(connection, username);
|
||||||
|
connection.end();
|
||||||
|
if (users[0]) {
|
||||||
|
if (users[0].password === sha256(password)) {
|
||||||
|
const token = jwt.sign({ id: users[0].id }, process.env.JWT_SECRET, {
|
||||||
|
expiresIn: 1000 * 60 * 60 * 24 * 7,
|
||||||
|
});
|
||||||
|
return res.send({ token: token });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.status(401).send({ error: 'Invalid username or password' });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/register', async (req, res) => {
|
||||||
|
const { username, password } = req.body;
|
||||||
|
const connection = await getConnection();
|
||||||
|
const hash = sha256(password);
|
||||||
|
await addUser(connection, username, hash);
|
||||||
|
connection.end();
|
||||||
|
res.send({ message: 'User added' });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/me', async (req, res) => {
|
||||||
|
const { token } = req.body;
|
||||||
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
|
const connection = await getConnection();
|
||||||
|
const users = await getUser(connection, decoded.id);
|
||||||
|
connection.end();
|
||||||
|
if (users[0]) {
|
||||||
|
res.send({ id: users[0].id, username: users[0].username });
|
||||||
|
} else {
|
||||||
|
res.status(401).send({ error: 'Invalid token' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
|
@ -11,10 +11,10 @@ router.get('/', async (req, res) => {
|
||||||
res.send(channels);
|
res.send(channels);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/:id', async (req, res) => {
|
router.get('/:name', async (req, res) => {
|
||||||
const id = req.params.id;
|
const name = req.params.name;
|
||||||
const connection = await getConnection();
|
const connection = await getConnection();
|
||||||
const channel = await getChannel(connection, id);
|
const channel = await getChannel(connection, name);
|
||||||
connection.end();
|
connection.end();
|
||||||
if (channel[0]) {
|
if (channel[0]) {
|
||||||
res.send(channel[0]);
|
res.send(channel[0]);
|
||||||
|
@ -23,22 +23,22 @@ router.get('/:id', async (req, res) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/:id/messages', async (req, res) => {
|
router.get('/:name/messages', async (req, res) => {
|
||||||
const id = req.params.id;
|
const name = req.params.name;
|
||||||
const connection = await getConnection();
|
const connection = await getConnection();
|
||||||
const channel = await getChannel(connection, id);
|
const channel = await getChannel(connection, name);
|
||||||
if (!channel[0]) {
|
if (!channel[0]) {
|
||||||
connection.end();
|
connection.end();
|
||||||
return res.send('No channel found');
|
return res.send('No channel found');
|
||||||
}
|
}
|
||||||
const messages = await getMessages(connection, id);
|
const messages = await getMessages(connection, channel[0].id);
|
||||||
connection.end();
|
connection.end();
|
||||||
res.send(messages);
|
res.send(messages);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/:id/messages/send', async (req, res) => {
|
router.post('/:name/messages/send', async (req, res) => {
|
||||||
const { token, message } = req.body;
|
const { token, message } = req.body;
|
||||||
const id = req.params.id;
|
const name = req.params.name;
|
||||||
const connection = await getConnection();
|
const connection = await getConnection();
|
||||||
|
|
||||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||||
|
@ -48,7 +48,13 @@ router.post('/:id/messages/send', async (req, res) => {
|
||||||
return res.status(401).send({ error: 'Invalid token' });
|
return res.status(401).send({ error: 'Invalid token' });
|
||||||
}
|
}
|
||||||
|
|
||||||
await addMessage(connection, id, user[0].id, message.replace("\"", "'"));
|
const channel = await getChannel(connection, name);
|
||||||
|
if (!channel[0]) {
|
||||||
|
connection.end();
|
||||||
|
return res.send('No channel found');
|
||||||
|
}
|
||||||
|
|
||||||
|
await addMessage(connection, channel[0].id, user[0].id, message.replace("\"", "'"));
|
||||||
connection.end();
|
connection.end();
|
||||||
res.send({ message: 'Message sent' });
|
res.send({ message: 'Message sent' });
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,24 +0,0 @@
|
||||||
const express = require('express');
|
|
||||||
const sha256 = require("sha256");
|
|
||||||
const jwt = require('jsonwebtoken');
|
|
||||||
const { getConnection, getUserByUsername } = require('../libs/mysql');
|
|
||||||
|
|
||||||
const router = express.Router();
|
|
||||||
|
|
||||||
router.post('/', async (req, res) => {
|
|
||||||
const { username, password } = req.body;
|
|
||||||
const connection = await getConnection();
|
|
||||||
const users = await getUserByUsername(connection, username);
|
|
||||||
connection.end();
|
|
||||||
if (users[0]) {
|
|
||||||
if (users[0].password === sha256(password)) {
|
|
||||||
const token = jwt.sign({ id: users[0].id }, process.env.JWT_SECRET, {
|
|
||||||
expiresIn: 1000 * 60 * 60 * 24 * 7,
|
|
||||||
});
|
|
||||||
res.send({ token: token });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
res.status(401).send({ error: 'Invalid username or password' });
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
|
@ -10,19 +10,10 @@ router.get('/:id', async (req, res) => {
|
||||||
const users = await getUser(connection, id);
|
const users = await getUser(connection, id);
|
||||||
connection.end();
|
connection.end();
|
||||||
if (users[0]) {
|
if (users[0]) {
|
||||||
res.send(users[0]);
|
res.send({id: users[0].id, username: users[0].username});
|
||||||
} else {
|
} else {
|
||||||
res.send('No user found');
|
res.send('No user found');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/add', async (req, res) => {
|
|
||||||
const { username, password } = req.body;
|
|
||||||
const connection = await getConnection();
|
|
||||||
const hash = sha256(password);
|
|
||||||
await addUser(connection, username, hash);
|
|
||||||
connection.end();
|
|
||||||
res.send({ message: 'User added' });
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
|
@ -65,10 +65,10 @@ function getChannels(connection) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function getChannel(connection, id) {
|
function getChannel(connection, name) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
connection.query(
|
connection.query(
|
||||||
`SELECT * FROM channels WHERE id = ${id}`,
|
`SELECT * FROM channels WHERE name = "${name}"`,
|
||||||
(error, result) => {
|
(error, result) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
reject(new Error(error));
|
reject(new Error(error));
|
||||||
|
|
|
@ -4,12 +4,16 @@ import './index.css'
|
||||||
|
|
||||||
import Home from './pages/Home'
|
import Home from './pages/Home'
|
||||||
import Channel from './pages/Channel'
|
import Channel from './pages/Channel'
|
||||||
|
import Login from './pages/Login'
|
||||||
|
import Register from './pages/Register'
|
||||||
|
|
||||||
createRoot(document.getElementById('root')!).render(
|
createRoot(document.getElementById('root')!).render(
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Home />} />
|
<Route path="/" element={<Home />} />
|
||||||
<Route path="/channels/:id" element={<Channel />} />
|
<Route path="/channels/:name" element={<Channel />} />
|
||||||
|
<Route path="/login" element={<Login />} />
|
||||||
|
<Route path="/register" element={<Register />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
)
|
)
|
||||||
|
|
|
@ -1,37 +1,22 @@
|
||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { Channel_type, Messages } from "../types";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
|
||||||
type Channel ={
|
|
||||||
id: number,
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Message = {
|
|
||||||
id: number,
|
|
||||||
user_id: number,
|
|
||||||
username: string,
|
|
||||||
content: string,
|
|
||||||
date: number
|
|
||||||
}
|
|
||||||
|
|
||||||
type Messages = Message[]
|
|
||||||
|
|
||||||
export default function Channel() {
|
export default function Channel() {
|
||||||
const { id } = useParams();
|
const { name } = useParams();
|
||||||
const [channel, setChannel] = useState<Channel>();
|
const [channel, setChannel] = useState<Channel_type>();
|
||||||
const [messages, setMessages] = useState<Messages>();
|
const [messages, setMessages] = useState<Messages>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
axios.get(`/api/channels/${id}`).then((res) => {
|
axios.get(`/api/channels/${name}`).then((res) => {
|
||||||
setChannel(res.data);
|
setChannel(res.data);
|
||||||
});
|
});
|
||||||
|
|
||||||
axios.get(`/api/channels/${id}/messages`).then((res) => {
|
axios.get(`/api/channels/${name}/messages`).then((res) => {
|
||||||
setMessages(res.data);
|
setMessages(res.data);
|
||||||
});
|
});
|
||||||
}, [id]);
|
}, [name]);
|
||||||
|
|
||||||
if (!channel || !messages) {
|
if (!channel || !messages) {
|
||||||
return <div>Loading...</div>;
|
return <div>Loading...</div>;
|
||||||
|
|
|
@ -1,7 +1,56 @@
|
||||||
|
import { useState, useEffect } from "react"
|
||||||
|
import { Link } from "react-router-dom"
|
||||||
|
import { Channels, User } from "../types"
|
||||||
|
import axios from "axios"
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
|
const [user, setUser] = useState<User>();
|
||||||
|
const [channels, setChannels] = useState<Channels>();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const token = localStorage.getItem("token")
|
||||||
|
if (token) {
|
||||||
|
axios.post("/api/auth/me", {
|
||||||
|
token: token
|
||||||
|
}).then((res) => {
|
||||||
|
setUser(res.data)
|
||||||
|
}).catch((err) => {
|
||||||
|
console.error(err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
axios.get("/api/channels").then((res) => {
|
||||||
|
setChannels(res.data)
|
||||||
|
}).catch((err) => {
|
||||||
|
console.error(err)
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<h1>Home</h1>
|
<h1>Home</h1>
|
||||||
|
{user ? (
|
||||||
|
<div>
|
||||||
|
<p>Welcome {user.username}</p>
|
||||||
|
<button onClick={() => {
|
||||||
|
localStorage.removeItem("token")
|
||||||
|
window.location.reload()
|
||||||
|
}}>Logout</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<Link to="/login">Login</Link>
|
||||||
|
<Link to="/register">Register</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<h2>Channels</h2>
|
||||||
|
<ul>
|
||||||
|
{channels?.map((channel) => (
|
||||||
|
<li key={channel.id}>
|
||||||
|
<Link to={`/channels/${channel.name}`}>{channel.name}</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
45
front/src/pages/Login.tsx
Normal file
45
front/src/pages/Login.tsx
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
import axios from "axios";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate, Link } from "react-router-dom";
|
||||||
|
|
||||||
|
export default function Login() {
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
axios
|
||||||
|
.post("/api/auth/login", { username, password })
|
||||||
|
.then((res) => {
|
||||||
|
localStorage.setItem("token", res.data.token);
|
||||||
|
navigate("/");
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
alert(err.response.data.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Link to="/">Home</Link>
|
||||||
|
<h1>Login</h1>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Username"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="Password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit">Login</button>
|
||||||
|
</form>
|
||||||
|
<Link to="/register">Register</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
47
front/src/pages/Register.tsx
Normal file
47
front/src/pages/Register.tsx
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
import axios from "axios";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate, Link } from "react-router-dom";
|
||||||
|
|
||||||
|
export default function Register () {
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
axios.post("/api/auth/register", { username, password });
|
||||||
|
axios
|
||||||
|
.post("/api/auth/login", { username, password })
|
||||||
|
.then((res) => {
|
||||||
|
localStorage.setItem("token", res.data.token);
|
||||||
|
navigate("/");
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
alert(err.response.data.message);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Link to="/">Home</Link>
|
||||||
|
<h1>Register</h1>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Username"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="Password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit">Register</button>
|
||||||
|
</form>
|
||||||
|
<Link to="/login">Login</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
22
front/src/types.tsx
Normal file
22
front/src/types.tsx
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
export type Channel_type ={
|
||||||
|
id: number,
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Channels = Channel_type[]
|
||||||
|
|
||||||
|
export type Message = {
|
||||||
|
id: number,
|
||||||
|
user_id: number,
|
||||||
|
username: string,
|
||||||
|
content: string,
|
||||||
|
date: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Messages = Message[]
|
||||||
|
|
||||||
|
export type User = {
|
||||||
|
id: number,
|
||||||
|
username: string
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue