|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use async_trait::async_trait; |
| 4 | +use serde::Deserialize; |
| 5 | +use shield::{ |
| 6 | + Action, ActionMethod, Form, Input, InputType, InputTypeText, MethodSession, Request, Response, |
| 7 | + ResponseType, SessionAction, ShieldError, SignInAction, Storage, User, erased_action, |
| 8 | +}; |
| 9 | + |
| 10 | +use crate::provider::DummyProvider; |
| 11 | + |
| 12 | +#[derive(Debug, Deserialize)] |
| 13 | +#[serde(rename_all = "camelCase")] |
| 14 | +pub struct SignInData { |
| 15 | + pub user_id: String, |
| 16 | +} |
| 17 | + |
| 18 | +pub struct DummySignInAction<U: User> { |
| 19 | + storage: Arc<dyn Storage<U>>, |
| 20 | +} |
| 21 | + |
| 22 | +impl<U: User> DummySignInAction<U> { |
| 23 | + pub fn new(storage: Arc<dyn Storage<U>>) -> Self { |
| 24 | + Self { storage } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +#[async_trait] |
| 29 | +impl<U: User + 'static> Action<DummyProvider, ()> for DummySignInAction<U> { |
| 30 | + fn id(&self) -> String { |
| 31 | + SignInAction::id() |
| 32 | + } |
| 33 | + |
| 34 | + fn name(&self) -> String { |
| 35 | + SignInAction::name() |
| 36 | + } |
| 37 | + |
| 38 | + fn openapi_summary(&self) -> &'static str { |
| 39 | + "Sign in with dummy" |
| 40 | + } |
| 41 | + |
| 42 | + fn openapi_description(&self) -> &'static str { |
| 43 | + "Sign in with dummy." |
| 44 | + } |
| 45 | + |
| 46 | + fn method(&self) -> ActionMethod { |
| 47 | + ActionMethod::Post |
| 48 | + } |
| 49 | + |
| 50 | + async fn forms(&self, _provider: DummyProvider) -> Result<Vec<Form>, ShieldError> { |
| 51 | + Ok(vec![Form { |
| 52 | + inputs: vec![Input { |
| 53 | + name: "userId".to_owned(), |
| 54 | + label: Some("User ID".to_owned()), |
| 55 | + r#type: InputType::Text(InputTypeText { |
| 56 | + placeholder: Some("User ID".to_owned()), |
| 57 | + required: Some(true), |
| 58 | + ..Default::default() |
| 59 | + }), |
| 60 | + value: None, |
| 61 | + addon_start: None, |
| 62 | + addon_end: None, |
| 63 | + }], |
| 64 | + }]) |
| 65 | + } |
| 66 | + |
| 67 | + async fn call( |
| 68 | + &self, |
| 69 | + _provider: DummyProvider, |
| 70 | + _session: &MethodSession<()>, |
| 71 | + request: Request, |
| 72 | + ) -> Result<Response, ShieldError> { |
| 73 | + let data = serde_json::from_value::<SignInData>(request.form_data) |
| 74 | + .map_err(|err| ShieldError::Validation(err.to_string()))?; |
| 75 | + |
| 76 | + let user = self |
| 77 | + .storage |
| 78 | + .user_by_id(&data.user_id) |
| 79 | + .await? |
| 80 | + .ok_or_else(|| ShieldError::Validation("User not found.".to_owned()))?; |
| 81 | + |
| 82 | + Ok(Response::new(ResponseType::Default).session_action(SessionAction::authenticate(user))) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +erased_action!(DummySignInAction, <U: User>); |
0 commit comments