RestMacAuthPBean.java 2.76 KB
package fi.codecrew.moya.beans.auth;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import fi.codecrew.moya.beans.EventBean;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.utilities.UserLoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.AuthenticationResult;
import fi.codecrew.moya.beans.JaasBean.UserType;
import fi.codecrew.moya.beans.JaasBeanLocal;
import fi.codecrew.moya.model.ApiApplicationInstance;
import fi.codecrew.moya.utilities.PasswordFunctions;

@LocalBean
@Stateless
public class RestMacAuthPBean extends ApiAuth implements AuthenticationFormat {

	private static final Logger logger = LoggerFactory.getLogger(RestMacAuthPBean.class);

	@EJB
	private EventBean eventbean;

	@Override
	public AuthenticationResult authenticate(String jaasUsername, String password) {
		String username = UserLoginUtils.getUsernameFromJaasString(jaasUsername);
		String domain = UserLoginUtils.getDomainFromJaasString(jaasUsername);
		LanEvent event = eventbean.getEventForHostname(domain);

		AuthenticationResult ret = null;
		if ((username == null || username.isEmpty()) && password.startsWith(JaasBeanLocal.REST_PREFIX)) {
			ret = new AuthenticationResult();
			ret.setUsertype(UserType.REST.name());
			if(restAuth(password, event) != null) {
				ret.setUsername(jaasUsername);
			}
			//ret.setUsername(restAuth(password, event) + '@'+domain);
		}
		return ret;
	}

	private String restAuth(String restauth, LanEvent event) {
		String[] authsplit = restauth.split(":", 6);
		logger.info("Trying to auth with rest {}", (Object) authsplit);
		if (authsplit.length != 6 || !authsplit[0].equals("rest")) {
			return null;
		}

		return authenticateApp(authsplit[5], authsplit[1], authsplit[2], authsplit[3], authsplit[4], event);
	}

	public String authenticateApp(String pathInfo, String appId, String userId, String appStamp, String mac, LanEvent event) {

		logger.info("Authenticat app with pathinfo {}, appid {}, userid {}, appstamp {}, mac {}", new Object[]{pathInfo, appId, userId, appStamp, mac});
		if (mac == null) {
			logger.warn("Rest auth failed: Mac is null");
			return null;
		}
		ApiApplicationInstance apiInstance = verifyAppInstance(appId, userId, event);
		if (apiInstance == null) {
			return null;
		}

		String ret = null;
		String macSource = PasswordFunctions.mkSeparatedString("+", pathInfo, appId, userId, appStamp, apiInstance.getSecretKey());
		String macHash = PasswordFunctions.calculateSha1(macSource);
		logger.info("Calculated hash {}, comparing to {}", macHash, mac);
		if (mac.equalsIgnoreCase(macHash)) {
			ret = getUsername(apiInstance);
		} else {
			logger.warn("Rest auth failed: Calculated hash does not match received mac: Calculated {}, received {}", macHash, mac);
		}

		return ret;
	}

}