Skip to content

Commit

Permalink
Merge branch 'dev' into feature/mobile-360-update-user-profiles
Browse files Browse the repository at this point in the history
  • Loading branch information
alperenDagi authored Nov 27, 2023
2 parents aa58d7d + 53d2fd2 commit 952d58e
Show file tree
Hide file tree
Showing 49 changed files with 1,678 additions and 589 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ public class NeedController {

@GetMapping("/viewNeedsByFilter")
@PreAuthorize("hasRole('FACILITATOR') or hasRole('COORDINATOR')")
public ResponseEntity<List<NeedDto>> viewNeedsByFilter(@RequestParam(required = false) BigDecimal longitude,
@RequestParam(required = false) BigDecimal latitude,
public ResponseEntity<List<NeedDto>> viewNeedsByFilter(@RequestParam(required = false) BigDecimal longitude1,
@RequestParam(required = false) BigDecimal latitude1,
@RequestParam(required = false) BigDecimal longitude2,
@RequestParam(required = false) BigDecimal latitude2,
@RequestParam(required = false) String categoryTreeId,
@RequestParam(required = false) Long userId) {
log.info("Viewing needs for location: {}, {}, category: {}, user: {}", longitude, latitude, categoryTreeId, userId);
return needService.viewNeedsByFilter(longitude, latitude, categoryTreeId, userId);
log.info("Viewing needs for location: {}-{} / {}-{}, category: {}, user: {}", longitude1, latitude1, longitude2, latitude2, categoryTreeId, userId);
return needService.viewNeedsByFilter(longitude1, latitude1, longitude2, latitude2, categoryTreeId, userId);
}

@PostMapping("/createNeed")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.groupa1.resq.controller;

import com.groupa1.resq.config.ResqAppProperties;
import com.groupa1.resq.dto.NeedDto;
import com.groupa1.resq.dto.RequestDto;
import com.groupa1.resq.entity.Need;
import com.groupa1.resq.entity.Request;
Expand All @@ -11,6 +12,7 @@
import com.groupa1.resq.service.RequestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

Expand All @@ -31,13 +33,15 @@ public class RequestController {

@GetMapping("/viewRequestsByFilter")
@PreAuthorize("hasRole('FACILITATOR')")
public List<RequestDto> viewRequestsByFilter(@RequestParam(required = false) BigDecimal longitude,
@RequestParam(required = false) BigDecimal latitude,
public List<RequestDto> viewRequestsByFilter(@RequestParam(required = false) BigDecimal longitude1,
@RequestParam(required = false) BigDecimal latitude1,
@RequestParam(required = false) BigDecimal longitude2,
@RequestParam(required = false) BigDecimal latitude2,
@RequestParam(required = false) EStatus status,
@RequestParam(required = false) EUrgency urgency,
@RequestParam(required = false) Long userId) {
log.info("Viewing requests for location: {}, {}, status: {}, urgency: {}, user: {}", longitude, latitude, status, urgency, userId);
return requestService.viewRequestsByFilter(longitude, latitude, status, urgency, userId);
log.info("Viewing requests for location: {}-{} / {}-{}, status: {}, urgency: {}, user: {}", longitude1, latitude1, longitude2, latitude2, status, urgency, userId);
return requestService.viewRequestsByFilter(longitude1, latitude1, longitude2, latitude2, status, urgency, userId);
}


Expand Down Expand Up @@ -72,6 +76,15 @@ public String deleteRequest(@RequestParam Long userId, @RequestParam Long reques
return "Request successfully deleted.";
}

@GetMapping("/filterByDistance")
@PreAuthorize("hasRole('FACILITATOR') or hasRole('COORDINATOR')")
public ResponseEntity<List<RequestDto>> filterByDistance(@RequestParam BigDecimal longitude,
@RequestParam BigDecimal latitude,
@RequestParam BigDecimal distance) {
log.info("Filtering requests by distance");
return requestService.filterByDistance(longitude, latitude, distance);
}




Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package com.groupa1.resq.repository;

import com.groupa1.resq.entity.Need;
import com.groupa1.resq.entity.Request;
import com.groupa1.resq.entity.User;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.util.List;
Expand All @@ -16,6 +18,10 @@ public interface RequestRepository extends JpaRepository<Request, Long> {

List<Request> findAll(Specification<Request> specification);

//Haversine formula
@Query(value = "SELECT * FROM NEED WHERE (6371 * acos(cos(radians(?1)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?2)) + sin(radians(?1)) * sin(radians(latitude)))) < ?3", nativeQuery = true)
List<Request> filterByDistance(BigDecimal longitude, BigDecimal latitude, BigDecimal distance);



}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -17,6 +18,11 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@EnableWebSecurity
@Configuration
Expand Down Expand Up @@ -57,7 +63,7 @@ public PasswordEncoder passwordEncoder() {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// No need to give context-path, just give requestMapping and related Post, Get mappings etc.

http.csrf(csrf -> csrf.disable())
http.csrf(csrf -> csrf.disable()).cors(Customizer.withDefaults())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth ->
Expand All @@ -73,4 +79,15 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ public class NeedService {
@Autowired
NeedConverter needConverter;

public void setNeedConverter(NeedConverter needConverter) {
this.needConverter = needConverter;
}

public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}

public void setNeedRepository(NeedRepository needRepository) {
this.needRepository = needRepository;
}

public Long save(Long userId, CreateNeedRequest createNeedRequest) {
User requester = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
Expand Down Expand Up @@ -96,13 +107,13 @@ public ResponseEntity<String> update (UpdateNeedRequest updateNeedRequest, Long
}


public ResponseEntity<List<NeedDto>> viewNeedsByFilter(BigDecimal longitude, BigDecimal latitude, String categoryTreeId, Long userId) {
public ResponseEntity<List<NeedDto>> viewNeedsByFilter(BigDecimal longitude1, BigDecimal latitude1, BigDecimal longitude2, BigDecimal latitude2, String categoryTreeId, Long userId) {

Specification<Need> spec = Specification.where(null);

if (longitude != null && latitude != null) {
spec = spec.and(NeedSpecifications.hasLongitude(longitude));
spec = spec.and(NeedSpecifications.hasLatitude(latitude));
if (longitude1 != null && latitude1 != null && longitude2 != null && latitude2 != null) {
spec = spec.and(NeedSpecifications.isWithinRectangleScope(longitude1, longitude2, latitude1, latitude2));

}
if (categoryTreeId != null) {
spec = spec.and(NeedSpecifications.hasCategoryTreeId(categoryTreeId));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.groupa1.resq.service;

import com.groupa1.resq.converter.RequestConverter;
import com.groupa1.resq.dto.NeedDto;
import com.groupa1.resq.dto.RequestDto;
import com.groupa1.resq.entity.Need;
import com.groupa1.resq.entity.Request;
Expand All @@ -20,6 +21,7 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
Expand All @@ -46,6 +48,22 @@ public class RequestService {
@Autowired
RequestConverter requestConverter;

public void setNeedRepository(NeedRepository needRepository) {
this.needRepository = needRepository;
}

public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}

public void setRequestRepository(RequestRepository requestRepository) {
this.requestRepository = requestRepository;
}

public void setNotificationService(NotificationService notificationService) {
this.notificationService = notificationService;
}

public Long save(Long userId, CreateReqRequest createReqRequest) {
User requester = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found"));
Request request = new Request();
Expand Down Expand Up @@ -76,13 +94,12 @@ public List<RequestDto> viewAllRequests() {
return requestRepository.findAll().stream().map(request -> requestConverter.convertToDto(request)).toList();
}

public List<RequestDto> viewRequestsByFilter(BigDecimal longitude, BigDecimal latitude, EStatus status, EUrgency urgency, Long userId) {
public List<RequestDto> viewRequestsByFilter(BigDecimal longitude1, BigDecimal latitude1, BigDecimal longitude2, BigDecimal latitude2, EStatus status, EUrgency urgency, Long userId) {

Specification<Request> spec = Specification.where(null);

if (longitude != null && latitude != null) {
spec = spec.and(RequestSpecifications.hasLongitude(longitude));
spec = spec.and(RequestSpecifications.hasLatitude(latitude));
if (longitude1 != null && latitude1 != null && longitude2 != null && latitude2 != null) {
spec = spec.and(RequestSpecifications.isWithinRectangleScope(longitude1, longitude2, latitude1, latitude2));
}
if (status != null) {
spec = spec.and(RequestSpecifications.hasStatus(status));
Expand Down Expand Up @@ -120,4 +137,10 @@ public void deleteRequest(Long userId, Long needId) {
requestRepository.deleteById(needId);
}

public ResponseEntity<List<RequestDto>> filterByDistance(BigDecimal longitude,
BigDecimal latitude,
BigDecimal distance) {
return ResponseEntity.ok(requestRepository.filterByDistance(longitude, latitude, distance).stream().map(request -> requestConverter.convertToDto(request)).toList());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ public class UserProfileService {



public void saveProfile(UserProfile userProfile) {
userProfileRepository.save(userProfile);
public UserProfile saveProfile(UserProfile userProfile) {
return userProfileRepository.save(userProfile);
}

public String updateProfile(Long userId, ProfileDto profileDto)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ public static Specification<Need> hasRequester(Long requesterId) {
criteriaBuilder.equal(root.get("requester").get("id"), requesterId);
}

public static Specification<Need> isWithinRectangleScope(BigDecimal longitude1, BigDecimal longitude2,
BigDecimal latitude1, BigDecimal latitude2) {
return (root, query, criteriaBuilder) ->
criteriaBuilder.and(
criteriaBuilder.between(root.get("longitude"), longitude1, longitude2),
criteriaBuilder.between(root.get("latitude"), latitude1, latitude2)
);
}







Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.groupa1.resq.specification;

import com.groupa1.resq.entity.Need;
import com.groupa1.resq.entity.Request;
import com.groupa1.resq.entity.enums.EStatus;
import com.groupa1.resq.entity.enums.EUrgency;
Expand Down Expand Up @@ -34,6 +35,18 @@ public static Specification<Request> hasRequester(Long requesterId) {
criteriaBuilder.equal(root.get("requester").get("id"), requesterId);
}

public static Specification<Request> isWithinRectangleScope(BigDecimal longitude1, BigDecimal longitude2,
BigDecimal latitude1, BigDecimal latitude2) {
return (root, query, criteriaBuilder) ->
criteriaBuilder.and(
criteriaBuilder.between(root.get("longitude"), longitude1, longitude2),
criteriaBuilder.between(root.get("latitude"), latitude1, latitude2)
);
}







Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.groupa1.resq.auth.UserDetailsImpl;
import com.groupa1.resq.entity.User;
import com.groupa1.resq.entity.UserProfile;
import com.groupa1.resq.entity.enums.EUserRole;
import com.groupa1.resq.request.LoginUserRequest;
import com.groupa1.resq.request.RegisterUserRequest;
Expand Down Expand Up @@ -39,6 +40,9 @@ class AuthServiceTest {
@Mock
private AuthenticationManager authenticationManager;

@Mock
private UserProfileService userProfileService;

@Mock
private PasswordEncoder encoder;

Expand Down Expand Up @@ -75,11 +79,17 @@ void testSignup_ifEmailNotAlreadyInUse_success() {
mockUser.setEmail("test-email");
mockUser.setPassword(encodedPassword);

UserProfile mockUserProfile = new UserProfile();
mockUserProfile.setName("test-name");
mockUserProfile.setSurname("test-surname");
mockUserProfile.setUser(mockUser);

mockUser.setRoles(Set.of(EUserRole.VICTIM));

// when
when(userService.existsByEmail("test-email")).thenReturn(false);
when(encoder.encode("test-password")).thenReturn(encodedPassword);
when(userProfileService.saveProfile(mockUserProfile)).thenReturn(mockUserProfile);
when(userService.save(mockUser)).thenReturn(mockUser);

// then
Expand Down
Loading

0 comments on commit 952d58e

Please sign in to comment.