/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package httpauthenticationmechanism;

import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT;

import java.util.Optional;
import java.util.Set;
import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.security.enterprise.CallerPrincipal;
import javax.security.enterprise.credential.RememberMeCredential;
import javax.security.enterprise.identitystore.CredentialValidationResult;
import javax.security.enterprise.identitystore.RememberMeIdentityStore;
import javax.servlet.http.HttpServletRequest;

import business.user.TokenManager;
import business.user.PersonManager;
import model.person.Person;
import static model.person.enums.TokenType.REMEMBER_ME;

/**
 *
 * @author Patrick
 */
@ApplicationScoped
public class AppRememberMeIdentityStore implements RememberMeIdentityStore {
    @Inject
    HttpServletRequest request;
    
    @EJB
    PersonManager userManager;
    
    @EJB
    TokenManager tokenManager;

    @Override
    public CredentialValidationResult validate(RememberMeCredential rmc) {
        Optional<Person> user = this.userManager.getByLoginToken(rmc.getToken(), REMEMBER_ME);

        if (user.isPresent()) {
            return new CredentialValidationResult(user.get().getEmail());
        } else {
            return INVALID_RESULT;
        }
    }

    @Override
    public String generateLoginToken(CallerPrincipal cp, Set<String> set) {
        return this.tokenManager.generate(cp.getName(), getRemoteAddr(request), getDescription(), REMEMBER_ME);
    }

    @Override
    public void removeLoginToken(String string) {
        this.tokenManager.remove(string);
    }
    
    private String getRemoteAddr(HttpServletRequest request){
        return request.getRemoteAddr();
    }
    
    private String getDescription() {
        return "Remember me session: " + this.request.getHeader("User-Agent");
    }
}
