1
0

main.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. //! Run with:
  2. //!
  3. //! ```sh
  4. //! dioxus build --features web
  5. //! cargo run --features ssr
  6. //! ```
  7. #![allow(non_snake_case, unused)]
  8. #[cfg(feature = "ssr")]
  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 = "ssr")]
  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("", ServeConfigBuilder::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. fn app(cx: Scope) -> Element {
  67. let user_name = use_state(cx, || "?".to_string());
  68. let permissions = use_state(cx, || "?".to_string());
  69. cx.render(rsx! {
  70. div {
  71. button {
  72. onclick: move |_| {
  73. async move {
  74. login().await.unwrap();
  75. }
  76. },
  77. "Login Test User"
  78. }
  79. }
  80. div {
  81. button {
  82. onclick: move |_| {
  83. to_owned![user_name];
  84. async move {
  85. if let Ok(data) = get_user_name().await {
  86. user_name.set(data);
  87. }
  88. }
  89. },
  90. "Get User Name"
  91. }
  92. "User name: {user_name}"
  93. }
  94. div {
  95. button {
  96. onclick: move |_| {
  97. to_owned![permissions];
  98. async move {
  99. if let Ok(data) = get_permissions().await {
  100. permissions.set(data);
  101. }
  102. }
  103. },
  104. "Get Permissions"
  105. }
  106. "Permissions: {permissions}"
  107. }
  108. })
  109. }
  110. #[server(GetUserName)]
  111. pub async fn get_user_name() -> Result<String, ServerFnError> {
  112. let session: crate::auth::Session = extract().await?;
  113. Ok(session.0.current_user.unwrap().username.to_string())
  114. }
  115. #[server(Login)]
  116. pub async fn login() -> Result<(), ServerFnError> {
  117. let auth: crate::auth::Session = extract().await?;
  118. auth.login_user(2);
  119. Ok(())
  120. }
  121. #[server(Permissions)]
  122. pub async fn get_permissions() -> Result<String, ServerFnError> {
  123. let method: axum::http::Method = extract().await?;
  124. let auth: crate::auth::Session = extract().await?;
  125. let current_user = auth.current_user.clone().unwrap_or_default();
  126. // lets check permissions only and not worry about if they are anon or not
  127. if !axum_session_auth::Auth::<crate::auth::User, i64, sqlx::SqlitePool>::build(
  128. [axum::http::Method::POST],
  129. false,
  130. )
  131. .requires(axum_session_auth::Rights::any([
  132. axum_session_auth::Rights::permission("Category::View"),
  133. axum_session_auth::Rights::permission("Admin::View"),
  134. ]))
  135. .validate(&current_user, &method, None)
  136. .await
  137. {
  138. return Ok(format!(
  139. "User {}, Does not have permissions needed to view this page please login",
  140. current_user.username
  141. ));
  142. }
  143. Ok(format!(
  144. "User has Permissions needed. Here are the Users permissions: {:?}",
  145. current_user.permissions
  146. ))
  147. }