Skip to content

Commit 3e195e4

Browse files
committed
feat: add authenticated snack creation
1 parent 1aaf58a commit 3e195e4

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

src/auth/user.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ impl<'r> FromRequest<'r> for AuthenticatedUser {
2525
match token {
2626
Some(token) if token.starts_with("Bearer ") => {
2727
let token = &token[7..];
28-
let decoding_key = DecodingKey::from_secret("your_secret_key".as_ref());
28+
let decoding_key = DecodingKey::from_secret("SECRET".as_ref());
2929
match decode::<Claims>(token, &decoding_key, &Validation::new(Algorithm::HS256)) {
3030
Ok(token_data) => {
3131
let mut conn = crate::db::establish_connection();

src/models/snack.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,35 @@ pub struct Snack {
1818
pub created_at: NaiveDateTime,
1919
pub updated_at: NaiveDateTime,
2020
pub user_id: i32,
21-
2221
}
2322

24-
#[derive(Insertable, Deserialize)]
23+
#[derive(Insertable)]
2524
#[diesel(table_name = crate::schema::snacks)]
2625
pub struct NewSnack {
2726
pub name: String,
2827
pub category: String,
2928
#[diesel(sql_type = Numeric)]
3029
pub price: Decimal,
3130
pub image_url: String,
31+
pub user_id: i32,
32+
}
33+
34+
#[derive(Deserialize)]
35+
pub struct CreateSnackRequest {
36+
pub name: String,
37+
pub category: String,
38+
pub price: Decimal,
39+
pub image_url: String,
3240
}
3341

42+
impl CreateSnackRequest {
43+
pub fn into_new_snack(self, user_id: i32) -> NewSnack {
44+
NewSnack {
45+
name: self.name,
46+
category: self.category,
47+
price: self.price,
48+
image_url: self.image_url,
49+
user_id,
50+
}
51+
}
52+
}

src/routes/snack.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
use crate::auth::user::AuthenticatedUser;
12
use crate::db;
2-
use crate::models::snack::{NewSnack, Snack};
3+
use crate::models::snack::{CreateSnackRequest, Snack};
34
use crate::schema::snacks::dsl::snacks;
45
use diesel::prelude::*;
56
use rocket::http::Status;
@@ -16,10 +17,10 @@ pub struct UpdateSnack {
1617
}
1718

1819
#[post("/snack", data = "<snack_data>")]
19-
pub fn create_snack(snack_data: Json<NewSnack>) -> Result<Json<Snack>, Status> {
20-
let snack = snack_data.into_inner();
21-
20+
pub fn create_snack(snack_data: Json<CreateSnackRequest>, user: AuthenticatedUser) -> Result<Json<Snack>, Status> {
2221
let mut conn = db::establish_connection();
22+
let snack = snack_data.into_inner().into_new_snack(user.0.id);
23+
2324

2425
diesel::insert_into(snacks)
2526
.values(&snack)

0 commit comments

Comments
 (0)