1 package usecase.auth;
2
3 import model.entity.User;
4 import model.repository.GenericRepository;
5
6 import javax.enterprise.context.RequestScoped;
7 import javax.enterprise.context.SessionScoped;
8 import javax.enterprise.inject.Produces;
9 import javax.inject.Inject;
10 import javax.inject.Named;
11 import javax.transaction.Transactional;
12 import java.io.Serializable;
13 import java.time.Instant;
14
15
16
17
18 @SessionScoped
19 @Transactional
20 public class AuthenticationService implements Serializable {
21 private GenericRepository genericRepository;
22 private Pbkdf2PasswordHash passwordHash;
23 private int currentUserId = 0;
24
25 protected AuthenticationService(){}
26
27 @Inject
28 protected AuthenticationService(GenericRepository genericRepository,
29 Pbkdf2PasswordHash passwordHash){
30 this.genericRepository = genericRepository;
31 this.passwordHash = passwordHash;
32 }
33
34
35
36
37
38
39
40
41 public boolean authenticate(String username, String password){
42 User user = genericRepository.findByNaturalId(User.class,username);
43 if(user == null)
44 return false;
45 if (passwordHash.verify(password, user.getPassword(), user.getSalt())){
46 currentUserId = user.getId();
47 return true;
48 } else {
49 return false;
50 }
51 }
52
53
54
55
56
57 @Named("currentUser")
58 @RequestScoped
59 @Produces
60 public CurrentUser getCurrentUser(){
61 if(currentUserId <= 0)
62 return new CurrentUser();
63
64 User user = genericRepository.findById(User.class,currentUserId);
65 if(user == null)
66 return new CurrentUser();
67
68 Instant longestCurrentBan = user.getBans().isEmpty() ? null : user.getBans().get(0).getEndTime();
69
70 CurrentUser currentUser = CurrentUser.builder()
71 .username(user.getUsername())
72 .id(user.getId())
73 .isAdmin(user.getAdmin())
74 .picture(user.getPicture())
75 .banDuration(longestCurrentBan)
76 .isLoggedIn(true)
77 .build();
78
79 System.out.println(currentUser);
80 return currentUser;
81 }
82
83 }