mongodb / bson-rust

Encoding and decoding support for BSON in Rust
MIT License
400 stars 132 forks source link

Encode and Decode binary data #79

Closed greenpdx closed 7 years ago

greenpdx commented 7 years ago

I am trying to insert and find sodiumoxide cryptographic material in to a mongo database. Right now I encoding and decoding the crypto material in to base64. When I read a document and try to convert it to a rust structure, I have three unwrap() for each item.

I created from method, but the problem with this is I need to return Result<TmpLogin, Error> impl From for TmpLogin {

Nonce::from_slice(&decode(doc.get_str("nonce").unwrap()).unwrap()).unwrap(),

What is the code snippet that would let non = box_::gen_nonce(); let mut buf = Vec::new(); non.serialize(&mut rmp_serde::Serializer::new(&mut buf)).unwrap();

let src = (BinarySubtype::Generic, buf);
let tst = bson::????????(&src);

then later doc! { "nonce" => tst } I am new at rust so any help would be appreciated

zonyitoo commented 7 years ago

cc @kyeah

greenpdx commented 7 years ago

I worked out a way that is a little cleaner

` let mut buf = Vec::new(); sess.serialize(&mut rmp_serde::Serializer::new(&mut buf)).unwrap(); let src = (BinarySubtype::UserDefined(129), buf.clone());

  coll.insert_one(doc!{"sess" => src, "addr" => addr, "ts" => ts, "prekey" => fast, "nonce" => hello, "role" => 0, "salt" => Null }, None).unwrap();

Now I define 129 and session, I am still working on decoding. `

greenpdx commented 7 years ago

I hope I get and answer to this question. to want to convert a struct to document. I want to pass a value of a field to the document. I have tried to do something like this. But it does not like tl.FIELD, How do I pass a field to the doc! macro?

struct TmpLogin {
  sess: String,  // client session base64 encoded sodiumoxide PublicKey
  addr: String,  // remote address for hacking issues
  start: i64,   // session start time
  last: i64,   // last access
  prekey: PrecomputedKey,
  nonce: String,  // session nonce base64 encoded
  salt: Option<String>,  // The ID of the user, only decode during verification
  role: i32,
}

impl From<TmpLogin> for Document {
  fn from(tl: TmpLogin) -> Document {
    let last = DateTime::timestamp(&Utc::now());
    let doc = doc! {
      "sess" => tl.sess,
      "addr" => tl.addr,
      "start" => tl.start,
      "last" => last,
      "prekey" =>   BINARY FIELD,
      "nonce" => tl.nonce,
      "salt" =>  tl.salt,
      "role" => tl.role,
    };
    doc
  }
}
saghm commented 7 years ago

Can you be more specific than "does not like"? Is it a parser error due to the macro not yielding valid code? Is it a type error due to the field not being implicitly converted to BSON? Does it compile, but not give the result you expect when run?

kyeah commented 7 years ago

hey @greenpdx, IIRC the doc macro doesn't support .s in open value patterns at the moment; you may want to try wrapping your values in parens.

    let doc = doc! {
      "sess" => (tl.sess),
      "addr" => (tl.addr),
      "start" => (tl.start),
      "last" => last,
      "prekey" =>   BINARY FIELD,
      "nonce" => (tl.nonce),
      "salt" =>  (tl.salt),
      "role" => (tl.role),
    };
kyeah commented 7 years ago

note that if PrecomputedKey implements serde::ser::Serialize and serde::de::Deserialize, you can derive the traits for TmpLogin and utilize our to_bson/from_bson helpers:

#[derive(Serialize, Deserialize)]
struct TmpLogin {
  sess: String,  // client session base64 encoded sodiumoxide PublicKey
  addr: String,  // remote address for hacking issues
  start: i64,   // session start time
  last: i64,   // last access
  prekey: PrecomputedKey,
  nonce: String,  // session nonce base64 encoded
  salt: Option<String>,  // The ID of the user, only decode during verification
  role: i32,
}

impl From<TmpLogin> for Document {
  fn from(tl: TmpLogin) -> Document {
    let last = DateTime::timestamp(&Utc::now());

    bson::to_bson(&tl)?
      .as_document()
      .map(|doc| {
        doc.insert("last", last);
        doc
      })
      .unwrap()
  }
}
greenpdx commented 7 years ago

Thank you the () works now. so now I have pub fn to_bson(&self) -> Document { let doc = doc! { "email" => (&self.email), "fname" => (&self.fname), "lname" => (&self.lname), "salt" => (&self.salt), "pass" => (&self.pass), "age" => (self.age as i32), "wealth" => (self.wealth as i32), "social" => (self.social as i32), "fiscal" => (self.fiscal as i32), "id" => (&self.id), "first" => (self.first), "last" => (self.last) }; doc }

Thanks