Skip to content

Commit

Permalink
Add auth
Browse files Browse the repository at this point in the history
  • Loading branch information
The-DevBlog committed Feb 11, 2024
1 parent 814d1f5 commit ca5cf1f
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 33 deletions.
2 changes: 1 addition & 1 deletion devblog/devblog/client/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub enum Api {
}

impl Api {
pub async fn fetch2(
pub async fn fetch(
&self,
hdrs: Option<Headers>,
body: Option<JsValue>,
Expand Down
18 changes: 15 additions & 3 deletions devblog/devblog/client/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// use gloo::console::log;
use crate::store::Store;
use crate::{helpers, Api};
use crate::{router::Route, User, UserField};
// use gloo::console::log;
use gloo_net::http::{Headers, Method, Response};
use serde::de::DeserializeOwned;
use serde::Serialize;
Expand All @@ -9,6 +10,7 @@ use wasm_bindgen::JsValue;
use web_sys::{Event, HtmlInputElement, SubmitEvent};
use yew::{Callback, TargetCast, UseStateHandle};
use yew_router::navigator::Navigator;
use yewdux::Dispatch;

pub fn onchange(user: &UseStateHandle<User>, field: UserField) -> Callback<Event> {
let user = user.clone();
Expand All @@ -22,21 +24,31 @@ pub fn onchange(user: &UseStateHandle<User>, field: UserField) -> Callback<Event
})
}

pub fn onsubmit(user: &UseStateHandle<User>, nav: Navigator, api: Api) -> Callback<SubmitEvent> {
pub fn onsubmit(
user: &UseStateHandle<User>,
nav: Navigator,
api: Api,
dispatch: Dispatch<Store>,
) -> Callback<SubmitEvent> {
let user = user.clone();
Callback::from(move |e: SubmitEvent| {
e.prevent_default();
let dispatch_clone = dispatch.clone();
let nav = nav.clone();
let user = user.deref().clone();
let hdrs = Headers::new();
hdrs.append("content-type", "application/json");
wasm_bindgen_futures::spawn_local(async move {
let body = Some(helpers::to_jsvalue(user));
let response = api.fetch2(Some(hdrs), body, Method::POST).await;
let response = api.fetch(Some(hdrs), body, Method::POST).await;

// navigate home if the submission is successful
if let Some(res) = response {
if res.status() == 200 {
let obj: Store = serde_json::from_str(&res.text().await.unwrap()).unwrap();
dispatch_clone.reduce_mut(move |store| {
store.token = obj.token;
});
nav.push(&Route::Home);
}
}
Expand Down
1 change: 1 addition & 0 deletions devblog/devblog/client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::router::{switch, Route};
use api::*;
use components::navbar::Navbar;
use models::*;
use store::Store;
use stylist::yew::Global;
use yew::{function_component, html, Html};
use yew_router::{BrowserRouter, Switch};
Expand Down
9 changes: 8 additions & 1 deletion devblog/devblog/client/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ pub struct User {
#[serde(rename = "userName")]
pub username: String,
pub email: String,
pub subscribed: bool,
pub password: String,
#[serde(rename = "passwordHash")]
pub password_hash: String,
Expand All @@ -77,3 +76,11 @@ pub enum UserField {
PasswordHash,
Email,
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug, Default)]
pub struct UserInfo {
#[serde(rename = "userName")]
pub username: String,
pub subscribed: bool,
pub email: String,
}
4 changes: 2 additions & 2 deletions devblog/devblog/client/src/pages/home.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ pub fn home() -> Html {

use_effect_with((), move |_| {
wasm_bindgen_futures::spawn_local(async move {
let res = Api::GetPost(-1).fetch2(None, None, Method::GET).await;
let res = Api::GetPost(-1).fetch(None, None, Method::GET).await;
helpers::emit(&latest_post_cb, res.unwrap()).await;

let response = Api::GetPostsCount.fetch2(None, None, Method::GET).await;
let response = Api::GetPostsCount.fetch(None, None, Method::GET).await;
helpers::emit(&total_posts_count_cb, response.unwrap()).await;
});
});
Expand Down
12 changes: 8 additions & 4 deletions devblog/devblog/client/src/pages/insights.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
use crate::{
helpers::{self, CustomCallback},
Api, User,
store::Store,
Api, UserInfo,
};
use gloo_net::http::{Headers, Method};
use stylist::Style;
use yew::prelude::*;
use yewdux::prelude::*;

const STYLE: &str = include_str!("styles/insights.css");

#[function_component(Insights)]
pub fn insights() -> Html {
let style = Style::new(STYLE).unwrap();
let users = use_state(|| vec![User::default()]);
let users = use_state(|| vec![UserInfo::default()]);
let users_cb = CustomCallback::new(&users);
let store = use_store_value::<Store>();

use_effect_with((), move |_| {
wasm_bindgen_futures::spawn_local(async move {
let hdrs = Headers::new();
hdrs.append("Authorization", "Bearer ");
let auth = format!("Bearer {}", store.token.clone());
hdrs.append("Authorization", &auth);

let res = Api::GetUsers.fetch2(None, None, Method::GET).await;
let res = Api::GetUsers.fetch(Some(hdrs), None, Method::GET).await;
helpers::emit(&users_cb, res.unwrap()).await;
});
});
Expand Down
6 changes: 3 additions & 3 deletions devblog/devblog/client/src/pages/posts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ pub fn posts() -> Html {

use_effect_with((), move |_| {
wasm_bindgen_futures::spawn_local(async move {
let res = Api::GetPostsCount.fetch2(None, None, Method::GET).await;
let res = Api::GetPostsCount.fetch(None, None, Method::GET).await;
helpers::emit(&total_posts_count_cb, res.unwrap()).await;

let res = Api::GetPagesCount.fetch2(None, None, Method::GET).await;
let res = Api::GetPagesCount.fetch(None, None, Method::GET).await;
helpers::emit(&total_pages_count_cb, res.unwrap()).await;
});
});
Expand All @@ -38,7 +38,7 @@ pub fn posts() -> Html {
wasm_bindgen_futures::spawn_local(async move {
loading_clone.set(false);
let num = *page_num_clone as u32;
let res = Api::GetPage(num).fetch2(None, None, Method::GET).await;
let res = Api::GetPage(num).fetch(None, None, Method::GET).await;
helpers::emit(&posts_cb, res.unwrap()).await;
loading_clone.set(true);
});
Expand Down
11 changes: 4 additions & 7 deletions devblog/devblog/client/src/pages/sign_in.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::{components::items::text_input::TextInput, helpers, Api, User, UserField};
use crate::{components::items::text_input::TextInput, helpers, Api, Store, User, UserField};
use stylist::Style;
use yew::prelude::*;
use yew_router::hooks::use_navigator;
use yewdux::prelude::*;

const STYLE: &str = include_str!("styles/signIn.css");

Expand All @@ -10,17 +11,13 @@ pub fn sign_in() -> Html {
let style = Style::new(STYLE).unwrap();
let user = use_state(User::default);
let nav = use_navigator().unwrap();
// let (_state, dispatch) = use_store::<Store>();
// let onsubmit = { helpers::onsubmit(&user, nav, Api::SignIn) };
let (_, dispatch) = use_store::<Store>();

html! {
<div class={style}>
<div class="sign-in-container">

// {error && <span>{error}</span>}

<form onsubmit={helpers::onsubmit(&user, nav, Api::SignIn)} class="sign-in">
// <form {onsubmit}>
<form onsubmit={helpers::onsubmit(&user, nav, Api::SignIn, dispatch)} class="sign-in">
<TextInput label="username" input_type="text" value={user.username.clone()} onchange={helpers::onchange(&user, UserField::Username)}/>
<TextInput label="password" input_type="password" value={user.password.clone()} onchange={helpers::onchange(&user, UserField::Password)}/>
<button>{"Login"}</button>
Expand Down
7 changes: 4 additions & 3 deletions devblog/devblog/client/src/pages/sign_up.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::{components::items::text_input::TextInput, helpers, Api, Store, User, UserField};
use stylist::Style;
use yew::prelude::*;
use yew_router::hooks::use_navigator;

use crate::{components::items::text_input::TextInput, helpers, Api, User, UserField};
use yewdux::prelude::*;

const STYLE: &str = include_str!("styles/signUp.css");

Expand All @@ -11,11 +11,12 @@ pub fn sign_up() -> Html {
let style = Style::new(STYLE).unwrap();
let user = use_state(User::default);
let nav = use_navigator().unwrap();
let (_, dispatch) = use_store::<Store>();

html! {
<div class={style}>
<div class="sign-up-container">
<form onsubmit={helpers::onsubmit(&user, nav, Api::SignUp)}>
<form onsubmit={helpers::onsubmit(&user, nav, Api::SignUp, dispatch)}>
<TextInput label="username" input_type="text" value={user.username.clone()} onchange={helpers::onchange(&user, UserField::Username)}/>
<TextInput label="email" input_type="text" value={user.email.clone()} onchange={helpers::onchange(&user, UserField::Email)}/>
<TextInput label="password" input_type="password" value={user.password_hash.clone()} onchange={helpers::onchange(&user, UserField::PasswordHash)}/>
Expand Down
9 changes: 0 additions & 9 deletions devblog/devblog/client/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,3 @@ pub struct Store {
pub token: String,
pub expiration: String,
}

impl Store {
pub fn add_to_store(&self, dispatch: Dispatch<Store>) {
dispatch.reduce_mut(move |store| {
store.username = self.username.clone();
store.token = self.token.clone();
});
}
}

0 comments on commit ca5cf1f

Please sign in to comment.