diff options
author | Ilion Beyst <ilion.beyst@gmail.com> | 2021-12-29 19:56:31 +0100 |
---|---|---|
committer | Ilion Beyst <ilion.beyst@gmail.com> | 2021-12-29 19:56:31 +0100 |
commit | 3eeaab6cec70e7a06a99a1ac2662974f71064bee (patch) | |
tree | 9d5a2665ed32df41b2be131d5e27e8b321ce78a8 /backend/src/db/sessions.rs | |
parent | ee5af8d07625bfc7ad11b842b3941bb095aa6a6e (diff) | |
parent | 1fb4a5151bd8cfe6de4d8c19e2066a9281a0b61a (diff) | |
download | planetwars.dev-3eeaab6cec70e7a06a99a1ac2662974f71064bee.tar.xz planetwars.dev-3eeaab6cec70e7a06a99a1ac2662974f71064bee.zip |
Merge branch 'backend-server'
Diffstat (limited to 'backend/src/db/sessions.rs')
-rw-r--r-- | backend/src/db/sessions.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/backend/src/db/sessions.rs b/backend/src/db/sessions.rs new file mode 100644 index 0000000..96f3926 --- /dev/null +++ b/backend/src/db/sessions.rs @@ -0,0 +1,46 @@ +use super::users::User; +use crate::schema::{sessions, users}; +use base64; +use diesel::PgConnection; +use diesel::{insert_into, prelude::*, Insertable, RunQueryDsl}; +use rand::{self, Rng}; + +#[derive(Insertable)] +#[table_name = "sessions"] +struct NewSession { + token: String, + user_id: i32, +} + +#[derive(Queryable, Debug, PartialEq)] +pub struct Session { + pub id: i32, + pub user_id: i32, + pub token: String, +} + +pub fn create_session(user: &User, conn: &PgConnection) -> Session { + let new_session = NewSession { + token: gen_session_token(), + user_id: user.id, + }; + let session = insert_into(sessions::table) + .values(&new_session) + .get_result::<Session>(conn) + .unwrap(); + + return session; +} + +pub fn find_user_by_session(token: &str, conn: &PgConnection) -> QueryResult<(Session, User)> { + sessions::table + .inner_join(users::table) + .filter(sessions::token.eq(&token)) + .first::<(Session, User)>(conn) +} + +pub fn gen_session_token() -> String { + let mut rng = rand::thread_rng(); + let token: [u8; 32] = rng.gen(); + return base64::encode(&token); +} |