001package usecase.auth;
002
003import model.entity.User;
004import model.repository.GenericRepository;
005
006import javax.enterprise.context.RequestScoped;
007import javax.enterprise.context.SessionScoped;
008import javax.enterprise.inject.Produces;
009import javax.inject.Inject;
010import javax.inject.Named;
011import javax.transaction.Transactional;
012import java.io.Serializable;
013import java.time.Instant;
014
015/**
016 * Classe che fornisce i servizi relativi all'autenticazione.
017 */
018@SessionScoped
019@Transactional
020public class AuthenticationService implements Serializable {
021    private GenericRepository genericRepository;
022    private Pbkdf2PasswordHash passwordHash;
023    private int currentUserId = 0;
024
025    protected AuthenticationService(){}
026
027    @Inject
028    protected AuthenticationService(GenericRepository genericRepository,
029                                    Pbkdf2PasswordHash passwordHash){
030        this.genericRepository = genericRepository;
031        this.passwordHash = passwordHash;
032    }
033
034
035    /**
036     * Autentica un utente
037     * @param username stringa con nome utente
038     * @param password stringa con password
039     * @return esito dell'operazione
040     */
041    public boolean authenticate(String username, String password){
042        User user = genericRepository.findByNaturalId(User.class,username);
043        if(user == null)
044            return false;
045        if (passwordHash.verify(password, user.getPassword(), user.getSalt())){
046            currentUserId = user.getId();
047            return true;
048        } else {
049            return false;
050        }
051    }
052
053    /**
054     * Ritorna l'utente in uso e ne rende accessibile i dati nelle jsp
055     * @return utente in uso
056     */
057    @Named("currentUser") //accessibile nelle jsp con ${currentUser}
058    @RequestScoped
059    @Produces
060    public CurrentUser getCurrentUser(){
061        if(currentUserId <= 0)
062            return new CurrentUser();
063
064        User user = genericRepository.findById(User.class,currentUserId);
065        if(user == null)
066            return new CurrentUser();
067
068        Instant longestCurrentBan = user.getBans().isEmpty() ? null : user.getBans().get(0).getEndTime();
069
070        CurrentUser currentUser = CurrentUser.builder()
071                .username(user.getUsername())
072                .id(user.getId())
073                .isAdmin(user.getAdmin())
074                .picture(user.getPicture())
075                .banDuration(longestCurrentBan)
076                .isLoggedIn(true)
077                .build();
078
079        System.out.println(currentUser);
080        return currentUser;
081    }
082
083}