org.openmrs.cwf.security.base.BaseAuthenticationProvider.java Source code

Java tutorial

Introduction

Here is the source code for org.openmrs.cwf.security.base.BaseAuthenticationProvider.java

Source

/**
 * The contents of this file are subject to the openmrs Public License
 * Version 1.0 (the "License"); you may not use this file except in compliance with the License.
 * Please contact openmrs Institute if you would like to obtain a copy of the license.
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) openmrs Institute.  All Rights Reserved.
 */
package org.openmrs.cwf.security.base;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.carewebframework.api.domain.IUser;
import org.carewebframework.api.security.ISecurityDomain;
import org.carewebframework.security.spring.AbstractAuthenticationProvider;
import org.carewebframework.security.spring.CWFAuthenticationDetails;
import org.carewebframework.security.spring.Constants;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;

import org.zkoss.util.resource.Labels;

import org.openmrs.Privilege;
import org.openmrs.Role;
import org.openmrs.User;
import org.openmrs.api.context.Context;
import org.openmrs.api.context.ContextAuthenticationException;
import org.openmrs.api.context.UserContext;
import org.openmrs.cwf.api.domain.UserProxy;

/**
 * Provides authentication support for the framework. Takes provided authentication credentials and
 * authenticates them against the database.
 */
public class BaseAuthenticationProvider extends AbstractAuthenticationProvider {

    private static final Log log = LogFactory.getLog(BaseAuthenticationProvider.class);

    public BaseAuthenticationProvider() {
        super(false);
    }

    protected BaseAuthenticationProvider(boolean debugRole) {
        super(debugRole);
    }

    protected BaseAuthenticationProvider(List<String> grantedAuthorities) {
        super(grantedAuthorities);
    }

    /**
     * Performs a user authentication.
     * 
     * @param username Username for the login.
     * @param password Password for the login (ignored if the user is pre-authenticated).
     * @param domain Domain for which the login is requested.
     * @return Authorization result
     */
    @Override
    protected IUser authenticate(String username, String password, ISecurityDomain domain,
            CWFAuthenticationDetails details) {
        IUser user = null;

        try {
            Context.openSession();
            Context.authenticate(username, password);
            User authUser = Context.getAuthenticatedUser();
            user = authUser == null ? null : new UserProxy(authUser, domain);

            if (user != null) {
                UserContext ctx = Context.getUserContext();
                details.setDetail("userContext", ctx);

                for (String authority : grantedAuthorities) {
                    boolean remove = authority.startsWith("-");

                    if (remove) {
                        authority = authority.substring(1);
                    }

                    if (authority.startsWith(Constants.PRIV_PREFIX)) {
                        authority = authority.substring(Constants.PRIV_PREFIX.length());

                        if (remove) {
                            ctx.removeProxyPrivilege(authority);
                        } else {
                            ctx.addProxyPrivilege(authority);
                        }
                    }
                }
            }
        } catch (ContextAuthenticationException e) {
            throw mapException(e);
        } finally {
            Context.closeSession();
        }

        if (log.isInfoEnabled()) {
            log.info("Authentication " + (user == null ? "fail" : "succeed") + "ed for user " + username);
        }

        return user;
    }

    @Override
    protected List<String> getAuthorities(IUser user) {
        List<String> privs = new ArrayList<String>();
        User nativeUser = (User) user.getNativeUser();

        for (Privilege privilege : nativeUser.getPrivileges()) {
            privs.add(Constants.PRIV_PREFIX + privilege.getPrivilege());
        }

        for (Role role : nativeUser.getAllRoles()) {
            privs.add(Constants.ROLE_PREFIX + role.getRole());
        }

        return privs;
    }

    /**
     * Maps known exceptions to Spring authentication exceptions.
     * 
     * @param e Original exception
     * @return Mapped authentication exception
     */
    protected AuthenticationException mapException(ContextAuthenticationException e) {
        // Spring Security does not print the stack trace
        log.trace("Mapping authentication-related exception: " + e.getMessage(), e);
        return new BadCredentialsException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_INVALID), e);
        /*
        if (e instanceof AuthenticationException) {
        return (AuthenticationException) e;
        } else if (e instanceof UserLoginPasswordExpiredException) {
        return new CredentialsExpiredException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_EXPIRED_PASSWORD), e);
        } else if (e instanceof UserLoginExpiredException) {
        return new CredentialsExpiredException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_EXPIRED_USER), e);
        } else if (e instanceof UserLoginException) {
        return new BadCredentialsException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_INVALID), e);
        } else {
        //redundant but uncommon case so ensure visibility by logging error
        log.error(Labels.getLabel(Constants.LBL_LOGIN_ERROR_UNEXPECTED) + ": " + e.getMessage(), e);
        return new AuthenticationServiceException(Labels.getLabel(Constants.LBL_LOGIN_ERROR_UNEXPECTED), e);
        } */
    }

}