<commit_before>from django.shortcuts import redirect, render_to_response
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseNotFound, HttpRequest
from django.template.loader import render_to_string
from pltbelay.models import BelaySession, PltCredentials, GoogleCredentials, Stash, PendingLogin, PendingAccount
from xml.dom import minidom
import logging
import uuid
import urllib
import urllib2
from urlparse import urlparse
import hashlib

import smtplib

import belaylibs.dj_belay as bcap

from django.core.validators import validate_email
from django.core.mail import send_mail
from django.http import HttpResponse, HttpRequest
from django.template.loader import render_to_string

from pltbelay.models import BelaySession, PltCredentials, BelayAccount
from lib.py.common import logWith404
import settings

logger = logging.getLogger('default')

class BelayInit():
  def process_request(self, request):
    bcap.set_handlers(bcap.default_prefix, {
      'make-stash' : MakeStashHandler,
      'stash' : StashHandler,
      'create-account' : CreatePLTAccountHandler
    })
    return None

class StashHandler(bcap.CapHandler):
  def get(self, granted):
    stash = granted.stash
    return bcap.bcapResponse(bcap.dataPostProcess(stash.stashed_content))

  def put(self, granted, args):
    stash = granted.stash
    pd = bcap.dataPreProcess(args['private_data'])
    stash.stashed_content = pd
    stash.save()
    return bcap.bcapNullResponse()

  # TODO(joe): this isn't exactly what I want
  def post(self, granted, args):
    stash = Stash(stashed_content=bcap.dataPreProcess(args['private_data']))
    stash.save()
    stash_handler = bcap.grant('stash', stash)
    return bcap.bcapResponse(stash_handler)

  def delete(self, granted):
    granted.stash.delete()
    return bcap.bcapNullResponse()

class MakeStashHandler(bcap.CapHandler):
  def post_arg_names(self):
    return ['private_data']
  def post(self, granted, args):
    stash = Stash(stashed_content=bcap.dataPreProcess(args['private_data']))
    stash.save()
    stash_handler = bcap.grant('stash', stash)
    return bcap.bcapResponse(stash_handler)

def unameExists(uname):
  q = PltCredentials.objects.filter(username=uname)
  return len(q) == 1

HASH_ITERATIONS = 20
# TODO: non-ASCII characters can break this
# need to sanitize raw password
def get_hashed(rawpassword, salt):
  salted = rawpassword + salt
  for i in range(HASH_ITERATIONS):
    m1 = hashlib.sha1()
    m1.update(salted)
    salted = m1.hexdigest()

  logging.debug("Salted: %s" % salted)
  return salted

# TODO(matt): restore instead of urlopen?
def newStationCap():
  generated = urllib2.urlopen(settings.STATION_DOMAIN + '/generate/')
  return bcap.dataPostProcess(generated.read())

def notFoundResponse():
  message = 'We didn\'t recognize that email address.  Please check what you \
 entered and try again.'

  return bcap.bcapResponse({
    'emailError': True,
    'error': message,
    'message': message
  })

def emailErrorResponse():
  message = 'We had trouble sending your message.  If this problem \
persists, contact the system maintainer.'

  return bcap.bcapResponse({
    'emailError': True,
    'error': message,
    'message': message
  })

# TODO: exceptions
def sendLogEmail(subject, msg, address, fromaddr):
  try:
    validate_email(address)
  except Exception as e:
    logger.error('Couldn\'t send email (bad address): %s' % e)
    return notFoundResponse()
  logger.info('Trying to send e-mail')
  if settings.DEBUG:
    logger.error('send log email:\n %s (From: %s) \n %s \n%s' % (subject, fromaddr, address, msg))
    return False
  try:
    logger.error('Sending real email:\n %s (From: %s) \n %s \n%s' % (subject, fromaddr, address, msg))
    send_mail(subject, msg, fromaddr, [address], fail_silently=False)
  except smtplib.SMTPRecipientsRefused as e:
    logger.info('Couldn\'t send email (refused): %s' % e)
    return notFoundResponse()
  except Exception as e:
    logger.info('Couldn\'t send email (unknown): %s' % e)
    return emailErrorResponse()
  logger.info('Sent real email:\n %s \n%s' % (address, msg))
  return False

def request_plt_account(request):
  if request.method != 'POST':
    return HttpResponseNotAllowed(['POST'])
  args = bcap.dataPostProcess(request.read())
  logger.info('request: %s' % args)
  if not args.has_key('email'):
    return logWith404(logger, 'request_account: post data missing email')

  pa = PendingAccount(email = args['email'])
  pa.save()
  create_cap = bcap.grant('create-account', pa)

  message = """
Hi!  You've requested an account with Resume at the Brown University Department of Computer Science.

Visit this link to get started:

%s/new-applicant/#%s
""" % (settings.APPURL, create_cap.serialize())

  emailResponse = sendLogEmail('Resume Account Request', message, args['email'], '<NAME> <<EMAIL>>')
  if emailResponse: return emailResponse

  return bcap.bcapResponse({'success': True})

class CreatePLTAccountHandler(bcap.CapHandler):
  def post_arg_names(self):
    return ['username', 'password']

  def get(self, grantable):
    return bcap.bcapResponse(grantable.pendingaccount.email)

  def post(self, grantable, args):
    username = grantable.pendingaccount.email
    rawpassword = args['password']

    if len(username) > 20:
      return logWith404(logger, 'create_plt_account: bad username')

    if len(rawpassword) < 8:
      return logWith404(logger, 'create_plt_account: bad password')
<commit_msg>length<commit_after>from django.shortcuts import redirect, render_to_response
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseNotFound, HttpRequest
from django.template.loader import render_to_string
from pltbelay.models import BelaySession, PltCredentials, GoogleCredentials, Stash, PendingLogin, PendingAccount
from xml.dom import minidom
import logging
import uuid
import urllib
import urllib2
from urlparse import urlparse
import hashlib

import smtplib

import belaylibs.dj_belay as bcap

from django.core.validators import validate_email
from django.core.mail import send_mail
from django.http import HttpResponse, HttpRequest
from django.template.loader import render_to_string

from pltbelay.models import BelaySession, PltCredentials, BelayAccount
from lib.py.common import logWith404
import settings

logger = logging.getLogger('default')

class BelayInit():
  def process_request(self, request):
    bcap.set_handlers(bcap.default_prefix, {
      'make-stash' : MakeStashHandler,
      'stash' : StashHandler,
      'create-account' : CreatePLTAccountHandler
    })
    return None

class StashHandler(bcap.CapHandler):
  def get(self, granted):
    stash = granted.stash
    return bcap.bcapResponse(bcap.dataPostProcess(stash.stashed_content))

  def put(self, granted, args):
    stash = granted.stash
    pd = bcap.dataPreProcess(args['private_data'])
    stash.stashed_content = pd
    stash.save()
    return bcap.bcapNullResponse()

  # TODO(joe): this isn't exactly what I want
  def post(self, granted, args):
    stash = Stash(stashed_content=bcap.dataPreProcess(args['private_data']))
    stash.save()
    stash_handler = bcap.grant('stash', stash)
    return bcap.bcapResponse(stash_handler)

  def delete(self, granted):
    granted.stash.delete()
    return bcap.bcapNullResponse()

class MakeStashHandler(bcap.CapHandler):
  def post_arg_names(self):
    return ['private_data']
  def post(self, granted, args):
    stash = Stash(stashed_content=bcap.dataPreProcess(args['private_data']))
    stash.save()
    stash_handler = bcap.grant('stash', stash)
    return bcap.bcapResponse(stash_handler)

def unameExists(uname):
  q = PltCredentials.objects.filter(username=uname)
  return len(q) == 1

HASH_ITERATIONS = 20
# TODO: non-ASCII characters can break this
# need to sanitize raw password
def get_hashed(rawpassword, salt):
  salted = rawpassword + salt
  for i in range(HASH_ITERATIONS):
    m1 = hashlib.sha1()
    m1.update(salted)
    salted = m1.hexdigest()

  logging.debug("Salted: %s" % salted)
  return salted

# TODO(matt): restore instead of urlopen?
def newStationCap():
  generated = urllib2.urlopen(settings.STATION_DOMAIN + '/generate/')
  return bcap.dataPostProcess(generated.read())

def notFoundResponse():
  message = 'We didn\'t recognize that email address.  Please check what you \
 entered and try again.'

  return bcap.bcapResponse({
    'emailError': True,
    'error': message,
    'message': message
  })

def emailErrorResponse():
  message = 'We had trouble sending your message.  If this problem \
persists, contact the system maintainer.'

  return bcap.bcapResponse({
    'emailError': True,
    'error': message,
    'message': message
  })

# TODO: exceptions
def sendLogEmail(subject, msg, address, fromaddr):
  try:
    validate_email(address)
  except Exception as e:
    logger.error('Couldn\'t send email (bad address): %s' % e)
    return notFoundResponse()
  logger.info('Trying to send e-mail')
  if settings.DEBUG:
    logger.error('send log email:\n %s (From: %s) \n %s \n%s' % (subject, fromaddr, address, msg))
    return False
  try:
    logger.error('Sending real email:\n %s (From: %s) \n %s \n%s' % (subject, fromaddr, address, msg))
    send_mail(subject, msg, fromaddr, [address], fail_silently=False)
  except smtplib.SMTPRecipientsRefused as e:
    logger.info('Couldn\'t send email (refused): %s' % e)
    return notFoundResponse()
  except Exception as e:
    logger.info('Couldn\'t send email (unknown): %s' % e)
    return emailErrorResponse()
  logger.info('Sent real email:\n %s \n%s' % (address, msg))
  return False

def request_plt_account(request):
  if request.method != 'POST':
    return HttpResponseNotAllowed(['POST'])
  args = bcap.dataPostProcess(request.read())
  logger.info('request: %s' % args)
  if not args.has_key('email'):
    return logWith404(logger, 'request_account: post data missing email')

  pa = PendingAccount(email = args['email'])
  pa.save()
  create_cap = bcap.grant('create-account', pa)

  message = """
Hi!  You've requested an account with Resume at the Brown University Department of Computer Science.

Visit this link to get started:

%s/new-applicant/#%s
""" % (settings.APPURL, create_cap.serialize())

  emailResponse = sendLogEmail('Resume Account Request', message, args['email'], '<NAME> <<EMAIL>>')
  if emailResponse: return emailResponse

  return bcap.bcapResponse({'success': True})

class CreatePLTAccountHandler(bcap.CapHandler):
  def post_arg_names(self):
    return ['username', 'password']

  def get(self, grantable):
    return bcap.bcapResponse(grantable.pendingaccount.email)

  def post(self, grantable, args):
    username = grantable.pendingaccount.email
    rawpassword = args['password']

    if len(username) > 200:
      return logWith404(logger, 'create_plt_account: bad username')

    if len(rawpassword) < 8:
      return logWith404(logger, 'create_plt_account: bad password')

{'fraction_non_alphanumeric': 0.11281769976229658, 'fraction_numerical': 0.004479795209361858, 'mean_word_length': 4.59539641943734, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '5261473', 'n_tokens_mistral': 3532, 'n_tokens_neox': 3466, 'n_words': 922}