Skip to content
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

Deployed #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
21 changes: 19 additions & 2 deletions shoppingcart/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<version>2.2.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lambdaschool</groupId>
Expand All @@ -15,7 +15,7 @@
<description>Demo project for Spring Boot</description>

<properties>
<java.version>14</java.version>
<java.version>11</java.version>
</properties>

<dependencies>
Expand Down Expand Up @@ -63,6 +63,23 @@
<artifactId>javafaker</artifactId>
<version>1.0.1</version>
</dependency>

<!-- Security 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>
<!-- Security Dependencies -->
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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 {
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_WRITE = "write";
static final String SCOPE_READ = "read";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = -1;

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private PasswordEncoder encoder;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(CLIENT_ID)
.secret(encoder.encode(CLIENT_SECRET))
.authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE)
.scopes(SCOPE_WRITE, SCOPE_READ, 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,36 @@
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.csrf().disable();
http.headers().frameOptions().disable();
http.logout().disable();

http.authorizeRequests()
.antMatchers("/", "/h2-console/**").permitAll()
.antMatchers("/users/**").hasAnyRole("ADMIN", "USER")
.antMatchers("/products/**").hasAnyRole("ADMIN", "USER")
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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.authentication.configuration.EnableGlobalAuthentication;
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;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

@Resource(name = "securityUserService")
private UserDetailsService userDetailsService;

@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
}

@Bean
public TokenStore tokenStore(){
return new InMemoryTokenStore();
}

@Bean
public PasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
import com.lambdaschool.shoppingcart.models.Product;
import com.lambdaschool.shoppingcart.models.User;
import com.lambdaschool.shoppingcart.services.CartService;
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.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -24,13 +27,18 @@ public class CartController
@Autowired
private CartService cartService;

@Autowired
private UserService userService;

@GetMapping(value = "/user", produces = {"application/json"})
public ResponseEntity<?> listAllCarts(@PathVariable long userid)
public ResponseEntity<?> listAllCarts(Authentication authentication)
{
List<Cart> myCarts = cartService.findAllByUserId(userid);
User currentUser = userService.findByName(authentication.getName());
List<Cart> myCarts = cartService.findAllByUserId(currentUser.getUserid());
return new ResponseEntity<>(myCarts, HttpStatus.OK);
}

@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/cart/{cartId}",
produces = {"application/json"})
public ResponseEntity<?> getCartById(
Expand All @@ -42,12 +50,12 @@ public ResponseEntity<?> getCartById(
HttpStatus.OK);
}

@PostMapping(value = "/create/user/{userid}/product/{productid}")
public ResponseEntity<?> addNewCart(@PathVariable long userid,
@PostMapping(value = "/create/product/{productid}")
public ResponseEntity<?> addNewCart(Authentication authentication,
@PathVariable long productid)
{
User dataUser = new User();
dataUser.setUserid(userid);
dataUser.setUserid(userService.findByName(authentication.getName()).getUserid());

Product dataProduct = new Product();
dataProduct.setProductid(productid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
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.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -26,13 +28,15 @@ public class UserController
@Autowired
private UserService userService;

@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/users", produces = {"application/json"})
public ResponseEntity<?> listAllUsers()
{
List<User> myUsers = userService.findAll();
return new ResponseEntity<>(myUsers, HttpStatus.OK);
}

@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping(value = "/user/{userId}",
produces = {"application/json"})
public ResponseEntity<?> getUserById(
Expand All @@ -44,6 +48,7 @@ public ResponseEntity<?> getUserById(
HttpStatus.OK);
}

@PreAuthorize("hasAnyRole('ADMIN')")
@PostMapping(value = "/user", consumes = {"application/json"})
public ResponseEntity<?> addUser(@Valid @RequestBody User newuser)
{
Expand All @@ -63,6 +68,7 @@ public ResponseEntity<?> addUser(@Valid @RequestBody User newuser)
HttpStatus.CREATED);
}

@PreAuthorize("hasAnyRole('ADMIN')")
@DeleteMapping(value = "/user/{userId}")
public ResponseEntity<?> deleteUserById(
@PathVariable
Expand All @@ -71,4 +77,12 @@ public ResponseEntity<?> deleteUserById(
userService.delete(userId);
return new ResponseEntity<>(HttpStatus.OK);
}

// http://localhost:2019/users/myinfo
@GetMapping(value = "/myinfo", produces = "application/json")
public ResponseEntity<?> getMyInfo(Authentication authentication)
{
User myInfo = userService.findByName(authentication.getName());
return new ResponseEntity<>(myInfo, HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.lambdaschool.shoppingcart.models;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "roles")
public class Role extends Auditable{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long roleid;

@Column(nullable = false, unique = true)
private String name;

@OneToMany(mappedBy = "role", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonIgnoreProperties(value = "role", allowSetters = true)
private Set<UserRoles> users = new HashSet<>();

public Role() {
}

public Role(String name) {
this.name = name.toUpperCase();
}

public long getRoleid() {
return roleid;
}

public void setRoleid(long roleid) {
this.roleid = roleid;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name.toUpperCase();
}

public Set<UserRoles> getUsers() {
return users;
}

public void setUsers(Set<UserRoles> users) {
this.users = users;
}
}
Loading