Skip to content

Commit

Permalink
feat(auth): introduce use_user hook
Browse files Browse the repository at this point in the history
  • Loading branch information
H1ghBre4k3r committed Aug 29, 2023
1 parent ebbe830 commit ca5db4b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
11 changes: 3 additions & 8 deletions src/contexts/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::functions::{Login, Logout, Register, RegistrationResult};

cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::{hooks::use_identity, model::Session};
use crate::{hooks::{use_identity, use_user}};
}
}

Expand Down Expand Up @@ -47,17 +47,12 @@ impl AuthContext {

#[server(GetUserId, "/api")]

Check warning on line 48 in src/contexts/auth.rs

View workflow job for this annotation

GitHub Actions / Build & Test (nightly)

`&` without an explicit lifetime name cannot be used here

Check warning on line 48 in src/contexts/auth.rs

View workflow job for this annotation

GitHub Actions / Build & Test (nightly)

`&` without an explicit lifetime name cannot be used here

Check warning on line 48 in src/contexts/auth.rs

View workflow job for this annotation

GitHub Actions / Build & Test (nightly)

`&` without an explicit lifetime name cannot be used here

Check warning on line 48 in src/contexts/auth.rs

View workflow job for this annotation

GitHub Actions / Build & Test (nightly)

`&` without an explicit lifetime name cannot be used here
async fn get_user_id(cx: Scope) -> Result<Option<String>, ServerFnError> {
let identity = use_identity(cx)?;

let session_id = identity
.id()
.map_err(|_| ServerFnError::ServerError("User Not Found!".to_string()))?;

match Session::find_user_via_session(&session_id).await {
match use_user(cx).await {
Some(user) => {
return Ok(Some(user.username));
}
None => {
let identity = use_identity(cx)?;
identity.logout();
return Err(ServerFnError::ServerError("Inactive session!".to_string()));
}
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ cfg_if! {
if #[cfg(feature = "ssr")] {
mod database;
mod identity;
mod user;

pub use self::database::*;
pub use self::identity::*;
pub use self::user::*;
}
}
19 changes: 19 additions & 0 deletions src/hooks/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use leptos::*;

use crate::model::{Session, User};

use super::use_identity;

pub async fn use_user(cx: Scope) -> Option<User> {
let Ok(identity) = use_identity(cx) else {
error!("failed to get identity");
return None;
};

let Ok(session_id) = identity.id() else {
error!("failed to get session id!");
return None;
};

Session::find_user_via_session(&session_id).await
}

0 comments on commit ca5db4b

Please sign in to comment.