Skip to content
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
7 changes: 4 additions & 3 deletions src/main/java/com/app_api/auditing/ApplicationAuditAware.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@

import java.util.Optional;

public class ApplicationAuditAware implements AuditorAware<Integer> {
public class ApplicationAuditAware implements AuditorAware<User> {

@Override
public Optional<Integer> getCurrentAuditor() {
public Optional<User> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder
.getContext()
.getAuthentication();
Expand All @@ -22,6 +23,6 @@ public Optional<Integer> getCurrentAuditor() {
}

User userPrincipal = (User) authentication.getPrincipal();
return Optional.ofNullable(userPrincipal.getId());
return Optional.ofNullable(userPrincipal);
}
}
17 changes: 12 additions & 5 deletions src/main/java/com/app_api/auth/AuthenticationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import com.app_api.resource.enums.TokenType;
import com.app_api.resource.enums.UserRoleEnum;
import com.app_api.util.CurrentUserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
Expand All @@ -21,15 +20,23 @@
import org.springframework.web.server.ResponseStatusException;

@Service
@RequiredArgsConstructor
public class AuthenticationService extends BaseService {
private final UserRepository repository;
private final TokenRepository tokenRepository;
private final UserRoleRepository userRoleRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authenticationManager;
private final CurrentUserHolder currentUserHolder;

public AuthenticationService(CurrentUserHolder currentUserHolder, UserRepository repository, TokenRepository tokenRepository, UserRoleRepository userRoleRepository, PasswordEncoder passwordEncoder, JwtService jwtService, AuthenticationManager authenticationManager) {
super(currentUserHolder);
this.repository = repository;
this.tokenRepository = tokenRepository;
this.userRoleRepository = userRoleRepository;
this.passwordEncoder = passwordEncoder;
this.jwtService = jwtService;
this.authenticationManager = authenticationManager;
}

@Transactional
public void register(RegisterRequest request) {
Expand All @@ -51,7 +58,7 @@ public void register(RegisterRequest request) {
employer = whser;
}*/

User whser = currentUserHolder.getCurrentUser();
User whser = currentUser;

var user = User.builder()
.email(request.getEmail())
Expand All @@ -62,7 +69,7 @@ public void register(RegisterRequest request) {
//.employer(employer)
.depot(whser)
.phone(request.getPhone())
.auditInfo(createAudit(whser.getId()))
.auditInfo(createAudit())
.build();

var savedUser = repository.save(user);
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/com/app_api/config/CurrentUserFilter.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.app_api.config;

import com.app_api.util.CurrentUserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import jakarta.servlet.Filter;
Expand All @@ -14,14 +15,11 @@
import java.security.Principal;

@Component
@RequiredArgsConstructor
public class CurrentUserFilter implements Filter {

private final CurrentUserHolder currentUserHolder;

public CurrentUserFilter(CurrentUserHolder currentUserHolder) {
this.currentUserHolder = currentUserHolder;
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/com/app_api/resource/entity/AuditInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
import jakarta.persistence.Embeddable;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;

import java.sql.Timestamp;

Expand All @@ -13,15 +17,19 @@
public class AuditInfo {

@Column(name = "created_by")
@CreatedBy
private Integer createdBy;

@Column(name = "updated_by")
@LastModifiedBy
private Integer updatedBy;

@Column(name = "created_at", insertable = false, updatable = false)
@CreatedDate
private Timestamp createdAt;

@Column(name = "updated_at", insertable = false)
@LastModifiedDate
private Timestamp updatedAt;

}
2 changes: 2 additions & 0 deletions src/main/java/com/app_api/resource/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import jakarta.persistence.*;
import lombok.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

Expand All @@ -15,6 +16,7 @@
@AllArgsConstructor
@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
public class User implements UserDetails {
@Id
@Column(name = "id", nullable = false)
Expand Down
20 changes: 14 additions & 6 deletions src/main/java/com/app_api/service/BaseService.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
package com.app_api.service;

import com.app_api.resource.entity.AuditInfo;
import com.app_api.resource.entity.User;
import com.app_api.util.CurrentUserHolder;

import java.sql.Timestamp;

public abstract class BaseService {
public class BaseService {

public AuditInfo createAudit(Integer userId) {
protected User currentUser;

public BaseService(CurrentUserHolder currentUserHolder) {
currentUser = currentUserHolder.getCurrentUser();
}

public AuditInfo createAudit() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
AuditInfo audit = new AuditInfo();
audit.setCreatedBy(userId);
audit.setUpdatedBy(userId);
audit.setCreatedBy(currentUser.getId());
audit.setUpdatedBy(currentUser.getId());
audit.setCreatedAt(timestamp);
audit.setUpdatedAt(timestamp);
return audit;
}

public AuditInfo updateAudit(Integer userId, AuditInfo audit) {
public AuditInfo updateAudit(AuditInfo audit) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
audit.setUpdatedBy(userId);
audit.setUpdatedBy(currentUser.getId());
audit.setUpdatedAt(timestamp);
return audit;
}
Expand Down
54 changes: 27 additions & 27 deletions src/main/java/com/app_api/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,17 @@
import com.app_api.dto.response.UserResponse;
import com.app_api.resource.repo.TokenRepository;
import com.app_api.resource.repo.UserRepository;
import com.app_api.resource.repo.UserRoleRepository;
import com.app_api.dto.request.UserRequest;
import com.app_api.resource.entity.User;
import com.app_api.resource.enums.UserRoleEnum;
import com.app_api.util.CurrentUserHolder;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

@Service
@RequiredArgsConstructor
public class UserService extends BaseService {

private final UserRepository repo;
Expand All @@ -27,29 +24,34 @@ public class UserService extends BaseService {
private final PasswordEncoder passwordEncoder;
private final ModelMapper modelMapper;

private final CurrentUserHolder currentUserHolder;
public UserService(CurrentUserHolder currentUserHolder, UserRepository repo, TokenRepository tokenRepository, PasswordEncoder passwordEncoder, ModelMapper modelMapper) {
super(currentUserHolder);
this.repo = repo;
this.tokenRepository = tokenRepository;
this.passwordEncoder = passwordEncoder;
this.modelMapper = modelMapper;
}

public void changePassword(ChangePasswordRequest request) {
User user = currentUserHolder.getCurrentUser();

if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) {
if (!passwordEncoder.matches(request.getCurrentPassword(), currentUser.getPassword())) {
throw new ResponseStatusException(
HttpStatus.NOT_ACCEPTABLE, "Wrong password");
}
if (!request.getNewPassword().equals(request.getConfirmationPassword())) {
throw new ResponseStatusException(
HttpStatus.NOT_ACCEPTABLE, "Password are not the same");
}
user.setPassword(passwordEncoder.encode(request.getNewPassword()));
user.setAuditInfo(updateAudit(user.getId(), user.getAuditInfo()));
repo.save(user);
currentUser.setPassword(passwordEncoder.encode(request.getNewPassword()));
currentUser.setAuditInfo(updateAudit(currentUser.getAuditInfo()));
repo.save(currentUser);
}

public void changeActive(Integer id, boolean status) {
User user = repo.findById(id).orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_ACCEPTABLE, "Can't find user"));
user.setActive(status);
user.setAuditInfo(updateAudit(user.getId(), user.getAuditInfo()));
user.setAuditInfo(updateAudit(user.getAuditInfo()));
repo.save(user);
if (!status) {
revokeAllUserTokens(user);
Expand All @@ -68,28 +70,26 @@ private void revokeAllUserTokens(User user) {
}

public void updateUser(UserRequest userRequest) {
User user = currentUserHolder.getCurrentUser();
user.setName(userRequest.getName());
user.setPhone(userRequest.getPhone());
currentUser.setName(userRequest.getName());
currentUser.setPhone(userRequest.getPhone());

user.setCompanyName(userRequest.getCompanyName());
user.setStreet1(userRequest.getStreet1());
user.setStreet2(userRequest.getStreet2());
user.setCity(userRequest.getCity());
user.setState(userRequest.getState());
user.setZipCode(userRequest.getZipCode());
currentUser.setCompanyName(userRequest.getCompanyName());
currentUser.setStreet1(userRequest.getStreet1());
currentUser.setStreet2(userRequest.getStreet2());
currentUser.setCity(userRequest.getCity());
currentUser.setState(userRequest.getState());
currentUser.setZipCode(userRequest.getZipCode());

user.setAuditInfo(updateAudit(user.getId(), user.getAuditInfo()));
repo.save(user);
currentUser.setAuditInfo(updateAudit(currentUser.getAuditInfo()));
repo.save(currentUser);
}

public UserResponse getUserDetail() {
User user = currentUserHolder.getCurrentUser();
UserResponse userResponse = modelMapper.map(user, UserResponse.class);
if (user.getRole().getValue().equals(UserRoleEnum.whser)
|| user.getRole().getValue().equals(UserRoleEnum.whserEmp)) {
if (user.getRole().getValue().equals(UserRoleEnum.whserEmp)) {
user = user.getEmployer();
UserResponse userResponse = modelMapper.map(currentUser, UserResponse.class);
if (currentUser.getRole().getValue().equals(UserRoleEnum.whser)
|| currentUser.getRole().getValue().equals(UserRoleEnum.whserEmp)) {
if (currentUser.getRole().getValue().equals(UserRoleEnum.whserEmp)) {
currentUser = currentUser.getEmployer();
}
//userResponse.setCountryWhser(fetchCountryWhser(user));
}
Expand Down
33 changes: 2 additions & 31 deletions src/main/java/com/app_api/service/schedular/SchedularService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

@Component
@RequiredArgsConstructor
public class SchedularService extends BaseService {
public class SchedularService {

private final Logger logger = LoggerFactory.getLogger(getClass());

Expand All @@ -27,12 +27,11 @@ private void postConstruct() {
public void startBackgroundService() {
logger.warn("startBackgroundService");

ScheduledThreadPoolExecutor threadPool = new ScheduledThreadPoolExecutor(3);
ScheduledThreadPoolExecutor threadPool = new ScheduledThreadPoolExecutor(1);

Runnable exampleRunnableMethod = exampleRunnableMethod();

threadPool.scheduleWithFixedDelay(exampleRunnableMethod, 10, 10, TimeUnit.DAYS);
threadPool.scheduleWithFixedDelay(exampleRunnableMethod, calculateInitialDelayExample(), 168, TimeUnit.HOURS); // 24 * 7
}

private Runnable exampleRunnableMethod() {
Expand All @@ -42,33 +41,5 @@ private Runnable exampleRunnableMethod() {
};
}

private int calculateInitialDelayExample() {
HashMap<Integer, Integer> dayToDelay = new HashMap<>();
dayToDelay.put(Calendar.THURSDAY, 6);
dayToDelay.put(Calendar.FRIDAY, 5);
dayToDelay.put(Calendar.SATURDAY, 4);
dayToDelay.put(Calendar.SUNDAY, 3);
dayToDelay.put(Calendar.MONDAY, 2);
dayToDelay.put(Calendar.TUESDAY, 1);
dayToDelay.put(Calendar.WEDNESDAY, 0);

ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime now = ZonedDateTime.now(zoneId);

int dayOfWeek = now.getDayOfWeek().getValue();
int hour = now.getHour();

int delayInDays = dayToDelay.get(dayOfWeek);
int delayInHours = 0;

int targetHour = 20; // 8 pm
if (delayInDays == 6 && hour < targetHour) {
delayInHours = targetHour - hour;
} else {
delayInHours = delayInDays * 24 + ((24 - hour) + targetHour);
}

return delayInHours;
}
}

2 changes: 1 addition & 1 deletion src/main/java/com/app_api/util/CurrentUserHolder.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
public class CurrentUserHolder {
private static final ThreadLocal<Principal> currentPrincipal = new ThreadLocal<>();

public Principal getCurrentPrincipal() {
private Principal getCurrentPrincipal() {
return currentPrincipal.get();
}

Expand Down