add tests; add authentication cookie

This commit is contained in:
2023-04-03 22:03:45 +02:00
parent 38d757cf4a
commit 387d93bbaf
4 changed files with 82 additions and 52 deletions

View File

@ -1,8 +1,14 @@
use argon2::{password_hash::SaltString, Argon2, PasswordHasher};
use serde::Serialize;
use rocket::{
async_trait,
http::Status,
request::{self, FromRequest, Outcome},
Request,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
#[derive(FromRow, Debug, Serialize)]
#[derive(FromRow, Debug, Serialize, Deserialize)]
pub struct User {
id: i64,
name: String,
@ -16,6 +22,7 @@ pub struct User {
pub enum LoginError {
SqlxError(sqlx::Error),
InvalidAuthenticationCombo,
NotLoggedIn,
}
impl From<sqlx::Error> for LoginError {
@ -58,28 +65,31 @@ WHERE name like ?
}
}
#[async_trait]
impl<'r> FromRequest<'r> for User {
type Error = LoginError;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
match req.cookies().get_private("loggedin_user") {
Some(user) => {
let user: User = serde_json::from_str(&user.value()).unwrap(); //TODO: fixme
Outcome::Success(user)
}
None => Outcome::Failure((Status::Unauthorized, LoginError::NotLoggedIn)),
}
}
}
#[cfg(test)]
mod test {
use crate::testdb;
use super::User;
use sqlx::SqlitePool;
async fn setup() -> SqlitePool {
let pool = SqlitePool::connect(":memory:").await.unwrap();
sqlx::query_file!("./migration.sql")
.execute(&pool)
.await
.unwrap();
sqlx::query_file!("./seeds.sql")
.execute(&pool)
.await
.unwrap();
pool
}
#[sqlx::test]
fn succ_login_with_test_db() {
let pool = setup().await;
let pool = testdb!();
User::login(&pool, "admin".into(), "admin".into())
.await
.unwrap();
@ -87,7 +97,7 @@ mod test {
#[sqlx::test]
fn wrong_pw() {
let pool = setup().await;
let pool = testdb!();
assert!(User::login(&pool, "admin".into(), "admi".into())
.await
.is_err());
@ -95,7 +105,7 @@ mod test {
#[sqlx::test]
fn wrong_username() {
let pool = setup().await;
let pool = testdb!();
assert!(User::login(&pool, "admi".into(), "admin".into())
.await
.is_err());