fix logging in

This commit is contained in:
SadlyNotSappho 2024-02-02 12:05:39 -08:00
parent e46360eaa7
commit a97ee0586f
4 changed files with 77 additions and 18 deletions

11
Cargo.lock generated
View File

@ -517,6 +517,8 @@ dependencies = [
name = "fossil" name = "fossil"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"rand",
"rand_hc",
"rocket", "rocket",
"rocket_db_pools", "rocket_db_pools",
"sha256", "sha256",
@ -1341,6 +1343,15 @@ dependencies = [
"getrandom", "getrandom",
] ]
[[package]]
name = "rand_hc"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b363d4f6370f88d62bf586c80405657bde0f0e1b8945d47d2ad59b906cb4f54"
dependencies = [
"rand_core",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.4.1" version = "0.4.1"

View File

@ -6,6 +6,8 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
rand = "0.8.5"
rand_hc = "0.3.2"
rocket = {version="0.5.0",features=["secrets","json"]} rocket = {version="0.5.0",features=["secrets","json"]}
rocket_db_pools = {version="0.1.0",features=["sqlx_postgres"]} rocket_db_pools = {version="0.1.0",features=["sqlx_postgres"]}
sha256 = "1.5.0" sha256 = "1.5.0"

View File

@ -74,38 +74,66 @@ async fn getuser(db: Connection<Db>, username: String) -> String {
let user = User::get_by_username(db, &username).await; let user = User::get_by_username(db, &username).await;
match user { match user {
Some(user) => format!( Some(user) => format!(
"{}\n{}\n{}\n{}", "id: {}\nusername: {}\nhashed password: {}\ntoken: {}",
user.id, user.id,
user.username, user.username,
user.password, user.password,
user.token.is_some() match user.token {
Some(t) => t,
None => "no token".to_string()
}
), ),
None => format!("User {} doesn't exist.", &username), None => format!("User {} doesn't exist.", &username),
} }
} }
#[post("/login", data = "<info>")] #[get("/account")]
async fn login(db: Connection<Db>, info: Json<LoginInfo>, cookies: &CookieJar<'_>) -> &'static str { async fn account(db: Connection<Db>, cookies: &CookieJar<'_>) -> String {
let token = cookies.get_private("token"); let token = cookies.get_private("token");
match token { match token {
Some(t) => { Some(t) => {
if t.value_trimmed() == "skyetoken" { let user = User::get_by_token(db, t.to_string().split("=").collect::<Vec<&str>>()[1].to_string() /*GOD I LOVE RUST*/).await;
"logged in with token" format!("Username: {}", user.username)
},
None => {
format!("Not logged in")
}
}
}
#[post("/login", data = "<info>")]
async fn login(db: Connection<Db>, db2: Connection<Db>, info: Json<LoginInfo>, cookies: &CookieJar<'_>) -> String {
let token = cookies.get_private("token");
match token {
Some(t) => {
if User::get_by_token(db, t.to_string()).await.exists() /*god i fucking love rust, this function literally just returns true*/ {
"logged in with token".to_string()
} else { } else {
"unknown token" "unknown token".to_string()
} }
} }
None => { None => {
// just to be clear this is Not A Good Implementation of this match User::get_by_username(db, &info.username).await {
// the same token for everyone is a Bad Fucking Idea Some(user) => {
// but i'm just doing this to make sure that it. like. works. if user.password == sha256::digest(&info.password) {
// and it does!!! match user.token {
let user = User::get_by_username(db, &info.username).await; Some(t) => {cookies.add_private(("token", t)); "Logged in".to_string()},
if user.is_some() && user.expect("actually how").password == sha256::digest(&info.password) { None => {
cookies.add_private(("token", "skyetoken")); match user.set_new_token(db2).await {
"logged in!" Ok(t) => {
cookies.add_private(("token", t));
"logged in".to_string()
},
Err(why) => why,
}
}
}
} else { } else {
"invalid login info :(" String::from("Invalid username or password (to those whining about why it doesn't tell you if the username or password is incorrect, security)")
}
}
None =>
String::from("Invalid username or password (to those whining about why it doesn't tell you if the username or password is incorrect, security)"),
} }
} }
} }
@ -186,7 +214,7 @@ async fn main() {
.attach(AdHoc::on_ignite("DB Migrations", migrate)) .attach(AdHoc::on_ignite("DB Migrations", migrate))
.mount( .mount(
"/", "/",
routes![hello, get_book, delay, login, logout, dbtest, dbcreate, createuser, getuser], routes![hello, get_book, delay, login, logout, dbtest, dbcreate, createuser, getuser, account],
) )
.register("/", catchers![default_catcher]) .register("/", catchers![default_catcher])
.mount("/login", FileServer::from("/srv/web")) .mount("/login", FileServer::from("/srv/web"))

View File

@ -1,3 +1,4 @@
use rand::{SeedableRng, RngCore};
use rocket_db_pools::sqlx::Executor; use rocket_db_pools::sqlx::Executor;
use rocket_db_pools::Connection; use rocket_db_pools::Connection;
use sqlx::FromRow; use sqlx::FromRow;
@ -97,6 +98,7 @@ impl User {
let res = db let res = db
.fetch_one(sqlx::query("SELECT * FROM users WHERE token = $1;").bind(token)) .fetch_one(sqlx::query("SELECT * FROM users WHERE token = $1;").bind(token))
.await .await
// TODO: this errors sometimes i dont know why
.unwrap(); .unwrap();
User { User {
id: res.get::<i32, _>("id"), id: res.get::<i32, _>("id"),
@ -120,4 +122,20 @@ impl User {
Err(_) => None, Err(_) => None,
} }
} }
pub async fn set_new_token(&self, mut db: Connection<Db>) -> Result<String, String> {
let token_end = rand_hc::Hc128Rng::from_entropy().next_u64();
let token_start = sha256::digest(&self.username);
let token = sha256::digest(format!("{token_start}-{token_end}"));
match db.fetch_one(sqlx::query("UPDATE users SET token = $1 WHERE id = $2").bind(&token).bind(self.id)).await {
Ok(_) => Ok(token),
Err(why) => Err(why.to_string())
}
}
// god i fucking love rust
pub fn exists(&self) -> bool {
true
}
} }