Skip to content

Commit d9d260f

Browse files
committed
refactor exceptions
Took 2 hours 33 minutes
1 parent 0951dde commit d9d260f

39 files changed

+608
-565
lines changed

pom.xml

+11
Original file line numberDiff line numberDiff line change
@@ -49,54 +49,65 @@
4949
<artifactId>spring-boot-starter-web</artifactId>
5050
</dependency>
5151
<dependency>
52+
<!-- annotation processor that generates metadata about @ConfigurationProperties for IDE -->
5253
<groupId>org.springframework.boot</groupId>
5354
<artifactId>spring-boot-configuration-processor</artifactId>
5455
<optional>true</optional>
5556
</dependency>
5657
<dependency>
58+
<!-- jwt security -->
5759
<groupId>org.springframework.boot</groupId>
5860
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
5961
</dependency>
6062
<dependency>
63+
<!-- spring mail -->
6164
<groupId>org.springframework.boot</groupId>
6265
<artifactId>spring-boot-starter-mail</artifactId>
6366
</dependency>
6467
<dependency>
68+
<!-- email templates -->
6569
<groupId>org.springframework.boot</groupId>
6670
<artifactId>spring-boot-starter-thymeleaf</artifactId>
6771
</dependency>
6872

6973
<!-- DB -->
7074
<dependency>
75+
<!-- migrations -->
7176
<groupId>org.flywaydb</groupId>
7277
<artifactId>flyway-core</artifactId>
7378
</dependency>
7479
<dependency>
80+
<!-- sql db -->
7581
<groupId>org.postgresql</groupId>
7682
<artifactId>postgresql</artifactId>
7783
</dependency>
7884
<dependency>
85+
<!-- in memory db -->
7986
<groupId>org.springframework.boot</groupId>
8087
<artifactId>spring-boot-starter-data-redis</artifactId>
8188
</dependency>
8289

8390
<!-- UTILS -->
8491
<dependency>
92+
<!-- boilerplate code -->
8593
<groupId>org.projectlombok</groupId>
8694
<artifactId>lombok</artifactId>
8795
<optional>true</optional>
8896
</dependency>
8997
<dependency>
98+
<!-- generate ulid -->
9099
<groupId>io.azam.ulidj</groupId>
91100
<artifactId>ulidj</artifactId>
92101
<version>${ulidj.version}</version>
93102
</dependency>
94103
<dependency>
104+
<!-- graylog -->
95105
<groupId>de.siegmar</groupId>
96106
<artifactId>logback-gelf</artifactId>
97107
<version>${logback-gelf.version}</version>
98108
</dependency>
99109
<dependency>
110+
<!-- swagger -->
100111
<groupId>org.springdoc</groupId>
101112
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
102113
<version>${springdoc-openapi-starter-webmvc-ui.version}</version>

src/main/java/com/github/gribanoveu/cuddle/config/SecurityConfig.java

-2
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,13 @@
77
import lombok.RequiredArgsConstructor;
88
import org.springframework.context.annotation.Bean;
99
import org.springframework.context.annotation.Configuration;
10-
import org.springframework.http.HttpMethod;
1110
import org.springframework.security.authentication.AuthenticationManager;
1211
import org.springframework.security.authentication.ProviderManager;
1312
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
1413
import org.springframework.security.config.Customizer;
1514
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
1615
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
1716
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
18-
import org.springframework.security.config.annotation.web.configurers.CorsConfigurer;
1917
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
2018
import org.springframework.security.config.http.SessionCreationPolicy;
2119
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

src/main/java/com/github/gribanoveu/cuddle/controllers/anonymous/PublicAccountControllerImpl.java

+27-31
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,18 @@
33
import com.github.gribanoveu.cuddle.constants.Constants;
44
import com.github.gribanoveu.cuddle.constants.EmailMessages;
55
import com.github.gribanoveu.cuddle.dtos.enums.BanReason;
6-
import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode;
76
import com.github.gribanoveu.cuddle.dtos.enums.Role;
8-
import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel;
97
import com.github.gribanoveu.cuddle.dtos.request.*;
10-
import com.github.gribanoveu.cuddle.dtos.response.ResponseDetails;
11-
import com.github.gribanoveu.cuddle.dtos.response.StatusResponse;
128
import com.github.gribanoveu.cuddle.entities.services.EmailService;
139
import com.github.gribanoveu.cuddle.entities.services.RedisOtpService;
1410
import com.github.gribanoveu.cuddle.entities.services.UserService;
1511
import com.github.gribanoveu.cuddle.entities.tables.User;
16-
import com.github.gribanoveu.cuddle.exeptions.CredentialEx;
12+
import com.github.gribanoveu.cuddle.exeptions.errors.UserMessage;
13+
import com.github.gribanoveu.cuddle.exeptions.responses.RestException;
14+
import com.github.gribanoveu.cuddle.exeptions.responses.RestResponse;
1715
import com.github.gribanoveu.cuddle.utils.JsonUtils;
1816
import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates;
1917
import io.azam.ulidj.ULID;
20-
import jakarta.servlet.http.HttpServletRequest;
2118
import lombok.RequiredArgsConstructor;
2219
import lombok.extern.slf4j.Slf4j;
2320
import org.springframework.beans.factory.annotation.Value;
@@ -48,9 +45,9 @@ public class PublicAccountControllerImpl {
4845
private final EmailService emailService;
4946
private final JsonUtils jsonUtils;
5047

51-
public ResponseEntity<StatusResponse> registerUser(RegisterDto request) {
52-
if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS);
53-
if (userService.userExistByEmail(request.email())) throw new CredentialEx(ResponseCode.USER_ALREADY_EXIST);
48+
public ResponseEntity<RestResponse> registerUser(RegisterDto request) {
49+
if (!request.password().equals(request.confirmPassword())) throw new RestException(UserMessage.PASSWORD_NOT_EQUALS);
50+
if (userService.userExistByEmail(request.email())) throw new RestException(UserMessage.USER_ALREADY_EXIST);
5451

5552
var user = new User();
5653
user.setUlid(ULID.random(ThreadLocalRandom.current()));
@@ -69,28 +66,27 @@ public ResponseEntity<StatusResponse> registerUser(RegisterDto request) {
6966
EmailMessages.userRegisteredSubject, EmailMessages.userRegisteredTemplate));
7067
log.info("Register confirm send to email: {}", request.email());
7168

72-
return ResponseEntity.created (location).body(StatusResponse.create(
73-
ResponseCode.USER_CREATED, StatusLevel.SUCCESS));
69+
return ResponseEntity.created (location).body(RestResponse.create(UserMessage.USER_CREATED));
7470
}
7571

7672
// user change email from app, authenticated
77-
public ResponseEntity<StatusResponse> changeEmail(ChangeEmailDto request, Authentication authentication) {
73+
public ResponseEntity<RestResponse> changeEmail(ChangeEmailDto request, Authentication authentication) {
7874
var user = userService.findUserByEmail(authentication.getName());
7975
var oldEmail = user.getEmail();
80-
if (request.email().equals(oldEmail)) throw new CredentialEx(ResponseCode.EMAIL_ALREADY_EXIST);
76+
if (request.email().equals(oldEmail)) throw new RestException(UserMessage.EMAIL_ALREADY_EXIST);
8177
userService.updateEmail(user, request.email());
8278
emailService.sendMail(EmailTemplates.emailChanged(oldEmail, request.email()));
8379
log.info("Email change old email: {}, new email: {}", oldEmail, request.email());
84-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UPDATED, StatusLevel.SUCCESS));
80+
return ResponseEntity.ok(RestResponse.create(UserMessage.USER_UPDATED));
8581
}
8682

8783
// check that password and confirm password match
8884
// find user, if not exist -> error
8985
// verify that the old password matches, if not -> error
9086
// check that old password not equals new password, else -> error
9187
// change password
92-
public ResponseEntity<StatusResponse> changePassword(ChangePasswordDto request, Authentication authentication) {
93-
if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS);
88+
public ResponseEntity<RestResponse> changePassword(ChangePasswordDto request, Authentication authentication) {
89+
if (!request.password().equals(request.confirmPassword())) throw new RestException(UserMessage.PASSWORD_NOT_EQUALS);
9490

9591
var user = userService.findUserByEmail(authentication.getName());
9692
if (passwordEncoder.matches(request.oldPassword(), user.getPassword()))
@@ -101,10 +97,10 @@ public ResponseEntity<StatusResponse> changePassword(ChangePasswordDto request,
10197
EmailMessages.passwordChangedSubject, EmailMessages.passwordChangedTemplate));
10298
log.info("Password change message sent to: {}", user.getEmail());
10399

104-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.PASSWORD_UPDATED, StatusLevel.SUCCESS));
105-
} else throw new CredentialEx(ResponseCode.PASSWORD_EQUALS);
100+
return ResponseEntity.ok(RestResponse.create(UserMessage.PASSWORD_UPDATED));
101+
} else throw new RestException(UserMessage.PASSWORD_EQUALS);
106102

107-
throw new CredentialEx(ResponseCode.OLD_PASSWORD_NOT_MATCH);
103+
throw new RestException(UserMessage.OLD_PASSWORD_NOT_MATCH);
108104
}
109105

110106
// user open restore form and enter email
@@ -113,9 +109,9 @@ public ResponseEntity<StatusResponse> changePassword(ChangePasswordDto request,
113109
// else create new code
114110
// send email, if not -> error
115111
// save otp code to db (with lifetime)
116-
public ResponseEntity<StatusResponse> generateOtpCode(GenerateOtpDto request) {
112+
public ResponseEntity<RestResponse> generateOtpCode(GenerateOtpDto request) {
117113
var userExist = userService.userExistByEmail(request.email());
118-
if (!userExist) throw new CredentialEx(ResponseCode.USER_NOT_EXIST);
114+
if (!userExist) throw new RestException(UserMessage.USER_NOT_EXIST);
119115
var otpCode = jsonUtils.generateRandomOtpCode().toString();
120116
log.info("Generate OTP code. Email {}, Code {}", request.email(), otpCode);
121117

@@ -125,16 +121,16 @@ public ResponseEntity<StatusResponse> generateOtpCode(GenerateOtpDto request) {
125121
emailService.sendMail(EmailTemplates.generateOtpEmail(request.email(), otpCode, otpCodeLifeTime));
126122
log.info("Email with code send to: {}", request.email());
127123

128-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.OTP_CODE_CREATED, StatusLevel.SUCCESS));
124+
return ResponseEntity.ok(RestResponse.create(UserMessage.OTP_CODE_CREATED));
129125
}
130126

131127
// next screen user enter otp code and new password and re-enter password again
132128
// service check that code exist and have valid lifetime
133129
// service find userId by otp code and change password in db
134130
// send successful email
135-
public ResponseEntity<StatusResponse> restorePasswordByOtp(RestorePasswordDto request) {
136-
if (!request.password().equals(request.confirmPassword())) throw new CredentialEx(ResponseCode.PASSWORD_NOT_EQUALS);
137-
if (!redisOtpService.otpCodeValid(request.email(), request.otpCode())) throw new CredentialEx(ResponseCode.OTP_CODE_NOT_FOUND);
131+
public ResponseEntity<RestResponse> restorePasswordByOtp(RestorePasswordDto request) {
132+
if (!request.password().equals(request.confirmPassword())) throw new RestException(UserMessage.PASSWORD_NOT_EQUALS);
133+
if (!redisOtpService.otpCodeValid(request.email(), request.otpCode())) throw new RestException(UserMessage.OTP_CODE_NOT_FOUND);
138134

139135
var user = userService.findUserByEmail(request.email());
140136
if (!passwordEncoder.matches(request.password(), user.getPassword())) {
@@ -143,20 +139,20 @@ public ResponseEntity<StatusResponse> restorePasswordByOtp(RestorePasswordDto re
143139
emailService.sendMail(EmailTemplates.simpleEmail(request.email(),
144140
EmailMessages.passwordChangedSubject, EmailMessages.passwordChangedTemplate));
145141
log.info("Password change message sent to: {}", request.email());
146-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.PASSWORD_UPDATED, StatusLevel.SUCCESS));
142+
return ResponseEntity.ok(RestResponse.create(UserMessage.PASSWORD_UPDATED));
147143
}
148-
throw new CredentialEx(ResponseCode.PASSWORD_EQUALS);
144+
throw new RestException(UserMessage.PASSWORD_EQUALS);
149145
}
150146

151-
public ResponseEntity<StatusResponse> getRestrictionsReason(String email) {
147+
public ResponseEntity<RestResponse> getRestrictionsReason(String email) {
152148
var userExist = userService.userExistByEmail(email);
153-
if (!userExist) throw new CredentialEx(ResponseCode.USER_NOT_EXIST);
149+
if (!userExist) throw new RestException(UserMessage.USER_NOT_EXIST);
154150
var user = userService.findUserByEmail(email);
155-
if (user.getBanExpiration() == null) throw new CredentialEx(ResponseCode.NO_RESTRICTIONS);
151+
if (user.getBanExpiration() == null) throw new RestException(UserMessage.NO_RESTRICTIONS);
156152
var reason = BanReason.getBanMessageByCode(user.getRestrictionReason());
157153
var responseText = String.format("Ваша учетная запись заблокирована по причине: %1$s. Блокировка истекает: %2$s",
158154
reason, user.getBanExpiration().format(Constants.DEFAULT_TIME_FORMAT));
159155

160-
return ResponseEntity.ok(StatusResponse.create(new ResponseDetails(responseText), StatusLevel.SUCCESS));
156+
return ResponseEntity.ok(RestResponse.create(responseText));
161157
}
162158
}

src/main/java/com/github/gribanoveu/cuddle/controllers/secure/ModeratorControllerImpl.java

+13-15
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,20 @@
44
import com.github.gribanoveu.cuddle.constants.EmailMessages;
55
import com.github.gribanoveu.cuddle.dtos.enums.BanReason;
66
import com.github.gribanoveu.cuddle.dtos.enums.DisableReason;
7-
import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode;
8-
import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel;
97
import com.github.gribanoveu.cuddle.dtos.request.RestrictionDto;
10-
import com.github.gribanoveu.cuddle.dtos.response.StatusResponse;
118
import com.github.gribanoveu.cuddle.dtos.response.UsersResponse;
129
import com.github.gribanoveu.cuddle.entities.services.EmailService;
1310
import com.github.gribanoveu.cuddle.entities.services.UserService;
11+
import com.github.gribanoveu.cuddle.exeptions.errors.ModeratorMessage;
12+
import com.github.gribanoveu.cuddle.exeptions.errors.UserMessage;
13+
import com.github.gribanoveu.cuddle.exeptions.responses.RestResponse;
1414
import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates;
1515
import lombok.RequiredArgsConstructor;
1616
import lombok.extern.slf4j.Slf4j;
1717
import org.springframework.data.domain.Pageable;
1818
import org.springframework.http.ResponseEntity;
1919
import org.springframework.stereotype.Service;
2020

21-
import static org.springframework.http.HttpStatus.OK;
22-
2321
/**
2422
* @author Evgeny Gribanov
2523
* @version 26.09.2023
@@ -35,44 +33,44 @@ public ResponseEntity<UsersResponse> getAllUsersList(Pageable pageable) {
3533
return ResponseEntity.ok(UsersResponse.create(userService.getAllUsers(pageable)));
3634
}
3735

38-
public ResponseEntity<StatusResponse> deleteUser(String email) {
36+
public ResponseEntity<RestResponse> deleteUser(String email) {
3937
var user = userService.findUserByEmail(email);
4038
userService.deleteUserByEmail(email);
4139
emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(),
4240
EmailMessages.deleteSubject, EmailMessages.deleteModerTemplate));
43-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS));
41+
return ResponseEntity.ok(RestResponse.create(UserMessage.USER_DELETED));
4442
}
4543

46-
public ResponseEntity<StatusResponse> disableUser(RestrictionDto request) {
44+
public ResponseEntity<RestResponse> disableUser(RestrictionDto request) {
4745
var user = userService.findUserByEmail(request.userEmail()); // todo
4846
var disableReason = DisableReason.getDisableReasonByCode(request.reasonCode());
4947
userService.disableUser(user, disableReason.getCode());
5048
emailService.sendMail(EmailTemplates.disableUser(user.getEmail(), disableReason.getMessage()));
51-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DISABLED, StatusLevel.SUCCESS));
49+
return ResponseEntity.ok(RestResponse.create(ModeratorMessage.USER_DISABLED));
5250
}
5351

54-
public ResponseEntity<StatusResponse> enabledUser(String email) {
52+
public ResponseEntity<RestResponse> enabledUser(String email) {
5553
var user = userService.findUserByEmail(email);
5654
userService.enabledUser(user);
5755
emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(),
5856
EmailMessages.enabledSubject, EmailMessages.enabledTemplate));
59-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_ENABLED, StatusLevel.SUCCESS));
57+
return ResponseEntity.ok(RestResponse.create(ModeratorMessage.USER_ENABLED));
6058
}
6159

62-
public ResponseEntity<StatusResponse> banUser(RestrictionDto request) {
60+
public ResponseEntity<RestResponse> banUser(RestrictionDto request) {
6361
var user = userService.findUserByEmail(request.userEmail());
6462
var banReason = BanReason.getBanExpirationByCode(request.reasonCode());
6563
userService.lockUser(user, banReason.getBanExpiration().withNano(0), request.reasonCode());
6664
emailService.sendMail(EmailTemplates.banUser(user.getEmail(), banReason.getMessage(),
6765
banReason.getBanExpiration().format(Constants.DEFAULT_TIME_FORMAT)));
68-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_BANNED, StatusLevel.SUCCESS));
66+
return ResponseEntity.ok(RestResponse.create(ModeratorMessage.USER_BANNED));
6967
}
7068

71-
public ResponseEntity<StatusResponse> mercyUser(String email) {
69+
public ResponseEntity<RestResponse> mercyUser(String email) {
7270
var user = userService.findUserByEmail(email);
7371
userService.unlockUser(user);
7472
emailService.sendMail(EmailTemplates.simpleEmail(user.getEmail(),
7573
EmailMessages.enabledSubject, EmailMessages.enabledTemplate));
76-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_UN_BANNED, StatusLevel.SUCCESS));
74+
return ResponseEntity.ok(RestResponse.create(ModeratorMessage.USER_UN_BANNED));
7775
}
7876
}

src/main/java/com/github/gribanoveu/cuddle/controllers/secure/UserControllerImpl.java

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
package com.github.gribanoveu.cuddle.controllers.secure;
22

33
import com.github.gribanoveu.cuddle.constants.EmailMessages;
4-
import com.github.gribanoveu.cuddle.dtos.enums.ResponseCode;
5-
import com.github.gribanoveu.cuddle.dtos.enums.StatusLevel;
6-
import com.github.gribanoveu.cuddle.dtos.response.StatusResponse;
74
import com.github.gribanoveu.cuddle.dtos.response.UserDataResponse;
85
import com.github.gribanoveu.cuddle.entities.services.EmailService;
96
import com.github.gribanoveu.cuddle.entities.services.UserService;
10-
import com.github.gribanoveu.cuddle.exeptions.CredentialEx;
7+
import com.github.gribanoveu.cuddle.exeptions.errors.UserMessage;
8+
import com.github.gribanoveu.cuddle.exeptions.responses.RestResponse;
119
import com.github.gribanoveu.cuddle.utils.emails.EmailTemplates;
1210
import lombok.RequiredArgsConstructor;
1311
import lombok.extern.slf4j.Slf4j;
@@ -32,10 +30,10 @@ public ResponseEntity<UserDataResponse> getUserData(Authentication authenticatio
3230
return ResponseEntity.ok(resp);
3331
}
3432

35-
public ResponseEntity<StatusResponse> deleteUser(Authentication authentication) {
33+
public ResponseEntity<RestResponse> deleteUser(Authentication authentication) {
3634
userService.deleteUserByEmail(authentication.getName());
3735
emailService.sendMail(EmailTemplates.simpleEmail(authentication.getName(),
3836
EmailMessages.deleteSubject, EmailMessages.deleteSelfTemplate));
39-
return ResponseEntity.ok(StatusResponse.create(ResponseCode.USER_DELETED, StatusLevel.SUCCESS));
37+
return ResponseEntity.ok(RestResponse.create(UserMessage.USER_DELETED));
4038
}
4139
}

0 commit comments

Comments
 (0)