api: validate email against regex

This commit is contained in:
Peter Cai 2020-02-22 16:44:43 +08:00
parent a38c13f21c
commit 565a6008f8
No known key found for this signature in database
GPG Key ID: 71F5FB4E4F3FD54F
4 changed files with 14 additions and 1 deletions

1
Cargo.lock generated
View File

@ -1080,6 +1080,7 @@ dependencies = [
"diesel_migrations",
"dotenv",
"lazy_static",
"regex 1.3.4",
"rocket",
"rocket_contrib",
"rocket_cors",

View File

@ -16,4 +16,5 @@ serde = { version = "1.0.104", features = ["derive"] }
scrypt = "0.2.0"
uuid = { version = "0.8", features = ["v4"] }
chrono = "0.4"
serde_json = "1.0"
serde_json = "1.0"
regex = "1"

View File

@ -9,6 +9,12 @@ use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize};
use std::vec::Vec;
lazy_static! {
static ref EMAIL_RE: regex::Regex =
regex::Regex::new(r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})")
.unwrap();
}
pub fn routes() -> impl Into<Vec<rocket::Route>> {
routes![
auth,
@ -56,6 +62,10 @@ struct AuthResult {
#[post("/auth", format = "json", data = "<new_user>")]
fn auth(db: DbConn, new_user: Json<user::NewUser>) -> Custom<JsonResp<AuthResult>> {
if !EMAIL_RE.is_match(&new_user.email) {
return error_resp(Status::BadRequest, vec!["Invalid email address".into()]);
}
match user::User::create(&db.0, &new_user) {
Ok(_) => _sign_in(db, &new_user.email, &new_user.password),
Err(user::UserOpError(e)) =>

View File

@ -1,5 +1,6 @@
#![feature(proc_macro_hygiene, decl_macro)]
extern crate regex;
#[macro_use]
extern crate rocket;
#[macro_use]