[fdfbdde] | 1 | package com.example.task.service;
|
---|
| 2 |
|
---|
| 3 | import com.example.task.entity.StudentEntity;
|
---|
| 4 | import com.example.task.entity.TaskEntity;
|
---|
| 5 | import com.example.task.repository.StudentRepository;
|
---|
| 6 | import lombok.AllArgsConstructor;
|
---|
| 7 | import org.springframework.security.core.GrantedAuthority;
|
---|
| 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
---|
| 9 | import org.springframework.security.core.userdetails.User;
|
---|
| 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.password.PasswordEncoder;
|
---|
| 14 | import org.springframework.stereotype.Service;
|
---|
| 15 |
|
---|
| 16 | import java.util.ArrayList;
|
---|
| 17 | import java.util.List;
|
---|
| 18 | import java.util.Optional;
|
---|
| 19 |
|
---|
| 20 | @Service
|
---|
| 21 | @AllArgsConstructor
|
---|
| 22 | public class StudentService implements UserDetailsService {
|
---|
| 23 |
|
---|
| 24 | private final StudentRepository studentRepository;
|
---|
| 25 | private final PasswordEncoder passwordEncoder;
|
---|
| 26 |
|
---|
| 27 | public void registerNewStudent(String firstName, String lastName, String username, String password) throws Exception {
|
---|
| 28 | if (studentRepository.findByUsername(username).isPresent()) {
|
---|
| 29 | throw new Exception("Username already exists");
|
---|
| 30 | }
|
---|
| 31 | StudentEntity student = studentRepository.save(new StudentEntity(username, firstName, lastName, passwordEncoder.encode(password)));
|
---|
| 32 | }
|
---|
| 33 |
|
---|
| 34 |
|
---|
| 35 | @Override
|
---|
| 36 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
---|
| 37 | Optional<StudentEntity> user = studentRepository.findByUsername(username);
|
---|
| 38 | if (user.isEmpty()) {
|
---|
| 39 | throw new UsernameNotFoundException(username);
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | List<GrantedAuthority> authorities = new ArrayList<>();
|
---|
| 43 |
|
---|
| 44 | authorities.add(new SimpleGrantedAuthority("USER"));
|
---|
| 45 |
|
---|
| 46 | return new User(user.get().getUsername(), user.get().getPassword(), authorities);
|
---|
| 47 | }
|
---|
| 48 | }
|
---|