signup func

This commit is contained in:
Mitchell Marino 2023-04-02 19:05:10 -05:00
parent 6a039f350a
commit 6c8d0e4bd4
2 changed files with 30 additions and 21 deletions

View File

@ -13,5 +13,5 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
tracing = "0.1" tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
sha256 = "1.1"

View File

@ -1,10 +1,12 @@
use axum::{ use axum::{
extract::{Query, State},
http::StatusCode, http::StatusCode,
response::IntoResponse, response::IntoResponse,
routing::{get, post}, routing::{get, post},
Extension, Json, Router, Json, Router,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json;
use sqlx::postgres::PgPoolOptions; use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool; use sqlx::PgPool;
use std::net::SocketAddr; use std::net::SocketAddr;
@ -14,10 +16,6 @@ async fn main() {
// initialize tracing // initialize tracing
tracing_subscriber::fmt::init(); 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") let db_url = std::env::var("DATABASE_URL")
.expect("Set `DATABASE_URL` to the url of the postgres database."); .expect("Set `DATABASE_URL` to the url of the postgres database.");
@ -25,15 +23,15 @@ async fn main() {
.max_connections(50) .max_connections(50)
.connect(&db_url) .connect(&db_url)
.await .await
.context("could not connect to database_url")?; .expect("could not connect to database_url");
// build our application with a route // build our application with a route
let app = Router::new() let app = Router::new()
// `GET /` goes to `root` // `GET /` goes to `root`
.route("/", get(root)) .route("/", post(root))
// `POST /users` goes to `create_user` // `POST /users` goes to `create_user`
.route("/user/signup", post(signup)) .route("/user/signup", post(signup))
.layer(Extension(pool)); .with_state(pool);
// run our app with hyper // run our app with hyper
// `axum::Server` is a re-export of `hyper::Server` // `axum::Server` is a re-export of `hyper::Server`
@ -51,25 +49,36 @@ async fn root() -> &'static str {
} }
async fn signup( async fn signup(
// this argument tells axum to parse the request body State(pool): State<PgPool>,
// as JSON into a `CreateUser` type Query(query_params): Query<Signup>,
Json(payload): Json<Signup>,
Extension(pool): Extension<PgPool>,
) -> impl IntoResponse { ) -> impl IntoResponse {
println!("{:?}", query_params);
// insert your application logic here // insert your application logic here
sqlx::query!( let pass_hash = sha256::digest(&*query_params.password);
let result = sqlx::query!(
r#" r#"
INSERT INTO users (username, password)
VALUES ( $1, $2 )
RETURNING id;
"#,
query_params.username,
pass_hash.as_bytes(),
)
.fetch_one(&pool)
.await;
"# match result {
); Ok(record) => (StatusCode::CREATED, Json(json!({"id": record.id}))),
Err(err) => (
// this will be converted into a JSON response StatusCode::INTERNAL_SERVER_ERROR,
// with a status code of `201 Created` Json(json!({ "error": format!("Error signing up: {}", err) })),
(StatusCode::CREATED, Json(user)) ),
}
} }
// the input to our `create_user` handler // the input to our `create_user` handler
#[derive(Deserialize)] #[derive(Clone, Debug, Deserialize)]
struct Signup { struct Signup {
username: String, username: String,
password: String, password: String,