at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.configuration.struts.action.IndexAction.java

Source

/*******************************************************************************
 * Copyright 2014 Federal Chancellery Austria
 * MOA-ID has been developed in a cooperation between BRZ, the Federal
 * Chancellery Austria - ICT staff unit, and Graz University of Technology.
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * http://www.osor.eu/eupl/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 *
 * This product combines work with different licenses. See the "NOTICE" text
 * file for details on the various modules and licenses.
 * The "NOTICE" text file is part of the distribution. Any derivative works
 * that you distribute must include a readable copy of the "NOTICE" text file.
 *******************************************************************************/
package at.gv.egovernment.moa.id.configuration.struts.action;

import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.BasicSAMLMessageContext;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.binding.decoding.HTTPPostDecoder;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.Conditions;
import org.opensaml.saml2.core.EncryptedAssertion;
import org.opensaml.saml2.core.NameID;
import org.opensaml.saml2.core.Response;
import org.opensaml.saml2.core.StatusCode;
import org.opensaml.saml2.core.Subject;
import org.opensaml.saml2.encryption.Decrypter;
import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver;
import org.opensaml.saml2.metadata.IDPSSODescriptor;
import org.opensaml.security.MetadataCredentialResolver;
import org.opensaml.security.MetadataCredentialResolverFactory;
import org.opensaml.security.MetadataCriteria;
import org.opensaml.security.SAMLSignatureProfileValidator;
import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver;
import org.opensaml.xml.encryption.InlineEncryptedKeyResolver;
import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver;
import org.opensaml.xml.parse.BasicParserPool;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.credential.UsageType;
import org.opensaml.xml.security.criteria.EntityIDCriteria;
import org.opensaml.xml.security.criteria.UsageCriteria;
import org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver;
import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver;
import org.opensaml.xml.security.keyinfo.KeyInfoProvider;
import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver;
import org.opensaml.xml.security.keyinfo.provider.DSAKeyValueProvider;
import org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider;
import org.opensaml.xml.security.keyinfo.provider.RSAKeyValueProvider;
import org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter;
import org.opensaml.xml.security.x509.X509Credential;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.impl.ExplicitKeySignatureTrustEngine;

import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead;
import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils;
import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication;
import at.gv.egovernment.moa.id.commons.db.dao.config.UserDatabase;
import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
import at.gv.egovernment.moa.id.commons.validation.ValidationHelper;
import at.gv.egovernment.moa.id.configuration.Constants;
import at.gv.egovernment.moa.id.configuration.auth.AuthenticatedUser;
import at.gv.egovernment.moa.id.configuration.auth.AuthenticationManager;
import at.gv.egovernment.moa.id.configuration.auth.pvp2.PVP2Utils;
import at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider;
import at.gv.egovernment.moa.id.configuration.data.UserDatabaseFrom;
import at.gv.egovernment.moa.id.configuration.exception.BasicActionException;
import at.gv.egovernment.moa.id.configuration.exception.ConfigurationException;
import at.gv.egovernment.moa.id.configuration.helper.AuthenticationHelper;
import at.gv.egovernment.moa.id.configuration.helper.DateTimeHelper;
import at.gv.egovernment.moa.id.configuration.helper.LanguageHelper;
import at.gv.egovernment.moa.id.configuration.helper.MailHelper;
import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
import at.gv.egovernment.moa.id.util.Random;
import at.gv.egovernment.moa.util.MiscUtil;

public class IndexAction extends BasicAction {

    /**
     * @throws ConfigurationException
     */

    private static final long serialVersionUID = -2781497863862504896L;

    private static final Logger log = Logger.getLogger(IndexAction.class);

    private String password;
    private String username;
    private UserDatabaseFrom user = null;
    private String formID;

    private String ssologouturl;

    private boolean pvp2LoginActiv = false;

    public IndexAction() throws BasicActionException {
        super();
    }

    public String start() {
        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        pvp2LoginActiv = configuration.isPVP2LoginActive();

        if (session.getAttribute(Constants.SESSION_I18n) == null)
            session.setAttribute(Constants.SESSION_I18n, Locale.forLanguageTag(configuration.getDefaultLanguage()));

        if (configuration.isLoginDeaktivated()) {
            return "loginWithOutAuth";

        } else {
            return Constants.STRUTS_SUCCESS;

        }
    }

    public String authenticate() {

        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        pvp2LoginActiv = configuration.isPVP2LoginActive();

        String key = null;

        if (MiscUtil.isNotEmpty(username)) {
            if (ValidationHelper.containsPotentialCSSCharacter(username, false)) {
                log.warn("Username contains potentail XSS characters: " + username);
                addActionError(LanguageHelper.getErrorString("validation.edituser.username.valid",
                        new Object[] { ValidationHelper.getPotentialCSSCharacter(false) }, request));
                return Constants.STRUTS_ERROR;
            }
        } else {
            log.warn("Username is empty");
            addActionError(LanguageHelper.getErrorString("validation.edituser.username.empty", request));
            return Constants.STRUTS_ERROR;
        }

        if (MiscUtil.isEmpty(password)) {
            log.warn("Password is empty");
            addActionError(LanguageHelper.getErrorString("validation.edituser.password.empty", request));
            return Constants.STRUTS_ERROR;

        } else {
            key = AuthenticationHelper.generateKeyFormPassword(password);
            if (key == null) {
                addActionError(LanguageHelper.getErrorString("validation.edituser.password.valid", request));
                return Constants.STRUTS_ERROR;
            }
        }

        UserDatabase dbuser = ConfigurationDBRead.getUserWithUserName(username);
        if (dbuser == null) {
            log.warn("Unknown Username");
            addActionError(LanguageHelper.getErrorString("webpages.index.login.notallowed", request));
            return Constants.STRUTS_ERROR;

        } else {
            //TODO: maybe remove this default value in a later version
            if (dbuser.isIsUsernamePasswordAllowed() == null)
                dbuser.setIsUsernamePasswordAllowed(true);

            if (!dbuser.isIsActive() || !dbuser.isIsUsernamePasswordAllowed()) {
                log.warn("Username " + dbuser.getUsername()
                        + " is not active or Username/Password login is not allowed");
                addActionError(LanguageHelper.getErrorString("webpages.index.login.notallowed", request));
                return Constants.STRUTS_ERROR;
            }

            if (!dbuser.getPassword().equals(key)) {
                log.warn("Username " + dbuser.getUsername() + " use a false password");
                addActionError(LanguageHelper.getErrorString("webpages.index.login.notallowed", request));
                return Constants.STRUTS_ERROR;
            }

            //TODO: maybe remove this default value in a later version 
            boolean ismandateuser = false;
            if (dbuser.isIsMandateUser() != null)
                ismandateuser = dbuser.isIsMandateUser();

            int sessionTimeOut = session.getMaxInactiveInterval();
            Date sessionExpired = new Date(
                    new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

            AuthenticatedUser authuser = new AuthenticatedUser(dbuser, true, ismandateuser, false,
                    dbuser.getHjid() + "dbID", "username/password", sessionExpired);

            //store user as authenticated user
            AuthenticationManager authManager = AuthenticationManager.getInstance();
            authManager.setActiveUser(authuser);

            Date date = DateTimeHelper.parseDateTime(dbuser.getLastLogin());
            if (date != null)
                authuser.setLastLogin(date);
            ;

            dbuser.setLastLogin(DateTimeHelper.getDateTime(new Date()));

            try {
                ConfigurationDBUtils.saveOrUpdate(dbuser);

            } catch (MOADatabaseException e) {
                log.warn("UserDatabase communicaton error", e);
                addActionError(LanguageHelper.getErrorString("error.login", request));
                return Constants.STRUTS_ERROR;
            } finally {
                ConfigurationDBUtils.closeSession();
            }

            HttpSession session = generateNewJSession(request);
            session.setAttribute(Constants.SESSION_AUTH, authuser);

            return Constants.STRUTS_SUCCESS;
        }
    }

    public String pvp2login() {

        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        String method = request.getMethod();
        if (session == null) {
            log.info("NO HTTP Session");
            return Constants.STRUTS_ERROR;
        }

        String authID = (String) session.getAttribute(Constants.SESSION_PVP2REQUESTID);
        session.setAttribute(Constants.SESSION_PVP2REQUESTID, null);

        if (method.equals("POST")) {

            try {
                pvp2LoginActiv = configuration.isPVP2LoginActive();

                //Decode with HttpPost Binding
                HTTPPostDecoder decode = new HTTPPostDecoder(new BasicParserPool());
                BasicSAMLMessageContext<Response, ?, ?> messageContext = new BasicSAMLMessageContext<Response, SAMLObject, SAMLObject>();
                messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request));
                decode.decode(messageContext);

                Response samlResponse = (Response) messageContext.getInboundMessage();

                //ckeck InResponseTo matchs requestID 
                if (MiscUtil.isEmpty(authID)) {
                    log.info("NO AuthRequestID");
                    return Constants.STRUTS_ERROR;
                }

                if (!authID.equals(samlResponse.getInResponseTo())) {
                    log.warn("PVPRequestID does not match PVP2 Assertion ID!");
                    return Constants.STRUTS_ERROR;

                }

                //check response destination
                String serviceURL = configuration.getPublicUrlPreFix(request);
                if (!serviceURL.endsWith("/"))
                    serviceURL = serviceURL + "/";

                String responseDestination = samlResponse.getDestination();
                if (MiscUtil.isEmpty(responseDestination)
                        || !responseDestination.equals(serviceURL + Constants.SERVLET_PVP2ASSERTION)) {
                    log.warn("PVPResponse destination does not match requested destination");
                    return Constants.STRUTS_ERROR;
                }

                //check if response is signed
                Signature sign = samlResponse.getSignature();
                if (sign == null) {
                    log.info("Only http POST Requests can be used");
                    addActionError(LanguageHelper.getErrorString("error.login", request));
                    return Constants.STRUTS_ERROR;
                }

                //validate signature
                PVP2Utils.validateSignature(samlResponse, configuration);

                log.info("PVP2 Assertion is valid");

                if (samlResponse.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) {

                    List<org.opensaml.saml2.core.Assertion> saml2assertions = new ArrayList<org.opensaml.saml2.core.Assertion>();

                    //check encrypted Assertion
                    List<EncryptedAssertion> encryAssertionList = samlResponse.getEncryptedAssertions();
                    if (encryAssertionList != null && encryAssertionList.size() > 0) {
                        //decrypt assertions

                        log.debug("Found encryped assertion. Start decryption ...");

                        KeyStore keyStore = configuration.getPVP2KeyStore();

                        X509Credential authDecCredential = new KeyStoreX509CredentialAdapter(keyStore,
                                configuration.getPVP2KeystoreAuthRequestEncryptionKeyAlias(),
                                configuration.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray());

                        StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(
                                authDecCredential);

                        ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver();
                        encryptedKeyResolver.getResolverChain().add(new InlineEncryptedKeyResolver());
                        encryptedKeyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver());
                        encryptedKeyResolver.getResolverChain()
                                .add(new SimpleRetrievalMethodEncryptedKeyResolver());

                        Decrypter samlDecrypter = new Decrypter(null, skicr, encryptedKeyResolver);

                        for (EncryptedAssertion encAssertion : encryAssertionList) {
                            saml2assertions.add(samlDecrypter.decrypt(encAssertion));

                        }

                        log.debug("Assertion decryption finished. ");

                    } else {
                        saml2assertions = samlResponse.getAssertions();

                    }

                    for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) {

                        Conditions conditions = saml2assertion.getConditions();
                        DateTime notbefore = conditions.getNotBefore();
                        DateTime notafter = conditions.getNotOnOrAfter();
                        if (notbefore.isAfterNow() || notafter.isBeforeNow()) {
                            log.warn("PVP2 Assertion is out of Date");
                            return Constants.STRUTS_ERROR;

                        }

                        Subject subject = saml2assertion.getSubject();
                        if (subject == null) {
                            log.warn("Assertion has no Subject element");
                            return Constants.STRUTS_ERROR;

                        }

                        NameID nameID = subject.getNameID();
                        if (nameID == null) {
                            log.warn("No NameID element in PVP2 assertion!");
                            return Constants.STRUTS_ERROR;
                        }

                        String bpkwbpk = nameID.getNameQualifier() + "+" + nameID.getValue();

                        int sessionTimeOut = session.getMaxInactiveInterval();
                        Date sessionExpired = new Date(
                                new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

                        //search user
                        UserDatabase dbuser = ConfigurationDBRead.getUserWithUserBPKWBPK(bpkwbpk);
                        if (dbuser == null) {
                            log.info("No user found with bpk/wbpk " + bpkwbpk);

                            //read PVP2 assertion attributes;
                            user = new UserDatabaseFrom();
                            user.setActive(false);
                            user.setAdmin(false);
                            user.setBpk(bpkwbpk);
                            user.setIsusernamepasswordallowed(false);
                            user.setIsmandateuser(false);
                            user.setPVPGenerated(true);

                            //loop through the nodes to get what we want
                            List<AttributeStatement> attributeStatements = saml2assertion.getAttributeStatements();
                            for (int i = 0; i < attributeStatements.size(); i++) {
                                List<Attribute> attributes = attributeStatements.get(i).getAttributes();
                                for (int x = 0; x < attributes.size(); x++) {
                                    String strAttributeName = attributes.get(x).getDOM().getAttribute("Name");

                                    if (strAttributeName.equals(PVPConstants.PRINCIPAL_NAME_NAME)) {
                                        user.setFamilyName(attributes.get(x).getAttributeValues().get(0).getDOM()
                                                .getTextContent());
                                    }

                                    if (strAttributeName.equals(PVPConstants.GIVEN_NAME_NAME)) {
                                        user.setGivenName(attributes.get(x).getAttributeValues().get(0).getDOM()
                                                .getTextContent());
                                    }

                                    if (strAttributeName.equals(PVPConstants.MANDATE_TYPE_NAME)) {
                                        user.setIsmandateuser(true);
                                    }

                                    if (strAttributeName.equals(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME)) {
                                        user.setInstitut(attributes.get(x).getAttributeValues().get(0).getDOM()
                                                .getTextContent());
                                    }
                                }
                            }

                            //create AuthUser data element
                            authUser = AuthenticatedUser.generateUserRequestUser(user, nameID.getValue(),
                                    nameID.getFormat(), sessionExpired);

                            //store user as authenticated user
                            AuthenticationManager authManager = AuthenticationManager.getInstance();
                            authManager.setActiveUser(authUser);

                            //set Random value
                            formID = Random.nextRandom();
                            session.setAttribute(Constants.SESSION_FORMID, formID);
                            session.setAttribute(Constants.SESSION_FORM, user);
                            session.setAttribute(Constants.SESSION_AUTH, authUser);

                            ConfigurationDBUtils.closeSession();

                            return Constants.STRUTS_NEWUSER;

                        } else {
                            if (!dbuser.isIsActive()) {

                                if (!dbuser.isIsMailAddressVerified()) {

                                    formID = Random.nextRandom();
                                    session.setAttribute(Constants.SESSION_FORMID, formID);

                                    user = new UserDatabaseFrom(dbuser);
                                    authUser = new AuthenticatedUser(dbuser, false, dbuser.isIsMandateUser(), true,
                                            nameID.getValue(), nameID.getFormat(), sessionExpired);

                                    //store user as authenticated user
                                    AuthenticationManager authManager = AuthenticationManager.getInstance();
                                    authManager.setActiveUser(authUser);

                                    session.setAttribute(Constants.SESSION_FORM, user);
                                    session.setAttribute(Constants.SESSION_AUTH, authUser);

                                    return Constants.STRUTS_NEWUSER;

                                }

                                log.info("User with bpk/wbpk " + bpkwbpk + " is not active");
                                addActionError(LanguageHelper.getErrorString("webpages.index.username.notactive",
                                        request));
                                return Constants.STRUTS_ERROR;
                            }

                            //TODO: maybe remove this default value in a later version 
                            boolean ismandateuser = false;
                            if (dbuser.isIsMandateUser() != null)
                                ismandateuser = dbuser.isIsMandateUser();

                            authUser = new AuthenticatedUser(dbuser, true, ismandateuser, true, nameID.getValue(),
                                    nameID.getFormat(), sessionExpired);

                            //store user as authenticated user
                            AuthenticationManager authManager = AuthenticationManager.getInstance();
                            authManager.setActiveUser(authUser);

                            Date date = DateTimeHelper.parseDateTime(dbuser.getLastLogin());
                            if (date != null)
                                authUser.setLastLogin(date);
                            ;

                            dbuser.setLastLogin(DateTimeHelper.getDateTime(new Date()));

                            try {
                                ConfigurationDBUtils.saveOrUpdate(dbuser);

                            } catch (MOADatabaseException e) {
                                log.warn("UserDatabase communicaton error", e);
                                addActionError(LanguageHelper.getErrorString("error.login", request));
                                return Constants.STRUTS_ERROR;
                            } finally {
                                ConfigurationDBUtils.closeSession();
                            }

                            HttpSession newsession = generateNewJSession(request);
                            newsession.setAttribute(Constants.SESSION_AUTH, authUser);
                            return Constants.STRUTS_SUCCESS;

                        }
                    }

                    log.info(
                            "PVP2 Assertion was maybe not well formed, because no Assertion element could be found.");
                    addActionError(LanguageHelper.getErrorString("error.login.internal", request));
                    return Constants.STRUTS_ERROR;

                } else {
                    log.info("Receive Error Assertion.");
                    addActionError(LanguageHelper.getErrorString("error.login", request));
                    return Constants.STRUTS_ERROR;
                }

            } catch (Exception e) {
                log.warn("An internal error occurs.", e);
                addActionError(LanguageHelper.getErrorString("error.login.internal", request));
                return Constants.STRUTS_ERROR;
            }

        } else {
            log.info("Only http POST Requests can be used");
            addActionError(LanguageHelper.getErrorString("error.login.internal", request));
            return Constants.STRUTS_ERROR;
        }
    }

    public String requestNewUser() {

        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        if (session == null) {
            log.warn("No active Session found");
            return Constants.STRUTS_ERROR;
        }

        Object formidobj = session.getAttribute(Constants.SESSION_FORMID);
        if (formidobj != null && formidobj instanceof String) {
            String formid = (String) formidobj;
            if (!formid.equals(formID)) {
                log.warn("FormIDs does not match. Some suspect Form is received from user "
                        + authUser.getFamilyName() + authUser.getGivenName() + authUser.getUserID());
                return Constants.STRUTS_ERROR;
            }
        } else {
            log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName()
                    + authUser.getGivenName() + authUser.getUserID());
            return Constants.STRUTS_ERROR;
        }
        session.setAttribute(Constants.SESSION_FORMID, null);

        Object sessionformobj = session.getAttribute(Constants.SESSION_FORM);
        if (sessionformobj != null && sessionformobj instanceof UserDatabaseFrom) {
            UserDatabaseFrom sessionform = (UserDatabaseFrom) sessionformobj;

            Object authUserObj = session.getAttribute(Constants.SESSION_AUTH);
            authUser = (AuthenticatedUser) authUserObj;

            if (user == null) {
                log.warn("No form transmited");
                return Constants.STRUTS_ERROR;
            }

            //get UserID
            String useridobj = user.getUserID();
            long userID = -1;
            if (MiscUtil.isEmpty(useridobj)) {
                userID = -1;

            } else {
                if (!ValidationHelper.validateOAID(useridobj)) {
                    log.warn("User with ID " + authUser.getUserID() + " would access UserDatabase ID " + useridobj);
                    addActionError(LanguageHelper.getErrorString("errors.edit.user.notallowed", request));
                    return Constants.STRUTS_ERROR;
                }
                userID = Long.valueOf(useridobj);
            }

            String check;
            if (!sessionform.isIsmandateuser()) {
                check = user.getInstitut();
                if (MiscUtil.isNotEmpty(check)) {
                    if (ValidationHelper.containsPotentialCSSCharacter(check, false)) {
                        log.warn("Organisation contains potentail XSS characters: " + check);
                        addActionError(LanguageHelper.getErrorString("validation.edituser.institut.valid",
                                new Object[] { ValidationHelper.getPotentialCSSCharacter(false) }, request));
                    }
                } else {
                    log.warn("Organisation is empty");
                    addActionError(LanguageHelper.getErrorString("validation.edituser.institut.empty", request));
                }
            }

            check = user.getMail();
            if (MiscUtil.isNotEmpty(check)) {
                if (!ValidationHelper.isEmailAddressFormat(check)) {
                    log.warn("Mailaddress is not valid: " + check);
                    addActionError(LanguageHelper.getErrorString("validation.edituser.mail.valid",
                            new Object[] { ValidationHelper.getPotentialCSSCharacter(false) }, request));
                }
            } else {
                log.warn("Mailaddress is empty");
                addActionError(LanguageHelper.getErrorString("validation.edituser.mail.empty", request));
            }

            check = user.getPhone();
            if (MiscUtil.isNotEmpty(check)) {
                if (!ValidationHelper.validatePhoneNumber(check)) {
                    log.warn("No valid Phone Number: " + check);
                    addActionError(LanguageHelper.getErrorString("validation.edituser.phone.valid",
                            new Object[] { ValidationHelper.getPotentialCSSCharacter(false) }, request));
                }
            } else {
                log.warn("Phonenumber is empty");
                addActionError(LanguageHelper.getErrorString("validation.edituser.phone.empty", request));
            }

            if (hasActionErrors()) {
                log.info("Some form errors found. Send user back to form");

                user.setPVPGenerated(true);
                user.setFamilyName(sessionform.getFamilyName());
                user.setGivenName(sessionform.getGivenName());
                user.setIsmandateuser(sessionform.isIsmandateuser());
                user.setBpk(sessionform.getBpk());

                if (sessionform.isIsmandateuser())
                    user.setInstitut(sessionform.getInstitut());

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);

                return Constants.STRUTS_NEWUSER;
            }

            UserDatabase dbuser;

            if (userID < 0) {
                dbuser = new UserDatabase();
                dbuser.setBpk(sessionform.getBpk());
                dbuser.setFamilyname(sessionform.getFamilyName());
                dbuser.setGivenname(sessionform.getGivenName());

                if (sessionform.isIsmandateuser())
                    dbuser.setInstitut(sessionform.getInstitut());
                else
                    dbuser.setInstitut(user.getInstitut());

                dbuser.setIsPVP2Generated(true);
                dbuser.setLastLogin(DateTimeHelper.getDateTime(new Date()));
                dbuser.setIsActive(false);
                dbuser.setIsAdmin(false);
                dbuser.setIsMandateUser(sessionform.isIsmandateuser());
                dbuser.setIsUsernamePasswordAllowed(false);

            } else
                dbuser = ConfigurationDBRead.getUserWithID(userID);

            dbuser.setMail(user.getMail());
            dbuser.setPhone(user.getPhone());
            dbuser.setIsAdminRequest(true);
            dbuser.setIsMailAddressVerified(false);
            dbuser.setUserRequestTokken(Random.nextRandom());

            try {
                ConfigurationDBUtils.saveOrUpdate(dbuser);

                MailHelper.sendUserMailAddressVerification(dbuser);

            } catch (MOADatabaseException e) {
                log.warn("New UserRequest can not be stored in database", e);
                return Constants.STRUTS_ERROR;

            } catch (ConfigurationException e) {
                log.warn("Sending of mailaddress verification mail failed.", e);
                addActionError(LanguageHelper.getErrorString("error.mail.send", request));
                return Constants.STRUTS_NEWUSER;
            }

            finally {
                session.setAttribute(Constants.SESSION_FORM, null);
                session.setAttribute(Constants.SESSION_AUTH, null);
                ConfigurationDBUtils.closeSession();
            }

            addActionMessage(LanguageHelper.getGUIString("webpages.edituser.changemailaddress.verify", request));

            session.invalidate();

            return Constants.STRUTS_SUCCESS;

        } else {
            log.warn("No SessionForm found");
            return Constants.STRUTS_ERROR;
        }

    }

    public String mailAddressVerification() {

        try {
            populateBasicInformations();

        } catch (BasicActionException e) {
            return Constants.STRUTS_ERROR;

        }

        String userrequesttokken = request.getParameter(Constants.REQUEST_USERREQUESTTOKKEN);
        if (MiscUtil.isNotEmpty(userrequesttokken)) {

            userrequesttokken = StringEscapeUtils.escapeHtml(userrequesttokken);

            try {
                Long.parseLong(userrequesttokken);

            } catch (NumberFormatException e) {
                log.warn("Verificationtokken has no number format.");
                return Constants.STRUTS_ERROR;
            }

            UserDatabase dbuser = ConfigurationDBRead.getNewUserWithTokken(userrequesttokken);
            if (dbuser != null) {
                dbuser.setUserRequestTokken(null);
                dbuser.setIsMailAddressVerified(true);

                if (dbuser.isIsActive())
                    dbuser.setIsAdminRequest(false);

                try {
                    ConfigurationDBUtils.saveOrUpdate(dbuser);

                    int numoas = 0;
                    int numusers = 0;

                    List<OnlineApplication> openOAs = ConfigurationDBRead.getAllNewOnlineApplications();
                    if (openOAs != null)
                        numoas = openOAs.size();

                    List<UserDatabase> openUsers = ConfigurationDBRead.getAllNewUsers();
                    if (openUsers != null)
                        numusers = openUsers.size();

                    if (numusers > 0 || numoas > 0)
                        MailHelper.sendAdminMail(numoas, numusers);

                } catch (MOADatabaseException e) {
                    log.warn("Userinformation can not be stored in Database.", e);
                    addActionError(LanguageHelper.getErrorString("error.mail.verification", request));

                } catch (ConfigurationException e) {
                    log.warn("Send mail to admin failed.", e);
                }

                finally {
                    ConfigurationDBUtils.closeSession();
                }

                addActionMessage(LanguageHelper.getGUIString("validation.newuser.mailaddress", request));
                return Constants.STRUTS_SUCCESS;
            }
        }

        return Constants.STRUTS_ERROR;
    }

    public String logout() {
        HttpSession session = request.getSession(false);

        if (session != null) {
            if (MiscUtil.isNotEmpty((String) session.getAttribute(Constants.SESSION_SLOSUCCESS)))
                addActionMessage((String) session.getAttribute(Constants.SESSION_SLOSUCCESS));

            if (MiscUtil.isNotEmpty((String) session.getAttribute(Constants.SESSION_SLOERROR)))
                addActionError((String) session.getAttribute(Constants.SESSION_SLOERROR));

            session.invalidate();

        }

        return Constants.STRUTS_SUCCESS;
    }

    private HttpSession generateNewJSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);

        if (session != null) {

            HashMap<String, Object> attributes = new HashMap<String, Object>();

            Enumeration<String> enames = session.getAttributeNames();
            while (enames.hasMoreElements()) {
                String name = enames.nextElement();
                if (!name.equals("JSESSIONID"))
                    attributes.put(name, session.getAttribute(name));
            }
            session.invalidate();

            session = request.getSession(true);
            for (Entry<String, Object> et : attributes.entrySet())
                session.setAttribute(et.getKey(), et.getValue());

        } else
            session = request.getSession(true);

        return session;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the user
     */
    public UserDatabaseFrom getUser() {
        return user;
    }

    /**
     * @param user the user to set
     */
    public void setUser(UserDatabaseFrom user) {
        this.user = user;
    }

    /**
     * @return the ssologouturl
     */
    public String getSsologouturl() {
        return ssologouturl;
    }

    /**
     * @return the formID
     */
    public String getFormID() {
        return formID;
    }

    /**
     * @param formID the formID to set
     */
    public void setFormID(String formID) {
        this.formID = formID;
    }

    /**
     * @return the pvp2LoginActiv
     */
    public boolean isPvp2LoginActiv() {
        return pvp2LoginActiv;
    }

}