1 | package finki.it.phoneluxbackend.services;
|
---|
2 |
|
---|
3 | import finki.it.phoneluxbackend.entities.User;
|
---|
4 | import finki.it.phoneluxbackend.repositories.UserRepository;
|
---|
5 | import finki.it.phoneluxbackend.entities.ConfirmationToken;
|
---|
6 | import lombok.AllArgsConstructor;
|
---|
7 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
8 | import org.springframework.security.core.userdetails.UserDetailsService;
|
---|
9 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
---|
10 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
---|
11 | import org.springframework.stereotype.Service;
|
---|
12 |
|
---|
13 | import java.time.LocalDateTime;
|
---|
14 | import java.util.UUID;
|
---|
15 |
|
---|
16 | @Service
|
---|
17 | @AllArgsConstructor
|
---|
18 | public class UserService implements UserDetailsService {
|
---|
19 | private final UserRepository userRepository;
|
---|
20 | private final BCryptPasswordEncoder bCryptPasswordEncoder;
|
---|
21 | private final ConfirmationTokenService confirmationTokenService;
|
---|
22 |
|
---|
23 |
|
---|
24 | @Override
|
---|
25 | public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
|
---|
26 | return userRepository.findByEmail(email)
|
---|
27 | .orElseThrow(() -> new UsernameNotFoundException("User with email "+email+" not found!"));
|
---|
28 | }
|
---|
29 |
|
---|
30 | public String signUpUser(User user)
|
---|
31 | {
|
---|
32 | boolean userExists = userRepository.findByEmail(user.getEmail()).isPresent();
|
---|
33 |
|
---|
34 | if (userExists && user.getEnabled()){
|
---|
35 | throw new IllegalStateException("Email "+user.getEmail()+" already taken!");
|
---|
36 | }
|
---|
37 |
|
---|
38 | String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
|
---|
39 |
|
---|
40 | user.setPassword(encodedPassword);
|
---|
41 |
|
---|
42 | String token = UUID.randomUUID().toString();
|
---|
43 | ConfirmationToken confirmationToken = new ConfirmationToken(token,
|
---|
44 | LocalDateTime.now(),
|
---|
45 | LocalDateTime.now().plusMinutes(15),
|
---|
46 | user
|
---|
47 | );
|
---|
48 |
|
---|
49 | confirmationTokenService.saveConfirmationToken(confirmationToken);
|
---|
50 |
|
---|
51 | return token;
|
---|
52 | }
|
---|
53 |
|
---|
54 | public int enableUser(String email) {
|
---|
55 | return userRepository.enableUser(email);
|
---|
56 | }
|
---|
57 |
|
---|
58 |
|
---|
59 | }
|
---|