Skip to content

Commit

Permalink
Merge pull request #35 from Pugma:feat/session
Browse files Browse the repository at this point in the history
succeeded in create session by cookie
  • Loading branch information
Pugma authored Jul 27, 2024
2 parents d25d376 + 5e2483c commit f2ebf82
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 12 deletions.
4 changes: 2 additions & 2 deletions docs/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS `groups` (
`groupUuid` VARCHAR(32) NOT NULL,
`groupName` VARCHAR(32) NOT NULL,
`ownerName` VARCHAR(50) NOT NULL,
`lastUpdate` DATETIME NOT NULL,
`lastUpdate` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`groupId`),
INDEX (`lastUpdate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Expand All @@ -27,7 +27,7 @@ CREATE TABLE IF NOT EXISTS `schedule` (
`since` DATE NOT NULL,
`until` DATE NOT NULL,
`condition` TINYINT(1) NOT NULL,
`lastUpdate` DATETIME NOT NULL,
`lastUpdate` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`groupId`),
INDEX (`lastUpdate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
28 changes: 21 additions & 7 deletions server/app/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::repository::user_sessions::Aaa;
use crate::repository::Repository;
use axum::http::Method;
use axum::http::{HeaderMap, Method};
use axum::{
body::Body,
extract::{Host, Path, State},
Expand All @@ -22,11 +23,11 @@ pub async fn sign_up_post(
_cookies: CookieJar,
State(repo): State<Repository>,
Json(body): Json<PostLogin>,
) -> Result<Response> {
) -> Result<(HeaderMap, Response)> {
repo.add_user(body.user_name.clone(), body.password.clone())
.await?;

let _user_session = match repo.create_session_for_user(body.user_name.clone()).await {
let user_session = match repo.create_session_for_user(body.user_name.clone()).await {
Ok(session) => session,
Err(e) => {
println!("error: {}", e);
Expand All @@ -38,8 +39,10 @@ pub async fn sign_up_post(

let response = Response::builder();

let headers = HeaderMap::make_cookie_header(user_session).await?;

let rep = response.status(200).body(Body::empty()).unwrap();
Ok(rep)
Ok((headers, rep))
}

pub async fn login_post(
Expand All @@ -48,9 +51,10 @@ pub async fn login_post(
_cookies: CookieJar,
State(repo): State<Repository>,
Json(body): Json<PostLogin>,
) -> Result<Response> {
) -> Result<(HeaderMap, Response)> {
let copied_password: String = body.password.clone();
let db_result: Result<bool, String> = repo.check_user(body.user_name, body.password).await;
let db_result: Result<bool, String> =
repo.check_user(body.user_name.clone(), body.password).await;

let _result = match db_result {
Ok(true) => Ok(LoginPostResponse::Status200_Success),
Expand All @@ -61,6 +65,16 @@ pub async fn login_post(
Err(e) => Err(e),
};

let user_session = match repo.create_session_for_user(body.user_name).await {
Ok(session) => session,
Err(e) => {
println!("error: {}", e);
"".to_string()
}
};

let headers = HeaderMap::make_cookie_header(user_session).await?;

let response = Response::builder();

// let resp = match result {
Expand Down Expand Up @@ -98,7 +112,7 @@ pub async fn login_post(
// };

let rep = response.status(200).body(Body::empty()).unwrap();
Ok(rep)
Ok((headers, rep))
}

pub async fn me_get(
Expand Down
6 changes: 5 additions & 1 deletion server/app/src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ use openapi::models::GroupItem;
mod group_schedules;
mod user_groups;
mod user_passwords;
mod user_sessions;
pub mod user_sessions;

pub mod constants {
pub const SESSION_COOKIE_NAME: &str = "session_id";
pub const SESSION_COOKIE_DURATION: u64 = 604800; // 7days
}
#[derive(Debug, Clone)]
pub struct Repository {
pool: MySqlPool,
Expand Down
4 changes: 2 additions & 2 deletions server/app/src/repository/user_groups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ impl Repository {
let _request = query(
"
INSERT INTO `groups`
( `groupUuid`, `groupName`, `ownerName`, `lastUpdate`, )
VALUES ( ?, ?, ?, ? )
( `groupUuid`, `groupName`, `ownerName` )
VALUES ( ?, ?, ? )
",
)
.bind(uuid)
Expand Down
24 changes: 24 additions & 0 deletions server/app/src/repository/user_sessions.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use std::time::Duration;

use super::constants::{SESSION_COOKIE_DURATION, SESSION_COOKIE_NAME};
use anyhow::{Context, Result};
use async_session::{Session, SessionStore};
use axum::http::{header::SET_COOKIE, HeaderMap};

use super::UserName;
use crate::Repository;
Expand All @@ -13,6 +17,8 @@ impl Repository {
.insert("user", user)
.with_context(|| "failed to insert user into session")?;

session.expire_in(Duration::from_secs(SESSION_COOKIE_DURATION));

let res = self
.session_store
.store_session(session)
Expand All @@ -36,3 +42,21 @@ impl Repository {
Ok(Some(()))
}
}

pub trait Aaa {
async fn make_cookie_header(value: String) -> crate::Result<HeaderMap>;
}

impl Aaa for HeaderMap {
async fn make_cookie_header(value: String) -> crate::Result<HeaderMap> {
let header = [(
SET_COOKIE,
format!("{SESSION_COOKIE_NAME}={value}; Path=/; Max-Age={SESSION_COOKIE_DURATION}; HttpOnly",)
.parse()
.with_context(|| "failed to set cookie to header value")?,
)]
.into_iter()
.collect();
Ok(header)
}
}

0 comments on commit f2ebf82

Please sign in to comment.