mirror of
https://github.com/LukeMathWalker/zero-to-production.git
synced 2025-01-31 11:02:29 +00:00
Generate random token.
This commit is contained in:
parent
9a3420073c
commit
a8f1bc9024
3 changed files with 27 additions and 3 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
@ -2655,10 +2655,12 @@ dependencies = [
|
|||
"linkify",
|
||||
"quickcheck",
|
||||
"quickcheck_macros",
|
||||
"rand 0.8.3",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde-aux",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sqlx",
|
||||
"tokio",
|
||||
"tracing",
|
||||
|
|
|
@ -29,6 +29,8 @@ tracing-actix-web = "0.3.0-beta.2"
|
|||
serde-aux = "1.0.1"
|
||||
unicode-segmentation = "1.7.1"
|
||||
validator = "0.12.0"
|
||||
rand = { version = "0.8", features=["std_rng"] }
|
||||
sha2 = { version = "0.9" }
|
||||
|
||||
[dev-dependencies]
|
||||
lazy_static = "1.4.0"
|
||||
|
|
|
@ -3,6 +3,8 @@ use crate::email_client::EmailClient;
|
|||
use crate::startup::ApplicationBaseUrl;
|
||||
use actix_web::{web, HttpResponse};
|
||||
use chrono::Utc;
|
||||
use rand::distributions::Alphanumeric;
|
||||
use rand::{thread_rng, Rng};
|
||||
use sqlx::PgPool;
|
||||
use std::convert::TryInto;
|
||||
use uuid::Uuid;
|
||||
|
@ -45,10 +47,25 @@ pub async fn subscribe(
|
|||
.await
|
||||
.map_err(|_| HttpResponse::InternalServerError().finish())?;
|
||||
// We are swallowing the error for the time being.
|
||||
let _ = send_confirmation_email(&email_client, new_subscriber, &base_url.0, "mytoken").await;
|
||||
let subscription_token = generate_subscription_token();
|
||||
let _ = send_confirmation_email(
|
||||
&email_client,
|
||||
new_subscriber,
|
||||
&base_url.0,
|
||||
&subscription_token,
|
||||
)
|
||||
.await;
|
||||
Ok(HttpResponse::Ok().finish())
|
||||
}
|
||||
|
||||
fn generate_subscription_token() -> String {
|
||||
let mut rng = thread_rng();
|
||||
std::iter::repeat_with(|| rng.sample(Alphanumeric))
|
||||
.map(char::from)
|
||||
.take(25)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "Send a confirmation email to a new subscriber",
|
||||
skip(email_client, new_subscriber, base_url, subscription_token)
|
||||
|
@ -57,9 +74,12 @@ pub async fn send_confirmation_email(
|
|||
email_client: &EmailClient,
|
||||
new_subscriber: NewSubscriber,
|
||||
base_url: &str,
|
||||
subscription_token: &str
|
||||
subscription_token: &str,
|
||||
) -> Result<(), reqwest::Error> {
|
||||
let confirmation_link = format!("{}/subscriptions/confirm?subscription_token={}", base_url, subscription_token);
|
||||
let confirmation_link = format!(
|
||||
"{}/subscriptions/confirm?subscription_token={}",
|
||||
base_url, subscription_token
|
||||
);
|
||||
let plain_body = format!(
|
||||
"Welcome to our newsletter!\nVisit {} to confirm your subscription.",
|
||||
confirmation_link
|
||||
|
|
Loading…
Reference in a new issue