1
+ package com .itbulls .learnit .onlinestore .web .owasp .bopla ;
2
+
3
+ import static com .itbulls .learnit .onlinestore .persistence .dto .RoleDto .ADMIN_ROLE_NAME ;
4
+
5
+ import java .io .BufferedReader ;
6
+ import java .io .IOException ;
7
+ import java .util .Base64 ;
8
+
9
+ import com .google .gson .Gson ;
10
+ import com .itbulls .learnit .onlinestore .core .facades .PurchaseFacade ;
11
+ import com .itbulls .learnit .onlinestore .core .facades .UserFacade ;
12
+ import com .itbulls .learnit .onlinestore .core .facades .impl .DefaultPurchaseFacade ;
13
+ import com .itbulls .learnit .onlinestore .core .facades .impl .DefaultUserFacade ;
14
+ import com .itbulls .learnit .onlinestore .persistence .dto .PurchaseDto ;
15
+ import com .itbulls .learnit .onlinestore .persistence .dto .converters .PurchaseDtoToPurchaseConverter ;
16
+ import com .itbulls .learnit .onlinestore .persistence .enteties .Purchase ;
17
+ import com .itbulls .learnit .onlinestore .persistence .enteties .User ;
18
+
19
+ import jakarta .servlet .ServletException ;
20
+ import jakarta .servlet .annotation .WebServlet ;
21
+ import jakarta .servlet .http .HttpServlet ;
22
+ import jakarta .servlet .http .HttpServletRequest ;
23
+ import jakarta .servlet .http .HttpServletResponse ;
24
+
25
+ @ WebServlet ("/bopla/solution/purchases/*" )
26
+ public class SolutionPurchaseServlet extends HttpServlet {
27
+
28
+ private PurchaseFacade purchaseFacade = DefaultPurchaseFacade .getInstance (); // Assume this facade handles data operations
29
+ private UserFacade userFacade = DefaultUserFacade .getInstance (); // Assume this facade handles user operations
30
+ private Gson gson = new Gson (); // For JSON conversion
31
+ private PurchaseDtoToPurchaseConverter purchaseConverter = new PurchaseDtoToPurchaseConverter ();
32
+
33
+ @ Override
34
+ protected void doGet (HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException {
35
+ try {
36
+ Integer purchaseId = Integer .parseInt (request .getPathInfo ().substring (1 )); // Extract purchaseId from URL
37
+
38
+ // Extract user from Basic Auth
39
+ User authenticatedUser = extractUserFromBasicAuth (request , response );
40
+ if (authenticatedUser == null ) {
41
+ return ; // If user is null, it means authentication failed
42
+ }
43
+ Purchase purchase = purchaseFacade .getPurchaseById (purchaseId ); // Facade retrieves DTO from DAO, and converts it to business object
44
+
45
+ // Authorization check
46
+ if (!purchase .getCustomer ().equals (authenticatedUser ) && !authenticatedUser .getRoleName ().equals (ADMIN_ROLE_NAME )) {
47
+ response .setStatus (HttpServletResponse .SC_FORBIDDEN );
48
+ response .getWriter ().write ("Access is denied." );
49
+ return ;
50
+ }
51
+
52
+ // Optionally apply any additional business logic to the Purchase object
53
+ // For example, let's set Credit Card Number and Customer information to null before returning the purchase information back to the client
54
+ purchase .setCreditCardNumber ("" );
55
+ purchase .setCustomer (null );
56
+ response .setContentType ("application/json" );
57
+ response .getWriter ().write (gson .toJson (purchase )); // Expose safe, business-relevant object
58
+ } catch (Exception e ) {
59
+ response .setStatus (HttpServletResponse .SC_INTERNAL_SERVER_ERROR );
60
+ response .getWriter ().write ("An error occurred." );
61
+ }
62
+ }
63
+
64
+
65
+ @ Override
66
+ protected void doPut (HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException {
67
+ try {
68
+ // Extract user from Basic Auth
69
+ User authenticatedUser = extractUserFromBasicAuth (request , response );
70
+ if (authenticatedUser == null ) {
71
+ return ; // If user is null, it means authentication failed
72
+ }
73
+
74
+ Integer purchaseId = Integer .parseInt (request .getPathInfo ().substring (1 )); // Extract purchaseId
75
+ BufferedReader reader = request .getReader ();
76
+ PurchaseDto updatedPurchaseDto = gson .fromJson (reader , PurchaseDto .class ); // Directly bind request body to DTO
77
+ Purchase updatedPurchase = purchaseConverter .convertPurchaseDtoToPurchase (updatedPurchaseDto );
78
+
79
+ // Purchase Facade retrieves the purchase DTO from the database and converts it to the business object
80
+ Purchase originalPurchase = purchaseFacade .getPurchaseById (purchaseId );
81
+
82
+ // Authorization check
83
+ if (!originalPurchase .getCustomer ().equals (authenticatedUser ) && !authenticatedUser .getRoleName ().equals (ADMIN_ROLE_NAME )) {
84
+ response .setStatus (HttpServletResponse .SC_FORBIDDEN );
85
+ response .getWriter ().write ("Access is denied." );
86
+ return ;
87
+ }
88
+
89
+ // Apply ONLY allowed updates - update list of products
90
+ originalPurchase .setProducts (updatedPurchase .getProducts ());
91
+ // Additional validation can be applied here if necessary
92
+
93
+ // Save the updated purchase
94
+ purchaseFacade .updatePurchase (originalPurchase );
95
+
96
+ // Convert updated purchase to DTO and return JSON
97
+ response .setContentType ("application/json" );
98
+ originalPurchase .setCreditCardNumber ("" );
99
+ originalPurchase .setCustomer (null );
100
+ response .getWriter ().write (gson .toJson (originalPurchase ));
101
+ } catch (Exception e ) {
102
+ response .setStatus (HttpServletResponse .SC_INTERNAL_SERVER_ERROR );
103
+ response .getWriter ().write ("An error occurred." );
104
+ }
105
+ }
106
+
107
+ private User extractUserFromBasicAuth (HttpServletRequest request , HttpServletResponse response ) throws IOException {
108
+ // Extract Basic Auth credentials
109
+ String authHeader = request .getHeader ("Authorization" );
110
+ if (authHeader == null || !authHeader .startsWith ("Basic " )) {
111
+ response .setStatus (HttpServletResponse .SC_UNAUTHORIZED );
112
+ response .getWriter ().write ("Authorization header missing or invalid." );
113
+ return null ;
114
+ }
115
+
116
+ String encodedCredentials = authHeader .substring ("Basic " .length ()).trim ();
117
+ String decodedCredentials = new String (Base64 .getDecoder ().decode (encodedCredentials ), "UTF-8" );
118
+ String [] credentials = decodedCredentials .split (":" , 2 );
119
+ if (credentials .length != 2 ) {
120
+ response .setStatus (HttpServletResponse .SC_BAD_REQUEST );
121
+ response .getWriter ().write ("Invalid authorization credentials." );
122
+ return null ;
123
+ }
124
+
125
+ String email = credentials [0 ];
126
+ String password = credentials [1 ];
127
+ User authenticatedUser = userFacade .getUserByEmail (email );
128
+
129
+ // Verify user credentials
130
+ if (authenticatedUser == null || !authenticatedUser .getPassword ().equals (password )) {
131
+ response .setStatus (HttpServletResponse .SC_UNAUTHORIZED );
132
+ response .getWriter ().write ("Invalid email or password." );
133
+ return null ;
134
+ }
135
+
136
+ return authenticatedUser ;
137
+ }
138
+ }
0 commit comments