mitm.djigzo.web.pages.portal.secure.OTP.java Source code

Java tutorial

Introduction

Here is the source code for mitm.djigzo.web.pages.portal.secure.OTP.java

Source

/*
 * Copyright (c) 2011-2012, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Common Development and 
 * Distribution License (CDDL), Common Public License (CPL) the 
 * licensors of this Program grant you additional permission to 
 * convey the resulting work.
 */
package mitm.djigzo.web.pages.portal.secure;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import mitm.application.djigzo.ws.OTPWS;
import mitm.common.mail.EmailAddressUtils;
import mitm.common.ws.WebServiceCheckedException;
import mitm.djigzo.web.services.DisableHttpCache;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Cached;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;

/**
 * One Time Password generator page
 */
@IncludeJavaScriptLibrary("otp.js")
@IncludeStylesheet("context:styles/pages/portal/secure/otp.css")
public class OTP {
    private final static Logger logger = LoggerFactory.getLogger(OTP.class);

    private final static String PASSWORD_ID_PARAMETER = "id";
    private final static String PASSWORD_LENGTH_PARAMETER = "pwl";

    @Inject
    private Request request;

    @Inject
    private OTPWS otpWS;

    /*
     * The 'unique' id which will be used together with the client secret to
     * generate the password
     * 
     * Note: FLASH persistency is used to keep the passwordID when the user switches between different pages 
     */
    @Persist(PersistenceConstants.FLASH)
    private String passwordID;

    /*
     * The generated password
     */
    @Persist(PersistenceConstants.FLASH)
    private String password;

    /*
     * The password length (in bytes)
     * 
     * Note: FLASH persistency is used to keep the passwordID when the user switches between different pages 
     */
    @Persist(PersistenceConstants.FLASH)
    private Integer passwordLength;

    /*
     * True if and error has occurred
     */
    @Persist(PersistenceConstants.FLASH)
    private boolean error;

    /*
     * Error message if an error has occurred
     */
    @Persist(PersistenceConstants.FLASH)
    private String errorMessage;

    @SuppressWarnings("unused")
    @Component(id = "passwordID", parameters = { "value = passwordID", "validate = required" })
    private TextField passwordIDField;

    @BeginRender
    @DisableHttpCache
    public void beginRender() {
        /*
         * empty on purpose. We need beginRender to set @DisableHttpCache
         */
    }

    protected void onActivate() {
        String paramValue = StringUtils.trimToNull(request.getParameter(PASSWORD_ID_PARAMETER));

        if (paramValue != null) {
            passwordID = paramValue;
        }

        paramValue = StringUtils.trimToNull(request.getParameter(PASSWORD_LENGTH_PARAMETER));

        if (paramValue != null) {
            passwordLength = NumberUtils.toInt(paramValue);

            if (passwordLength <= 0) {
                /*
                 * Fallback to default for the user
                 */
                passwordLength = null;
            }
        }
    }

    protected void onActivate(String passwordID) {
        this.passwordID = passwordID;
    }

    protected void onActivate(String passwordID, Integer passwordLength) {
        this.passwordID = passwordID;
        this.passwordLength = passwordLength;
    }

    protected Collection<Object> onPassivate() {
        List<Object> context = new LinkedList<Object>();

        if (passwordID != null) {
            context.add(passwordID);
        }

        if (passwordLength != null) {
            context.add(passwordLength);
        }

        return context;
    }

    /*
     * Returns the currently logged-in user
     */
    @Cached
    public String getLoginName() {
        String name = null;

        Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();

        if (currentUser != null) {
            name = currentUser.getName();
        }

        /*
         * The login name must be a valid email address
         */
        name = EmailAddressUtils.canonicalizeAndValidate(name, true);

        if (name == null) {
            throw new IllegalArgumentException("The user is not a valid email address.");
        }

        return name;
    }

    /*
     * Generates the one time password based on the client secret and mail id
     */
    private void generatePassword() throws WebServiceCheckedException {
        if (StringUtils.isNotEmpty(passwordID)) {
            password = otpWS.generate(getLoginName(), passwordID, passwordLength);
        }
    }

    public void onSuccess() {
        try {
            generatePassword();
        } catch (Exception e) {
            error = true;

            errorMessage = e.getMessage();
        }
    }

    public boolean isSecretKeySet() {
        boolean result = false;

        try {
            result = otpWS.hasClientSecret(getLoginName());
        } catch (WebServiceCheckedException e) {
            logger.error("Error otpWS#hasClientSecret", e);
        }

        return result;
    }

    public boolean isError() {
        return error;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public String getPassword() {
        return password;
    }

    public String getPasswordID() {
        return passwordID;
    }

    public void setPasswordID(String passwordID) {
        this.passwordID = StringUtils.trim(passwordID);
    }
}