Skip to content

done #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

done #22

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions shoppingcart/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
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 {

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private PasswordEncoder passwordEncoder;

static final String CLIENT_ID = System.getenv("OAUTHCLIENTID");
static final String CLIENT_SECRET = System.getenv("OAUTHCLIENTSECRET");
static final String GRANT_TYPE_PASSWORD = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String SCOPE_TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = -1;

@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);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager);
endpoints.pathMapping("/oauth/token","/login");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
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);
}

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/",
"/h2-console/**",
"/swagger-resources/**",
"/swagger-resource/**",
"/swagger-ui.html",
"/v2/api-docs",
"/webjars/**")
.permitAll()
.antMatchers("/roles/**", "/products/**")
.hasAnyRole("ADMIN")
.antMatchers("/users/**", "/cart/**", "/logout")
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());

http.csrf().disable();
http.headers().frameOptions().disable();
http.logout().disable();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
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 SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService securityUserService;

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception
{

auth.userDetailsService(securityUserService).passwordEncoder(passwordEncoder());

}

@Bean
public PasswordEncoder passwordEncoder()
{

return new BCryptPasswordEncoder();

}

@Bean
public TokenStore tokenStore()
{

return new InMemoryTokenStore();

}


@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import com.lambdaschool.shoppingcart.models.CartItem;
import com.lambdaschool.shoppingcart.models.User;
import com.lambdaschool.shoppingcart.services.CartItemService;
import com.lambdaschool.shoppingcart.services.SecurityUserService;
import com.lambdaschool.shoppingcart.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
Expand All @@ -19,41 +21,41 @@ public class CartController
@Autowired
private UserService userService;

@GetMapping(value = "/user/{userid}",
@GetMapping(value = "/",
produces = {"application/json"})
public ResponseEntity<?> listCartItemsByUserId(
@PathVariable
long userid)
public ResponseEntity<?> listCartItemsByUserId()
{
User u = userService.findUserById(userid);
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User u = userService.findByName(username);
return new ResponseEntity<>(u,
HttpStatus.OK);
}

@PutMapping(value = "/add/user/{userid}/product/{productid}",
@PutMapping(value = "/add/product/{productid}",
produces = {"application/json"})
public ResponseEntity<?> addToCart(
@PathVariable
long userid,

@PathVariable
long productid)
{
CartItem addCartTtem = cartItemService.addToCart(userid,
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User u = userService.findByName(username);
CartItem addCartTtem = cartItemService.addToCart(u.getUserid(),
productid,
"I am not working");
return new ResponseEntity<>(addCartTtem,
HttpStatus.OK);
}

@DeleteMapping(value = "/remove/user/{userid}/product/{productid}",
@DeleteMapping(value = "/remove/product/{productid}",
produces = {"application/json"})
public ResponseEntity<?> removeFromCart(
@PathVariable
long userid,
@PathVariable
long productid)
{
CartItem removeCartItem = cartItemService.removeFromCart(userid,
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User u = userService.findByName(username);
CartItem removeCartItem = cartItemService.removeFromCart(u.getUserid(),
productid,
"I am still not working");
return new ResponseEntity<>(removeCartItem,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

Expand Down Expand Up @@ -34,6 +35,7 @@ public class UserController
* @return JSON list of all users with a status of OK
* @see UserService#findAll() UserService.findAll()
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/users",
produces = "application/json")
public ResponseEntity<?> listAllUsers()
Expand All @@ -51,6 +53,7 @@ public ResponseEntity<?> listAllUsers()
* @return JSON object of the user you seek
* @see UserService#findUserById(long) UserService.findUserById(long)
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/user/{userId}",
produces = "application/json")
public ResponseEntity<?> getUserById(
Expand All @@ -70,6 +73,7 @@ public ResponseEntity<?> getUserById(
* @return JSON object of the user you seek
* @see UserService#findByName(String) UserService.findByName(String)
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/user/name/{userName}",
produces = "application/json")
public ResponseEntity<?> getUserByName(
Expand All @@ -89,6 +93,7 @@ public ResponseEntity<?> getUserByName(
* @return A JSON list of users you seek
* @see UserService#findByNameContaining(String) UserService.findByNameContaining(String)
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/user/name/like/{userName}",
produces = "application/json")
public ResponseEntity<?> getUserLikeName(
Expand All @@ -111,6 +116,7 @@ public ResponseEntity<?> getUserLikeName(
* @throws URISyntaxException Exception if something does not work in creating the location header
* @see UserService#save(User) UserService.save(User)
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@PostMapping(value = "/user",
consumes = "application/json")
public ResponseEntity<?> addNewUser(
Expand Down Expand Up @@ -148,6 +154,7 @@ public ResponseEntity<?> addNewUser(
* @return status of OK
* @see UserService#save(User) UserService.save(User)
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@PutMapping(value = "/user/{userid}",
consumes = "application/json")
public ResponseEntity<?> updateFullUser(
Expand All @@ -174,6 +181,7 @@ public ResponseEntity<?> updateFullUser(
* @return A status of OK
* @see UserService#update(User, long) UserService.update(User, long)
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@PatchMapping(value = "/user/{id}",
consumes = "application/json")
public ResponseEntity<?> updateUser(
Expand All @@ -194,6 +202,7 @@ public ResponseEntity<?> updateUser(
* @param id the primary key of the user you wish to delete
* @return Status of OK
*/
@PreAuthorize("hasAnyRole('ADMIN')")
@DeleteMapping(value = "/user/{id}")
public ResponseEntity<?> deleteUserById(
@PathVariable
Expand All @@ -202,4 +211,6 @@ public ResponseEntity<?> deleteUserById(
userService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}


}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.lambdaschool.shoppingcart.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
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
Expand Down Expand Up @@ -169,6 +171,14 @@ 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;
}
Expand Down Expand Up @@ -212,4 +222,17 @@ public void setCarts(Set<CartItem> carts)
{
this.carts = carts;
}

@JsonIgnore
public List<SimpleGrantedAuthority> getAuthority()
{

List<SimpleGrantedAuthority> returnList = new ArrayList<>();
for(UserRoles R : this.roles)
{
String myRole = "ROLE_" + R.getRole().getName().toUpperCase();
returnList.add(new SimpleGrantedAuthority(myRole));
}
return returnList;
}
}
Loading