aboutsummaryrefslogtreecommitdiff
path: root/backend/src/db/sessions.rs
diff options
context:
space:
mode:
authorIlion Beyst <ilion.beyst@gmail.com>2021-12-13 22:41:20 +0100
committerIlion Beyst <ilion.beyst@gmail.com>2021-12-13 22:41:20 +0100
commiteabeb7ed7b641dea0b8e71ab33ab97b4ed7a4cda (patch)
tree9cd2f38290fa059020feb049d8a2e2e91adac68b /backend/src/db/sessions.rs
parent8b4440f7236b0972c1a804eea4c8305b958ad03c (diff)
downloadplanetwars.dev-eabeb7ed7b641dea0b8e71ab33ab97b4ed7a4cda.tar.xz
planetwars.dev-eabeb7ed7b641dea0b8e71ab33ab97b4ed7a4cda.zip
start implementing basic login functionality
Diffstat (limited to 'backend/src/db/sessions.rs')
-rw-r--r--backend/src/db/sessions.rs46
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..0cc3f1a
--- /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.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);
+}