user.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. use serde::{Serialize, Deserialize};
  2. use bson::{oid::ObjectId, DateTime, doc};
  3. use mongodb::{Collection, error::Error};
  4. use crate::app_error::AppError;
  5. #[derive(Debug, Serialize, Deserialize)]
  6. pub struct User {
  7. #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
  8. pub _id: Option<ObjectId>,
  9. pub email: String,
  10. pub password_hash: String,
  11. pub password_salt: String,
  12. pub created_at: bson::DateTime
  13. }
  14. #[derive(Debug, Deserialize)]
  15. pub struct NewUserInput {
  16. pub email: String,
  17. pub password_hash: String,
  18. pub password_salt: String
  19. }
  20. impl User {
  21. pub async fn insert(collection: &Collection<User>, input: NewUserInput) -> Result<(), Error> {
  22. let user = User {
  23. _id: None,
  24. email: input.email,
  25. password_hash: input.password_hash,
  26. password_salt: input.password_salt,
  27. created_at: DateTime::now()
  28. };
  29. collection.insert_one(user, None).await?;
  30. Ok(())
  31. }
  32. pub async fn find_by_email(collection: &Collection<User>, email: &str) -> Result<User, AppError> {
  33. match collection.find_one(doc!{"email": email}, None).await {
  34. Ok(Some(u)) => Ok(u),
  35. Ok(None) => Err(AppError::invalid_input("No user with this email address")),
  36. Err(e) => Err(AppError::Database(e.into()))
  37. }
  38. }
  39. pub async fn find_by_id(collection: &Collection<User>, user_id: String) -> Result<User, AppError> {
  40. let object_id = ObjectId::parse_str(id_str)?;
  41. match collection.find_one(doc!{"_id", object_id}) {
  42. Ok(Some(u)) => Ok(u),
  43. Ok(None) => Err(AppError::auth),
  44. Err(e) => Err(AppError::Database(e.into()))
  45. }
  46. }
  47. }