Skip to content

Commit

Permalink
wip:permissions fix
Browse files Browse the repository at this point in the history
  • Loading branch information
argha-dot committed Aug 29, 2024
1 parent c5e6d31 commit f4df9c0
Show file tree
Hide file tree
Showing 12 changed files with 338 additions and 99 deletions.
90 changes: 37 additions & 53 deletions hosted-frontend/src/api/manage_profile/api_token/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,77 +5,61 @@ use crate::prelude::*;
#[server(CreateApiTokenFn, endpoint = "/user/api-token/create")]
pub async fn create_api_token(
access_token: Option<String>,
token_name: String,
token_exp: String,
token_nbf: String,
api_token_info: CreateApiTokenRequest,
) -> Result<CreateApiTokenResponse, ServerFnError<ErrorType>> {
use std::{collections::BTreeMap, str::FromStr};
use std::str::FromStr;

use models::{api::user::*, rbac::WorkspacePermission};
use time::{
macros::{datetime, format_description},
Date,
OffsetDateTime,
};
use models::api::user::*;

let access_token = BearerToken::from_str(access_token.unwrap().as_str())
.map_err(|_| ServerFnError::WrappedServerError(ErrorType::MalformedAccessToken))?;

let format = format_description!("[year]-[month]-[day]");

let token_nbf = token_nbf
.some_if_not_empty()
.map(|nbf| {
let date = Date::parse(nbf.as_str(), &format).map_err(|er| {
logging::log!("{:#?}", er);
ServerFnError::WrappedServerError(ErrorType::WrongParameters)
})?;

Ok::<OffsetDateTime, ServerFnError<ErrorType>>(
datetime!(2020-01-01 0:00 UTC).replace_date(date),
)
})
.transpose()?;

let token_exp = token_exp
.some_if_not_empty()
.map(|exp| {
let date = Date::parse(exp.as_str(), &format).map_err(|er| {
logging::log!("{:#?}", er);
ServerFnError::WrappedServerError(ErrorType::WrongParameters)
})?;

Ok::<OffsetDateTime, ServerFnError<ErrorType>>(
datetime!(2020-01-01 0:00 UTC).replace_date(date),
)
})
.transpose()?;

logging::log!("date tokens: {:?} {:?}", token_exp, token_nbf);

let token = UserApiToken {
name: token_name,
token_exp,
token_nbf,
allowed_ips: None,
created: OffsetDateTime::now_utc(),
permissions: BTreeMap::<Uuid, WorkspacePermission>::new(),
};
// let format = format_description!("[year]-[month]-[day]");
//
// let token_nbf = token_nbf
// .some_if_not_empty()
// .map(|nbf| {
// let date = Date::parse(nbf.as_str(), &format).map_err(|er| {
// logging::log!("{:#?}", er);
// ServerFnError::WrappedServerError(ErrorType::WrongParameters)
// })?;
//
// Ok::<OffsetDateTime, ServerFnError<ErrorType>>(
// datetime!(2020-01-01 0:00 UTC).replace_date(date),
// )
// })
// .transpose()?;
//
// let token_exp = token_exp
// .some_if_not_empty()
// .map(|exp| {
// let date = Date::parse(exp.as_str(), &format).map_err(|er| {
// logging::log!("{:#?}", er);
// ServerFnError::WrappedServerError(ErrorType::WrongParameters)
// })?;
//
// Ok::<OffsetDateTime, ServerFnError<ErrorType>>(
// datetime!(2020-01-01 0:00 UTC).replace_date(date),
// )
// })
// .transpose()?;
//
// logging::log!("date tokens: {:?} {:?}", token_exp, token_nbf);

let api_response = make_api_call::<CreateApiTokenRequest>(
ApiRequest::builder()
.path(CreateApiTokenPath)
.query(())
.headers(CreateApiTokenRequestHeaders {
authorization: access_token,
user_agent: UserAgent::from_static("hyper/0.12.2"),
user_agent: UserAgent::from_static(constants::USER_AGENT_STRING),
})
.body(CreateApiTokenRequest { token })
.body(api_token_info)
.build(),
)
.await;

api_response
.map(|res| res.body)
.map_err(|_| ServerFnError::WrappedServerError(ErrorType::InternalServerError))
.map_err(|err| ServerFnError::WrappedServerError(err))
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::prelude::*;
#[server(GetApiTokenFn, endpoint = "/user/api-token/get")]
pub async fn get_api_token(
access_token: Option<String>,
token_id: String,
token_id: Uuid,
) -> Result<GetApiTokenInfoResponse, ServerFnError<ErrorType>> {
use std::str::FromStr;

Expand All @@ -14,9 +14,6 @@ pub async fn get_api_token(
let access_token = BearerToken::from_str(access_token.unwrap().as_str())
.map_err(|_| ServerFnError::WrappedServerError(ErrorType::MalformedAccessToken))?;

let token_id = Uuid::parse_str(token_id.clone().as_str())
.map_err(|_| ServerFnError::WrappedServerError(ErrorType::WrongParameters))?;

let api_response = make_api_call::<GetApiTokenInfoRequest>(
ApiRequest::builder()
.path(GetApiTokenInfoPath { token_id })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::{collections::BTreeMap, rc::Rc};

use ev::MouseEvent;
use serde_json::to_string;

use crate::{prelude::*, queries::create_deployment_query};

Expand Down Expand Up @@ -46,7 +45,6 @@ pub fn CreateDeployment() -> impl IntoView {
let on_submit = move |ev: MouseEvent| {
ev.prevent_default();
if let Some(deployment_info) = deployment_info.get().convert_to_deployment_req() {
logging::log!("value: {:#?}", to_string(&deployment_info));
create_deployment_action.dispatch(deployment_info);
} else {
logging::error!("Invalid deployment info");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ pub fn ChoosePermission(
resource_permissions_new.insert(r.to_owned(), permission_types.clone());
});

logging::log!("filtered_permissions {:?}", filtered_permissions.get());
api_token.update(|token| {
if let Some(token) = token.as_mut() {
token.data.permissions.insert(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
use codee::string::FromToStringCodec;
use ev::SubmitEvent;
use leptos_use::use_cookie;
use models::api::user::CreateApiTokenRequest;

use crate::{
pages::{PermissionCard, TokenModal},
prelude::*,
};
use super::super::{utils::CreateApiTokenInfo, CreatePermissionCard};
use crate::{pages::TokenModal, prelude::*, queries::create_api_token_query};

/// The Create API Token Page
#[component]
pub fn CreateApiToken() -> impl IntoView {
let create_api_token_action = create_server_action::<CreateApiTokenFn>();
// let response = create_api_token_action.value();

let (access_token, _) = use_cookie::<String, FromToStringCodec>(constants::ACCESS_TOKEN);
let access_token_signal = move || access_token.get();
let workspace_list = create_resource(access_token_signal, move |value| async move {
list_user_workspace(value).await
});
let workspace_list = create_resource(
move || access_token.get(),
move |value| async move { list_user_workspace(value).await },
);

let create_api_token_action = create_api_token_query();
let response = create_api_token_action.value();

let api_token_info = create_rw_signal(CreateApiTokenInfo::new());

provide_context(api_token_info);

let on_submit_create = move |ev: SubmitEvent| {
ev.prevent_default();

if let Some(api_token_info) = api_token_info.get().convert_to_user_api_token() {
let request = CreateApiTokenRequest {
token: api_token_info,
};

create_api_token_action.dispatch(request);
} else {
logging::error!("Invalid Api Token Info");
}
};

view! {
{
move || match response.get() {
Expand All @@ -34,12 +51,10 @@ pub fn CreateApiToken() -> impl IntoView {
None => view! {}.into_view()
}
}
<ActionForm action={create_api_token_action}
<form on:submit={on_submit_create}
class="w-full fit-wide-screen h-full px-md \
text-white flex flex-col items-start justify-start"
>
<input type="hidden" name="access_token" prop:value={access_token}/>

<div class="flex justify-start items-center mb-md w-full">
<p class="text-md">
<strong class="text-md">"Create new API Token"</strong>
Expand Down Expand Up @@ -121,31 +136,40 @@ pub fn CreateApiToken() -> impl IntoView {
<Transition>
{
move || match workspace_list.get() {
Some(workspace_list) => {
match workspace_list {
Ok(data) => {
data.workspaces.into_iter()
.map(|workspace| view! {
<PermissionCard workspace={workspace} />
})
.collect_view()
},
Err(_) => view! {}.into_view()
}
Some(Ok(workspace_list)) => {
workspace_list.workspaces.into_iter().map(|workspace| view! {
<CreatePermissionCard workspace={workspace} />
}.into_view()).collect_view()
},
None => view! {}.into_view()
Some(Err(err)) => view! {
<div>"Error loading workspaces"</div>
}.into_view(),
None => view! {
<div>"Loading workspaces..."</div>
}.into_view()
}
}
</Transition>
</div>
</div>

<div class="w-full flex items-center justify-end py-md mt-auto">
<Link r#type={Variant::Link} to="/user/api-tokens" class="text-sm text-medium mr-sm">"BACK"</Link>
<Link should_submit={true} r#type={Variant::Button} style_variant={LinkStyleVariant::Contained} class="txt-sm txt-medium mr-sm">
<Link
r#type={Variant::Link}
to="/user/api-tokens"
class="text-sm text-medium mr-sm"
>
"BACK"
</Link>
<Link
should_submit={true}
r#type={Variant::Button}
style_variant={LinkStyleVariant::Contained}
class="txt-sm txt-medium mr-sm"
>
"Create"
</Link>
</div>
</ActionForm>
</form>
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use codee::string::FromToStringCodec;
use ev::MouseEvent;
use leptos_query::QueryResult;
use leptos_use::use_cookie;
use models::api::user::UserApiToken;
use time::{
Expand All @@ -9,11 +10,12 @@ use time::{
OffsetDateTime,
};

use crate::prelude::*;
use crate::{prelude::*, queries::get_api_token_query};

mod choose_permission;
mod create_token;
mod permission_card;
mod permission_card_create;
mod permission_item;
mod revoke_regen;
mod token_info;
Expand All @@ -23,6 +25,7 @@ pub use self::{
choose_permission::*,
create_token::*,
permission_card::*,
permission_card_create::*,
permission_item::*,
revoke_regen::*,
token_info::*,
Expand Down Expand Up @@ -87,6 +90,7 @@ fn EditApiTokenPermission() -> impl IntoView {
<PermissionCard
workspace={workspace}
/>
<div>""</div>
}
})
.collect_view()
Expand Down Expand Up @@ -123,13 +127,19 @@ pub fn EditApiToken() -> impl IntoView {
.as_ref()
.map(|param: &TokenParams| param.token_id.clone().unwrap_or_default())
.unwrap_or_default()
.parse::<Uuid>()
.unwrap()
}));

let token_info = create_resource(
move || (access_token.get(), token_id.get()),
move |(access_token, token_id)| async move { get_api_token(access_token, token_id).await },
);
let QueryResult {
data: token_info, ..
} = get_api_token_query().use_query(move || token_id.get());

// let token_info = create_resource(
// move || (access_token.get(), token_id.get()),
// move |(access_token, token_id)| async move { get_api_token(access_token,
// token_id).await }, );
//
let token_info_signal = create_rw_signal::<Option<WithId<UserApiToken>>>(None);
provide_context(ApiTokenInfo(token_info_signal));

Expand All @@ -141,7 +151,7 @@ pub fn EditApiToken() -> impl IntoView {
logging::log!("token_info_signal {:?}", token_info);
let x = update_api_token(
access_token.get_untracked(),
token_id.get_untracked(),
token_id.with_untracked(|token| token.to_string()),
Some(token_info.name.clone()),
Some(convert_offset_to_date(token_info.token_exp)),
Some(convert_offset_to_date(token_info.token_nbf)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
};

#[component]
fn ListPermissions(
pub fn ListPermissions(
/// The Permission Items
#[prop(into)]
permissions: MaybeSignal<Option<WorkspacePermission>>,
Expand Down
Loading

0 comments on commit f4df9c0

Please sign in to comment.