Răsfoiți Sursa

Create the base route for creating a new user.

Lee Morgan 1 an în urmă
părinte
comite
aa55c83fb1

Fișier diff suprimat deoarece este prea mare
+ 606 - 24
Cargo.lock


+ 4 - 0
Cargo.toml

@@ -7,3 +7,7 @@ edition = "2024"
 actix-web = "4"
 actix-files = "0.6"
 tokio = {version = "1", features = ["full"]}
+serde = {version = "1", features = ["derive"]}
+mongodb = {version = "2.8.0", features = ["tokio-runtime"]}
+bson = "2.8.0"
+uuid = {version = "1", features = ["v4"]}

+ 19 - 0
bruno/Suma/User/Create.bru

@@ -0,0 +1,19 @@
+meta {
+  name: Create
+  type: http
+  seq: 1
+}
+
+post {
+  url: http://localhost:8000/api/user
+  body: json
+  auth: none
+}
+
+body:json {
+  {
+    "email": "lee@leemorgan.dev",
+    "password_hash": "something",
+    "password_salt": "Something else"
+  }
+}

+ 9 - 0
bruno/Suma/bruno.json

@@ -0,0 +1,9 @@
+{
+  "version": "1",
+  "name": "Suma",
+  "type": "collection",
+  "ignore": [
+    "node_modules",
+    ".git"
+  ]
+}

+ 1 - 0
src/controllers/mod.rs

@@ -0,0 +1 @@
+pub mod user;

+ 19 - 0
src/controllers/user.rs

@@ -0,0 +1,19 @@
+use actix_web::{post, web, HttpResponse, Responder};
+use mongodb::Database;
+use crate::models::user::{User, NewUserInput};
+
+#[post("/api/user")]
+pub async fn create(
+    db: web::Data<Database>,
+    payload: web::Json<NewUserInput>
+) -> impl Responder {
+    let users = db.collection::<User>("users");
+
+    match User::insert(&users, payload.into_inner()).await {
+        Ok(id) => HttpResponse::Ok().body("{'success': 'true'}"),
+        Err(e) => {
+            eprintln!("Error: {:?}", e);
+            HttpResponse::InternalServerError().body("Failed to create user")
+        }
+    }
+}

+ 14 - 2
src/main.rs

@@ -1,21 +1,33 @@
-use actix_web::{App, HttpServer};
+use actix_web::{App, HttpServer, web};
 use std::sync::OnceLock;
+use mongodb::{Client, Database};
 
 mod routes;
+mod models;
+mod controllers;
 
 pub static HTML: OnceLock<String> = OnceLock::new();
 
 #[actix_web::main]
 async fn main() -> std::io::Result<()> {
+    let db = connect_db("mongodb://localhost:27017", "suma").await;
+
     let html = std::fs::read_to_string("src/views/build.html")
         .expect("Failed to read HTML");
     HTML.set(html).expect("Failed to set global HTML");
 
-    HttpServer::new(|| {
+    HttpServer::new(move || {
         App::new()
+            .app_data(web::Data::new(db.clone()))
             .configure(routes::other::config)
+            .configure(routes::user::config)
     })
         .bind(("127.0.0.1", 8000))?
         .run()
         .await
 }
+
+pub async fn connect_db(uri: &str, db_name: &str) -> Database {
+    let client = Client::with_uri_str(uri).await.expect("Failed to connect to database");
+    client.database(db_name)
+}

+ 1 - 0
src/models/mod.rs

@@ -0,0 +1 @@
+pub mod user;

+ 35 - 0
src/models/user.rs

@@ -0,0 +1,35 @@
+use serde::{Serialize, Deserialize};
+use bson::{oid::ObjectId, DateTime, doc};
+use mongodb::{Collection, error::Error};
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct User {
+    #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
+    pub _id: Option<ObjectId>,
+    pub email: String,
+    pub password_hash: String,
+    pub password_salt: String,
+    pub created_at: bson::DateTime
+}
+
+#[derive(Debug, Deserialize)]
+pub struct NewUserInput {
+    pub email: String,
+    pub password_hash: String,
+    pub password_salt: String
+}
+
+impl User {
+    pub async fn insert(collection: &Collection<User>, input: NewUserInput) -> Result<ObjectId, Error> {
+        let user = User {
+            _id: None,
+            email: input.email,
+            password_hash: input.password_hash,
+            password_salt: input.password_salt,
+            created_at: DateTime::now()
+        };
+
+        let result = collection.insert_one(user, None).await?;
+        Ok(result.inserted_id.as_object_id().unwrap())
+    }
+}

+ 1 - 0
src/routes/mod.rs

@@ -1 +1,2 @@
 pub mod other;
+pub mod user;

+ 6 - 0
src/routes/user.rs

@@ -0,0 +1,6 @@
+use actix_web::web;
+use crate::controllers::user::create;
+
+pub fn config(cfg: &mut web::ServiceConfig) {
+    cfg.service(create);
+}

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff