-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathall_code.txt
More file actions
2791 lines (2179 loc) · 87.5 KB
/
all_code.txt
File metadata and controls
2791 lines (2179 loc) · 87.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/MainApplication.java =====
package chat.ping.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Starting point of the application
@SpringBootApplication
public class MainApplication
{
public static void main(String[] args)
{
SpringApplication.run(MainApplication.class, args);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/config/SecurityFilterConfig.java =====
package chat.ping.main.config;
import chat.ping.main.infrastructure.security.JWTAuthFilter;
import chat.ping.main.infrastructure.security.UserDetailsServiceImplementation;
import chat.ping.main.config.SecurityConfig.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityFilterConfig
{
private final JWTAuthFilter jwtAuthFilter;
private final UserDetailsServiceImplementation userDetailsService;
private final PasswordEncoder passwordEncoder;
public SecurityFilterConfig(JWTAuthFilter jwtAuthFilter, UserDetailsServiceImplementation userDetailsService, PasswordEncoder passwordEncoder)
{
this.jwtAuthFilter = jwtAuthFilter;
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception
{
http
.csrf(AbstractHttpConfigurer::disable) // disable CSRF
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // stateless session
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers("/api/hello").permitAll()
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated() // All other requests require authentication
)
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public AuthenticationProvider authenticationProvider()
{
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder);
return authenticationProvider;
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/config/SecurityConfig.java =====
package chat.ping.main.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig
{
@Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/config/AppConfig.java =====
package chat.ping.main.config;
import chat.ping.main.entity.MessageThread.MessageThreadFactory;
import chat.ping.main.entity.Messaging.MessageFactory;
import chat.ping.main.entity.user.UserFactory;
import chat.ping.main.infrastructure.auth.gateway.UserAuthDsGateway;
import chat.ping.main.infrastructure.auth.presenter.UserLoginPresenter;
import chat.ping.main.infrastructure.auth.presenter.UserRegisterPresenter;
import chat.ping.main.infrastructure.messaging.gateway.messages.MessageGateway;
import chat.ping.main.infrastructure.messaging.gateway.threads.ThreadGateway;
import chat.ping.main.infrastructure.messaging.presenter.CreateThreadPresenter;
import chat.ping.main.infrastructure.messaging.presenter.GetMessagesPresenter;
import chat.ping.main.infrastructure.messaging.presenter.GetThreadsPresenter;
import chat.ping.main.infrastructure.messaging.presenter.SendMessagePresenter;
import chat.ping.main.infrastructure.security.JWTUtils;
import chat.ping.main.usecase.auth.login.UserLoginInteractor;
import chat.ping.main.usecase.auth.register.UserRegisterInteractor;
import chat.ping.main.usecase.messaging.createThreads.CreateThreadInteractor;
import chat.ping.main.usecase.messaging.getMessages.GetMessageInteractor;
import chat.ping.main.usecase.messaging.getThreads.GetThreadsInteractor;
import chat.ping.main.usecase.messaging.sendMessage.SendMessageInteractor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class AppConfig
{
@Bean
public UserRegisterPresenter userRegisterPresenter()
{
return new UserRegisterPresenter();
}
@Bean
public UserRegisterInteractor userRegisterInteractor(UserAuthDsGateway userAuthDsGateway,
UserRegisterPresenter userRegisterPresenter,
UserFactory userFactory)
{
return new UserRegisterInteractor(
userAuthDsGateway,
userRegisterPresenter,
userFactory
);
}
@Bean
public UserLoginPresenter userLoginPresenter()
{
return new UserLoginPresenter();
}
@Bean
public UserLoginInteractor userLoginInteractor(UserAuthDsGateway userAuthDsGateway,
PasswordEncoder passwordEncoder,
UserLoginPresenter userLoginPresenter,
JWTUtils jwtUtils)
{
return new UserLoginInteractor(
userAuthDsGateway,
passwordEncoder,
userLoginPresenter,
jwtUtils
);
}
@Bean
public UserFactory userFactory(PasswordEncoder passwordEncoder)
{
return new UserFactory(passwordEncoder);
}
@Bean
public MessageThreadFactory messageThreadFactory()
{
return new MessageThreadFactory();
}
@Bean
public MessageFactory messageFactory()
{
return new MessageFactory();
}
@Bean
public CreateThreadPresenter createThreadPresenter()
{
return new CreateThreadPresenter();
}
@Bean
public GetThreadsPresenter getThreadsPresenter()
{
return new GetThreadsPresenter();
}
@Bean
public GetMessagesPresenter getMessagesPresenter()
{
return new GetMessagesPresenter();
}
@Bean
public SendMessagePresenter sendMessagePresenter()
{
return new SendMessagePresenter();
}
@Bean
public CreateThreadInteractor createThreadInteractor(ThreadGateway threadGateway,
UserAuthDsGateway userAuthDsGateway,
CreateThreadPresenter presenter,
MessageThreadFactory threadFactory)
{
return new CreateThreadInteractor(threadGateway, userAuthDsGateway, presenter, threadFactory);
}
@Bean
public GetThreadsInteractor getThreadsInteractor(ThreadGateway threadGateway,
GetThreadsPresenter presenter)
{
return new GetThreadsInteractor(threadGateway, presenter);
}
@Bean
public GetMessageInteractor getMessagesInteractor(MessageGateway messageGateway,
ThreadGateway threadGateway,
GetMessagesPresenter presenter)
{
return new GetMessageInteractor(messageGateway, threadGateway, presenter);
}
@Bean
public SendMessageInteractor sendMessageInteractor(MessageGateway messageGateway,
ThreadGateway threadGateway,
UserAuthDsGateway userAuthDsGateway,
SendMessagePresenter presenter,
MessageFactory messageFactory)
{
return new SendMessageInteractor(messageGateway, threadGateway, userAuthDsGateway, presenter, messageFactory);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/user/User.java =====
package chat.ping.main.entity.user;
import chat.ping.main.entity.MessageThread.MessageThread;
import java.util.ArrayList;
import java.util.List;
public class User
{
// properties
private final String email;
private final String username;
private final String passwordHash;
private List<MessageThread> messageThreadList = new ArrayList<>();
// Constructor
public User(String email, String username, String passwordHash)
{
this.email = email;
this.username = username;
this.passwordHash = passwordHash;
}
// Additional constructor
public User(String username)
{
this.email = null;
this.username = username;
this.passwordHash = null;
}
public String getEmail()
{
return email;
}
public String getUsername()
{
return username;
}
public String getPasswordHash()
{
return passwordHash;
}
public List<MessageThread> getThreadMessages()
{
return messageThreadList;
}
public void addThreadMessage(MessageThread newMessageThread)
{
this.messageThreadList.add(newMessageThread);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/user/UserFactory.java =====
package chat.ping.main.entity.user;
import org.springframework.security.crypto.password.PasswordEncoder;
public class UserFactory
{
private final PasswordEncoder passwordEncoder;
public UserFactory(PasswordEncoder passwordEncoder)
{
this.passwordEncoder = passwordEncoder;
}
public User createUser(String email, String username, String password)
{
String hashedPassword = passwordEncoder.encode(password);
return new User(email, username, hashedPassword);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/MessageThread/MessageThreadFactory.java =====
package chat.ping.main.entity.MessageThread;
import chat.ping.main.entity.user.User;
import java.util.List;
public class MessageThreadFactory
{
public MessageThread createThread(String threadName, List<User> participants)
{
MessageThread thread = new MessageThread(null, threadName);
thread.setParticipants(participants);
return thread;
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/MessageThread/MessageThread.java =====
package chat.ping.main.entity.MessageThread;
import chat.ping.main.entity.Messaging.AbstractMessage;
import chat.ping.main.entity.user.User;
import java.util.ArrayList;
import java.util.List;
public class MessageThread
{
private Long threadID;
private String threadName;
private List<User> participants = new ArrayList<>();
private List<AbstractMessage> messages = new ArrayList<>();
public MessageThread(Long threadID, String threadName)
{
this.threadID = threadID;
this.threadName = threadName;
}
public Long getThreadID()
{
return threadID;
}
public void setThreadID(Long threadID)
{
this.threadID = threadID;
}
public String getThreadName()
{
return threadName;
}
public void setThreadName(String threadName)
{
this.threadName = threadName;
}
public List<User> getParticipants()
{
return participants;
}
public void setParticipants(List<User> participants)
{
this.participants = participants;
}
public List<AbstractMessage> getMessages()
{
return messages;
}
public void addMessage(AbstractMessage message)
{
this.messages.add(message);
}
public void addParticipant(User user)
{
this.participants.add(user);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/Messaging/MessageFactory.java =====
package chat.ping.main.entity.Messaging;
import chat.ping.main.entity.MessageThread.MessageThread;
import chat.ping.main.entity.user.User;
public class MessageFactory
{
public TextMessage createTextMessage(String content, User sender, MessageThread thread)
{
return new TextMessage(thread, sender, content);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/Messaging/TextMessage.java =====
package chat.ping.main.entity.Messaging;
import chat.ping.main.entity.MessageThread.MessageThread;
import chat.ping.main.entity.user.User;
public class TextMessage extends AbstractMessage
{
private String content;
public TextMessage(MessageThread messageThread,
User sender,
String content)
{
super(messageThread, sender);
this.content = content;
}
@Override
public String getContent()
{
return content;
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/entity/Messaging/AbstractMessage.java =====
package chat.ping.main.entity.Messaging;
import chat.ping.main.entity.MessageThread.MessageThread;
import chat.ping.main.entity.user.User;
import java.util.Date;
public abstract class AbstractMessage
{
private Long messageId;
private User sender;
private MessageThread thread;
private Date timestamp;
public AbstractMessage(MessageThread thread, User sender)
{
this.sender = sender;
this.thread = thread;
this.timestamp = new Date(); // Defaults to current timestamp
}
public Long getMessageId()
{
return messageId;
}
public User getSender()
{
return sender;
}
public MessageThread getThread()
{
return thread;
}
public Date getTimestamp()
{
return timestamp;
}
public void setTimestamp(Date timestamp)
{
this.timestamp = timestamp;
}
public void setMessageId(Long messageId)
{
this.messageId = messageId;
}
public abstract String getContent();
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/util/JsonUtil.java =====
package chat.ping.main.shared.util;
public class JsonUtil
{
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/util/DateFormatter.java =====
package chat.ping.main.shared.util;
public class DateFormatter
{
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/error/GlobalExceptionHandler.java =====
package chat.ping.main.shared.error;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
public class GlobalExceptionHandler
{
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse(
"InternalServerError",
"An unexpected error occurred."
);
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/error/ErrorResponse.java =====
package chat.ping.main.shared.error;
public class ErrorResponse
{
private String error;
private String message;
public ErrorResponse(String error, String message)
{
this.error = error;
this.message = message;
}
// Getters and Setters
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/validation/CredentialsValidator.java =====
package chat.ping.main.shared.validation;
public class CredentialsValidator
{
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/validation/UniqueUsernameValidator.java =====
package chat.ping.main.shared.validation;
public class UniqueUsernameValidator
{
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/validation/EmailValidator.java =====
package chat.ping.main.shared.validation;
import chat.ping.main.infrastructure.security.exception.InvalidCredentialsException;
import java.util.regex.Pattern;
public class EmailValidator
{
// Regular expression for email validation
private static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
/**
* Checks if the given string is a valid email.
*
* @param email The email to validate.
* @return True if valid, false otherwise.
*/
public static boolean isValid(String email)
{
if (email == null || email.trim().isEmpty())
{
return false;
}
return EMAIL_PATTERN.matcher(email).matches();
}
/**
* Validates the email and throws an exception if invalid.
*
* @param email The email to validate.
* @throws InvalidCredentialsException if email is invalid.
*/
public static void validate(String email)
{
if (!isValid(email))
{
throw new InvalidCredentialsException("Invalid email format.");
}
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/shared/validation/PasswordValidator.java =====
package chat.ping.main.shared.validation;
import chat.ping.main.infrastructure.security.exception.InvalidPasswordException;
import java.util.regex.Pattern;
public class PasswordValidator
{
// Define password rules
private static final int MIN_LENGTH = 8;
private static final int MAX_LENGTH = 32;
private static final String SPECIAL_CHARACTER_REGEX = "[^a-zA-Z0-9]";
private static final String DIGIT_REGEX = "\\d";
private static final String UPPERCASE_REGEX = "[A-Z]";
private static final String LOWERCASE_REGEX = "[a-z]";
public static boolean isValid(String password) {
// Null or empty check
if (password == null || password.trim().isEmpty()) {
throw new InvalidPasswordException("Password cannot be empty.");
}
// Length validation
if (password.length() < MIN_LENGTH || password.length() > MAX_LENGTH) {
throw new InvalidPasswordException("Password must be between " + MIN_LENGTH + " and " + MAX_LENGTH + " characters.");
}
// Special character validation
if (!Pattern.compile(SPECIAL_CHARACTER_REGEX).matcher(password).find()) {
throw new InvalidPasswordException("Password must contain at least one special character.");
}
// Digit validation
if (!Pattern.compile(DIGIT_REGEX).matcher(password).find()) {
throw new InvalidPasswordException("Password must contain at least one digit.");
}
// Uppercase letter validation
if (!Pattern.compile(UPPERCASE_REGEX).matcher(password).find()) {
throw new InvalidPasswordException("Password must contain at least one uppercase letter.");
}
// Lowercase letter validation
if (!Pattern.compile(LOWERCASE_REGEX).matcher(password).find()) {
throw new InvalidPasswordException("Password must contain at least one lowercase letter.");
}
return true;
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/helloWorld/HelloWorldController.java =====
package chat.ping.main.infrastructure.helloWorld;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController
{
@GetMapping("/api/hello")
public String helloWorld()
{
return "Hello, World!";
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/security/JWTUtils.java =====
package chat.ping.main.infrastructure.security;
import chat.ping.main.infrastructure.security.exception.InvalidTokenException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Map;
import java.util.function.Function;
@Component
public class JWTUtils
{
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private long jwtExpiration;
public String generateToken(@NotNull String username, Map<String, Object> claims)
{
return Jwts.builder()
.setClaims(claims)
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))
.signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)), SignatureAlgorithm.HS256)
.compact();
}
public String extractUserName(@NotNull String token)
{
return extractClaim(token, Claims::getSubject);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver)
{
Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token)
{
try
{
return Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret)))
.build()
.parseClaimsJws(token)
.getBody();
}
catch (JwtException e)
{
throw new InvalidTokenException("Invalid JWT Token");
}
}
public boolean isTokenValid(String token, String username)
{
if (!(username.equals(extractUserName(token)) && !isTokenExpired(token)))
{
throw new InvalidTokenException("Token Validation Failed: " + token);
}
return true;
}
private boolean isTokenExpired(String token)
{
return extractAllClaims(token).getExpiration().before(new Date());
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/security/JWTAuthFilter.java =====
package chat.ping.main.infrastructure.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class JWTAuthFilter extends OncePerRequestFilter
{
private final JWTUtils jwtUtils;
private final UserDetailsService userDetailsService;
public JWTAuthFilter(JWTUtils jwtUtils, UserDetailsService userDetailsService)
{
this.jwtUtils = jwtUtils;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException
{
// collect the authorization header
String authorizationHeader = request.getHeader("Authorization");
// make sure the response is valid
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer "))
{
filterChain.doFilter(request, response);
return;
}
// collect the token and extract the user id
String jwtToken = authorizationHeader.substring(7);
String username = jwtUtils.extractUserName(jwtToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null)
{
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// make sure token is valid
if (jwtUtils.isTokenValid(jwtToken, username))
{
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/security/exception/InvalidCredentialsException.java =====
package chat.ping.main.infrastructure.security.exception;
public class InvalidCredentialsException extends RuntimeException
{
public InvalidCredentialsException(String message) {
super(message);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/security/exception/InvalidTokenException.java =====
package chat.ping.main.infrastructure.security.exception;
public class InvalidTokenException extends RuntimeException
{
public InvalidTokenException(String message)
{
super(message);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/security/exception/InvalidPasswordException.java =====
package chat.ping.main.infrastructure.security.exception;
public class InvalidPasswordException extends RuntimeException
{
public InvalidPasswordException(String message) {
super(message);
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/security/UserDetailsServiceImplementation.java =====
package chat.ping.main.infrastructure.security;
import chat.ping.main.infrastructure.auth.gateway.JpaUserRepository;
import chat.ping.main.infrastructure.auth.gateway.UserDataMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.User;
@Service
public class UserDetailsServiceImplementation implements UserDetailsService {
private final JpaUserRepository userRepository;
public UserDetailsServiceImplementation(JpaUserRepository userRepository)
{
this.userRepository = userRepository;
}
/**
* Loads user-specific data by username or email for Spring Security.
*
* @param username The username provided during login.
* @return UserDetails containing user information (username, password, authorities).
* @throws UsernameNotFoundException if no user is found with the provided username/email.
*/
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException
{
// Attempt to find user by username or email
UserDataMapper user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found with Username: " + username));
// Return UserDetails object expected by Spring Security
return User.builder()
.username(user.getUsername())
.password(user.getPasswordHash()) // Password must be hashed
.authorities("ROLE_USER") // Default role, can be adjusted based on user data
.build();
}
}
===== /Users/ali/Documents/Projects/207.nosync/PingServer/src/main/java/chat/ping/main/infrastructure/auth/presenter/UserRegisterPresenter.java =====
package chat.ping.main.infrastructure.auth.presenter;
import chat.ping.main.entity.user.User;
import chat.ping.main.shared.error.ErrorResponse;
import chat.ping.main.usecase.auth.dto.UserRegisterResponseModel;
import chat.ping.main.usecase.auth.register.UserRegisterOutputBoundary;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
@Component
public class UserRegisterPresenter implements UserRegisterOutputBoundary
{
private ResponseEntity<?> responseEntity;
@Override
public void prepareSuccessView(User user)
{
UserRegisterResponseModel responseModel = new UserRegisterResponseModel(
user.getUsername(),
"User registered successfully!"
);
this.responseEntity = ResponseEntity.status(HttpStatus.CREATED).body(responseModel);
}
@Override
public void prepareUsernameAlreadyExistsView(String username) {
ErrorResponse errorResponse = new ErrorResponse(
"UsernameAlreadyExists",
"The username '" + username + "' is already taken."
);
this.responseEntity = ResponseEntity.status(HttpStatus.CONFLICT).body(errorResponse);
}
@Override
public void prepareEmailAlreadyExistsView(String email) {
ErrorResponse errorResponse = new ErrorResponse(
"EmailAlreadyExists",