<commit_before>"""Module containing the bliss WSGI handlers."""

import cgi
import json
import logging
import os
import re
import urllib

from jinja2 import Environment
from jinja2 import FileSystemLoader

import webapp2
from webapp2_extras import security
from webapp2_extras import sessions

from __mimic import common
from __mimic import mimic

import codesite
import error
import model
import secret
import settings
import shared

from google.appengine.api import app_identity
from google.appengine.api import namespace_manager
from google.appengine.api import users
from google.appengine.ext import ndb


_JSON_MIME_TYPE = 'application/json'

_JSON_ENCODER = json.JSONEncoder()
_JSON_ENCODER.indent = 4
_JSON_ENCODER.sort_keys = True

_DEV_APPSERVER = os.environ['SERVER_SOFTWARE'].startswith('Development/')

_JINJA2_ENV = Environment(autoescape=True, loader=FileSystemLoader(''))

_DASH_DOT_DASH = '-dot-'

# must fit in front of '-dot-appid.appspot.com' and not contain '-dot-'
_VALID_PROJECT_RE = re.compile('^[a-z0-9-]{0,50}$')

_ANON_USER_KEY = u'anon_user_key'


def tojson(r):
  return _JSON_ENCODER.encode(r)


# From http://webapp-improved.appspot.com/guide/extras.html
class SessionHandler(webapp2.RequestHandler):
  """Convenience request handler for dealing with sessions."""

  def get_user_key(self):
    """Returns the email from logged in user or the session user key."""
    user = users.get_current_user()
    if user:
      return user.email()
    return self.session.get(_ANON_USER_KEY)

  def _PerformCsrfRequestValidation(self):
    session_csrf = self.session['csrf']
    client_csrf = self.request.headers['X-Bliss-CSRF']
    if not client_csrf:
      raise Exception('Missing client csrf token')
    if client_csrf != session_csrf:
      raise Exception('Client csrf token {0!r} does not match '
                      'session csrf token {1!r}'
                      .format(client_csrf, session_csrf))

  def PerformValidation(self):
    """To be overriden by subclasses."""
    if self.request.method != 'GET':
      self._PerformCsrfRequestValidation()

  def dispatch(self):
    # Get a session store for this request.
    self.session_store = sessions.get_store(request=self.request)
    # Ensure valid session is present (including GET requests)
    _ = self.session
    try:
      self.user = model.GetUser(self.get_user_key())
      self.PerformValidation()
    except error.BlissError, e:
      # Manually dispatch to handle_exception
      self.handle_exception(e, self.app.debug)

    try:
      # Exceptions during dispatch automatically handled by handle_exception
      super(SessionHandler, self).dispatch()
    finally:<commit_msg>don't dispatch the request after a validation error has been raised<commit_after>"""Module containing the bliss WSGI handlers."""

import cgi
import json
import logging
import os
import re
import urllib

from jinja2 import Environment
from jinja2 import FileSystemLoader

import webapp2
from webapp2_extras import security
from webapp2_extras import sessions

from __mimic import common
from __mimic import mimic

import codesite
import error
import model
import secret
import settings
import shared

from google.appengine.api import app_identity
from google.appengine.api import namespace_manager
from google.appengine.api import users
from google.appengine.ext import ndb


_JSON_MIME_TYPE = 'application/json'

_JSON_ENCODER = json.JSONEncoder()
_JSON_ENCODER.indent = 4
_JSON_ENCODER.sort_keys = True

_DEV_APPSERVER = os.environ['SERVER_SOFTWARE'].startswith('Development/')

_JINJA2_ENV = Environment(autoescape=True, loader=FileSystemLoader(''))

_DASH_DOT_DASH = '-dot-'

# must fit in front of '-dot-appid.appspot.com' and not contain '-dot-'
_VALID_PROJECT_RE = re.compile('^[a-z0-9-]{0,50}$')

_ANON_USER_KEY = u'anon_user_key'


def tojson(r):
  return _JSON_ENCODER.encode(r)


# From http://webapp-improved.appspot.com/guide/extras.html
class SessionHandler(webapp2.RequestHandler):
  """Convenience request handler for dealing with sessions."""

  def get_user_key(self):
    """Returns the email from logged in user or the session user key."""
    user = users.get_current_user()
    if user:
      return user.email()
    return self.session.get(_ANON_USER_KEY)

  def _PerformCsrfRequestValidation(self):
    session_csrf = self.session['csrf']
    client_csrf = self.request.headers['X-Bliss-CSRF']
    if not client_csrf:
      raise Exception('Missing client csrf token')
    if client_csrf != session_csrf:
      raise Exception('Client csrf token {0!r} does not match '
                      'session csrf token {1!r}'
                      .format(client_csrf, session_csrf))

  def PerformValidation(self):
    """To be overriden by subclasses."""
    if self.request.method != 'GET':
      self._PerformCsrfRequestValidation()

  def dispatch(self):
    # Get a session store for this request.
    self.session_store = sessions.get_store(request=self.request)
    # Ensure valid session is present (including GET requests)
    _ = self.session
    try:
      self.user = model.GetUser(self.get_user_key())
      self.PerformValidation()
    except error.BlissError, e:
      # Manually dispatch to handle_exception
      self.handle_exception(e, self.app.debug)
      return

    try:
      # Exceptions during dispatch automatically handled by handle_exception
      super(SessionHandler, self).dispatch()
    finally:
{'fraction_non_alphanumeric': 0.09090909090909091, 'fraction_numerical': 0.0055319933616079665, 'mean_word_length': 4.059701492537314, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3324592', 'n_tokens_mistral': 1708, 'n_tokens_neox': 1666, 'n_words': 458}