main.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. //! Run with:
  2. //!
  3. //! ```sh
  4. //! dx build --features web
  5. //! cargo run --features server
  6. //! ```
  7. #![allow(non_snake_case, unused)]
  8. #[cfg(feature = "server")]
  9. mod auth;
  10. use dioxus::prelude::*;
  11. use dioxus_fullstack::prelude::*;
  12. use serde::{Deserialize, Serialize};
  13. fn main() {
  14. #[cfg(feature = "web")]
  15. // Hydrate the application on the client
  16. dioxus_web::launch_cfg(app, dioxus_web::Config::new().hydrate(true));
  17. #[cfg(feature = "server")]
  18. {
  19. use crate::auth::*;
  20. use axum::routing::*;
  21. use axum_session::SessionConfig;
  22. use axum_session::SessionStore;
  23. use axum_session_auth::AuthConfig;
  24. use axum_session_auth::SessionSqlitePool;
  25. simple_logger::SimpleLogger::new().init().unwrap();
  26. tokio::runtime::Runtime::new()
  27. .unwrap()
  28. .block_on(async move {
  29. let pool = connect_to_database().await;
  30. //This Defaults as normal Cookies.
  31. //To enable Private cookies for integrity, and authenticity please check the next Example.
  32. let session_config = SessionConfig::default().with_table_name("test_table");
  33. let auth_config = AuthConfig::<i64>::default().with_anonymous_user_id(Some(1));
  34. let session_store = SessionStore::<SessionSqlitePool>::new(
  35. Some(pool.clone().into()),
  36. session_config,
  37. )
  38. .await
  39. .unwrap();
  40. //Create the Database table for storing our Session Data.
  41. session_store.initiate().await.unwrap();
  42. User::create_user_tables(&pool).await;
  43. // build our application with some routes
  44. let app = Router::new()
  45. // Server side render the application, serve static assets, and register server functions
  46. .serve_dioxus_application("", ServerConfig::new(app, ()))
  47. .layer(
  48. axum_session_auth::AuthSessionLayer::<
  49. crate::auth::User,
  50. i64,
  51. axum_session_auth::SessionSqlitePool,
  52. sqlx::SqlitePool,
  53. >::new(Some(pool))
  54. .with_config(auth_config),
  55. )
  56. .layer(axum_session::SessionLayer::new(session_store));
  57. // run it
  58. let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));
  59. axum::Server::bind(&addr)
  60. .serve(app.into_make_service())
  61. .await
  62. .unwrap();
  63. });
  64. }
  65. }
  66. //
  67. fn app() -> Element {
  68. let user_name = use_signal(|| "?".to_string());
  69. let permissions = use_signal(|| "?".to_string());
  70. rsx! {
  71. div {
  72. button {
  73. onclick: move |_| {
  74. async move {
  75. login().await.unwrap();
  76. }
  77. },
  78. "Login Test User"
  79. }
  80. }
  81. div {
  82. button {
  83. onclick: move |_| {
  84. to_owned![user_name];
  85. async move {
  86. if let Ok(data) = get_user_name().await {
  87. user_name.set(data);
  88. }
  89. }
  90. },
  91. "Get User Name"
  92. }
  93. "User name: {user_name}"
  94. }
  95. div {
  96. button {
  97. onclick: move |_| {
  98. to_owned![permissions];
  99. async move {
  100. if let Ok(data) = get_permissions().await {
  101. permissions.set(data);
  102. }
  103. }
  104. },
  105. "Get Permissions"
  106. }
  107. "Permissions: {permissions}"
  108. }
  109. }
  110. }
  111. #[server(GetUserName)]
  112. pub async fn get_user_name() -> Result<String, ServerFnError> {
  113. let session: crate::auth::Session = extract().await?;
  114. Ok(session.0.current_user.unwrap().username.to_string())
  115. }
  116. #[server(Login)]
  117. pub async fn login() -> Result<(), ServerFnError> {
  118. let auth: crate::auth::Session = extract().await?;
  119. auth.login_user(2);
  120. Ok(())
  121. }
  122. #[server(Permissions)]
  123. pub async fn get_permissions() -> Result<String, ServerFnError> {
  124. let method: axum::http::Method = extract().await?;
  125. let auth: crate::auth::Session = extract().await?;
  126. let current_user = auth.current_user.clone().unwrap_or_default();
  127. // lets check permissions only and not worry about if they are anon or not
  128. if !axum_session_auth::Auth::<crate::auth::User, i64, sqlx::SqlitePool>::build(
  129. [axum::http::Method::POST],
  130. false,
  131. )
  132. .requires(axum_session_auth::Rights::any([
  133. axum_session_auth::Rights::permission("Category::View"),
  134. axum_session_auth::Rights::permission("Admin::View"),
  135. ]))
  136. .validate(&current_user, &method, None)
  137. .await
  138. {
  139. return Ok(format!(
  140. "User {}, Does not have permissions needed to view this page please login",
  141. current_user.username
  142. ));
  143. }
  144. Ok(format!(
  145. "User has Permissions needed. Here are the Users permissions: {:?}",
  146. current_user.permissions
  147. ))
  148. }