// Copyright 2008 Google Inc.
//
// 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 com.google.gerrit.server;

import com.google.gerrit.client.Gerrit;
import com.google.gwtjsonrpc.client.CookieAccess;
import com.google.gwtjsonrpc.server.ActiveCall;
import com.google.gwtjsonrpc.server.JsonServlet;
import com.google.gwtjsonrpc.server.SignedToken;
import com.google.gwtjsonrpc.server.XsrfException;
import com.google.gwtorm.client.OrmException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

/**
 * Base JSON servlet to ensure the current user is not forged.
 */
public abstract class GerritJsonServlet extends JsonServlet {
  private GerritServer server;

  @Override
  public void init(final ServletConfig config) throws ServletException {
    super.init(config);

    try {
      server = GerritServer.getInstance();
    } catch (OrmException e) {
      throw new ServletException("Cannot configure GerritServer", e);
    } catch (XsrfException e) {
      throw new ServletException("Cannot configure GerritServer", e);
    }
  }

  @Override
  protected SignedToken createXsrfSignedToken() throws XsrfException {
    try {
      return GerritServer.getInstance().getXsrfToken();
    } catch (OrmException e) {
      throw new XsrfException("Cannot configure GerritServer", e);
    }
  }

  @Override
  protected abstract Object createServiceHandle() throws Exception;

  @Override
  protected String xsrfUser(final ActiveCall call) {
    final String idstr = CookieAccess.getTokenText(Gerrit.ACCOUNT_COOKIE);
    return idstr != null ? "account" + idstr : "anonymous";
  }

  @Override
  protected boolean xsrfValidate(final ActiveCall call) throws XsrfException {
    final String usertok = CookieAccess.get(Gerrit.ACCOUNT_COOKIE);
    if (usertok == null || server.getAccountToken().checkToken(usertok, null)) {
      return super.xsrfValidate(call);
    } else {
      LoginServlet.forceLogout(call.getHttpServletResponse());
      return false;
    }
  }
}

Define a base servlet for use within Gerrit RPC servers