token_storage.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use std::fs::File;
  2. use std::io::{Read, Write};
  3. use std::path::Path;
  4. use anyhow::Result;
  5. use cdk::mint_url::MintUrl;
  6. use serde::{Deserialize, Serialize};
  7. #[derive(Debug, Serialize, Deserialize)]
  8. pub struct TokenData {
  9. pub mint_url: String,
  10. pub access_token: String,
  11. pub refresh_token: String,
  12. }
  13. /// Stores authentication tokens in the work directory
  14. pub async fn save_tokens(
  15. work_dir: &Path,
  16. mint_url: &MintUrl,
  17. access_token: &str,
  18. refresh_token: &str,
  19. ) -> Result<()> {
  20. let token_data = TokenData {
  21. mint_url: mint_url.to_string(),
  22. access_token: access_token.to_string(),
  23. refresh_token: refresh_token.to_string(),
  24. };
  25. let json = serde_json::to_string_pretty(&token_data)?;
  26. let file_path = work_dir.join(format!(
  27. "auth_tokens_{}",
  28. mint_url.to_string().replace("/", "_")
  29. ));
  30. let mut file = File::create(file_path)?;
  31. file.write_all(json.as_bytes())?;
  32. Ok(())
  33. }
  34. /// Gets authentication tokens from the work directory
  35. pub async fn get_token_for_mint(work_dir: &Path, mint_url: &MintUrl) -> Result<Option<TokenData>> {
  36. let file_path = work_dir.join(format!(
  37. "auth_tokens_{}",
  38. mint_url.to_string().replace("/", "_")
  39. ));
  40. if !file_path.exists() {
  41. return Ok(None);
  42. }
  43. let mut file = File::open(file_path)?;
  44. let mut contents = String::new();
  45. file.read_to_string(&mut contents)?;
  46. let token_data: TokenData = serde_json::from_str(&contents)?;
  47. if token_data.mint_url == mint_url.to_string() {
  48. Ok(Some(token_data))
  49. } else {
  50. Ok(None)
  51. }
  52. }