Compare commits

...

6 commits

9 changed files with 17921 additions and 17868 deletions

35443
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{ {
"name": "epq-web-project", "name": "epq-web-project",
"version": "0.2.1", "version": "0.3.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@stomp/stompjs": "^7.0.0", "@stomp/stompjs": "^7.0.0",
@ -11,6 +11,7 @@
"@types/node": "^16.18.68", "@types/node": "^16.18.68",
"@types/react": "^18.2.45", "@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18", "@types/react-dom": "^18.2.18",
"ed25519": "^0.0.5",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
@ -41,5 +42,8 @@
"last 1 firefox version", "last 1 firefox version",
"last 1 safari version" "last 1 safari version"
] ]
},
"devDependencies": {
"@types/ed25519": "^0.0.3"
} }
} }

View file

@ -52,7 +52,7 @@ const Wrapper = (): React.ReactElement => {
}; };
const setNameOnServer = async (name: string) => { const setNameOnServer = async (name: string) => {
const responseRaw = await fetch( const responseRaw = await fetch(
`http://${domain}:${port}${endpoints.user}`, `https://${domain}:${port}${endpoints.user}`,
{ {
method: "POST", method: "POST",
mode: "cors", mode: "cors",

View file

@ -1,171 +1,158 @@
import { useContext, useState } from "react"; import { useContext, useState } from "react";
import { contentTypes, domain, endpoints, port } from "../consts"; import { contentTypes, domain, endpoints, port } from "../consts";
import { LangContext, LoginType } from "../context"; import { LangContext, LoginType } from "../context";
import { User } from "../type/userTypes"; import { AuthData, User } from "../type/userTypes";
import "./Login.css"; import "./Login.css";
import strings from "../Intl/strings.json"; import strings from "../Intl/strings.json";
import { ECDH } from "crypto";
import { digestMessage } from "../crypto";
const encrypt = (rawPasswordString: string) => { const encrypt = (rawPasswordString: string) => {
// TODO Encryption method stub // TODO Encryption method stub
return rawPasswordString; return rawPasswordString;
}; };
export const Login = ({ export const Login = ({
setLogin, setLogin,
}: { }: {
setLogin: (newLogin: LoginType | undefined) => void; setLogin: (newLogin: LoginType | undefined) => void;
}): React.ReactElement => { }): React.ReactElement => {
const [valid, setValid] = useState<boolean | undefined>(undefined); const [valid, setValid] = useState<boolean | undefined>(undefined);
const [validText, setValidText] = useState<string | undefined>(); const [validText, setValidText] = useState<string | undefined>();
const lang = useContext(LangContext); const lang = useContext(LangContext);
const loginPage = strings[lang].login; const loginPage = strings[lang].login;
const registrationHandler = () => { // TODO mk unit test
const uname = ( const registrationHandler = () => {
document.getElementById("username") as HTMLInputElement const uname = (document.getElementById("username") as HTMLInputElement)
).value; .value;
const passwd = encrypt( digestMessage((document.getElementById("passwd") as HTMLInputElement).value).then((passwd) => {
(document.getElementById("passwd") as HTMLInputElement) fetch(`https://${domain}:${port}${endpoints.register}`, {
.value method: "POST",
); mode: "cors",
fetch(`http://${domain}:${port}${endpoints.user}`, { headers: contentTypes.json,
method: "POST", body: JSON.stringify({
mode: "cors", userName: uname,
headers: contentTypes.json, newUserPassword: passwd,
body: JSON.stringify({ }),
userName: uname, })
dateJoined: Date.now(), .then((res) => res.json()).then((body) => {
passwordHash: passwd, const response = body as AuthData;
}), if (response.exists && !response.success) {throw new Error(loginPage.error.unameTakenOrInvalid)}
}).then((response) => { getProfile(uname).then((user) => {
if (response.status === 400) { setValid(true);
// 400 Bad request const futureDate = new Date();
console.log("Username is taken or invalid!"); futureDate.setHours(futureDate.getHours() + 2);
setValid(false); setLogin({
setValidText( username: user.userName,
loginPage.error.unameTakenOrInvalid lastSeen: Date.now(),
); validUntil: futureDate.getUTCMilliseconds(),
} else if (response.status === 200) { });
// 200 OK document.title = `IRC User ${user.userName}`;
const futureDate = new Date(); });
futureDate.setHours(futureDate.getHours() + 2); })
setLogin({ .catch((error: Error) => {
username: uname, setValid(false);
lastSeen: Date.now(), setValidText(error.message);
validUntil: futureDate.getUTCMilliseconds(), })
}); });
document.title = `IRC User ${uname}`; };
}
}); // TODO Make unit test
}; const getProfile = async(userName: string): Promise<User> => {
// login button press handler const res = await (await fetch(`https://${domain}:${port}${endpoints.user}?name=${userName}`,
const loginHandler = () => { {
const uname = ( method: "GET",
document.getElementById("username") as HTMLInputElement mode: "cors"
).value; }
const passwd = encrypt( )).json()
(document.getElementById("passwd") as HTMLInputElement) return res;
.value }
); // login button press handler
// async invocation of Fetch API // TODO make unit test
fetch( const loginHandler = () => {
`http://${domain}:${port}${endpoints.user}?name=${uname}`, const uname = (document.getElementById("username") as HTMLInputElement)
{ .value;
method: "GET", digestMessage(
mode: "cors", (document.getElementById("passwd") as HTMLInputElement).value
} ).then((passwd) => {
) // async invocation of Fetch API
.then((res) => { fetch(`https://${domain}:${port}${endpoints.auth}`, {
if (res.status === 404) { method: "POST",
console.log( mode: "cors",
"404 not found encountered" headers: {"Content-Type": "application/json"},
); body: JSON.stringify({
throw new Error( userName: uname,
loginPage.error.unameNotExists userPasswordHash: passwd,
); })
} else if (res.status === 200) { })
console.log("200 OK"); .then(res => res.json())
} .then((body) => {
return res.json(); const response = body as AuthData;
}) if (!response.exists) {throw new Error(loginPage.error.unameNotExists)}
.then((userObject) => { else if (!response.success) {throw new Error(loginPage.error.passwdInvalid)}
if (!userObject) { else {
return; getProfile(uname).then((user) => {
} // login valid
const user = userObject as User; setValid(true);
const validLogin = passwd === user.passwordHash; const validUntilDate: Date = new Date();
if (!validLogin) { validUntilDate.setHours(validUntilDate.getHours() + 2);
// login invalid setLogin({
throw new Error( username: user.userName,
loginPage.error.passwdInvalid lastSeen: user.lastSeen,
); validUntil: validUntilDate.getUTCMilliseconds(),
} else { });
// login valid document.title = `IRC User ${uname}`;
setValid(true); });
const validUntilDate: Date = new Date(); }
validUntilDate.setHours( })
validUntilDate.getHours() + 2 .catch((reason: Error) => {
); setValid(false);
setLogin({ setValidText(reason.message);
username: user.userName, });
lastSeen: user.lastSeen, });
validUntil: validUntilDate.getUTCMilliseconds(), };
}); return (
document.title = `IRC User ${uname}`; <div className="login">
} <fieldset>
}) <legend>{loginPage.window.title}</legend>
.catch((reason: Error) => { <p className="uname-error-text">
setValid(false); {!valid && valid !== undefined ? validText : ""}
setValidText(reason.message); </p>
}); <label htmlFor="username">{loginPage.window.uname}</label>
}; <br />
return ( <input id="username" type="text"></input>
<div className="login"> <br />
<fieldset> <label htmlFor="passwd">{loginPage.window.passwd}</label>
<legend>{loginPage.window.title}</legend> <br />
<p className="uname-error-text"> <input id="passwd" type="password"></input>
{!valid && valid !== undefined <br />
? validText <button
: ""} disabled={valid}
</p> type="submit"
<label htmlFor="username"> onClick={() => {
{loginPage.window.uname} loginHandler();
</label> }}
<br /> >
<input id="username" type="text"></input> {loginPage.window.login}
<br /> </button>
<label htmlFor="passwd"> <button
{loginPage.window.passwd} disabled={valid}
</label> type="submit"
<br /> onClick={() => {
<input id="passwd" type="password"></input> registrationHandler();
<br /> }}
<button >
disabled={valid} {loginPage.window.register}
type="submit" </button>
onClick={() => { <button
loginHandler(); disabled={!valid}
}} type="submit"
> onClick={() => {
{loginPage.window.login} setLogin(undefined);
</button> setValid(undefined);
<button }}
disabled={valid} >
type="submit" {loginPage.window.logout}
onClick={() => { </button>
registrationHandler(); </fieldset>
}} </div>
> );
{loginPage.window.register}
</button>
<button
disabled={!valid}
type="submit"
onClick={() => {
setLogin(undefined);
setValid(undefined);
}}
>
{loginPage.window.logout}
</button>
</fieldset>
</div>
);
}; };

View file

@ -1,4 +1,3 @@
import { useState } from "react";
import "./Sidebar.css"; import "./Sidebar.css";
import { SidebarMenu } from "./Components/SidebarMenu"; import { SidebarMenu } from "./Components/SidebarMenu";
export const Sidebar = ({ export const Sidebar = ({

View file

@ -24,9 +24,6 @@ export const Topbar = ({
<h1 className="topbar-span children"> <h1 className="topbar-span children">
{strings[lang].homepage.title} {strings[lang].homepage.title}
</h1> </h1>
{/* <p className="topbar-span children">
{strings[lang].homepage.description}
</p> */}
</span> </span>
</div> </div>
); );

View file

@ -1,11 +1,14 @@
export const domain = window.location.hostname; export const domain = window.location.hostname;
export const port = "8080"; export const port = "8080";
export const connectionAddress = `ws://${domain}:${port}/ws`; export const connectionAddress = `wss://${domain}:${port}/ws`;
export const endpoints = { export const endpoints = {
destination: "/app/chat", destination: "/app/chat",
subscription: "/sub/chat", subscription: "/sub/chat",
history: "/api/v1/msg/", history: "/api/v1/msg/",
user: "/api/v1/user", user: "/api/v1/user",
auth: "/api/v1/auth",
register: "/api/v1/register",
oauth2: "",
}; };
export const contentTypes = { export const contentTypes = {
json: { json: {

15
src/crypto.ts Normal file
View file

@ -0,0 +1,15 @@
export const ENCRYPTION_TYPE = "SHA-256";
// Implemented according to https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
export const digestMessage = async (plaintext: string) => {
const textEncoder = new TextEncoder();
const digestArray = Array.from(
new Uint8Array(
await window.crypto.subtle.digest(
ENCRYPTION_TYPE,
textEncoder.encode(plaintext)
)
)
)
return digestArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
}

View file

@ -11,3 +11,10 @@ export type User = {
passwordHash: string; passwordHash: string;
// avatar: UserAvatar; // avatar: UserAvatar;
}; };
export type AuthData = {
success: boolean;
hasProfile: boolean;
exists: boolean;
authMessage: string;
authResponseTimestampMillis: number;
}