<commit_before>/*
 * Copyright 2015 <NAME> <<EMAIL>>
 * 
 * Licensed 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 li.strolch.rest.endpoint;

import java.text.MessageFormat;
import java.util.Base64;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

import li.strolch.exception.StrolchException;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.InvalidCredentialsException;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.IPrivilege;
import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.privilege.model.Usage;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.utils.helper.ExceptionHelper;

/**
 * @author <NAME> <<EMAIL>>
 */
@Path("strolch/authentication")
public class AuthenticationService {

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

	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response authenticate(@Context HttpServletRequest request, @Context HttpHeaders headers, String data) {

		JsonObject login = new JsonParser().parse(data).getAsJsonObject();
		JsonObject loginResult = new JsonObject();

		try {

			StringBuilder sb = new StringBuilder();
			JsonElement usernameE = login.get("username");
			if (usernameE == null || usernameE.getAsString().length() < 2) {
				sb.append("Username was not given or is too short!"); //$NON-NLS-1$
			}

			JsonElement passwordE = login.get("password");
			if (passwordE == null) {
				if (sb.length() > 0)
					sb.append("\n");
				sb.append("Password was not given!"); //$NON-NLS-1$
			}

			char[] password = passwordE == null ? new char[] {}
					: new String(Base64.getDecoder().decode(passwordE.getAsString())).toCharArray();
			if (password.length < 3) {
				if (sb.length() > 0)
					sb.append("\n");
				sb.append("Password not given or too short!"); //$NON-NLS-1$
			}

			if (sb.length() != 0) {
				loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", sb.toString())); //$NON-NLS-2$
				return Response.status(Status.BAD_REQUEST).entity(loginResult).build();
			}

			StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
			Certificate certificate = sessionHandler.authenticate(usernameE.getAsString(), password);

			return getAuthenticationResponse(request, loginResult, certificate);

		} catch (InvalidCredentialsException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg", "Could not log in as the given credentials are invalid"); //$NON-NLS-1$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (AccessDeniedException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (StrolchException | PrivilegeException e) {
			logger.error(e.getMessage(), e);
			loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.FORBIDDEN).entity(loginResult.toString()).build();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			String msg = e.getMessage();
			loginResult.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
			return Response.serverError().entity(loginResult.toString()).build();
		}
	}

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Path("sso")
	public Response authenticateSingleSignOn(@Context HttpServletRequest request, @Context HttpHeaders headers) {

		JsonObject loginResult = new JsonObject();

		try {

			StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
			Certificate certificate = sessionHandler.authenticateSingleSignOn(request.getUserPrincipal());

			return getAuthenticationResponse(request, loginResult, certificate);

		} catch (InvalidCredentialsException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg", "Could not log in as the given credentials are invalid"); //$NON-NLS-1$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (AccessDeniedException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (StrolchException | PrivilegeException e) {
			logger.error(e.getMessage(), e);
			loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.FORBIDDEN).entity(loginResult.toString()).build();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			String msg = e.getMessage();
			loginResult.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
			return Response.serverError().entity(loginResult.toString()).build();
		}
	}

	@DELETE
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	@Path("{authToken}")
	public Response invalidateSession(@PathParam("authToken") String authToken) {

		JsonObject logoutResult = new JsonObject();

		try {

			StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
			Certificate certificate = sessionHandler.validate(authToken);
			sessionHandler.invalidate(certificate);

			logoutResult.addProperty("username", certificate.getUsername());
			logoutResult.addProperty("authToken", authToken);
			logoutResult.addProperty("msg", //$NON-NLS-1$
					MessageFormat.format("{0} has been logged out.", certificate.getUsername()));
			return Response.ok().entity(logoutResult.toString()).build();

		} catch (StrolchException | PrivilegeException e) {
			logger.error("Failed to invalidate session due to: " + e.getMessage());
			logoutResult.addProperty("msg", MessageFormat.format("Could not logout due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.UNAUTHORIZED).entity(logoutResult.toString()).build();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			String msg = e.getMessage();
			logoutResult.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
			return Response.serverError().entity(logoutResult.toString()).build();
		}
	}

	@HEAD
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	@Path("{authToken}")
	public Response validateSession(@PathParam("authToken") String authToken) {
<commit_msg>[Fix] Return String, not JsonObject in REST Auth method<commit_after>/*
 * Copyright 2015 <NAME> <<EMAIL>>
 *
 * Licensed 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 li.strolch.rest.endpoint;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.text.MessageFormat;
import java.util.Base64;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.google.gson.*;
import li.strolch.exception.StrolchException;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.InvalidCredentialsException;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.IPrivilege;
import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.privilege.model.Usage;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.utils.helper.ExceptionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <NAME> <<EMAIL>>
 */
@Path("strolch/authentication")
public class AuthenticationService {

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

	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response authenticate(@Context HttpServletRequest request, @Context HttpHeaders headers, String data) {

		JsonObject login = new JsonParser().parse(data).getAsJsonObject();
		JsonObject loginResult = new JsonObject();

		try {

			StringBuilder sb = new StringBuilder();
			JsonElement usernameE = login.get("username");
			if (usernameE == null || usernameE.getAsString().length() < 2) {
				sb.append("Username was not given or is too short!"); //$NON-NLS-1$
			}

			JsonElement passwordE = login.get("password");
			if (passwordE == null) {
				if (sb.length() > 0)
					sb.append("\n");
				sb.append("Password was not given!"); //$NON-NLS-1$
			}

			char[] password = passwordE == null ?
					new char[] {} :
					new String(Base64.getDecoder().decode(passwordE.getAsString())).toCharArray();
			if (password.length < 3) {
				if (sb.length() > 0)
					sb.append("\n");
				sb.append("Password not given or too short!"); //$NON-NLS-1$
			}

			if (sb.length() != 0) {
				logger.error("Authentication failed due to: " + sb.toString());
				loginResult.addProperty("msg",
						MessageFormat.format("Could not log in due to: {0}", sb.toString())); //$NON-NLS-2$
				return Response.status(Status.BAD_REQUEST).entity(loginResult.toString()).build();
			}

			StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
			Certificate certificate = sessionHandler.authenticate(usernameE.getAsString(), password);

			return getAuthenticationResponse(request, loginResult, certificate);

		} catch (InvalidCredentialsException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg", "Could not log in as the given credentials are invalid"); //$NON-NLS-1$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (AccessDeniedException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg",
					MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (StrolchException | PrivilegeException e) {
			logger.error(e.getMessage(), e);
			loginResult.addProperty("msg",
					MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.FORBIDDEN).entity(loginResult.toString()).build();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			String msg = e.getMessage();
			loginResult.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
			return Response.serverError().entity(loginResult.toString()).build();
		}
	}

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Path("sso")
	public Response authenticateSingleSignOn(@Context HttpServletRequest request, @Context HttpHeaders headers) {

		JsonObject loginResult = new JsonObject();

		try {

			StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
			Certificate certificate = sessionHandler.authenticateSingleSignOn(request.getUserPrincipal());

			return getAuthenticationResponse(request, loginResult, certificate);

		} catch (InvalidCredentialsException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg", "Could not log in as the given credentials are invalid"); //$NON-NLS-1$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (AccessDeniedException e) {
			logger.error("Authentication failed due to: " + e.getMessage());
			loginResult.addProperty("msg",
					MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
		} catch (StrolchException | PrivilegeException e) {
			logger.error(e.getMessage(), e);
			loginResult.addProperty("msg",
					MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.FORBIDDEN).entity(loginResult.toString()).build();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			String msg = e.getMessage();
			loginResult.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
			return Response.serverError().entity(loginResult.toString()).build();
		}
	}

	@DELETE
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	@Path("{authToken}")
	public Response invalidateSession(@PathParam("authToken") String authToken) {

		JsonObject logoutResult = new JsonObject();

		try {

			StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
			Certificate certificate = sessionHandler.validate(authToken);
			sessionHandler.invalidate(certificate);

			logoutResult.addProperty("username", certificate.getUsername());
			logoutResult.addProperty("authToken", authToken);
			logoutResult.addProperty("msg", //$NON-NLS-1$
					MessageFormat.format("{0} has been logged out.", certificate.getUsername()));
			return Response.ok().entity(logoutResult.toString()).build();

		} catch (StrolchException | PrivilegeException e) {
			logger.error("Failed to invalidate session due to: " + e.getMessage());
			logoutResult.addProperty("msg",
					MessageFormat.format("Could not logout due to: {0}", e.getMessage())); //$NON-NLS-2$
			return Response.status(Status.UNAUTHORIZED).entity(logoutResult.toString()).build();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			String msg = e.getMessage();
			logoutResult
					.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
			return Response.serverError().entity(logoutResult.toString()).build();
		}
	}

	@HEAD
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	@Path("{authToken}")
	public Response validateSession(@PathParam("authToken") String authToken) {

{'fraction_non_alphanumeric': 0.142744527317931, 'fraction_numerical': 0.005700078830877448, 'mean_word_length': 5.124025250649833, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5714524', 'n_tokens_mistral': 5366, 'n_tokens_neox': 4952, 'n_words': 1074}