package consulo.webService.update.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.intellij.openapi.diagnostic.Logger;
import consulo.webService.ServiceIsNotReadyException;
import consulo.webService.update.UpdateChannel;

/**
 * @author VISTALL
 * @since 28-Aug-16
 */
@WebServlet(urlPatterns = {"/v2/consulo/plugins/deploy"})
public class PluginsDeployServlet extends HttpServlet
{
	private static final Logger LOGGER = Logger.getInstance(PluginsDeployServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		resp.sendError(HttpServletResponse.SC_FORBIDDEN);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		try
		{
			String channelParameter = req.getParameter("channel");
			UpdateChannel channel = channelParameter == null ? null : UpdateChannel.valueOf(channelParameter);
			if(channel == null)
			{
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
				return;
			}

			PluginDeploy.deployPlugin(channel, req::getInputStream);
		}
		catch(ServiceIsNotReadyException e)
		{
			resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
		}
		catch(Exception e)
		{
			LOGGER.error(e.getMessage(), e);

			resp.sendError(HttpServletResponse.SC_FORBIDDEN);
		}
	}
}

@@ -52,27 +52,106 @@
 java.io.
-IOException
+File;%0Aimport java.io.FileInputStream;%0Aimport java.io.IOException;%0Aimport java.util.Objects
 ;%0A%0Aimpor
@@ -408,16 +408,101 @@
 Logger;%0A
+import com.intellij.openapi.util.io.FileUtil;%0Aimport consulo.webService.RootService;%0A
 import c
@@ -1418,16 +1418,242 @@
 ;%0A%09%09%09%7D%0A%0A
+%09%09%09String keyFromClient = req.getHeader(%22Authorization%22);%0A%09%09%09String keyFromFs = loadDeployKey();%0A%09%09%09if(!Objects.equals(keyFromClient, keyFromFs))%0A%09%09%09%7B%0A%09%09%09%09resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);%0A%09%09%09%09return;%0A%09%09%09%7D%0A%0A
 %09%09%09Plugi
@@ -1936,13 +1936,325 @@
 N);%0A
-
 %09%09%7D%0A%09%7D
+%0A%0A%09private static String loadDeployKey() throws ServiceIsNotReadyException, IOException%0A%09%7B%0A%09%09RootService rootService = RootService.getInstance();%0A%09%09File file = new File(rootService.getConsuloWebServiceHome(), %22deploy.key%22);%0A%09%09return file.exists() ? FileUtil.loadTextAndClose(new FileInputStream(file)) : null;%0A%09%7D
 %0A%7D%0A

add some auth