megacommit
This commit is contained in:
+105
-3
@@ -1,6 +1,21 @@
|
||||
use rocket::{post, serde::json::Json};
|
||||
use rocket_db_pools::{Connection, Database, sqlx};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rand::Rng;
|
||||
use rocket::{
|
||||
Request,
|
||||
http::{CookieJar, Status},
|
||||
outcome::Outcome,
|
||||
post,
|
||||
request::{self, FromRequest},
|
||||
serde::json::Json,
|
||||
};
|
||||
use rocket_db_pools::{
|
||||
Connection, Database,
|
||||
sqlx::{self},
|
||||
};
|
||||
use rocket_dyn_templates::{Template, context};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Database)]
|
||||
#[database("postgres_db")]
|
||||
@@ -14,12 +29,44 @@ pub struct UserCredentials {
|
||||
|
||||
#[post("/signup", data = "<cred>")]
|
||||
pub async fn signup(
|
||||
conn: Connection<DbConn>,
|
||||
cred: Json<UserCredentials>,
|
||||
jar: &CookieJar<'_>,
|
||||
mut db: Connection<DbConn>,
|
||||
) -> Result<Json<String>, String> {
|
||||
let result = sqlx::query!(
|
||||
"INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id",
|
||||
cred.username,
|
||||
cred.password
|
||||
)
|
||||
.fetch_one(&mut **db)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let session = SessionToken::new(result.id as usize);
|
||||
let result = sqlx::query!(
|
||||
"INSERT INTO sessions (user_id, token) VALUES ($1, $2)",
|
||||
result.id,
|
||||
session.token,
|
||||
)
|
||||
.execute(&mut **db)
|
||||
.await;
|
||||
|
||||
if let Err(e) = result {
|
||||
eprintln!("Failed to create session: {}", e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
|
||||
jar.add_private(("session", session.token));
|
||||
|
||||
println!("Signup successful");
|
||||
Ok(Json("Signup successful".to_string()))
|
||||
}
|
||||
|
||||
#[get("/signup")]
|
||||
pub async fn signup_page() -> Template {
|
||||
Template::render("signup", context!())
|
||||
}
|
||||
|
||||
#[post("/login", data = "<cred>")]
|
||||
pub async fn login(
|
||||
conn: Connection<DbConn>,
|
||||
@@ -28,3 +75,58 @@ pub async fn login(
|
||||
// TODO: implement actual login logic, e.g. verify password and generate token
|
||||
Ok(Json("Login successful".to_string()))
|
||||
}
|
||||
|
||||
pub struct SessionToken {
|
||||
pub token: String,
|
||||
pub user_id: usize,
|
||||
}
|
||||
|
||||
impl SessionToken {
|
||||
pub fn new(user_id: usize) -> Self {
|
||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
let random: u32 = rand::rng().random();
|
||||
let token = format!("{}-{}", current_time.as_secs(), random);
|
||||
let hashed = format!("{:x}", Sha256::digest(token.as_bytes()));
|
||||
SessionToken {
|
||||
token: hashed,
|
||||
user_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type UserID = usize;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthGuard(pub UserID);
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for AuthGuard {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
if let Some(c) = request.cookies().get_private("session") {
|
||||
let mut pool = match request.guard::<Connection<DbConn>>().await {
|
||||
Outcome::Success(pool) => pool,
|
||||
_ => return Outcome::Error((Status::Unauthorized, ())),
|
||||
};
|
||||
|
||||
let value = c.value();
|
||||
let result = sqlx::query!(
|
||||
"SELECT user_id FROM sessions WHERE token = $1 AND expires_at > NOW()",
|
||||
value
|
||||
)
|
||||
.fetch_optional(&mut **pool)
|
||||
.await
|
||||
.expect("query failed!");
|
||||
|
||||
if let Some(token) = result {
|
||||
let user_id = token.user_id;
|
||||
Outcome::Success(AuthGuard(user_id as usize))
|
||||
} else {
|
||||
Outcome::Error((Status::Unauthorized, ()))
|
||||
}
|
||||
} else {
|
||||
Outcome::Error((Status::Unauthorized, ()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user