forked from ShiftLeftSecurity/shiftleft-java-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomerController.java
More file actions
392 lines (344 loc) · 13.2 KB
/
CustomerController.java
File metadata and controls
392 lines (344 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package io.shiftleft.controller;
import io.shiftleft.model.Account;
import io.shiftleft.model.Address;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import io.shiftleft.data.DataLoader;
import io.shiftleft.exception.CustomerNotFoundException;
import io.shiftleft.exception.InvalidCustomerRequestException;
import io.shiftleft.model.Customer;
import io.shiftleft.repository.CustomerRepository;
import org.springframework.web.util.HtmlUtils;
/**
* Customer Controller exposes a series of RESTful endpoints
*/
@Configuration
@EnableEncryptableProperties
@PropertySource({ "classpath:config/application-sfdc.properties" })
@RestController
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@Autowired
Environment env;
private static Logger log = LoggerFactory.getLogger(CustomerController.class);
@PostConstruct
public void init() {
log.info("Start Loading SalesForce Properties");
log.info("Url is {}", env.getProperty("sfdc.url"));
log.info("UserName is {}", env.getProperty("sfdc.username"));
log.info("Password is {}", env.getProperty("sfdc.password"));
log.info("End Loading SalesForce Properties");
}
private void dispatchEventToSalesForce(String event)
throws ClientProtocolException, IOException, AuthenticationException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(env.getProperty("sfdc.url"));
httpPost.setEntity(new StringEntity(event));
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(env.getProperty("sfdc.username"),
env.getProperty("sfdc.password"));
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
CloseableHttpResponse response = client.execute(httpPost);
log.info("Response from SFDC is {}", response.getStatusLine().getStatusCode());
client.close();
}
/**
* Get customer using id. Returns HTTP 404 if customer not found
*
* @param customerId
* @return retrieved customer
*/
@RequestMapping(value = "/customers/{customerId}", method = RequestMethod.GET)
public Customer getCustomer(@PathVariable("customerId") Long customerId) {
/* validate customer Id parameter */
if (null == customerId) {
throw new InvalidCustomerRequestException();
}
Customer customer = customerRepository.findOne(customerId);
if (null == customer) {
throw new CustomerNotFoundException();
}
Account account = new Account(4242l,1234, "savings", 1, 0);
log.info("Account Data is {}", account);
log.info("Customer Data is {}", customer);
try {
dispatchEventToSalesForce(String.format(" Customer %s Logged into SalesForce", customer));
} catch (Exception e) {
log.error("Failed to Dispatch Event to SalesForce . Details {} ", e.getLocalizedMessage());
}
return customer;
}
/**
* Handler for / loads the index.tpl
* @param httpResponse
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(HttpServletResponse httpResponse, WebRequest request) throws IOException {
ClassPathResource cpr = new ClassPathResource("static/index.html");
String ret = "";
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
ret= new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
//LOG.warn("IOException", e);
}
return ret;
}
/**
* Check if settings= is present in cookie
* @param request
* @return
*/
private boolean checkCookie(WebRequest request) throws Exception {
try {
return request.getHeader("Cookie").startsWith("settings=");
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
return false;
}
/**
* restores the preferences on the filesystem
*
* @param httpResponse
* @param request
* @throws Exception
*/
@RequestMapping(value = "/loadSettings", method = RequestMethod.GET)
public void loadSettings(HttpServletResponse httpResponse, WebRequest request) throws Exception {
// get cookie values
if (!checkCookie(request)) {
httpResponse.getOutputStream().println("Error");
throw new Exception("cookie is incorrect");
}
String md5sum = request.getHeader("Cookie").substring("settings=".length(), 41);
ClassPathResource cpr = new ClassPathResource("static");
File folder = new File(cpr.getPath());
File[] listOfFiles = folder.listFiles();
String filecontent = new String();
for (File f : listOfFiles) {
// not efficient, i know
filecontent = new String();
byte[] encoded = Files.readAllBytes(f.toPath());
filecontent = new String(encoded, StandardCharsets.UTF_8);
if (filecontent.contains(md5sum)) {
// this will send me to the developer hell (if exists)
// encode the file settings, md5sum is removed
String s = new String(Base64.getEncoder().encode(filecontent.replace(md5sum, "").getBytes()));
// setting the new cookie
httpResponse.setHeader("Cookie", "settings=" + s + "," + md5sum);
return;
}
}
}
/**
* Saves the preferences (screen resolution, language..) on the filesystem
*
* @param httpResponse
* @param request
* @throws Exception
*/
@RequestMapping(value = "/saveSettings", method = RequestMethod.GET)
public void saveSettings(HttpServletResponse httpResponse, WebRequest request) throws Exception {
// "Settings" will be stored in a cookie
// schema: base64(filename,value1,value2...), md5sum(base64(filename,value1,value2...))
if (!checkCookie(request)){
httpResponse.getOutputStream().println("Error");
throw new Exception("cookie is incorrect");
}
String settingsCookie = request.getHeader("Cookie");
String[] cookie = settingsCookie.split(",");
if(cookie.length<2) {
httpResponse.getOutputStream().println("Malformed cookie");
throw new Exception("cookie is incorrect");
}
String base64txt = cookie[0].replace("settings=","");
// Check md5sum
String cookieMD5sum = cookie[1];
String calcMD5Sum = DigestUtils.md5Hex(base64txt);
if(!cookieMD5sum.equals(calcMD5Sum))
{
httpResponse.getOutputStream().println("Wrong md5");
throw new Exception("Invalid MD5");
}
// Now we can store on filesystem
String[] settings = new String(Base64.getDecoder().decode(base64txt)).split(",");
// storage will have ClassPathResource as basepath
ClassPathResource cpr = new ClassPathResource("./static/");
File file = new File(cpr.getPath()+settings[0]);
if(!file.exists()) {
file.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(file, true);
// First entry is the filename -> remove it
String[] settingsArr = Arrays.copyOfRange(settings, 1, settings.length);
// on setting at a line
fos.write(String.join("\n",settingsArr).getBytes());
fos.write(("\n"+cookie[cookie.length-1]).getBytes());
fos.close();
httpResponse.getOutputStream().println("Settings Saved");
}
/**
* Debug test for saving and reading a customer
*
* @param firstName String
* @param lastName String
* @param dateOfBirth String
* @param ssn String
* @param tin String
* @param phoneNumber String
* @param httpResponse
* @param request
* @return String
* @throws IOException
*/
@RequestMapping(value = "/debug", method = RequestMethod.GET)
public String debug(@RequestParam String customerId,
@RequestParam int clientId,
@RequestParam String firstName,
@RequestParam String lastName,
@RequestParam String dateOfBirth,
@RequestParam String ssn,
@RequestParam String socialSecurityNum,
@RequestParam String tin,
@RequestParam String phoneNumber,
HttpServletResponse httpResponse,
WebRequest request) throws IOException{
// empty for now, because we debug
Set<Account> accounts1 = new HashSet<Account>();
//dateofbirth example -> "1982-01-10"
Customer customer1 = new Customer(customerId, clientId, firstName, lastName, DateTime.parse(dateOfBirth).toDate(),
ssn, socialSecurityNum, tin, phoneNumber, new Address("Debug str",
"", "Debug city", "CA", "12345"),
accounts1);
customerRepository.save(customer1);
httpResponse.setStatus(HttpStatus.CREATED.value());
httpResponse.setHeader("Location", String.format("%s/customers/%s",
request.getContextPath(), customer1.getId()));
return customer1.toString().toLowerCase().replace("script","");
}
/**
* Debug test for saving and reading a customer
*
* @param firstName String
* @param httpResponse
* @param request
* @return void
* @throws IOException
*/
@RequestMapping(value = "/debugEscaped", method = RequestMethod.GET)
public void debugEscaped(@RequestParam String firstName, HttpServletResponse httpResponse,
WebRequest request) throws IOException{
String escaped = HtmlUtils.htmlEscape(firstName);
System.out.println(escaped);
httpResponse.getOutputStream().println(escaped);
}
/**
* Gets all customers.
*
* @return the customers
*/
@RequestMapping(value = "/customers", method = RequestMethod.GET)
public List<Customer> getCustomers() {
return (List<Customer>) customerRepository.findAll();
}
/**
* Create a new customer and return in response with HTTP 201
*
* @param the
* customer
* @return created customer
*/
@RequestMapping(value = { "/customers" }, method = { RequestMethod.POST })
public Customer createCustomer(@RequestParam Customer customer, HttpServletResponse httpResponse,
WebRequest request) {
Customer createdcustomer = null;
createdcustomer = customerRepository.save(customer);
httpResponse.setStatus(HttpStatus.CREATED.value());
httpResponse.setHeader("Location",
String.format("%s/customers/%s", request.getContextPath(), customer.getId()));
return createdcustomer;
}
/**
* Update customer with given customer id.
*
* @param customer
* the customer
*/
@RequestMapping(value = { "/customers/{customerId}" }, method = { RequestMethod.PUT })
public void updateCustomer(@RequestBody Customer customer, @PathVariable("customerId") Long customerId,
HttpServletResponse httpResponse) {
if (!customerRepository.exists(customerId)) {
httpResponse.setStatus(HttpStatus.NOT_FOUND.value());
} else {
customerRepository.save(customer);
httpResponse.setStatus(HttpStatus.NO_CONTENT.value());
}
}
/**
* Deletes the customer with given customer id if it exists and returns
* HTTP204.
*
* @param customerId
* the customer id
*/
@RequestMapping(value = "/customers/{customerId}", method = RequestMethod.DELETE)
public void removeCustomer(@PathVariable("customerId") Long customerId, HttpServletResponse httpResponse) {
if (customerRepository.exists(customerId)) {
customerRepository.delete(customerId);
}
httpResponse.setStatus(HttpStatus.NO_CONTENT.value());
}
}