Package org.wso2.carbon.identity.provider

Source Code of org.wso2.carbon.identity.provider.OpenIDProviderService

/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. licenses this file to you under the Apache License,
*  Version 2.0 (the "License"); you may not use this file except
*  in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.provider;

import org.apache.axiom.om.util.UUIDGenerator;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.message.*;
import org.openid4java.server.ServerManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.base.IdentityConstants.ServerConfig;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.IdentityClaimManager;
import org.wso2.carbon.identity.core.dao.InfoCardDAO;
import org.wso2.carbon.identity.core.dao.OpenIDRememberMeDAO;
import org.wso2.carbon.identity.core.model.OpenIDRememberMeDO;
import org.wso2.carbon.identity.core.model.XMPPSettingsDO;
import org.wso2.carbon.identity.core.persistence.IdentityPersistenceManager;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.provider.dto.*;
import org.wso2.carbon.identity.provider.openid.OpenIDProvider;
import org.wso2.carbon.identity.provider.openid.OpenIDUtil;
import org.wso2.carbon.identity.provider.openid.extensions.OpenIDExtension;
import org.wso2.carbon.identity.provider.openid.extensions.OpenIDPape;
import org.wso2.carbon.identity.provider.openid.handlers.OpenIDAuthenticationRequest;
import org.wso2.carbon.identity.provider.openid.handlers.OpenIDExtensionFactory;
import org.wso2.carbon.identity.provider.xmpp.MPAuthenticationProvider;
import org.wso2.carbon.identity.relyingparty.RelyingPartyData;
import org.wso2.carbon.identity.relyingparty.RelyingPartyException;
import org.wso2.carbon.identity.relyingparty.TokenVerifierConstants;
import org.wso2.carbon.identity.relyingparty.saml.SAMLTokenVerifier;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.user.core.claim.Claim;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.TenantUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.*;

public class OpenIDProviderService {

    private static final String OPENID_LOGGEDIN_USER = "OPENID_LOGGEDIN_USER";
    protected Log log = LogFactory.getLog(OpenIDProviderService.class);

    /**
     * @param openID
     * @param password
     * @return
     * @throws Exception
     */
    public boolean authenticateWithOpenID(String openID, String password) throws Exception {
        String userName = OpenIDUtil.getUserName(openID);
        boolean authenticationStatus = true;
        boolean isAutheticated = false;
        String domainName = null;
        String tenantUser = null;

        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager
                .getPersistanceManager();
        domainName = TenantUtils.getDomainNameFromOpenId(openID);
        tenantUser = UserCoreUtil.getTenantLessUsername(userName);

        XMPPSettingsDO xmppSettingsDO = persistenceManager.getXmppSettings(IdentityTenantUtil
                .getRegistry(domainName, userName), tenantUser);
        isAutheticated = IdentityTenantUtil.getRealm(domainName, userName).getUserStoreManager()
                .authenticate(tenantUser, password);

        // attempts to do multi-factor authentication, if the user has enabled it.
        if (xmppSettingsDO != null && xmppSettingsDO.isXmppEnabled() && isAutheticated) {
            MPAuthenticationProvider mpAuthenticationProvider = new MPAuthenticationProvider(
                    xmppSettingsDO);
            authenticationStatus = mpAuthenticationProvider.authenticate();
            if (log.isDebugEnabled()) {
                log.debug("XMPP Multifactor Authentication was completed Successfully.");
            }
        }

        if (authenticationStatus && isAutheticated) {
            MessageContext msgContext = MessageContext.getCurrentMessageContext();
            HttpServletRequest request = (HttpServletRequest) msgContext
                    .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            HttpSession httpSession = request.getSession(false);
            if (httpSession != null) {
                httpSession.setAttribute(OPENID_LOGGEDIN_USER, userName);

            }
        }

        // combining the results of OpenID authentication. and XMPP based
        // multi-factor authentication and returning it.
        return (authenticationStatus && isAutheticated);
    }

    /**
     *
     * @param openID
     * @param password
     * @param ipaddress
     * @param cookie
     * @return
     * @throws Exception
     */
    public OpenIDRememberMeDTO authenticateWithOpenIDRememberMe(String openID, String password,
            String ipaddress, String cookie) throws Exception {
        String userName = OpenIDUtil.getUserName(openID);
        boolean isAutheticated = false;
        String domainName = null;
        String tenantUser = null;
        String hmac = null;
        OpenIDRememberMeDTO dto = new OpenIDRememberMeDTO();
        dto.setAuthenticated(false);

        if (password != null && password.trim().length() > 0) {
            isAutheticated = authenticateWithOpenID(openID, password);
            if (!isAutheticated) {
                return dto;
            }
        } else {
            if (cookie == null || "null".equals(cookie) || ipaddress == null) {
                return dto;
            }
        }

        OpenIDRememberMeDO rememberMe = null;
        OpenIDRememberMeDAO dao = null;
        String token = null;
        tenantUser = UserCoreUtil.getTenantLessUsername(userName);

        rememberMe = new OpenIDRememberMeDO();
        rememberMe.setOpenID(openID);
        rememberMe.setUserName(tenantUser);

        domainName = TenantUtils.getDomainNameFromOpenId(openID);
        dao = new OpenIDRememberMeDAO(IdentityTenantUtil.getRegistry(domainName, null));

        if (ipaddress != null && cookie != null && !"null".equals(cookie)) {
            hmac = IdentityUtil.getHMAC(ipaddress, cookie);
            token = dao.getToken(rememberMe);
            if (token == null || !token.equals(hmac)) {
                return dto;
            }

            cookie = UUIDGenerator.getUUID();
            hmac = IdentityUtil.getHMAC(ipaddress, cookie);
            rememberMe.setToken(hmac);
            dao.updateToken(rememberMe);
            dto.setNewCookieValue(cookie);
            dto.setAuthenticated(true);

            MessageContext msgContext = MessageContext.getCurrentMessageContext();
            HttpServletRequest request = (HttpServletRequest) msgContext
                    .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            HttpSession httpSession = request.getSession(false);

            if (httpSession != null) {
                httpSession.setAttribute(OPENID_LOGGEDIN_USER, userName);
            }

            return dto;
        }

        if (ipaddress != null && (cookie == null || "null".equals(cookie)) && isAutheticated) {

            cookie = UUIDGenerator.getUUID();
            hmac = IdentityUtil.getHMAC(ipaddress, cookie);
            rememberMe.setToken(hmac);
            dao.updateToken(rememberMe);
            dto.setNewCookieValue(cookie);
            dto.setAuthenticated(true);

            MessageContext msgContext = MessageContext.getCurrentMessageContext();
            HttpServletRequest request = (HttpServletRequest) msgContext
                    .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            HttpSession httpSession = request.getSession(false);

            if (httpSession != null) {
                httpSession.setAttribute(OPENID_LOGGEDIN_USER, userName);
            }

            return dto;
        }

        return dto;
    }

    /**
     * @param userName
     * @return
     * @throws Exception
     */
    public OpenIDProviderInfoDTO getOpenIDProviderInfo(String userName, String openid)
            throws Exception {
        OpenIDProviderInfoDTO providerInfo = null;
        String domain = null;
        UserRealm realm = null;
        providerInfo = new OpenIDProviderInfoDTO();

        try {
            domain = TenantUtils.getDomainNameFromOpenId(openid);
            realm = IdentityTenantUtil.getRealm(domain, userName);
        } catch (Exception ignore) {
            log.error(ignore);
        }
        if (realm == null) {
            return providerInfo;
        }

        providerInfo.setSubDomain(domain);
        userName = UserCoreUtil.getTenantLessUsername(userName);
        providerInfo.setUserExist(realm.getUserStoreManager().isExistingUser(userName));
        providerInfo.setOpenIDProviderServerUrl(IdentityUtil
                .getProperty(ServerConfig.OPENID_SERVER_URL));
        providerInfo.setOpenID(IdentityUtil.getProperty(ServerConfig.OPENID_USER_PATTERN)
                + userName);
        return providerInfo;
    }

    /**
     * @param openId
     * @param profileId
     * @param requredClaims
     * @return
     * @throws IdentityException
     */
    public OpenIDClaimDTO[] getClaimValues(String openId, String profileId,
            OpenIDParameterDTO[] requredClaims) throws Exception {
        List<String> claimList = null;
        ParameterList paramList = null;
        AuthRequest authReq = null;

        String message = "Invalid parameters provided to getClaimValues";
        validateInputParameters(new String[]{openId, profileId}, message);
        checkUserAuthorization(OpenIDUtil.getUserName(openId), "getClaimValues");

        paramList = getParameterList(requredClaims);
        authReq = AuthRequest.createAuthRequest(paramList, OpenIDProvider.getInstance()
                .getManager().getRealmVerifier());
        claimList = getRequestedAttributes(authReq);
        return getOpenIDClaimValues(openId, profileId, claimList);
    }

    /**
     * @param params
     * @return
     * @throws Exception
     */
    public String getOpenIDAssociationResponse(OpenIDParameterDTO[] params) throws Exception {
        Message message = null;
        ParameterList paramList = null;

        paramList = getParameterList(params);
        message = OpenIDProvider.getInstance().getManager().associationResponse(paramList);
        return message.keyValueFormEncoding();
    }

    /**
     * @param params
     * @return
     * @throws Exception
     */
    public String verify(OpenIDParameterDTO[] params) throws Exception {
        Message message = null;
        ParameterList paramList = null;

        paramList = getParameterList(params);
        message = OpenIDProvider.getInstance().getManager().verify(paramList);
        return message.keyValueFormEncoding();
    }

    /**
     * @param request
     * @return
     * @throws Exception
     */
    public OpenIDAuthResponseDTO getOpenIDAuthResponse(OpenIDAuthRequestDTO request)
            throws Exception {
        ParameterList paramList = null;
        Message message = null;
        paramList = getParameterList(request.getParams());
        String destinationUrl = null;
        AuthRequest authReq = null;
        ServerManager manager = null;
        OpenIDAuthResponseDTO response = null;

        response = new OpenIDAuthResponseDTO();
        manager = OpenIDProvider.getInstance().getManager();
        authReq = AuthRequest.createAuthRequest(paramList, manager.getRealmVerifier());
        message = manager.authResponse(paramList, request.getOpLocalId(), request
                .getUserSelectedClaimedId(), request.isAuthenticated());

        if (message instanceof DirectError || message instanceof AuthFailure) {
            // Validation fails - returns 'cancel'.
            destinationUrl = message.getDestinationUrl(true);
            response.setDestinationUrl(destinationUrl);
            response.setValidated(false);
        } else {
            OpenIDExtension extension = null;
            OpenIDAuthenticationRequest req = null;
            req = new OpenIDAuthenticationRequest();

            if (request.isPhishiingResistanceAuthRequest()) {
                // Relying party requests phishing-resistant login.
                req.setPhishingResistanceLogin(true);
            }
            if (request.isMultiFactorAuthRequested()) {
                // Relying party requests phishing-resistant login.
                req.setMultifactorLogin(true);
            }

            req.setAuthRequest(authReq);

            // A given OpenID authentication request can contain multiple
            // extensions.
            // OpenIDProvider is not aware of extensions - we simply delegate
            // the extension
            // processing logic to a subclass of OpenIDExtension.
            for (Object alias : authReq.getExtensions()) {
                req.setExtensionAlias((String) alias);

                // Get the corresponding OpenIDExtension instance from the
                // OpenIDExtensionFactory.
                extension = OpenIDExtensionFactory.getInstance().getExtension(req);
                if (extension != null) {
                    MessageExtension messageExtension = null;
                    messageExtension = extension.getMessageExtension(request.getOpenID(), request
                            .getProfileName());
                    if (messageExtension != null) {
                        message.addExtension(messageExtension);
                        AuthSuccess authSuccess = (AuthSuccess) message;
                        authSuccess.addSignExtension((String) alias);
                        manager.sign(authSuccess);
                    }
                }
            }

            // We only have SReg extensions.
            destinationUrl = message.getDestinationUrl(true);
            response.setDestinationUrl(destinationUrl);
            response.setValidated(true);
        }
        return response;
    }

    /**
     * @param infocard
     * @return
     * @throws Exception
     */
    public InfoCardSignInDTO signInWithInfoCard(InfoCardDTO infocard) throws Exception {
        SAMLTokenVerifier verifier = new SAMLTokenVerifier();
        MessageContext msgCtx = MessageContext.getCurrentMessageContext();
        HttpServletRequest request = (HttpServletRequest) msgCtx
                .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        HttpSession httpSession = request.getSession();
        Hashtable<String, String> attributes = null;
        InfoCardSignInDTO dto = new InfoCardSignInDTO();

        ByteArrayInputStream bais = new ByteArrayInputStream(infocard.getXmlToken().getBytes());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder().parse(bais);
        Element token = doc.getDocumentElement();
        boolean isAuthenticated = false;

        if (verifier.verifyDecryptedToken(token, RelyingPartyData.getInstance())) {
            attributes = verifier.getAttributeTable();
            String ppid = null;
            String user = null;
            if (validateIssuerInfoPolicy(verifier, RelyingPartyData.getInstance())) {
                ppid = attributes.get(IdentityConstants.CLAIM_PPID);
                String tenant = attributes.get(IdentityConstants.CLAIM_TENANT_DOMAIN);
                user = getUserName(ppid, tenant);
                String tenatAwareUserNameFromOpenID = UserCoreUtil.getTenantLessUsername(OpenIDUtil
                        .getUserName(infocard.getOpenId()));
               
                String tenantFromOpenID = null;

                tenantFromOpenID = TenantUtils.getDomainNameFromOpenId(infocard.getOpenId());

                String supperTenant = IdentityConstants.DEFAULT_SUPER_TENAT;
               
                if (tenantFromOpenID == null) {
                    tenantFromOpenID = supperTenant;
                }

                if (tenant.equals(tenantFromOpenID) && tenatAwareUserNameFromOpenID.equals(user)) {
                    if (IdentityConstants.SELF_ISSUED_ISSUER.equals(verifier.getIssuerName())) {
                        dto.setPpid(ppid);
                    }
                    if (httpSession != null) {
                        httpSession.setAttribute(OPENID_LOGGEDIN_USER, user);
                    }
                    isAuthenticated = true;
                    dto.setAuthenticated(true);
                    dto.setUserID(user);
                }
            }
        }

        if (!isAuthenticated) {
            httpSession.removeAttribute(OPENID_LOGGEDIN_USER);
        }

        return dto;
    }
    /**
     * Service method for retrieving PAPE info.
     *
     * @param dto
     * @return
     * @throws IdentityProviderException
     */
    public PapeInfoResponseDTO retrievePapeInfo(PapeInfoRequestDTO dto)
            throws IdentityProviderException {
        PapeInfoResponseDTO respDTO = new PapeInfoResponseDTO();

        String message = "Invalid parameters provided to retrievePapeInfo";
        if (dto == null) {
            throw new IllegalArgumentException(message);
        }
        validateInputParameters(new String[]{dto.getOpenID()}, message);
        respDTO.setPolicies(getPapeInfo(dto));
        return respDTO;
    }

    /**
     * @param authRequest
     * @return
     * @throws IdentityException
     */
    private List<String> getRequestedAttributes(AuthRequest authRequest) throws IdentityException {
        OpenIDAuthenticationRequest req = null;
        OpenIDExtension extension = null;
        List<String> requiredAttributes = null;

        req = new OpenIDAuthenticationRequest();
        req.setAuthRequest(authRequest);
        requiredAttributes = new ArrayList<String>();

        for (Object alias : authRequest.getExtensions()) {
            req.setExtensionAlias((String) alias);
            extension = OpenIDExtensionFactory.getInstance().getExtension(req);
            if (extension != null) {
                extension.addRequiredAttributes(requiredAttributes);
            }
        }

        return requiredAttributes;
    }

    /**
     * @param ppid
     * @return
     * @throws IdentityException
     * @throws RegistryException
     */
    private String getUserName(String ppid, String tenantDomain) throws IdentityException,
            RegistryException, CarbonException {
        String username = null;
        Registry registry = null;
       
        String superTenant = IdentityConstants.DEFAULT_SUPER_TENAT;
       
        if (tenantDomain == null || tenantDomain.equals(superTenant)) {
            // if domain is null then check for the super tenant
            registry = IdentityTenantUtil.getRegistry(null, null);
        } else {
            registry = IdentityTenantUtil.getRegistry(tenantDomain, null);
        }
        IdentityPersistenceManager manager = IdentityPersistenceManager.getPersistanceManager();
        username = manager.getUserByPPID(registry, ppid);
        return username;
    }

    /**
     * @param params
     * @return
     */
    private ParameterList getParameterList(OpenIDParameterDTO[] params) {
        ParameterList paramList = null;
        Map<String, String> paramMap = null;
        paramMap = new HashMap<String, String>();

        for (int i = 0; i < params.length; i++) {
            paramMap.put(params[i].getName(), params[i].getValue());
        }

        paramList = new ParameterList(paramMap);
        return paramList;
    }

    /**
     * @param verifier
     * @param data
     * @return
     * @throws RelyingPartyException
     */
    private boolean validateIssuerInfoPolicy(SAMLTokenVerifier verifier, RelyingPartyData data)
            throws RelyingPartyException {
        boolean validated = false;
        String issuerName = verifier.getIssuerName();
        String issuerPolicy = data.getIssuerPolicy();

        try {
            if (IdentityConstants.SELF_ISSUED_ISSUER.equals(issuerName)) {
                if (issuerPolicy == null || issuerPolicy.equals(TokenVerifierConstants.SELF_ONLY)
                        || issuerPolicy.equals(TokenVerifierConstants.SELF_AND_MANGED)) {
                    validated = true;
                }
            } else if (issuerPolicy.equals(TokenVerifierConstants.SELF_ONLY)) {
                // not a self issued card when self only
                validated = false;
            } else {
                validated = true;
            }
        } catch (Exception e) {
            throw new RelyingPartyException("errorValidatingIssuerPolicy", e);
        }

        return validated;
    }

    /**
     * @param papeInfoRequestDto
     * @return
     */
    private OpenIDParameterDTO[] getPapeInfo(PapeInfoRequestDTO papeInfoRequestDto) {

        ParameterList paramList = getParameterList(papeInfoRequestDto.getParamList());
        String username = OpenIDUtil.getUserName(papeInfoRequestDto.getOpenID());

        AuthRequest authReq = null;
        ServerManager manager = null;
        String domainName = null;
        Registry registry;
        String tenatUser = null;

        try {
            manager = OpenIDProvider.getInstance().getManager();
            authReq = AuthRequest.createAuthRequest(paramList, manager.getRealmVerifier());
            OpenIDAuthenticationRequest req = new OpenIDAuthenticationRequest();
            req.setAuthRequest(authReq);
            setPAPEProperties(req, paramList);
            domainName = TenantUtils.getDomainNameFromOpenId(papeInfoRequestDto.getOpenID());
            tenatUser = UserCoreUtil.getTenantLessUsername(username);

            registry = IdentityTenantUtil.getRegistry(domainName, username);

            OpenIDPape openIDPape = new OpenIDPape(req);
            OpenIDParameterDTO[] policySet = openIDPape.getPapeInfoFromRequest();

            if (policySet[0].getValue().equals("true")) {
                InfoCardDAO infoCardDAO = new InfoCardDAO(registry);
                if (infoCardDAO.getInfoCardsForUser(tenatUser).length < 1) {
                    policySet[0].setValue("false");
                }
            }

            if (policySet[1].getValue().equals("true")) {
                IdentityPersistenceManager identityPersistentManager = IdentityPersistenceManager
                        .getPersistanceManager();
                InfoCardDAO infoCardDAO = new InfoCardDAO(registry);

                if ((infoCardDAO.getInfoCardsForUser(username).length > 0)
                        || (identityPersistentManager.hasXMPPSettings(registry, tenatUser) && identityPersistentManager
                                .isXmppSettingsEnabled(registry, tenatUser))) {

                    if (infoCardDAO.getInfoCardsForUser(tenatUser).length > 0) {
                        policySet[2].setValue("true");
                    }

                    if (identityPersistentManager.hasXMPPSettings(registry, tenatUser)
                            && identityPersistentManager.isXmppSettingsEnabled(registry, tenatUser)) {
                        policySet[3].setValue("true");
                    }
                } else {
                    policySet[1].setValue("false");
                }
            }

            return policySet;

        } catch (Exception ex) {
            log.error("Error retrieving Pape Information for the user " + username, ex);
        }

        return null;
    }

    /**
     * @param req
     * @param paramList
     */
    private void setPAPEProperties(OpenIDAuthenticationRequest req, ParameterList paramList) {
        List list = null;

        list = paramList.getParameters();
        for (Object object : list) {
            Parameter param = (Parameter) object;
            if (param.getValue().contains(
                    "http://schemas.openid.net/pape/policies/2007/06/phishing-resistant")) {
                req.setPhishingResistanceLogin(true);
            }
            if (param.getValue().contains(
                    "http://schemas.openid.net/pape/policies/2007/06/multi-factor")) {
                req.setMultifactorLogin(true);
            }
        }
    }

    /**
     * A new method to do XMPP based authentication for a given user
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public boolean doXMPPBasedMultiFactorAuthForInfocard(String userId) throws Exception {
        boolean authenticationStatus = true;

        IdentityPersistenceManager persistenceManager = IdentityPersistenceManager
                .getPersistanceManager();
        XMPPSettingsDO xmppSettingsDO = persistenceManager.getXmppSettings(IdentityTenantUtil
                .getRegistry(null, userId), UserCoreUtil.getTenantLessUsername(userId));

        // attempts to do multi-factor authentication, if the user has enabled
        // it.
        if (xmppSettingsDO != null && xmppSettingsDO.isXmppEnabled()) {
            MPAuthenticationProvider mpAuthenticationProvider = new MPAuthenticationProvider(
                    xmppSettingsDO);
            authenticationStatus = mpAuthenticationProvider.authenticate();
        }

        if (log.isInfoEnabled()) {
            log.info("XMPP Multifactor Authentication was completed Successfully.");
        }

        return authenticationStatus;
    }

    /**
     * Get Profile details of an user
     *
     * @param openId
     * @return
     * @throws Exception
     */
    public OpenIDUserProfileDTO[] getUserProfiles(String openId, OpenIDParameterDTO[] requredClaims)
            throws Exception {
        String userName = null;
        UserRealm realm = null;
        UserStoreManager reader = null;
        String tenatUser = null;
        String domainName = null;

        try {
            userName = OpenIDUtil.getUserName(openId);
            tenatUser = UserCoreUtil.getTenantLessUsername(userName);

            domainName = TenantUtils.getDomainNameFromOpenId(openId);

            realm = IdentityTenantUtil.getRealm(domainName, userName);
            reader = realm.getUserStoreManager();
            String[] profileNames = reader.getProfileNames(tenatUser);
            OpenIDUserProfileDTO[] profileDtoSet = new OpenIDUserProfileDTO[profileNames.length];

            ParameterList paramList = null;
            AuthRequest authReq = null;
            List<String> claimList = null;

            paramList = getParameterList(requredClaims);
            authReq = AuthRequest.createAuthRequest(paramList, OpenIDProvider.getInstance()
                    .getManager().getRealmVerifier());

            claimList = getRequestedAttributes(authReq);

            for (int i = 0; i < profileNames.length; i++) {
                OpenIDUserProfileDTO profileDTO = new OpenIDUserProfileDTO();
                OpenIDClaimDTO[] claimSet = getOpenIDClaimValues(openId, profileNames[i], claimList);
                profileDTO.setProfileName(profileNames[i]);
                profileDTO.setClaimSet(claimSet);
                profileDtoSet[i] = profileDTO;
            }
            return profileDtoSet;
        } catch (UserStoreException e) {
            throw new Exception(e.getMessage(), e);
        }
    }

    /**
     *
     * @param openId
     * @param profileId
     * @param claimList
     * @return
     * @throws Exception
     */
    private OpenIDClaimDTO[] getOpenIDClaimValues(String openId, String profileId,
            List<String> claimList) throws Exception {
        UserStoreManager userStore = null;
        Map<String, String> claimValues = null;
        OpenIDClaimDTO[] claims = null;
        OpenIDClaimDTO dto = null;
        IdentityClaimManager claimManager = null;
        Claim[] claimData = null;
        String[] claimArray = new String[claimList.size()];
        String userName = null;
        String domainName = null;
        String tenatUser;
        UserRealm realm = null;

        userName = OpenIDUtil.getUserName(openId);
        domainName = TenantUtils.getDomainNameFromOpenId(openId);
        tenatUser = UserCoreUtil.getTenantLessUsername(userName);

        realm = IdentityTenantUtil.getRealm(domainName, userName);
        userStore = realm.getUserStoreManager();
        claimValues = userStore.getUserClaimValues(tenatUser, claimList.toArray(claimArray),
                profileId);

        claims = new OpenIDClaimDTO[claimValues.size()];
        int i = 0;
        claimManager = IdentityClaimManager.getInstance();
        claimData = claimManager.getAllSupportedClaims(realm);

        for (int j = 0; j < claimData.length; j++) {
            if (claimValues.containsKey(claimData[j].getClaimUri())) {
                dto = new OpenIDClaimDTO();
                dto.setClaimUri(claimData[j].getClaimUri());
                dto.setClaimValue(claimValues.get(claimData[j].getClaimUri()));
                dto.setDisplayTag(claimData[j].getDisplayTag());
                dto.setDescription(claimData[j].getDescription());
                claims[i++] = dto;
            }
        }
        return claims;
    }

    /**
     *
     * @param username
     * @param operation
     * @throws IdentityProviderException
     */
    private void checkUserAuthorization(String username, String operation)
            throws IdentityProviderException {
        MessageContext msgContext = MessageContext.getCurrentMessageContext();
        HttpServletRequest request = (HttpServletRequest) msgContext
                .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            String userName = (String) httpSession.getAttribute(OPENID_LOGGEDIN_USER);
            if (!username.equals(userName)) {
                throw new IdentityProviderException("Unauthorised action by user " + username
                        + " to access " + operation);
            }
            return;
        }
        throw new IdentityProviderException("Unauthorised action by user " + username
                + " to access " + operation);
    }

    /**
     *
     * @param params
     * @param message
     */
    private void validateInputParameters(String[] params, String message) {
        for (int i = 0; i < params.length; i++) {
            if (params[i] == null || params[i].trim().length() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug(message);
                }
                throw new IllegalArgumentException(message);
            }
        }
    }
}
TOP

Related Classes of org.wso2.carbon.identity.provider.OpenIDProviderService

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.