File tree Expand file tree Collapse file tree 3 files changed +27
-7
lines changed Expand file tree Collapse file tree 3 files changed +27
-7
lines changed Original file line number Diff line number Diff line change @@ -25,7 +25,7 @@ impl<'r> FromRequest<'r> for AuthenticatedUser {
25
25
match token {
26
26
Some ( token) if token. starts_with ( "Bearer " ) => {
27
27
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 ( ) ) ;
29
29
match decode :: < Claims > ( token, & decoding_key, & Validation :: new ( Algorithm :: HS256 ) ) {
30
30
Ok ( token_data) => {
31
31
let mut conn = crate :: db:: establish_connection ( ) ;
Original file line number Diff line number Diff line change @@ -18,16 +18,35 @@ pub struct Snack {
18
18
pub created_at : NaiveDateTime ,
19
19
pub updated_at : NaiveDateTime ,
20
20
pub user_id : i32 ,
21
-
22
21
}
23
22
24
- #[ derive( Insertable , Deserialize ) ]
23
+ #[ derive( Insertable ) ]
25
24
#[ diesel( table_name = crate :: schema:: snacks) ]
26
25
pub struct NewSnack {
27
26
pub name : String ,
28
27
pub category : String ,
29
28
#[ diesel( sql_type = Numeric ) ]
30
29
pub price : Decimal ,
31
30
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 ,
32
40
}
33
41
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
+ }
Original file line number Diff line number Diff line change
1
+ use crate :: auth:: user:: AuthenticatedUser ;
1
2
use crate :: db;
2
- use crate :: models:: snack:: { NewSnack , Snack } ;
3
+ use crate :: models:: snack:: { CreateSnackRequest , Snack } ;
3
4
use crate :: schema:: snacks:: dsl:: snacks;
4
5
use diesel:: prelude:: * ;
5
6
use rocket:: http:: Status ;
@@ -16,10 +17,10 @@ pub struct UpdateSnack {
16
17
}
17
18
18
19
#[ 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 > {
22
21
let mut conn = db:: establish_connection ( ) ;
22
+ let snack = snack_data. into_inner ( ) . into_new_snack ( user. 0 . id ) ;
23
+
23
24
24
25
diesel:: insert_into ( snacks)
25
26
. values ( & snack)
You can’t perform that action at this time.
0 commit comments