logged_user.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. use crate::entities::token::{Claim, Token};
  2. use chrono::{DateTime, Utc};
  3. use dashmap::DashMap;
  4. use flowy_net::errors::ServerError;
  5. use lazy_static::lazy_static;
  6. lazy_static! {
  7. pub static ref AUTHORIZED_USERS: AuthorizedUsers = AuthorizedUsers::new();
  8. }
  9. #[derive(Debug, PartialEq, Eq, Hash, Clone)]
  10. pub struct LoggedUser {
  11. pub email: String,
  12. }
  13. impl std::convert::From<Claim> for LoggedUser {
  14. fn from(c: Claim) -> Self {
  15. Self {
  16. email: c.get_email(),
  17. }
  18. }
  19. }
  20. impl std::convert::From<String> for LoggedUser {
  21. fn from(email: String) -> Self { Self { email } }
  22. }
  23. impl LoggedUser {
  24. pub fn from_token(token: String) -> Result<Self, ServerError> {
  25. let user: LoggedUser = Token::decode_token(&token.into())?.into();
  26. match AUTHORIZED_USERS.is_authorized(&user) {
  27. true => Ok(user),
  28. false => Err(ServerError::unauthorized()),
  29. }
  30. }
  31. }
  32. // use futures::{
  33. // executor::block_on,
  34. // future::{ready, Ready},
  35. // };
  36. // impl FromRequest for LoggedUser {
  37. // type Config = ();
  38. // type Error = ServerError;
  39. // type Future = Ready<Result<Self, Self::Error>>;
  40. //
  41. // fn from_request(_req: &HttpRequest, payload: &mut Payload) ->
  42. // Self::Future { let result: Result<SignOutParams, ServerError> =
  43. // block_on(parse_from_dev_payload(payload)); match result {
  44. // Ok(params) => ready(LoggedUser::from_token(params.token)),
  45. // Err(e) => ready(Err(e)),
  46. // }
  47. // }
  48. // }
  49. #[derive(Clone, Debug, Copy)]
  50. enum AuthStatus {
  51. Authorized(DateTime<Utc>),
  52. NotAuthorized,
  53. }
  54. pub struct AuthorizedUsers(DashMap<LoggedUser, AuthStatus>);
  55. impl AuthorizedUsers {
  56. pub fn new() -> Self { Self(DashMap::new()) }
  57. pub fn is_authorized(&self, user: &LoggedUser) -> bool {
  58. match self.0.get(user) {
  59. None => false,
  60. Some(status) => match *status {
  61. AuthStatus::Authorized(last_time) => {
  62. let current_time = Utc::now();
  63. (current_time - last_time).num_days() < 5
  64. },
  65. AuthStatus::NotAuthorized => false,
  66. },
  67. }
  68. }
  69. pub fn store_auth(&self, user: LoggedUser, is_auth: bool) -> Result<(), ServerError> {
  70. let current_time = Utc::now();
  71. let status = if is_auth {
  72. AuthStatus::Authorized(current_time)
  73. } else {
  74. AuthStatus::NotAuthorized
  75. };
  76. self.0.insert(user, status);
  77. Ok(())
  78. }
  79. }