| 1 | module main |
| 2 | |
| 3 | import veb |
| 4 | import encoding.base64 |
| 5 | import json |
| 6 | |
| 7 | @['/controller/products'; get] |
| 8 | pub fn (mut app App) controller_get_all_products(mut ctx Context) veb.Result { |
| 9 | token := ctx.req.header.get_custom('token') or { '' } |
| 10 | |
| 11 | if !auth_verify(token) { |
| 12 | ctx.res.set_status(.unauthorized) |
| 13 | return ctx.text('Not valid token') |
| 14 | } |
| 15 | |
| 16 | jwt_payload_stringify := base64.url_decode_str(token.split('.')[1]) |
| 17 | |
| 18 | jwt_payload := json.decode(JwtPayload, jwt_payload_stringify) or { |
| 19 | ctx.res.set_status(.internal_server_error) |
| 20 | return ctx.text('jwt decode error') |
| 21 | } |
| 22 | |
| 23 | user_id := jwt_payload.sub |
| 24 | |
| 25 | response := app.service_get_all_products_from(user_id.int()) or { |
| 26 | ctx.res.set_status(.bad_request) |
| 27 | return ctx.text('${err}') |
| 28 | } |
| 29 | return ctx.json(response) |
| 30 | } |
| 31 | |
| 32 | @['/controller/product/create'; post] |
| 33 | pub fn (mut app App) controller_create_product(mut ctx Context, product_name string) veb.Result { |
| 34 | if product_name == '' { |
| 35 | ctx.res.set_status(.bad_request) |
| 36 | return ctx.text('product name cannot be empty') |
| 37 | } |
| 38 | |
| 39 | token := ctx.req.header.get_custom('token') or { '' } |
| 40 | |
| 41 | if !auth_verify(token) { |
| 42 | ctx.res.set_status(.unauthorized) |
| 43 | return ctx.text('Not valid token') |
| 44 | } |
| 45 | |
| 46 | jwt_payload_stringify := base64.url_decode_str(token.split('.')[1]) |
| 47 | |
| 48 | jwt_payload := json.decode(JwtPayload, jwt_payload_stringify) or { |
| 49 | ctx.res.set_status(.internal_server_error) |
| 50 | return ctx.text('jwt decode error') |
| 51 | } |
| 52 | |
| 53 | user_id := jwt_payload.sub |
| 54 | |
| 55 | app.service_add_product(product_name, user_id.int()) or { |
| 56 | ctx.res.set_status(.bad_request) |
| 57 | return ctx.text('error: ${err}') |
| 58 | } |
| 59 | ctx.res.set_status(.created) |
| 60 | return ctx.text('product created successfully') |
| 61 | } |
| 62 | |