diff options
author | Teddy Wing | 2018-11-09 15:24:39 +0100 |
---|---|---|
committer | Teddy Wing | 2018-11-09 15:37:43 +0100 |
commit | 890c690007d55702d5eea9964e38e600bbc3dd15 (patch) | |
tree | abf7689d1e7d8b9baeec96dca1e0ce8c6f80f97f /license-generator/src | |
parent | 0a11429d59d0955ad19d798506b410cb7453b76e (diff) | |
download | dome-key-web-890c690007d55702d5eea9964e38e600bbc3dd15.tar.bz2 |
Purchaser: Add `generate_secret()` method
This new method generates a secret, which is a SHA1 digest of the
purchaser's name, email, and a random integer.
In order to use the `hexdigest()` method in the 'sha1' crate, I needed
to add the feature `std`
(https://docs.rs/sha1/0.6.0/sha1/struct.Sha1.html#method.hexdigest).
Needed to change the `secret` field to a `String` because otherwise the
generated digest string doesn't have a long enough lifetime to assign to
it.
Update `with_secret()` to use the new `String` type.
Update `insert()` to correctly handle the `Option` in `secret`.
Diffstat (limited to 'license-generator/src')
-rw-r--r-- | license-generator/src/lib.rs | 42 |
1 files changed, 33 insertions, 9 deletions
diff --git a/license-generator/src/lib.rs b/license-generator/src/lib.rs index 9f73f6b..cc39cdb 100644 --- a/license-generator/src/lib.rs +++ b/license-generator/src/lib.rs @@ -1,6 +1,8 @@ #[macro_use] extern crate error_chain; extern crate mysql; +extern crate rand; +extern crate sha1; mod errors { use mysql; @@ -17,7 +19,7 @@ use errors::*; struct Purchaser<'a> { name: &'a str, email: &'a str, - secret: Option<&'a str>, + secret: Option<String>, } impl<'a> Purchaser<'a> { @@ -29,11 +31,20 @@ impl<'a> Purchaser<'a> { } } - fn with_secret(mut self, secret: &'a str) -> Self { + fn with_secret(mut self, secret: String) -> Self { self.secret = Some(secret); self } + fn generate_secret(&mut self) { + let random: usize = rand::random(); + + let source = format!("{}{}{}", self.name, self.email, random); + let digest = sha1::Sha1::from(source).hexdigest(); + + self.secret = Some(digest); + } + fn insert(&self, cx: &mut mysql::Conn) -> Result<()> { let mut tx = cx.start_transaction( false, // consistent_snapshot @@ -41,13 +52,26 @@ impl<'a> Purchaser<'a> { None, // readonly )?; - tx.prep_exec(" - INSERT INTO purchasers - (name, email, secret) - VALUES - (?, ?, ?)", - (self.name, self.email, self.secret), - )?; + match self.secret { + Some(ref s) => { + tx.prep_exec(" + INSERT INTO purchasers + (name, email, secret) + VALUES + (?, ?, ?)", + (self.name, self.email, s), + )?; + }, + None => { + tx.prep_exec(" + INSERT INTO purchasers + (name, email) + VALUES + (?, ?)", + (self.name, self.email), + )?; + }, + } Ok(()) } |