1 | package edu.gjoko.schedlr.services;
|
---|
2 |
|
---|
3 | import edu.gjoko.schedlr.entity.Business;
|
---|
4 | import edu.gjoko.schedlr.entity.BusinessStatus;
|
---|
5 | import edu.gjoko.schedlr.entity.Stakeholder;
|
---|
6 | import edu.gjoko.schedlr.entity.StakeholderType;
|
---|
7 | import edu.gjoko.schedlr.repositories.BusinessRepository;
|
---|
8 | import edu.gjoko.schedlr.repositories.StakeholderRepository;
|
---|
9 | import lombok.RequiredArgsConstructor;
|
---|
10 | import org.springframework.security.core.GrantedAuthority;
|
---|
11 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
---|
12 | import org.springframework.security.core.userdetails.User;
|
---|
13 | import org.springframework.security.core.userdetails.UserDetails;
|
---|
14 | import org.springframework.security.core.userdetails.UserDetailsService;
|
---|
15 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
---|
16 | import org.springframework.stereotype.Service;
|
---|
17 |
|
---|
18 | import java.util.HashSet;
|
---|
19 | import java.util.Set;
|
---|
20 |
|
---|
21 | @Service
|
---|
22 | @RequiredArgsConstructor
|
---|
23 | public class PostgresUserDetailsService implements UserDetailsService {
|
---|
24 |
|
---|
25 | private final StakeholderRepository stakeholderRepository;
|
---|
26 | private final BusinessRepository businessRepository;
|
---|
27 |
|
---|
28 | @Override
|
---|
29 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
---|
30 | Stakeholder user = stakeholderRepository.findStakeholderByUsername(username);
|
---|
31 | if (user == null) {
|
---|
32 | throw new UsernameNotFoundException("Non existing user");
|
---|
33 | }
|
---|
34 |
|
---|
35 | if (user.getStakeholderType() == StakeholderType.BUSINESS_OWNER) {
|
---|
36 | Business business = businessRepository.findBusinessByOwner(user);
|
---|
37 | if (business.getBusinessStatus() != BusinessStatus.ACTIVE) {
|
---|
38 | throw new SecurityException("User not approved by admin");
|
---|
39 | }
|
---|
40 | }
|
---|
41 | Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
|
---|
42 | grantedAuthorities.add(new SimpleGrantedAuthority(user.getStakeholderType().name()));
|
---|
43 |
|
---|
44 | return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
|
---|
45 | }
|
---|
46 |
|
---|
47 | public Long loadStakeholderId(String username) {
|
---|
48 | return stakeholderRepository.findStakeholderByUsername(username).getId();
|
---|
49 | }
|
---|
50 | }
|
---|