-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthenticationService.java
48 lines (40 loc) · 1.76 KB
/
AuthenticationService.java
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
package com.github.yangricardo.api_spring_boot.modules.auth.services;
import com.github.yangricardo.api_spring_boot.modules.auth.model.CreateUserDTO;
import com.github.yangricardo.api_spring_boot.modules.users.model.User;
import com.github.yangricardo.api_spring_boot.modules.users.services.IUserService;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class AuthenticationService implements UserDetailsService {
@Autowired
private IUserService userService;
@Autowired
PasswordEncoder passwordEncoder;
public AuthenticationService(IUserService userService) {
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> user = userService.findByUsername(username);
if (user.isPresent()) {
return user.get();
}
throw new UsernameNotFoundException("User not found");
}
public User createUser(CreateUserDTO createUserDTO) throws Exception {
Optional<User> userFound = this.userService.findByUsername(createUserDTO.getUsername());
if (userFound.isPresent()) {
throw new Exception("Email already Taken");
}
User user = User.builder()
.username(createUserDTO.getUsername())
.password(passwordEncoder.encode(createUserDTO.getPassword()))
.build();
return userService.create(user);
}
}