Skip to content

Commit

Permalink
reworked endpoints to better work with cors filter
Browse files Browse the repository at this point in the history
  • Loading branch information
spencerstock committed Jun 26, 2019
1 parent 864ab95 commit 7466af9
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 38 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.lambdaschool.starthere.config;
package com.lambdaschool.starthere.config;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
Expand All @@ -20,26 +20,30 @@ public SimpleCorsFilter()
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
// response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Methods", "*");
// response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type, access_token");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Max-Age", "3600");

if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
} else
{
chain.doFilter(req, res);
String temp = request.getRequestURI();
if (!temp.equals("/oauth/token")) {
response.setHeader("Access-Control-Allow-Origin", "*");
// response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");

response.setHeader("Access-Control-Allow-Methods", "*");
// response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type, access_token");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Max-Age", "3600");
}


if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}

}


@Override
public void init(FilterConfig filterConfig) throws ServletException
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lambdaschool.starthere.controllers;

import com.lambdaschool.starthere.exceptions.ResourceNotFoundException;
import com.lambdaschool.starthere.models.User;
import com.lambdaschool.starthere.models.UserRoles;
import com.lambdaschool.starthere.services.RoleService;
Expand All @@ -8,6 +9,8 @@
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -18,11 +21,12 @@
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.security.InvalidParameterException;
import java.util.ArrayList;

@RestController
public class OpenController
{
public class OpenController {
private static final Logger logger = LoggerFactory.getLogger(RolesController.class);

@Autowired
Expand All @@ -34,8 +38,7 @@ public class OpenController
@PostMapping(value = "/createnewuser", consumes = {"application/json"}, produces = {"application/json"})
public ResponseEntity<?> addNewUser(HttpServletRequest request, @Valid
@RequestBody
User newuser) throws URISyntaxException
{
User newuser) throws URISyntaxException {

logger.trace(request.getRequestURI() + " accessed");

Expand All @@ -44,39 +47,51 @@ public ResponseEntity<?> addNewUser(HttpServletRequest request, @Valid
newuser.setUserRoles(newRoles);

String temp = newuser.getPasswordRaw();
newuser = userService.save(newuser); //passwordRaw is nullified
try {
newuser = userService.save(newuser); //passwordRaw is nullified
} catch (Exception e) {
throw new ResourceNotFoundException("This username is taken");
}


return validateUser(newuser, temp);
}


@PostMapping(value = "/loginuser", consumes = {"application/json"}, produces = {"application/json"})
public ResponseEntity<?> loginUser(HttpServletRequest request, @Valid
@RequestBody
User user) throws URISyntaxException {

logger.trace(request.getRequestURI() + " accessed");


String temp = user.getPasswordRaw();

return validateUser(user, temp);


}

private ResponseEntity<?> validateUser(User user, String temp) {
String loginUrl
= "https://sgs-lambda-bookr.herokuapp.com//oauth/token";
= "https://sgs-lambda-bookr.herokuapp.com/oauth/token";


RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

headers.add("Authorization", "Basic bGFtYmRhLWNsaWVudDpsYW1iZGEtc2VjcmV0");
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "password");
map.add("username", newuser.getUsername());
map.add("username", user.getUsername());
map.add("password", temp);
HttpEntity<MultiValueMap<String, String>> request2 = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(
loginUrl, request2 , String.class);




/* // set the location header for the newly created resource - to another controller!
HttpHeaders responseHeaders = new HttpHeaders();
URI createUserURI = ServletUriComponentsBuilder
.fromUriString(request.getServerName() + ":" + request.getLocalPort() + "/users/user/{userId}")
.buildAndExpand(newuser.getUserid()).toUri();
responseHeaders.setLocation(createUserURI);*/


loginUrl, request2, String.class);
return response;
//return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
}

}

0 comments on commit 7466af9

Please sign in to comment.