source: src/main/java/com/example/task/service/StudentService.java@ fdfbdde

Last change on this file since fdfbdde was fdfbdde, checked in by Stojilkova Sara <sara.stojilkova.students.finki.ukim.mk>, 9 months ago

Initial commit

  • Property mode set to 100644
File size: 1.9 KB
Line 
1package com.example.task.service;
2
3import com.example.task.entity.StudentEntity;
4import com.example.task.entity.TaskEntity;
5import com.example.task.repository.StudentRepository;
6import lombok.AllArgsConstructor;
7import org.springframework.security.core.GrantedAuthority;
8import org.springframework.security.core.authority.SimpleGrantedAuthority;
9import org.springframework.security.core.userdetails.User;
10import org.springframework.security.core.userdetails.UserDetails;
11import org.springframework.security.core.userdetails.UserDetailsService;
12import org.springframework.security.core.userdetails.UsernameNotFoundException;
13import org.springframework.security.crypto.password.PasswordEncoder;
14import org.springframework.stereotype.Service;
15
16import java.util.ArrayList;
17import java.util.List;
18import java.util.Optional;
19
20@Service
21@AllArgsConstructor
22public 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}
Note: See TracBrowser for help on using the repository browser.