1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package cz.zcu.mre.service.account;
23
24 import cz.zcu.mre.data.account.Account;
25 import java.util.Collections;
26 import org.springframework.beans.factory.annotation.Autowired;
27 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
28 import org.springframework.security.core.*;
29 import org.springframework.security.core.authority.SimpleGrantedAuthority;
30 import org.springframework.security.core.context.SecurityContextHolder;
31 import org.springframework.security.core.userdetails.*;
32 import org.springframework.security.crypto.password.PasswordEncoder;
33 import cz.zcu.mre.service.data.DataService;
34 import org.springframework.context.annotation.Scope;
35 import org.springframework.context.annotation.ScopedProxyMode;
36 import org.springframework.stereotype.Service;
37
38
39
40
41
42 @Service
43 @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
44 public class AccountServiceImpl implements AccountService {
45
46 @Autowired
47 private DataService dataService;
48
49 @Autowired
50 private PasswordEncoder passwordEncoder;
51
52 public AccountServiceImpl() {
53 }
54
55 public AccountServiceImpl(DataService dataService, PasswordEncoder passwordEncoder) {
56
57 this.dataService = dataService;
58 this.passwordEncoder = passwordEncoder;
59 }
60
61 @Override
62 public Account save(Account account) {
63 account.setPassword(passwordEncoder.encode(account.getPassword()));
64 dataService.save(account);
65 return account;
66 }
67
68 @Override
69 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
70
71 Account account;
72
73 try {
74 account = findOneByEmail(username);
75 } catch (UsernameNotFoundException e) {
76 throw e;
77 }
78
79 return createUser(account);
80 }
81
82 @Override
83 public Account findOneByEmail(String username) {
84
85 Account query = new Account(username);
86 Account account = (Account) dataService.get(query);
87 if (account == null) {
88 throw new UsernameNotFoundException("User not found");
89 }
90
91 return account;
92 }
93
94 @Override
95 public void login(Account account) {
96 SecurityContextHolder.getContext().setAuthentication(authenticate(account));
97 }
98
99 private Authentication authenticate(Account account) {
100 return new UsernamePasswordAuthenticationToken(createUser(account), null, Collections.singleton(createAuthority(account)));
101 }
102
103 private User createUser(Account account) {
104 return new User(account.getEmail(), account.getPassword(), Collections.singleton(createAuthority(account)));
105 }
106
107 private GrantedAuthority createAuthority(Account account) {
108 return new SimpleGrantedAuthority(account.getRole());
109 }
110
111 }