com.nkapps.billing.services.AuthenticationService.java Source code

Java tutorial

Introduction

Here is the source code for com.nkapps.billing.services.AuthenticationService.java

Source

/*
 * 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 com.nkapps.billing.services;

import java.security.SecureRandom;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 *
 * @author administrator
 */
@Service("authenticationService")
@Scope("singleton")
public class AuthenticationService {

    private final static int TOKEN_TIMEOUT = 1000 * 60;

    private final SecureRandom random;

    private final Map<String, Token> map = new ConcurrentHashMap();

    public AuthenticationService() {
        random = new SecureRandom((new Date()).toString().getBytes());
    }

    public String getNonce(String serialNumber, String remoteAddr) {
        synchronized (map) {
            byte[] r = new byte[128];
            random.nextBytes(r);
            // fake algorithm
            String nonce = Hex.toHexString(new byte[] { 0 });
            map.put(serialNumber, new Token(serialNumber, nonce, remoteAddr));
            clearTimedOut();
            return nonce;
        }
    }

    public void clearTimedOut() {
        List<String> list = new LinkedList();
        for (String serialNumber : map.keySet()) {
            Token t = map.get(serialNumber);
            if (t.isTimedOut())
                list.add(serialNumber);
        }
        for (String sn : list) {
            map.remove(sn);
        }
    }

    public Token getToken(String serialNumber) {
        return map.remove(serialNumber);
    }

    public class Token {

        private final String serialNumber;

        private final String nonce;

        private final String remoteAddr;

        private final Date validTo;

        public Token(String serialNumber, String nonce, String remoteAddr) {
            this.serialNumber = serialNumber;
            this.nonce = nonce;
            this.remoteAddr = remoteAddr;
            this.validTo = new Date(new Date().getTime() + TOKEN_TIMEOUT);
        }

        public String getSerialNumber() {
            return serialNumber;
        }

        public String getNonce() {
            return nonce;
        }

        public String getRemoteAddr() {
            return remoteAddr;
        }

        public Date getValidTo() {
            return validTo;
        }

        public boolean isTimedOut() {
            Date now = new Date();
            return now.getTime() > validTo.getTime();
        }
    }
}