def get_authenticated_user(self):
     if not CFG.get_instance().is_live():
         db_session = DB_Session_Factory.get_db_session()
         return db_session.query(User).get("*****@*****.**")
     try:
         cookie_string = os.environ['HTTP_COOKIE']
         cookie = Cookie.SimpleCookie(cookie_string)
         session_cookie = cookie['session_id'].value
     except (Cookie.CookieError, KeyError):
         session_cookie = None
     result = None
     return User.user_for_session_cookie(session_cookie)
 def register_for_push_notifications(self, interviewer):
     hostname = CFG.get_instance().get('installation', 'hostname')
     response = self.service.events().watch(calendarId = interviewer.email, body = {
         'id' : get_resource_id_for_interviewer(interviewer),
         'type' : "web_hook",
         'address' : 'https://' + hostname + '/api/calendar_notification',
         'params' : {
             'ttl' : 24*60*60,
         }
     }).execute()
     interviewer.push_notification_id = response.get("resourceId", "")
     db_session = DB_Session_Factory.get_db_session()
     db_session.add(interviewer)
     db_session.commit()
def main(argv):
    update_dirty_calendars_only = False
    if len(argv) is 2 and argv[1] == "dirty_only":
        update_dirty_calendars_only = True
    now = datetime.now(timezone(LOS_ANGELES_TZ))
    period_start = datetime(year = now.year, month = now.month, day = now.day, tzinfo = now.tzinfo)
    period_end = period_start + timedelta(days = int(CFG.get_instance().get('refresh_interview_schedule', 'num_days_to_get_schedule_for')))
    calendar = Google_Calendar.get_calendar()
    db_session = DB_Session_Factory.get_db_session()
    if update_dirty_calendars_only is True:
        interviewer_list = db_session.query(Interviewer).filter(Interviewer.needs_calendar_sync == 1).with_lockmode('update').all()
        for interviewer in interviewer_list:
            interviewer.needs_calendar_sync = 0
        db_session.commit()
    else:
        interviewer_list = db_session.query(Interviewer).filter(Interviewer.employed == 1).order_by(Interviewer.email)
    for interviewer in interviewer_list:
        print "Checking schedule for " + interviewer.name
        calendar.refresh_interviews(interviewer, period_start, period_end)
        calendar.stop_push_notifications(interviewer)
def flush_interviews(interviewer, interviews_to_delete, interviews_for_interviewer, from_date, to_date, db_session):
    for interview_to_delete in interviews_to_delete:
        delete_interview(interview_to_delete, db_session)
    phone_number_index = 0 
    phone_numbers = CFG.get_instance().get('twilio', 'from_phone_numbers').split(',')
    latest_existing_interview_start_time = datetime.fromordinal(from_date.toordinal())
    for index, existing_interview in enumerate(interviews_for_interviewer):
        if latest_existing_interview_start_time < existing_interview.start_time:
            latest_existing_interview_start_time = existing_interview.start_time
        if existing_interview.phone_number_to_use is None:
            # Make sure that no two consecutive interviews use the same phone number
            while len(phone_numbers) > 1 and (get_phone_number(interviews_for_interviewer, index - 1) == phone_numbers[phone_number_index] or get_phone_number(interviews_for_interviewer, index + 1) == phone_numbers[phone_number_index]):
                phone_number_index = (phone_number_index + 1)%len(phone_numbers)
            existing_interview.phone_number_to_use = phone_numbers[phone_number_index]
    db_session.flush()
    db_session.commit()
    print "DELETE: " + str(latest_existing_interview_start_time) + " - " + str(to_date)
    for deleted_interview in interviewer.interviews.filter(Interview.start_time > latest_existing_interview_start_time, Interview.start_time < to_date):
        delete_interview(deleted_interview, db_session)
    db_session.flush()
    db_session.commit()
    def check_auth(self):
        if not CFG.get_instance().is_live():
            return None
        try:
            cookie_string = os.environ['HTTP_COOKIE']
            cookie = Cookie.SimpleCookie(cookie_string)
            session_cookie = cookie['session_id'].value
        except (Cookie.CookieError, KeyError):
            session_cookie = None
        result = None
        if session_cookie is None or User.session_is_active(session_cookie) is False:
            result = {'error' : 'authn_needed'}
            authn_request = """\
<?xml version="1.0" encoding="UTF-8"?>
<saml2p:AuthnRequest xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" AssertionConsumerServiceURL="http://onsite-inflight.com/api/post-sso" Destination="https://box.okta.com/app/template_saml_2_0/k5jimobgREMCSHKGRLVB/sso/saml" ForceAuthn="false" ID="%s" IsPassive="false" IssueInstant="%s" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0">
    <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">http://onsite-inflight.com/api/post-sso</saml2:Issuer>
    <saml2p:NameIDPolicy AllowCreate="false" Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" SPNameQualifier="http://onsite-inflight.com/api/post-sso"/>
</saml2p:AuthnRequest>
""" % (uuid.uuid4().hex, datetime.now().isoformat())
            result['authn_request'] = base64.b64encode(authn_request)
        return result
def get_resource_id_for_interviewer(interviewer):
    if interviewer is None:
        return None
    return CFG.get_instance().get("installation", "env_name") + "_" + re.sub("@.*", "", interviewer.email)
#!/usr/bin/env python

import sys
from model.db_session import DB_Session_Factory
from model.interview import Interview
from model.interviewer import Interviewer
from model.interviewer_tag import Interviewer_Tag
from urllib import urlretrieve
from os import listdir, remove, path, walk
from lib.conf import CFG
import re

ROOT = CFG.get_instance().get('installation', 'root') + '/code/webapp'

def main(argv):
    db_session = DB_Session_Factory.get_db_session()
    deletion_sql = Interviewer.__table__.delete('1')
    db_session.execute(deletion_sql)
    interviewers = {}
    
    with open("../data/bootstrap/interviewers.dat", "r") as interviewer_file:
        for interviewer_info in interviewer_file:
            interviewer_info = interviewer_info.strip(' \t\n\r')
            if not interviewer_info:
                continue
            interviewer_data = interviewer_info.split("\t")
            print interviewer_data[0] + "\t" + interviewer_data[1] + "\t" + interviewer_data[2]
            interviewer = Interviewer(interviewer_data[1], interviewer_data[0], interviewer_data[2])
            if len(interviewer_data) == 4:
                original_url = interviewer_data[3]
                final_url = '/avatars/' + interviewer.name.lower().replace(' ', '-')
#!/usr/bin/env python

import sys
from lib.conf import CFG

root_path = CFG.get_instance().get("installation", "root")
sys.path.insert(1, root_path + "/code/lib/gcal_sdk")

import gflags
import httplib2
import os
import pprint
import re
import logging
from model.interviewer import Interviewer
from model.interview import Interview
from model.candidate import Candidate
from model.db_session import DB_Session_Factory
from pytz import timezone, utc
from datetime import datetime, timedelta
import pdb

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

SECS_IN_DAY = 24 * 60 * 60
LOS_ANGELES_TZ = "America/Los_Angeles"
FLAGS = gflags.FLAGS
 def get_db_session():
     if DB_Session_Factory.session is None:
         db_engine = create_engine(CFG.get_instance().get('db', 'dsn'), echo=False)
         Session = sessionmaker(bind = db_engine)
         DB_Session_Factory.session = Session()
     return DB_Session_Factory.session
def send_email(to_email_address, email_subject, email_body):
    s = smtplib.SMTP('localhost')
    s.sendmail("*****@*****.**", to_email_address, 
"""From: Onsite Inflight <*****@*****.**>
Content-Type: text/plain; charset=ISO-8859-1
X-Envelope-From: Onsite Inflight <*****@*****.**>
To: %s
Subject: %s

%s
""" % (to_email_address, email_subject, email_body))
    s.quit()

db_session = DB_Session_Factory.get_db_session()
week_ago = datetime.now() - timedelta(days = 7)
template = Template(file = CFG.get_instance().get('installation', 'root') + '/data/email_interview_summary.tmpl')
for interviewer_email in db_session.query(Interview.interviewer_email).distinct().filter(Interview.start_time > week_ago, Interview.end_time < date.today()):
    interviewer_email = interviewer_email[0]
    interviewer = db_session.query(Interviewer).get(interviewer_email)
    interview_count = 0
    responded_interview_count = 0
    avg_response_time = 0
    template.interviewer_first_name = interviewer.nickname()
    for interview in interviewer.interviews.filter(Interview.start_time > week_ago, Interview.end_time < date.today()):
        interview_count += 1
        time_to_feedback = interview.time_to_feedback()
        if time_to_feedback != timedelta.max:
            responded_interview_count += 1
            avg_response_time = (avg_response_time*(interview_count-1) + time_to_feedback.total_seconds())/interview_count
    template.num_interviews = interview_count
    template.avg_time_to_feedback = round(avg_response_time/60)