diff --git a/shoppingcart/pom.xml b/shoppingcart/pom.xml index 1a2d4e3a..ad69489c 100644 --- a/shoppingcart/pom.xml +++ b/shoppingcart/pom.xml @@ -76,6 +76,23 @@ 2.9.2 + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-test + test + + + org.springframework.security.oauth + spring-security-oauth2 + 2.3.6.RELEASE + + diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/AuthorizationServerConfig.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/AuthorizationServerConfig.java new file mode 100644 index 00000000..0aaaae8a --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/AuthorizationServerConfig.java @@ -0,0 +1,52 @@ +package com.lambdaschool.shoppingcart.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.provider.token.TokenStore; + +@Configuration +@EnableAuthorizationServer +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { + private static final String CLIENT_ID = System.getenv("OAUTHCLIENTID"); + private static final String CLIENT_SECRET = System.getenv("OAUTHCLIENTSECRET"); + + private static final String GRANT_TYPE_PASSWORD = "password"; + private static final String AUTHORIZATION_CODE = "authorization_code"; + private static final String SCOPE_READ = "read"; + private static final String SCOPE_WRITE = "write"; + private static final String SCOPE_TRUST = "trust"; + + private static final int ACCESS_TOKEN_VALIDITY_SECONDS = -1; + + @Autowired + private TokenStore tokenStore; + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints.tokenStore(tokenStore) + .authenticationManager(authenticationManager); + endpoints.pathMapping("/oauth/token", "/login"); + } + + @Override + public void configure(ClientDetailsServiceConfigurer clients) throws Exception { + clients.inMemory() + .withClient(CLIENT_ID) + .secret(passwordEncoder.encode(CLIENT_SECRET)) + .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE) + .scopes(SCOPE_READ, SCOPE_WRITE, SCOPE_TRUST) + .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS); + } +} diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/ResourceServerConfig.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/ResourceServerConfig.java new file mode 100644 index 00000000..e9108a5a --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/ResourceServerConfig.java @@ -0,0 +1,48 @@ +package com.lambdaschool.shoppingcart.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; + +@Configuration +@EnableResourceServer +public class ResourceServerConfig extends ResourceServerConfigurerAdapter { + private static final String RESOURCE_ID = "resource_id"; + + @Override + public void configure(ResourceServerSecurityConfigurer resources) throws Exception { + resources.resourceId(RESOURCE_ID) + .stateless(false);//Does not need username for testing + } + + @Override + public void configure(HttpSecurity http) throws Exception {//which roles has access to which endpoints + http.authorizeRequests() + .antMatchers("/", "/h2-console/**", + "/swagger-resources/**", + "/swagger-resource/**", + "/swagger-ui.html", + "/v2/api-docs", + "/webjars/**", + "/createnewuser", + "/signup", + "/login") + .permitAll() + .antMatchers("/roles/**") + .hasAnyRole("ADMIN", "ANALYST") + .antMatchers("/users/**", "/logout") + .authenticated() + .antMatchers("/carts/**") + .hasAnyRole("ADMIN", "ANALYST") + .and() + .exceptionHandling() + .accessDeniedHandler(new OAuth2AccessDeniedHandler()); + + http.csrf().disable(); + http.headers().frameOptions().disable(); //Allows h2 console to work + http.logout().disable(); //We will write a custom logout + } +} diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/SecurityServerConfig.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/SecurityServerConfig.java new file mode 100644 index 00000000..1609ed1e --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/SecurityServerConfig.java @@ -0,0 +1,47 @@ +package com.lambdaschool.shoppingcart.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SecurityServerConfig extends WebSecurityConfigurerAdapter { + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public TokenStore tokenStore(){ + return new InMemoryTokenStore(); + } + + @Bean + public PasswordEncoder passwordEncoder(){ + return new BCryptPasswordEncoder(); + } + + @Autowired + private UserDetailsService securityUserDetails; + + @Autowired + public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(securityUserDetails) + .passwordEncoder(passwordEncoder()); + } + +} diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/SimpleCorsFilter.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/SimpleCorsFilter.java new file mode 100644 index 00000000..3b383369 --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/config/SimpleCorsFilter.java @@ -0,0 +1,67 @@ +package com.lambdaschool.shoppingcart.config; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpMethod; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Spring uses filters to manage web traffic. Here we manually add a CORS (Cross-Origin Resource Sharing) filter to the chain. + * Using the Order annotation, we tell Spring this is the most important filter. If this filter blocks a request, + * don't do anything else. Just block the request. + */ +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class SimpleCorsFilter + implements Filter +{ + @Override + public void doFilter( + ServletRequest servletRequest, + ServletResponse servletResponse, + FilterChain filterChain) + throws + IOException, + ServletException + { + // Convert our request and response to Http ones. If they are not Http ones, an + // exception would be thrown + // that would handled by our exception handler! + HttpServletResponse response = (HttpServletResponse) servletResponse; + HttpServletRequest request = (HttpServletRequest) servletRequest; + // white list domains that can access this API. * says let everyone access it. + // To restrict access use something like + // response.setHeader("Access-Control-Allow-Origin", + // "https://lambdaschool.com/"); + response.setHeader("Access-Control-Allow-Origin", + "*"); + // white list http methods that can be used with this API. * says lets them all work! + // To restrict access use something like + // response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Allow-Methods", + "*"); + // while list access headers that can be used with this API. * says lets them all work! + // To restrict access use something like + // response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, + // content-type, access_token"); + response.setHeader("Access-Control-Allow-Headers", + "*"); + // maximum seconds results can be cached + response.setHeader("Access-Control-Max-Age", + "3600"); + if (HttpMethod.OPTIONS.name() + .equalsIgnoreCase(request.getMethod())) + { + response.setStatus(HttpServletResponse.SC_OK); + } else + { + filterChain.doFilter(servletRequest, + servletResponse); + } + } +} \ No newline at end of file diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/NewUserController.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/NewUserController.java new file mode 100644 index 00000000..8a01ad7a --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/NewUserController.java @@ -0,0 +1,102 @@ +package com.lambdaschool.shoppingcart.controllers; + +import com.lambdaschool.shoppingcart.exceptions.ResourceFoundException; +import com.lambdaschool.shoppingcart.exceptions.ResourceNotFoundException; +import com.lambdaschool.shoppingcart.models.*; +import com.lambdaschool.shoppingcart.repository.RoleRepository; +import com.lambdaschool.shoppingcart.repository.UserRepository; +import com.lambdaschool.shoppingcart.services.RoleService; +import com.lambdaschool.shoppingcart.services.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.*; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; + +@RestController +public class NewUserController { + + @Autowired + private UserRepository userrepos; + + @Autowired + private RoleRepository rolerepos; + + + @PostMapping(value = "/createnewuser", + consumes = {"application/json"}, + produces = {"application/json"}) + public ResponseEntity addSelf( + HttpServletRequest httpServletRequest, + @Valid + @RequestBody + UserMinimum checkuser) throws URISyntaxException { + if (checkuser.getUsername().isBlank() || checkuser.getPassword().isBlank() ){ + throw new ResourceNotFoundException("Username, and/or password cannot be blank"); + } + if (userrepos.findByUsername(checkuser.getUsername()) != null) { + throw new ResourceFoundException("Username already exists!"); + } + User newuser = new User(); + newuser.setUsername(checkuser.getUsername().toLowerCase()); + newuser.setPassword(checkuser.getPassword()); + newuser.setPrimaryemail(checkuser.getPrimaryemail().toLowerCase()); + newuser.getRoles().clear(); + for (UserRoles ur : newuser.getRoles()) + { + Role addRole = rolerepos.findByNameIgnoreCase(("USER")); + newuser.getRoles() + .add(new UserRoles(newuser, + addRole)); + } + newuser = userrepos.save(newuser); + + HttpHeaders responseHeaders = new HttpHeaders(); + URI newUserURI = ServletUriComponentsBuilder.fromUriString(httpServletRequest.getServerName() + ":" + httpServletRequest.getLocalPort() + "/users/user/{userId}") + .buildAndExpand(newuser.getUserid()) + .toUri(); + responseHeaders.setLocation(newUserURI); + + RestTemplate restTemplate = new RestTemplate(); + String requestURI = "http://localhost" + ":" + httpServletRequest.getLocalPort() + "/login"; + + List acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(MediaType.APPLICATION_JSON); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + headers.setAccept(acceptableMediaTypes); + headers.setBasicAuth(System.getenv("OAUTHCLIENTID"), + System.getenv("OAUTHCLIENTSECRET")); + + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("grant_type", + "password"); + map.add("scope", + "read write trust"); + map.add("username", + checkuser.getUsername()); + map.add("password", + checkuser.getPassword()); + + HttpEntity> request = new HttpEntity<>(map, + headers); + + String theToken = restTemplate.postForObject(requestURI, + request, + String.class); + + return new ResponseEntity<>(theToken, + responseHeaders, + HttpStatus.CREATED); + } +} diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/UserController.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/UserController.java index 50737ff4..be1ca700 100755 --- a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/UserController.java +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/controllers/UserController.java @@ -1,17 +1,25 @@ package com.lambdaschool.shoppingcart.controllers; -import com.lambdaschool.shoppingcart.models.User; +import com.lambdaschool.shoppingcart.exceptions.ResourceFoundException; +import com.lambdaschool.shoppingcart.exceptions.ResourceNotFoundException; +import com.lambdaschool.shoppingcart.models.*; +import com.lambdaschool.shoppingcart.repository.RoleRepository; +import com.lambdaschool.shoppingcart.repository.UserRepository; +import com.lambdaschool.shoppingcart.services.RoleService; import com.lambdaschool.shoppingcart.services.UserService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.http.*; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; +import java.util.ArrayList; import java.util.List; /** @@ -27,6 +35,10 @@ public class UserController @Autowired private UserService userService; + @Autowired + private TokenStore tokenStore; + + /** * Returns a list of all users *
Example: http://localhost:2019/users/users @@ -54,12 +66,16 @@ public ResponseEntity listAllUsers() @GetMapping(value = "/user/{userId}", produces = "application/json") public ResponseEntity getUserById( - @PathVariable - Long userId) - { + @PathVariable Long userId){ User u = userService.findUserById(userId); + String uname = SecurityContextHolder.getContext().getAuthentication().getName(); + User user = userService.findByName(uname); + if (userId == user.getUserid()) { return new ResponseEntity<>(u, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } } /** @@ -158,9 +174,14 @@ public ResponseEntity updateFullUser( long userid) { updateUser.setUserid(userid); - userService.save(updateUser); - - return new ResponseEntity<>(HttpStatus.OK); + String uname = SecurityContextHolder.getContext().getAuthentication().getName(); + User user = userService.findByName(uname); + if (userid == user.getUserid()) { + userService.save(updateUser); + return new ResponseEntity<>(HttpStatus.OK); + }else { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } } /** @@ -182,9 +203,15 @@ public ResponseEntity updateUser( @PathVariable long id) { - userService.update(updateUser, - id); - return new ResponseEntity<>(HttpStatus.OK); + String uname = SecurityContextHolder.getContext().getAuthentication().getName(); + User user = userService.findByName(uname); + if (id == user.getUserid()) { + userService.update(updateUser, + id); + return new ResponseEntity<>(HttpStatus.OK); + }else { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } } /** @@ -199,7 +226,34 @@ public ResponseEntity deleteUserById( @PathVariable long id) { - userService.delete(id); + String uname = SecurityContextHolder.getContext().getAuthentication().getName(); + User user = userService.findByName(uname); + if (id == user.getUserid()) { + userService.delete(id); + return new ResponseEntity<>(HttpStatus.OK); + }else { + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + } + @GetMapping(value = "/myinfo", produces = "application/json") + public ResponseEntity getCurrentUserInfo(){ + String uname = SecurityContextHolder.getContext().getAuthentication().getName(); + User user = userService.findByName(uname); + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @GetMapping(value = "/logout") + public ResponseEntity logoutSelf(HttpServletRequest request){ + String authHeader = request.getHeader("Authorization"); + if (authHeader != null) { + //find the token + String tokenValue = authHeader.replace("Bearer", "") + .trim(); + //now remove it + OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue); + tokenStore.removeAccessToken(accessToken); + } return new ResponseEntity<>(HttpStatus.OK); } + } \ No newline at end of file diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java index fcc02f61..96eeffa8 100644 --- a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/User.java @@ -1,12 +1,12 @@ package com.lambdaschool.shoppingcart.models; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.*; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.persistence.*; import javax.validation.constraints.Email; -import java.util.HashSet; -import java.util.Set; +import java.util.*; /** * The entity allowing interaction with the users table @@ -169,6 +169,12 @@ public String getPassword() * @param password the new password (String) for the user */ public void setPassword(String password) + { + BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + this.password = passwordEncoder.encode(password); + } + + public void setPasswordNoEncrypt(String password) { this.password = password; } @@ -212,4 +218,13 @@ public void setCarts(Set carts) { this.carts = carts; } + @JsonIgnore + public List getAuthority(){ + List rtnList = new ArrayList<>(); + for (UserRoles ur : this.roles) { + String myRole = "ROLE_" + ur.getRole().getName().toUpperCase(); + rtnList.add(new SimpleGrantedAuthority(myRole)); + } + return rtnList; + } } diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/UserMinimum.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/UserMinimum.java new file mode 100644 index 00000000..26d1b201 --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/models/UserMinimum.java @@ -0,0 +1,67 @@ +package com.lambdaschool.shoppingcart.models; + +import javax.validation.constraints.Email; + +public class UserMinimum { + /** + * The username (String) + */ + private String username; + + /** + * The user's password (String) + */ + private String password; + + @Email + private String primaryemail; + + /** + * Getter for the username + * + * @return the username (String) associated with this user + */ + public String getUsername() + { + return username; + } + + /** + * Setter for the username + * + * @param username the new username (String) associated with this user + */ + public void setUsername(String username) + { + this.username = username; + } + + /** + * Getter for the password of this user + * + * @return the password (String) for this user + */ + public String getPassword() + { + return password; + } + + /** + * Setter for the password of this user. This object is a temporary model used to create a new user. + * The password must remain in clear text until saved into the database. + * + * @param password the new password (String in clear texts) for this user + */ + public void setPassword(String password) + { + this.password = password; + } + + public String getPrimaryemail() { + return primaryemail; + } + + public void setPrimaryemail(String primaryemail) { + this.primaryemail = primaryemail; + } +} diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/SecurityUserServiceImpl.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/SecurityUserServiceImpl.java new file mode 100644 index 00000000..6e4f8e69 --- /dev/null +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/SecurityUserServiceImpl.java @@ -0,0 +1,28 @@ +package com.lambdaschool.shoppingcart.services; + + +import com.lambdaschool.shoppingcart.exceptions.ResourceNotFoundException; +import com.lambdaschool.shoppingcart.models.User; +import com.lambdaschool.shoppingcart.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.*; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +@Service(value = "securityUserDetails") +public class SecurityUserServiceImpl implements UserDetailsService { + + @Autowired + UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + User user = userRepository.findByUsername(username.toLowerCase()); + if (user == null) { + throw new ResourceNotFoundException("Invalid username or password"); + } + return new org.springframework.security.core.userdetails.User( + user.getUsername(), user.getPassword(), user.getAuthority()); + } +} diff --git a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/UserServiceImpl.java b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/UserServiceImpl.java index d84fad84..3179e263 100755 --- a/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/UserServiceImpl.java +++ b/shoppingcart/src/main/java/com/lambdaschool/shoppingcart/services/UserServiceImpl.java @@ -5,6 +5,7 @@ import com.lambdaschool.shoppingcart.models.Role; import com.lambdaschool.shoppingcart.models.User; import com.lambdaschool.shoppingcart.models.UserRoles; +import com.lambdaschool.shoppingcart.repository.RoleRepository; import com.lambdaschool.shoppingcart.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -28,6 +29,9 @@ public class UserServiceImpl @Autowired private UserRepository userrepos; + @Autowired + private RoleRepository rolerepos; + /** * Connects this service to the Role table */ @@ -101,7 +105,7 @@ public User save(User user) newUser.setUsername(user.getUsername() .toLowerCase()); - newUser.setPassword(user.getPassword()); + newUser.setPasswordNoEncrypt(user.getPassword()); newUser.setPrimaryemail(user.getPrimaryemail() .toLowerCase()); @@ -109,11 +113,17 @@ public User save(User user) .clear(); for (UserRoles ur : user.getRoles()) { - Role addRole = roleService.findRoleById(ur.getRole() - .getRoleid()); - newUser.getRoles() - .add(new UserRoles(newUser, - addRole)); +// Role addRole = roleService.findRoleById(ur.getRole() +// .getRoleid()); +// newUser.getRoles() +// .add(new UserRoles(newUser, +// addRole)); + + Role addRole = rolerepos.findById(ur.getRole().getRoleid()) + .orElseThrow(()-> new ResourceNotFoundException("Role id " + + ur.getRole().getRoleid() + " not found!")); + + newUser.getRoles().add(new UserRoles(newUser,addRole)); } return userrepos.save(newUser); @@ -141,7 +151,7 @@ public User update( if (user.getPassword() != null) { - currentUser.setPassword(user.getPassword()); + currentUser.setPasswordNoEncrypt(user.getPassword()); } if (user.getPrimaryemail() != null) diff --git a/shoppingcart/src/main/resources/data.sql b/shoppingcart/src/main/resources/data.sql index a1159b8b..2b948cbc 100644 --- a/shoppingcart/src/main/resources/data.sql +++ b/shoppingcart/src/main/resources/data.sql @@ -18,9 +18,9 @@ INSERT INTO ROLES(ROLEID, NAME, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODI (2, 'USER', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP); INSERT INTO USERS(USERID, USERNAME, PRIMARYEMAIL, PASSWORD, COMMENTS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE) - VALUES (1, 'barnbarn', 'barnbarn@host.local', 'LambdaLlama', '', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP), - (2, 'cinnamon', 'cinnamon@host.local', 'LambdaLlama', '', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP), - (3, 'stumps', 'stumps@host.local', 'LambdaLlama', '', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP); + VALUES (1, 'barnbarn', 'barnbarn@host.local', '$2y$12$EZtRr52L0SfjKgiQg/OcvOulbusBMlksCUq56AeANT5DJ8yNu1dsq', '', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP), + (2, 'cinnamon', 'cinnamon@host.local', '$2y$12$EZtRr52L0SfjKgiQg/OcvOulbusBMlksCUq56AeANT5DJ8yNu1dsq', '', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP), + (3, 'stumps', 'stumps@host.local', '$2y$12$EZtRr52L0SfjKgiQg/OcvOulbusBMlksCUq56AeANT5DJ8yNu1dsq', '', 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP); INSERT INTO USERROLES(ROLEID, USERID, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE) VALUES (1, 1, 'SYSTEM', CURRENT_TIMESTAMP, 'SYSTEM', CURRENT_TIMESTAMP),