Signup api, signup and login frontend

This commit is contained in:
whoswhip
2024-08-23 12:26:41 -04:00
parent 017abcfacc
commit 79276573bc
7 changed files with 588 additions and 2 deletions
+168 -2
View File
@@ -65,6 +65,41 @@ class Program
app.MapGet("/", async (HttpContext context) =>
{
var html = File.ReadAllText("assets\\index.html");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn)
{
html = html.Replace("{html}", "<a href=\"/dash\">Dashboard</a>");
}
else
{
html = html.Replace("{html}", "<a href=\"/login\">Login</a> <a href=\"/sign-up\">Sign up</a> ");
}
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
return;
});
app.MapGet("/login", async (HttpContext context) =>
{
if (await IsLoggedInAsync(context.Request.Cookies["token"]))
{
context.Response.Redirect("/");
return;
}
var html = File.ReadAllText("assets\\login.html");
html = html.Replace("{html}", "<a href=\"/sign-up\">Sign up</a>");
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
return;
});
app.MapGet("/sign-up", async (HttpContext context) =>
{
if (await IsLoggedInAsync(context.Request.Cookies["token"]))
{
context.Response.Redirect("/");
return;
}
var html = File.ReadAllText("assets\\signup.html");
html = html.Replace("{html}", "<a href=\"/login\">Login</a>");
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
return;
@@ -75,6 +110,15 @@ class Program
var error_html = File.ReadAllText("assets\\error.html");
error_html = error_html.Replace("{code}", "404");
error_html = error_html.Replace("{message}", "Paste not found");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn)
{
error_html = error_html.Replace("{html}", "<a href=\"/dash\">Dashboard</a>");
}
else
{
error_html = error_html.Replace("{html}", "<a href=\"/login\">Login</a> <a href=\"/sign-up\">Sign up</a>");
}
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(error_html);
return;
@@ -129,6 +173,15 @@ class Program
html = html.Replace("{pastetitle}", paste.Title);
html = html.Replace("{content}", content);
html = html.Replace("{pasteid}", paste.Id);
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn)
{
html = html.Replace("{html}", "<a href=\"/dash\">Dashboard</a>");
}
else
{
html = html.Replace("{html}", "<a href=\"/login\">Login</a> <a href=\"/sign-up\">Sign up</a>");
}
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(html);
return;
@@ -150,6 +203,15 @@ class Program
app.MapGet("/pastes", async (HttpContext context) =>
{
var html = File.ReadAllText("assets\\recent_pastes.html");
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn)
{
html = html.Replace("{html}", "<a href=\"/dash\">Dashboard</a>");
}
else
{
html = html.Replace("{html}", "<a href=\"/login\">Login</a> <a href=\"/sign-up\">Sign up</a>");
}
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
@@ -200,6 +262,16 @@ class Program
var html = File.ReadAllText("assets\\archives.html");
var page = context.Request?.Query["page"].ToString();
bool loggedIn = await IsLoggedInAsync(context.Request.Cookies["token"]);
if (loggedIn)
{
html = html.Replace("{html}", "<a href=\"/dash\">Dashboard</a>");
}
else
{
html = html.Replace("{html}", "<a href=\"/login\">Login</a> <a href=\"/sign-up\">Sign up</a>");
}
int pageNumber;
if (!int.TryParse(page, out pageNumber) || pageNumber <= 0)
{
@@ -346,7 +418,6 @@ class Program
app.MapPost("/api/accounts/create", async (HttpContext context) =>
{
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
string ip = context.Request.Headers["X-Forwarded-For"].ToString() ?? context.Connection.RemoteIpAddress.ToString();
Log log = await Logging.LogRequestAsync(context);
char[] disallowed = { ' ', '\'', '\"', '\\', '/', '(', ')', '[', ']', '{', '}', '<', '>', ';', ':', ',', '.', '!', '?', '@', '#', '$', '%', '^', '&', '*', '-', '+', '=', '~', '`' };
@@ -428,7 +499,7 @@ class Program
loginCommand.CommandText = "INSERT INTO logins (UUID,UserAgent, IP, LoginTime,ExpireTime, Token) VALUES (@UUID,@UserAgent, @IP, @LoginTime,@ExpireTime, @Token)";
loginCommand.Parameters.AddWithValue("@UserAgent", context.Request.Headers["User-Agent"].ToString());
loginCommand.Parameters.AddWithValue("@UUID", insertCommand.Parameters["@UUID"].Value);
loginCommand.Parameters.AddWithValue("@IP", ip);
loginCommand.Parameters.AddWithValue("@IP", log.IP);
loginCommand.Parameters.AddWithValue("@LoginTime", DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"));
loginCommand.Parameters.AddWithValue("@ExpireTime", expirationDate.ToString("dd/MM/yyyy-HH:mm:ss"));
loginCommand.Parameters.AddWithValue("@Token", token);
@@ -451,6 +522,101 @@ class Program
}).RequireRateLimiting("fixed");
app.MapPost("/api/accounts/login", async (HttpContext Context) =>
{
string requestBody = await new StreamReader(Context.Request.Body).ReadToEndAsync();
Log log = await Logging.LogRequestAsync(Context);
if (IsLoggedInAsync(Context.Request.Cookies["token"]).Result)
{
Context.Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
await Context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Already logged in" }.ToString());
return;
}
if (string.IsNullOrEmpty(requestBody))
{
Context.Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
await Context.Response.WriteAsJsonAsync(new JObject { ["error"] = "No data uploaded" }.ToString());
return;
}
if (!requestBody.Contains("username") || !requestBody.Contains("password") || Context.Request.ContentType != "application/json")
{
Context.Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
await Context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid request body" }.ToString());
return;
}
var data = JObject.Parse(requestBody);
var username = SanitizeInput(data["username"]?.ToString() ?? "");
var password = SanitizeInput(data["password"]?.ToString() ?? "");
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
Context.Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
await Context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid username or password" }.ToString());
return;
}
string passwordHash = BCrypt.Net.BCrypt.HashPassword(password, salt);
using (var connection = new SqliteConnection("Data Source=pastes.sqlite"))
{
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users WHERE Username = @Username";
command.Parameters.AddWithValue("@Username", username);
var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
if (!reader.HasRows)
{
Context.Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
await Context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid username or password" }.ToString());
return;
}
if (BCrypt.Net.BCrypt.Verify(password, reader.GetString(3)))
{
string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString())));
DateTime expirationDate = DateTime.Now.AddYears(1);
var loginCommand = connection.CreateCommand();
loginCommand.CommandText = "INSERT INTO logins (UUID,UserAgent, IP, LoginTime,ExpireTime, Token) VALUES (@UUID,@UserAgent, @IP, @LoginTime,@ExpireTime, @Token)";
loginCommand.Parameters.AddWithValue("@UserAgent", log.UserAgent);
loginCommand.Parameters.AddWithValue("@UUID", reader.GetString(1));
loginCommand.Parameters.AddWithValue("@IP", log.IP);
loginCommand.Parameters.AddWithValue("@LoginTime", DateTime.Now.ToString("dd/MM/yyyy-HH:mm:ss"));
loginCommand.Parameters.AddWithValue("@ExpireTime", expirationDate.ToString("dd/MM/yyyy-HH:mm:ss"));
loginCommand.Parameters.AddWithValue("@Token", token);
await loginCommand.ExecuteNonQueryAsync();
var cookie = new CookieOptions
{
Expires = expirationDate,
Secure = true,
HttpOnly = true,
SameSite = SameSiteMode.Strict
};
Context.Response.Cookies.Append("token", token, cookie);
Context.Response.StatusCode = 200;
Context.Response.ContentType = "application/json";
Console.WriteLine($"[{DateTime.Now}] Account {username} has logged in");
File.AppendAllText("logs.log", $"[{DateTime.Now}] Account {username} has logged in from {log.IP}\n");
await Context.Response.WriteAsJsonAsync(new JObject { ["message"] = "Logged in" }.ToString());
return;
}
else
{
Context.Response.StatusCode = 400;
Context.Response.ContentType = "application/json";
await Context.Response.WriteAsJsonAsync(new JObject { ["error"] = "Invalid username or password" }.ToString());
}
}
});
#endregion
+1
View File
@@ -11,6 +11,7 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="error-container">
+1
View File
@@ -11,6 +11,7 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="creation-container">
+195
View File
@@ -0,0 +1,195 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap" rel="stylesheet">
<title>create paste</title>
</head>
<body>
<div class="nav-div">
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="creation-container">
<h1>login</h1>
<form id="loginForm">
<label for="usernameTitle" class="label">Username</label>
<input type="text" id="usernameInput" class="textinput" name="pasteTitle" required maxlength="20">
<label for="passwordTitle" class="label">Password</label>
<input type="password" id="passwordInput" class="textinput" name="pasteTitle" required maxlength="50">
<button type="submit" class="button">Login</button>
</form>
</div>
</div>
</body>
<script>
document.getElementById("loginForm").addEventListener("submit", function (event) {
event.preventDefault();
var usernameContent = document.getElementById("usernameInput").value;
var passwordContent = document.getElementById("passwordInput").value;
var requestUrl = "/api/accounts/login";
fetch(requestUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: usernameContent,
password: passwordContent
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
window.location.href = "/";
}
})
});
</script>
<style>
body{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #0d0d0d;
}
.container-wrapper{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
}
.creation-container{
display: flex;
flex-direction: column;
align-items: center;
width: 80%;
padding: 20px;
background-color: #181818;
color: white;
border-radius: 5px;
height: fit-content;
max-height: 80vh;
min-height: 20%;
overflow-y: auto;
border: #222222 2px solid;
}
#loginForm{
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.label{
font-size: 1.5em;
}
.textinput{
transition: 300ms;
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #282828;
color: white;
border: #2a2a2a 2px solid;
box-sizing: border-box;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-size: 1.1em;
outline: none;
}
.textinput:focus{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
outline: none;
}
.textarea{
transition: 300ms;
width: 100%;
min-width: 100%;
max-width: 100%;
min-height: auto;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #282828;
color: white;
border: #2a2a2a 2px solid;
box-sizing: border-box;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-size: 1.08em;
outline: none;
}
.textarea:focus{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
outline: none;
}
.button{
transition: 300ms;
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #222222;
color: white;
border: #2a2a2a00 2px solid;
cursor: pointer;
font-size: 1.2em;
}
.button:hover{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
}
.nav-div{
top: 0;
margin-top: 10px;
position: absolute;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: fit-content;
background-color: #181818;
padding-left: 10px;
padding-right: 10px;
color: white;
border-radius: 5px;
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
}
.nav-div a{
text-decoration: none;
color: white;
padding: 10px;
margin: 10px;
border-radius: 5px;
background-color: #222222;
transition: 300ms;
border: #2a2a2a00 2px solid;
}
.nav-div a:hover{
transition: 300ms;
background-color: #333333;
border: #3a3a3a 2px solid;
}
</style>
</html>
+1
View File
@@ -11,6 +11,7 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="paste-container">
+1
View File
@@ -11,6 +11,7 @@
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="pastes-container">
+221
View File
@@ -0,0 +1,221 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Mono:wght@100..900&display=swap" rel="stylesheet">
<title>create paste</title>
</head>
<body>
<div class="nav-div">
<a href="/">home</a>
<a href="/pastes">recent pastes</a>
<a href="/archive">archive</a>
{html}
</div>
<div class="container-wrapper">
<div class="creation-container">
<h1>sign-up</h1>
<form id="signupForm">
<label for="usernameTitle" class="label" onforminput="">Username</label>
<input type="text" id="usernameInput" class="textinput" name="pasteTitle" required maxlength="20">
<label id="characterCount" for="characterCount" class="ccounter">0/20</label>
<label for="passwordTitle" class="label" id="margin-top">Password</label>
<input type="password" id="passwordInput" class="textinput" name="pasteTitle" required maxlength="50">
<label id="passcharacterCount" for="characterCount" class="ccounter">0/20</label>
<button type="submit" class="button" id="button-margin-top">Sign-up</button>
</form>
</div>
</div>
</body>
<script>
document.getElementById("signupForm").addEventListener("submit", function (event) {
event.preventDefault();
var usernameContent = document.getElementById("usernameInput").value;
var passwordContent = document.getElementById("passwordInput").value;
var requestUrl = "/api/accounts/create";
fetch(requestUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: usernameContent,
password: passwordContent
})
})
.then(response => response.json())
.then(obj => {
const result = JSON.parse(obj);
if (result.message != null) {
window.location.href = "/";
}
})
});
document.getElementById("usernameInput").addEventListener("input", function (event) {
var usernameContent = document.getElementById("usernameInput").value;
var characterCount = usernameContent.length;
document.getElementById("characterCount").innerText = `${characterCount}/20`;
});
document.getElementById("passwordInput").addEventListener("input", function (event) {
var passwordContent = document.getElementById("passwordInput").value;
var characterCount = passwordContent.length;
document.getElementById("passcharacterCount").innerText = `${characterCount}/50`;
});
</script>
<style>
body{
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-weight: bold;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #0d0d0d;
}
.container-wrapper{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
}
.creation-container{
display: flex;
flex-direction: column;
align-items: center;
width: 80%;
padding: 20px;
background-color: #181818;
color: white;
border-radius: 5px;
height: fit-content;
max-height: 80vh;
min-height: 20%;
overflow-y: auto;
border: #222222 2px solid;
}
#signupForm{
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.label{
font-size: 1.5em;
}
.textinput{
transition: 300ms;
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #282828;
color: white;
border: #2a2a2a 2px solid;
box-sizing: border-box;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-size: 1.1em;
outline: none;
}
.textinput:focus{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
outline: none;
}
.textarea{
transition: 300ms;
width: 100%;
min-width: 100%;
max-width: 100%;
min-height: auto;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #282828;
color: white;
border: #2a2a2a 2px solid;
box-sizing: border-box;
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
font-size: 1.08em;
outline: none;
}
.textarea:focus{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
outline: none;
}
.button{
transition: 300ms;
width: 100%;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
border: none;
background-color: #222222;
color: white;
border: #2a2a2a00 2px solid;
cursor: pointer;
font-size: 1.2em;
}
.button:hover{
transition: 300ms;
background-color: #333333;
border: 2px solid #3a3a3a;
}
.nav-div{
top: 0;
margin-top: 10px;
position: absolute;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: fit-content;
background-color: #181818;
padding-left: 10px;
padding-right: 10px;
color: white;
border-radius: 5px;
height: fit-content;
overflow-y: auto;
border: #222222 2px solid;
}
.nav-div a{
text-decoration: none;
color: white;
padding: 10px;
margin: 10px;
border-radius: 5px;
background-color: #222222;
transition: 300ms;
border: #2a2a2a00 2px solid;
}
.nav-div a:hover{
transition: 300ms;
background-color: #333333;
border: #3a3a3a 2px solid;
}
.ccounter{
align-self: flex-end;
text-align: right;
margin-top: -2.2rem;
margin-right: 10px;
font-size: 1.1em;
color: #888888;
}
#margin-top{
margin-top: 10px;
}
#button-margin-top{
margin-top: 30px;
}
</style>
</html>