1 | package finki.it.phoneluxbackend.services;
|
---|
2 |
|
---|
3 |
|
---|
4 | import finki.it.phoneluxbackend.entities.User;
|
---|
5 | import finki.it.phoneluxbackend.repositories.UserRepository;
|
---|
6 | import finki.it.phoneluxbackend.entities.ConfirmationToken;
|
---|
7 | import lombok.AllArgsConstructor;
|
---|
8 |
|
---|
9 | import org.springframework.http.ResponseEntity;
|
---|
10 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
11 | import org.springframework.security.core.userdetails.UserDetailsService;
|
---|
12 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
---|
13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
---|
14 | import org.springframework.stereotype.Service;
|
---|
15 |
|
---|
16 | import java.time.LocalDateTime;
|
---|
17 |
|
---|
18 | import java.util.UUID;
|
---|
19 |
|
---|
20 | @Service
|
---|
21 | @AllArgsConstructor
|
---|
22 | public class UserService implements UserDetailsService {
|
---|
23 | private final UserRepository userRepository;
|
---|
24 | private final BCryptPasswordEncoder bCryptPasswordEncoder;
|
---|
25 | private final ConfirmationTokenService confirmationTokenService;
|
---|
26 |
|
---|
27 |
|
---|
28 | @Override
|
---|
29 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
---|
30 | return userRepository.findByEmail(email)
|
---|
31 | .orElseThrow(() -> new UsernameNotFoundException("User with email "+email+" not found!"));
|
---|
32 | }
|
---|
33 |
|
---|
34 | public ResponseEntity<Object> signUpUser(User user)
|
---|
35 | {
|
---|
36 | boolean userExists = userRepository.findByEmail(user.getEmail()).isPresent();
|
---|
37 |
|
---|
38 |
|
---|
39 | if (userExists){
|
---|
40 | User userToRegister = userRepository.findByEmail(user.getEmail()).get();
|
---|
41 | if(userToRegister.getEnabled()) {
|
---|
42 | return ResponseEntity.badRequest().body("Error:Е-маил адресата е веќе зафатена!");
|
---|
43 | }
|
---|
44 | else {
|
---|
45 | return ResponseEntity.badRequest().body("Error:Профилот не е активиран. Потврдете на вашата е-маил адреса!" );
|
---|
46 | }
|
---|
47 | }
|
---|
48 |
|
---|
49 | String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
|
---|
50 |
|
---|
51 | user.setPassword(encodedPassword);
|
---|
52 |
|
---|
53 | String token = UUID.randomUUID().toString();
|
---|
54 | ConfirmationToken confirmationToken = new ConfirmationToken(token,
|
---|
55 | LocalDateTime.now(),
|
---|
56 | LocalDateTime.now().plusMinutes(15),
|
---|
57 | user
|
---|
58 | );
|
---|
59 |
|
---|
60 | confirmationTokenService.saveConfirmationToken(confirmationToken);
|
---|
61 |
|
---|
62 | return ResponseEntity.ok().body("token:"+token);
|
---|
63 | }
|
---|
64 |
|
---|
65 | public int enableUser(String email) {
|
---|
66 | return userRepository.enableUser(email);
|
---|
67 | }
|
---|
68 |
|
---|
69 |
|
---|
70 | }
|
---|