added login
This commit is contained in:
+53
-28
@@ -16,6 +16,7 @@ use rocket_db_pools::{
|
||||
use rocket_dyn_templates::{Template, context};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::postgres::PgQueryResult;
|
||||
|
||||
use crate::db::DbConn;
|
||||
|
||||
@@ -25,6 +26,11 @@ pub struct UserCredentials {
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[get("/signup")]
|
||||
pub async fn signup_page() -> Template {
|
||||
Template::render("signup", context!())
|
||||
}
|
||||
|
||||
#[post("/signup", data = "<cred>")]
|
||||
pub async fn signup(
|
||||
cred: Json<UserCredentials>,
|
||||
@@ -40,16 +46,8 @@ pub async fn signup(
|
||||
.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 {
|
||||
let session = Session::new(result.id as usize);
|
||||
if let Err(e) = session.commit(&mut db).await {
|
||||
eprintln!("Failed to create session: {}", e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
@@ -60,45 +58,70 @@ pub async fn signup(
|
||||
Ok(Json("Signup successful".to_string()))
|
||||
}
|
||||
|
||||
#[get("/signup")]
|
||||
pub async fn signup_page() -> Template {
|
||||
Template::render("signup", context!())
|
||||
#[get("/login")]
|
||||
pub async fn login_page() -> Template {
|
||||
Template::render("login", context!())
|
||||
}
|
||||
|
||||
#[post("/login", data = "<cred>")]
|
||||
pub async fn login(
|
||||
conn: Connection<DbConn>,
|
||||
mut db: Connection<DbConn>,
|
||||
jar: &CookieJar<'_>,
|
||||
cred: Json<UserCredentials>,
|
||||
) -> Result<Json<String>, String> {
|
||||
if let Ok(row) = sqlx::query!(
|
||||
"SELECT id FROM users WHERE username = $1 AND password = $2",
|
||||
cred.username,
|
||||
cred.password,
|
||||
)
|
||||
.fetch_one(&mut **db)
|
||||
.await
|
||||
{
|
||||
let session = Session::new(row.id as usize);
|
||||
if let Err(e) = session.commit(&mut db).await {
|
||||
eprintln!("Failed to create session: {}", e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
|
||||
jar.add_private(("session", session.token));
|
||||
return Ok(Json("Signup successful".to_string()));
|
||||
}
|
||||
|
||||
// TODO: implement actual login logic, e.g. verify password and generate token
|
||||
Ok(Json("Login successful".to_string()))
|
||||
Err("login failed".to_string())
|
||||
}
|
||||
|
||||
pub struct SessionToken {
|
||||
#[derive(Debug)]
|
||||
pub struct Session {
|
||||
pub token: String,
|
||||
pub user_id: usize,
|
||||
}
|
||||
|
||||
impl SessionToken {
|
||||
impl Session {
|
||||
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 {
|
||||
Self {
|
||||
token: hashed,
|
||||
user_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn commit(&self, db: &mut Connection<DbConn>) -> Result<PgQueryResult, sqlx::Error> {
|
||||
sqlx::query!(
|
||||
"INSERT INTO sessions (user_id, token) VALUES ($1, $2)",
|
||||
self.user_id as i32,
|
||||
self.token,
|
||||
)
|
||||
.execute(&mut ***db)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
type UserID = usize;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AuthGuard(pub UserID);
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for AuthGuard {
|
||||
impl<'r> FromRequest<'r> for Session {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
|
||||
@@ -110,16 +133,18 @@ impl<'r> FromRequest<'r> for AuthGuard {
|
||||
|
||||
let value = c.value();
|
||||
let result = sqlx::query!(
|
||||
"SELECT user_id FROM sessions WHERE token = $1 AND expires_at > NOW()",
|
||||
"SELECT user_id, token 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))
|
||||
if let Some(session) = result {
|
||||
Outcome::Success(Self {
|
||||
user_id: session.user_id as usize,
|
||||
token: session.token,
|
||||
})
|
||||
} else {
|
||||
Outcome::Error((Status::Unauthorized, ()))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user