From 6c8d0e4bd4d4f4d5bb6f764550b9245ada67093a Mon Sep 17 00:00:00 2001 From: Mitchell Marino Date: Sun, 2 Apr 2023 19:05:10 -0500 Subject: [PATCH] signup func --- Cargo.toml | 2 +- src/main.rs | 49 +++++++++++++++++++++++++++++-------------------- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7bbced4..8f4f9ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,5 +13,5 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } - +sha256 = "1.1" diff --git a/src/main.rs b/src/main.rs index 821369e..3eac076 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,12 @@ use axum::{ + extract::{Query, State}, http::StatusCode, response::IntoResponse, routing::{get, post}, - Extension, Json, Router, + Json, Router, }; use serde::{Deserialize, Serialize}; +use serde_json::json; use sqlx::postgres::PgPoolOptions; use sqlx::PgPool; use std::net::SocketAddr; @@ -14,10 +16,6 @@ async fn main() { // initialize tracing tracing_subscriber::fmt::init(); - PgPool::connect( - "postgresql://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."); @@ -25,15 +23,15 @@ async fn main() { .max_connections(50) .connect(&db_url) .await - .context("could not connect to database_url")?; + .expect("could not connect to database_url"); // build our application with a route let app = Router::new() // `GET /` goes to `root` - .route("/", get(root)) + .route("/", post(root)) // `POST /users` goes to `create_user` .route("/user/signup", post(signup)) - .layer(Extension(pool)); + .with_state(pool); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` @@ -51,25 +49,36 @@ async fn root() -> &'static str { } async fn signup( - // this argument tells axum to parse the request body - // as JSON into a `CreateUser` type - Json(payload): Json, - Extension(pool): Extension, + State(pool): State, + Query(query_params): Query, ) -> impl IntoResponse { + println!("{:?}", query_params); // insert your application logic here - sqlx::query!( + let pass_hash = sha256::digest(&*query_params.password); + + let result = sqlx::query!( r#" +INSERT INTO users (username, password) +VALUES ( $1, $2 ) +RETURNING id; + "#, + query_params.username, + pass_hash.as_bytes(), + ) + .fetch_one(&pool) + .await; - "# - ); - - // this will be converted into a JSON response - // with a status code of `201 Created` - (StatusCode::CREATED, Json(user)) + 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) })), + ), + } } // the input to our `create_user` handler -#[derive(Deserialize)] +#[derive(Clone, Debug, Deserialize)] struct Signup { username: String, password: String,