Package murban.exerciser.api.dao

Source Code of murban.exerciser.api.dao.TokenFacade

/*
* 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 murban.exerciser.api.dao;

import java.math.BigInteger;
import java.security.SecureRandom;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import murban.exerciser.api.models.Token;

/**
*
* @author PSYcho
*/
@Stateless
public class TokenFacade extends AbstractFacade<Token> {

    @PersistenceContext(unitName = "exerciser")
    private EntityManager em;

    private SecureRandom random = new SecureRandom();

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public TokenFacade() {
        super(Token.class);
    }

    public Token getToken(String userid) {
        try {
            Token token = (Token) em.createNamedQuery("Token.findByUserid").setParameter("userid", userid).getSingleResult();
            return token;
        } catch (Exception ex) {
            return null;
        }
    }

    public Token createToken(String userid) {
        deleteToken(userid);
        Token token = new Token();
        token.setToken(getRandomToken());
        token.setUserid(userid);
        create(token);
        return token;
    }

    public void deleteToken(String userid) {
        try {
            Query query = em.createNamedQuery("Token.deleteByUserid").setParameter("userid", userid);
            query.executeUpdate();
        } catch (Exception ex) {
        }
    }

    public Token validateToken(String tokenValue) {
        try {
            Token token = (Token) em.createNamedQuery("Token.findByToken").setParameter("token", tokenValue).getSingleResult();
            if (token != null) {
                em.remove(token);
                return token;
            }
        } catch (Exception ex) {
        }
        return null;
    }

    public String getRandomToken() {
        return new BigInteger(130, random).toString(32);
    }
}
TOP

Related Classes of murban.exerciser.api.dao.TokenFacade

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.