utils.rs 944 B

1234567891011121314151617181920212223242526272829
  1. use bcrypt::{hash, verify, DEFAULT_COST};
  2. use flowy_net::errors::{ErrorCode, ServerError};
  3. #[allow(dead_code)]
  4. pub fn uuid() -> String { uuid::Uuid::new_v4().to_string() }
  5. pub fn hash_password(plain: &str) -> Result<String, ServerError> {
  6. let hashing_cost = std::env::var("HASH_COST")
  7. .ok()
  8. .and_then(|c| c.parse().ok())
  9. .unwrap_or(DEFAULT_COST);
  10. hash(plain, hashing_cost).map_err(|e| ServerError::internal().context(e))
  11. }
  12. // The Source is the password user enter. The hash is the source after hashing.
  13. // let source = "123";
  14. // let hash = hash_password(source).unwrap();
  15. //
  16. // verify_password(source, hash)
  17. pub fn verify_password(source: &str, hash: &str) -> Result<bool, ServerError> {
  18. match verify(source, hash) {
  19. Ok(true) => Ok(true),
  20. _ => Err(ServerError::new(
  21. "Username and password don't match".to_string(),
  22. ErrorCode::PasswordNotMatch,
  23. )),
  24. }
  25. }