user_ext.rs 954 B

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