diff --git a/Cargo.toml b/Cargo.toml index 8f4f9ed..52cd3e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,4 +14,4 @@ serde_json = "1.0" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } sha256 = "1.1" - +jsonwebtoken = "8.3" diff --git a/src/main.rs b/src/main.rs index 49f08ce..8334360 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,8 @@ async fn main() { // initialize tracing tracing_subscriber::fmt::init(); + // Ex. + // export DATABASE_URL="postgres://school_app_api_user:school_app_api_pass@localhost/school_app_api" let db_url = std::env::var("DATABASE_URL") .expect("Set `DATABASE_URL` to the url of the postgres database."); @@ -49,7 +51,6 @@ async fn root() -> &'static str { } async fn signup(State(pool): State, Json(signup): Json) -> impl IntoResponse { - println!("{:?}", signup); // insert your application logic here let pass_hash = sha256::digest(&*signup.password); @@ -67,10 +68,27 @@ RETURNING id; match result { Ok(record) => (StatusCode::CREATED, Json(json!({"id": record.id}))), - Err(err) => ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(json!({ "error": format!("Error signing up: {}", err) })), - ), + Err(err) => { + // See if we get an error for a duplicate usename + if let sqlx::Error::Database(database_err) = &err { + if let Some(err_code) = database_err.code() { + if err_code == "23505" { + return ( + StatusCode::BAD_REQUEST, + Json(json!({ + "error": format!("username '{}' is taken.", signup.username) + })), + ); + } + } + } + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ + "error": format!("Unknown error signing up: {}", err) + })), + ) + } } }