Changeset 775e15e for phonelux-backend/src/main
- Timestamp:
- 09/17/22 01:23:47 (2 years ago)
- Branches:
- master
- Children:
- 7e88e46
- Parents:
- e5b84dc
- Location:
- phonelux-backend/src/main/java
- Files:
-
- 5 added
- 8 edited
Legend:
- Unmodified
- Added
- Removed
-
phonelux-backend/src/main/java/finki/it/phoneluxbackend/controllers/PhoneController.java
re5b84dc r775e15e 18 18 public class PhoneController { 19 19 private final PhoneService phoneService; 20 private final PhoneOfferService phoneOfferService;21 20 22 // handle request parameters for filtering phones23 21 @GetMapping(path = "/phones") 24 22 public List<Phone> getPhones(@RequestParam(name = "shops", required = false) String shops, … … 42 40 } 43 41 44 @GetMapping(path = "/shops")45 public List<String> getShops(){46 return phoneOfferService.getShops();47 }48 49 @GetMapping(path = "/lowestPrice")50 public int getLowestPrice()51 {52 return phoneOfferService.getLowestPrice();53 }54 55 @GetMapping(path = "/highestPrice")56 public int getHighestPrice()57 {58 return phoneOfferService.getHighestPrice();59 }60 61 62 42 } -
phonelux-backend/src/main/java/finki/it/phoneluxbackend/controllers/PhoneOfferController.java
re5b84dc r775e15e 18 18 public class PhoneOfferController { 19 19 private final PhoneOfferService phoneOfferService; 20 private final PhoneService phoneService;21 20 22 21 @GetMapping(path = "/phones/offers/{phoneId}") … … 30 29 } 31 30 31 @GetMapping(path = "/phoneoffer/{offerId}/cheaperoffers") 32 public List<PhoneOffer> getCheaperOffers(@PathVariable("offerId") Long offerId){ 33 return phoneOfferService.getCheaperOffers(offerId); 34 } 35 36 @GetMapping(path = "/shops") 37 public List<String> getShops(){ 38 return phoneOfferService.getShops(); 39 } 40 41 @GetMapping(path = "/lowestPrice") 42 public int getLowestPrice() 43 { 44 return phoneOfferService.getLowestPrice(); 45 } 46 47 @GetMapping(path = "/highestPrice") 48 public int getHighestPrice() 49 { 50 return phoneOfferService.getHighestPrice(); 51 } 52 32 53 } -
phonelux-backend/src/main/java/finki/it/phoneluxbackend/entities/User.java
re5b84dc r775e15e 1 1 package finki.it.phoneluxbackend.entities; 2 2 3 import com.fasterxml.jackson.annotation.JsonIgnore; 3 4 import finki.it.phoneluxbackend.data.UserRole; 4 5 import lombok.*; … … 15 16 @Getter 16 17 @Setter 18 @ToString 17 19 @EqualsAndHashCode 18 20 @NoArgsConstructor … … 48 50 inverseJoinColumns = @JoinColumn(name = "offer_id") 49 51 ) 52 @JsonIgnore 50 53 private List<PhoneOffer> favouriteOffers = new ArrayList<PhoneOffer>(); 51 54 … … 55 58 this.email = email; 56 59 this.password = password; 60 this.userRole = userRole; 61 } 62 63 public User(Long id, String firstName, UserRole userRole) { 64 this.id = id; 65 this.firstName = firstName; 66 this.userRole = userRole; 67 } 68 69 public User(Long id, String firstName, String lastName, String email, UserRole userRole) { 70 this.id = id; 71 this.firstName = firstName; 72 this.lastName = lastName; 73 this.email = email; 57 74 this.userRole = userRole; 58 75 } -
phonelux-backend/src/main/java/finki/it/phoneluxbackend/security/CustomAuthenticationFilter.java
re5b84dc r775e15e 50 50 .withClaim("role", user.getAuthorities().stream() 51 51 .map(GrantedAuthority::getAuthority).collect(Collectors.toList())) 52 .withClaim("name", user.getFirstName()) 53 .withClaim("id", user.getId()) 52 54 .sign(algorithm); 53 55 54 // String refresh_token = JWT.create()55 // .withSubject(user.getEmail())56 // .withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000))57 // .withIssuer(request.getRequestURL().toString())58 // .withClaim("role",user.getAuthorities().stream()59 // .map(GrantedAuthority::getAuthority).collect(Collectors.toList()))60 // .sign(algorithm);61 56 62 63 Map<String,String> tokens = new HashMap<>(); 64 tokens.put("access_token",access_token); 65 // tokens.put("refresh_token",refresh_token); 57 Map<String,String> authInfo = new HashMap<>(); 58 authInfo.put("access_token",access_token); 66 59 response.setContentType(APPLICATION_JSON_VALUE); 67 new ObjectMapper().writeValue(response.getOutputStream(), tokens);60 new ObjectMapper().writeValue(response.getOutputStream(),authInfo); 68 61 } 69 62 } -
phonelux-backend/src/main/java/finki/it/phoneluxbackend/security/configs/WebSecurityConfig.java
re5b84dc r775e15e 29 29 @Override 30 30 protected void configure(HttpSecurity http) throws Exception { 31 // http 32 // .csrf().disable() 33 // .authorizeRequests() 34 // .antMatchers("/registration/**") 35 // .permitAll() 36 // .anyRequest() 37 // .authenticated().and() 38 // .formLogin(); 31 39 32 40 33 http.csrf().disable(); 41 34 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 42 // http.authorizeRequests().antMatchers(GET,"/phones").hasAnyAuthority("USER"); 43 http.authorizeRequests().anyRequest().permitAll(); 35 36 http.authorizeRequests() 37 .and() 38 .authorizeRequests() 39 .antMatchers("/user/**") 40 .hasAnyAuthority("USER","ADMIN", "SUPERADMIN") 41 .and() 42 .authorizeRequests() 43 .antMatchers("/management/**") 44 .hasAnyAuthority("SUPERADMIN") 45 .anyRequest().permitAll(); 46 47 48 44 49 http.addFilter(new CustomAuthenticationFilter(authenticationManagerBean())); 45 50 http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class); -
phonelux-backend/src/main/java/finki/it/phoneluxbackend/services/PhoneOfferService.java
re5b84dc r775e15e 9 9 import java.util.Comparator; 10 10 import java.util.List; 11 import java.util.Objects; 11 12 import java.util.stream.Collectors; 12 13 … … 60 61 } 61 62 63 public List<PhoneOffer> getCheaperOffers(Long offerId) { 64 boolean exists = phoneOfferRepository.existsById(offerId); 65 66 if(!exists) 67 throw new IllegalStateException("Phone offer with id "+offerId+" does not exist"); 68 69 PhoneOffer offer = phoneOfferRepository.findById(offerId).get(); 70 71 return phoneOfferRepository.findAll() 72 .stream().filter(phoneOffer -> 73 Objects.equals(phoneOffer.getPhone().getModel(), offer.getPhone().getModel()) 74 && phoneOffer.getPrice() < offer.getPrice()) 75 .sorted(Comparator.comparing(PhoneOffer::getPrice).reversed()) 76 .collect(Collectors.toList()); 77 } 62 78 } -
phonelux-backend/src/main/java/finki/it/phoneluxbackend/services/UserService.java
re5b84dc r775e15e 1 1 package finki.it.phoneluxbackend.services; 2 2 3 3 import com.auth0.jwt.JWT; 4 import com.auth0.jwt.JWTVerifier; 5 import com.auth0.jwt.algorithms.Algorithm; 6 import com.auth0.jwt.interfaces.DecodedJWT; 7 import finki.it.phoneluxbackend.data.UserRole; 8 import finki.it.phoneluxbackend.entities.PhoneOffer; 4 9 import finki.it.phoneluxbackend.entities.User; 10 import finki.it.phoneluxbackend.repositories.PhoneOfferRepository; 5 11 import finki.it.phoneluxbackend.repositories.UserRepository; 6 12 import finki.it.phoneluxbackend.entities.ConfirmationToken; 7 13 import lombok.AllArgsConstructor; 8 9 14 import org.springframework.http.ResponseEntity; 10 15 import org.springframework.security.core.userdetails.UserDetails; … … 16 21 import java.time.LocalDateTime; 17 22 23 import java.util.Comparator; 24 import java.util.List; 18 25 import java.util.UUID; 26 import java.util.stream.Collectors; 19 27 20 28 @Service … … 22 30 public class UserService implements UserDetailsService { 23 31 private final UserRepository userRepository; 32 private final PhoneOfferRepository phoneOfferRepository; 24 33 private final BCryptPasswordEncoder bCryptPasswordEncoder; 25 34 private final ConfirmationTokenService confirmationTokenService; … … 68 77 69 78 79 public User getUserFromToken(String token) { 80 Algorithm algorithm = Algorithm.HMAC256("secret".getBytes()); 81 JWTVerifier verifier = JWT.require(algorithm).build(); 82 DecodedJWT decodedJWT = verifier.verify(token); 83 String email = decodedJWT.getSubject(); 84 UserRole role = UserRole.valueOf(decodedJWT.getClaim("role").asArray(String.class)[0]); 85 String name = decodedJWT.getClaim("name").as(String.class); 86 Long id = decodedJWT.getClaim("id").as(Long.class); 87 88 return new User(id,name,role); 89 } 90 91 public List<PhoneOffer> getFavouriteOffersForUser(Long userId) { 92 boolean exists = userRepository.existsById(userId); 93 if(!exists) 94 throw new IllegalStateException("User with id "+userId+" does not exist"); 95 96 return userRepository.findById(userId).get().getFavouriteOffers(); 97 } 98 99 public ResponseEntity<Object> editOfferForUser(Long userId, Long offerId, String option) { 100 boolean userExists = userRepository.existsById(userId); 101 if (!userExists) 102 { 103 return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist"); 104 } 105 106 boolean offerExists = phoneOfferRepository.existsById(offerId); 107 108 if (!offerExists) 109 { 110 return ResponseEntity.badRequest().body("Offer with id "+offerId+" doesn't exist"); 111 } 112 113 User user = userRepository.findById(userId).get(); 114 PhoneOffer phoneOffer = phoneOfferRepository.findById(offerId).get(); 115 116 if(option.equals("add")) { 117 user.getFavouriteOffers().add(phoneOffer); 118 } 119 else{ 120 user.getFavouriteOffers().remove(phoneOffer); 121 } 122 123 userRepository.save(user); 124 125 return ResponseEntity.ok().build(); 126 } 127 128 public List<User> getUsers(String searchValue) { 129 List<User> users = userRepository.findAll().stream() 130 .filter(user -> user.getUserRole() != UserRole.SUPERADMIN && user.getEnabled()) 131 .map(user -> new User(user.getId(),user.getFirstName(), 132 user.getLastName(),user.getEmail(),user.getUserRole())) 133 .collect(Collectors.toList()); 134 135 if(searchValue != null) 136 { 137 users = users.stream() 138 .filter(user -> user.getEmail().toLowerCase().contains(searchValue.stripIndent().toLowerCase()) 139 || user.getFirstName().toLowerCase().contains(searchValue.stripIndent().toLowerCase())) 140 .collect(Collectors.toList()); 141 } 142 143 return users.stream() 144 .sorted(Comparator.comparing(User::getId)) 145 .collect(Collectors.toList()); 146 147 } 148 149 public ResponseEntity<Object> giveAdminRoleToUser(Long userId) { 150 boolean userExists = userRepository.existsById(userId); 151 if (!userExists) 152 { 153 return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist"); 154 } 155 156 User user = userRepository.findById(userId).get(); 157 158 user.setUserRole(UserRole.ADMIN); 159 userRepository.save(user); 160 161 return ResponseEntity.ok().build(); 162 } 163 164 public ResponseEntity<Object> removeAdminRoleFromUser(Long userId) { 165 boolean userExists = userRepository.existsById(userId); 166 if (!userExists) 167 { 168 return ResponseEntity.badRequest().body("User with id "+userId+" doesn't exist"); 169 } 170 171 User user = userRepository.findById(userId).get(); 172 173 user.setUserRole(UserRole.USER); 174 userRepository.save(user); 175 return ResponseEntity.ok().build(); 176 } 70 177 }
Note:
See TracChangeset
for help on using the changeset viewer.