<commit_before>import urllib, urlparse, json
import config
from flask import request, session, redirect, url_for, jsonify
from models import connection
from urllib2 import Request, urlopen, URLError
from providers import *
from helpers import crossdomain, plain_resp, get_enrollments
from interfaces import ItsdangerousSessionInterface
from os import environ

from hummedia import app
#app.session_interface = ItsdangerousSessionInterface()
app.secret_key=config.SECRET_KEY
app.session_cookie_name=config.COOKIE_NAME
app.config['SESSION_COOKIE_DOMAIN']=config.COOKIE_DOMAIN
app.config['APPLICATION_ROOT']=config.APPLICATION_ROOT
app.config['SESSION_COOKIE_PATH']=app.config['APPLICATION_ROOT']
provider_lookup={"google":GoogleOAuth2,"cas":CasAuth}
oAuthService = provider_lookup["google"]("google") # done this way so eventually we can have multiple providers ... for now, it's hard coded
cas = provider_lookup["cas"]()
provider = oAuthService.get_remote_app()

@provider.tokengetter
def get_access_token():
    return session.get('access_token')
    
def get_user():
    return session.get('username')

def get_userid():
    return session.get('userid')
    
def get_role():
    return session.get('role')
    
def is_superuser():
    return session.get('superuser')
    
def get_profile():
    atts={}
    for att in ['username','userid','role','superuser','fullname','preferredLanguage','ta']:
        atts[att]=session.get(att)
    if (atts['username'] is None or atts['username']=="") and session.get('oauth'):
	atts['oauth']=session.get('oauth')['provider']
    return atts
    
def get_redirect_url():
    r = session.get("redirect") if session.get("redirect") else url_for("profile")
    url_parts = list(urlparse.urlparse(r))
    query = urlparse.parse_qs(url_parts[4])
    url_parts[4] = urllib.urlencode(query)
    return urlparse.urlunparse(url_parts)
  
def set_session_vars(user):
    for att in ('username','userid','role','superuser','fullname','preferredLanguage','ta'):
        if att in user:
            session[att]=user[att]

def make_token_header():
    access_token = get_access_token()
    if access_token is None:
        return False
    else:
        return 'OAuth '+access_token[0]

def verify_oauth_access(th):
    headers = {'Authorization': th}
    req = Request(oAuthService.token_verify_url,None, headers)
    try:
        res = urlopen(req)
    except URLError, e:
        if e.code == 401:
            session.pop('access_token', None)
            return False
    return json.loads(res.read())

def get_user_from_oauth(provider,atts,access_token=None):
    q = {"oauth.%s.id" % (provider):atts['id']}
    user=connection.User.find_one(q)
    if user is None:
        session["oauth"]={"provider":provider,"id":atts['id'],"access_token":access_token,"email":atts['email']}
        user={"username":"","role":"","superuser":False,"fullname":"","preferredLanguage":"en"}
    return {"username":user['username'],"role":user['role'],"superuser":user["superuser"],"fullname":user["fullname"],"preferredLanguage":user["preferredLanguage"], "ta":user["ta"]}
    
def get_user_from_cas(netid=None,atts=None):
    if not netid:
        netid=get_user()
    q = {"username":netid}
    user=connection.User.find_one(q)
    if user is None:
        user=connection.User()
        faculty_positions=["activeFulltimeInstructor","activeParttimeInstructor"]
        user["username"]=netid
        user["firstname"]=unicode(atts["preferredFirstName"])
        user["lastname"]=unicode(atts["preferredSurname"])
        user["email"]=atts["emailAddress"]
        user["fullname"]="%s %s" % (user["firstname"],user["lastname"])
        user["userid"]=str(atts["personId"])
        for ap in faculty_positions:
            if atts[ap]=="true":
                user["role"]="faculty"
    oauth=session.get('oauth',[])
    if "provider" in oauth:
        if user['oauth'][oauth['provider']]['id'] is None:
            user["oauth"][oauth['provider']]={"id":oauth['id'],"email": oauth['email'],"access_token":oauth['access_token']}
    user.save()
    set_session_vars(user)
    return {"user":get_user()}

@crossdomain(origin=config.CROSS_DOMAIN_HOSTS,headers=['Origin','x-requested-with','accept','Content-Type', 'Authorization'],credentials=True)
def auth_redirect(provider="cas",authUser=None,proxyUser=None):
    if provider=="google":
        th=make_token_header()
        if th:
            verification=verify_oauth_access(th)
            if verification:
                user=get_user_from_oauth(provider,verification,get_access_token())
                if user['username']!="":<commit_msg>When logging in for the first time via CAS, a user's netid will be converted to lowercase. Also using lowercase for lookup (this is all needed b/c CAS isn't case sensitive)<commit_after>import urllib, urlparse, json
import config
from flask import request, session, redirect, url_for, jsonify
from models import connection
from urllib2 import Request, urlopen, URLError
from providers import *
from helpers import crossdomain, plain_resp, get_enrollments
from interfaces import ItsdangerousSessionInterface
from os import environ

from hummedia import app
#app.session_interface = ItsdangerousSessionInterface()
app.secret_key=config.SECRET_KEY
app.session_cookie_name=config.COOKIE_NAME
app.config['SESSION_COOKIE_DOMAIN']=config.COOKIE_DOMAIN
app.config['APPLICATION_ROOT']=config.APPLICATION_ROOT
app.config['SESSION_COOKIE_PATH']=app.config['APPLICATION_ROOT']
provider_lookup={"google":GoogleOAuth2,"cas":CasAuth}
oAuthService = provider_lookup["google"]("google") # done this way so eventually we can have multiple providers ... for now, it's hard coded
cas = provider_lookup["cas"]()
provider = oAuthService.get_remote_app()

@provider.tokengetter
def get_access_token():
    return session.get('access_token')
    
def get_user():
    return session.get('username')

def get_userid():
    return session.get('userid')
    
def get_role():
    return session.get('role')
    
def is_superuser():
    return session.get('superuser')
    
def get_profile():
    atts={}
    for att in ['username','userid','role','superuser','fullname','preferredLanguage','ta']:
        atts[att]=session.get(att)
    if (atts['username'] is None or atts['username']=="") and session.get('oauth'):
	atts['oauth']=session.get('oauth')['provider']
    return atts
    
def get_redirect_url():
    r = session.get("redirect") if session.get("redirect") else url_for("profile")
    url_parts = list(urlparse.urlparse(r))
    query = urlparse.parse_qs(url_parts[4])
    url_parts[4] = urllib.urlencode(query)
    return urlparse.urlunparse(url_parts)
  
def set_session_vars(user):
    for att in ('username','userid','role','superuser','fullname','preferredLanguage','ta'):
        if att in user:
            session[att]=user[att]

def make_token_header():
    access_token = get_access_token()
    if access_token is None:
        return False
    else:
        return 'OAuth '+access_token[0]

def verify_oauth_access(th):
    headers = {'Authorization': th}
    req = Request(oAuthService.token_verify_url,None, headers)
    try:
        res = urlopen(req)
    except URLError, e:
        if e.code == 401:
            session.pop('access_token', None)
            return False
    return json.loads(res.read())

def get_user_from_oauth(provider,atts,access_token=None):
    q = {"oauth.%s.id" % (provider):atts['id']}
    user=connection.User.find_one(q)
    if user is None:
        session["oauth"]={"provider":provider,"id":atts['id'],"access_token":access_token,"email":atts['email']}
        user={"username":"","role":"","superuser":False,"fullname":"","preferredLanguage":"en"}
    return {"username":user['username'],"role":user['role'],"superuser":user["superuser"],"fullname":user["fullname"],"preferredLanguage":user["preferredLanguage"], "ta":user["ta"]}
    
def get_user_from_cas(netid=None,atts=None):
    if not netid:
        netid=get_user()
    q = {"username":netid.lower()}
    user=connection.User.find_one(q)
    if user is None:
        user=connection.User()
        faculty_positions=["activeFulltimeInstructor","activeParttimeInstructor"]
        user["username"]=netid.lower()
        user["firstname"]=unicode(atts["preferredFirstName"])
        user["lastname"]=unicode(atts["preferredSurname"])
        user["email"]=atts["emailAddress"]
        user["fullname"]="%s %s" % (user["firstname"],user["lastname"])
        user["userid"]=str(atts["personId"])
        for ap in faculty_positions:
            if atts[ap]=="true":
                user["role"]="faculty"
    oauth=session.get('oauth',[])
    if "provider" in oauth:
        if user['oauth'][oauth['provider']]['id'] is None:
            user["oauth"][oauth['provider']]={"id":oauth['id'],"email": oauth['email'],"access_token":oauth['access_token']}
    user.save()
    set_session_vars(user)
    return {"user":get_user()}

@crossdomain(origin=config.CROSS_DOMAIN_HOSTS,headers=['Origin','x-requested-with','accept','Content-Type', 'Authorization'],credentials=True)
def auth_redirect(provider="cas",authUser=None,proxyUser=None):
    if provider=="google":
        th=make_token_header()
        if th:
            verification=verify_oauth_access(th)
            if verification:
                user=get_user_from_oauth(provider,verification,get_access_token())
                if user['username']!="":
{'fraction_non_alphanumeric': 0.15328156579087332, 'fraction_numerical': 0.0017019466014253802, 'mean_word_length': 4.687840290381125, 'pattern_counts': {'":': 50, '<': 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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3988342', 'n_tokens_mistral': 2979, 'n_tokens_neox': 2932, 'n_words': 535}