From 890c690007d55702d5eea9964e38e600bbc3dd15 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Fri, 9 Nov 2018 15:24:39 +0100 Subject: 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`. --- license-generator/src/lib.rs | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) (limited to 'license-generator/src') 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, } 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(()) } -- cgit v1.2.3