package cz.hsrs.rest.util;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;

import cz.hsrs.db.util.UserUtil;
import cz.hsrs.servlet.security.JSPHelper;
import cz.hsrs.servlet.security.LoginUser;

/**
 * Utility class for authentication
 * @author mkepka
 *
 */
public class AuthUtil {

    /**
     * Method provides info about logged user by SessionId in HTTPRequest
     * @param request - HTTP request containing SESSIONID
     *
     */
    public static LoginUser getAuthenticatedLoginUser(HttpServletRequest request) throws AuthenticationException {
        LoginUser user = ((LoginUser) request.getSession().getAttribute(JSPHelper.USERATTRIBUTE));
        if(user != null){
            if (user.isAuthenticated()) {
                return user;
            } else {
                throw new AuthenticationException("Authentication failure for request " + request.getQueryString());
            }
        }
        else{
            String remoteHost = request.getRemoteHost();
            if ((remoteHost.equals("127.0.0.1") || remoteHost.equals("localhost")) && request.getParameter("user") != null) {
                try {
                    UserUtil uUtil = new UserUtil();
                    String userName = request.getParameter(JSPHelper.USERATTRIBUTE);
                    String pass = uUtil.getUserPassword(userName);
                    LoginUser userLocal = new LoginUser(request);

                    if(userLocal.athenticate(userName, pass)){
                        return userLocal;
                    } else{
                        throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
                    }
                } catch (Exception e) {
                    throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
                }
            } else{
                throw new AuthenticationException("Authentication fairlure for request " + request.getQueryString());
            }
        }
    }
}