add session creation ts
This commit is contained in:
parent
2097bd1cca
commit
d7a55f6579
3 changed files with 28 additions and 1 deletions
15
src/auth/auth.sql
Normal file
15
src/auth/auth.sql
Normal file
|
@ -0,0 +1,15 @@
|
|||
CREATE TYPE user_role AS ENUM ('regular', 'admin');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
username VARCHAR(255) NOT NULL PRIMARY KEY,
|
||||
"password" text NOT NULL,
|
||||
user_role user_role NOT NULL DEFAULT 'regular'
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_session (
|
||||
id UUID NOT NULL PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
token text NOT NULL,
|
||||
"user" varchar(255) NOT NULL,
|
||||
"created" timestamptz NOT NULL DEFAULT NOW(),
|
||||
FOREIGN KEY("user") REFERENCES users(username)
|
||||
);
|
|
@ -1,3 +1,4 @@
|
|||
use chrono::Utc;
|
||||
use data_encoding::HEXUPPER;
|
||||
use rand::RngCore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
@ -25,6 +26,8 @@ pub struct Session {
|
|||
pub token: String,
|
||||
/// The username associated with the session token
|
||||
pub user: String,
|
||||
/// Session creation time
|
||||
pub created: chrono::DateTime<Utc>
|
||||
}
|
||||
|
||||
/// A macro to check if a user has admin privileges.
|
||||
|
|
|
@ -26,6 +26,8 @@ pub struct User {
|
|||
pub password: String,
|
||||
/// The role of the user
|
||||
pub user_role: UserRole,
|
||||
#[sqlx(default)]
|
||||
pub session: String
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::Type)]
|
||||
|
@ -40,7 +42,14 @@ pub enum UserRole {
|
|||
impl User {
|
||||
// Get a user from session ID
|
||||
pub async fn from_session(session: &str) -> Option<Self> {
|
||||
sqlx::query_as("SELECT * FROM users WHERE username = (SELECT \"user\" FROM user_session WHERE token = $1)").bind(session).fetch_optional(get_pg!()).await.unwrap()
|
||||
let user: Option<Self> = sqlx::query_as("SELECT * FROM users WHERE username = (SELECT \"user\" FROM user_session WHERE token = $1)").bind(session).fetch_optional(get_pg!()).await.unwrap();
|
||||
|
||||
if let Some(mut user) = user {
|
||||
user.session = session.to_string();
|
||||
return Some(user);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Find a user by their username
|
||||
|
|
Loading…
Add table
Reference in a new issue