def view_friendship():
    """
        returns the degree of separation between two users
    """
    if request.method == 'GET':
        return render_template('view_friendship.html')
    elif request.method == 'POST': 
        client = get_db_client()
        user_1 = request.form.get('user_1', None)
        user_2 = request.form.get('user_2', None)
        if not (utils.user_exists(client, user_1) and utils.user_exists(client, user_2)):
            message = "Users Doesnot Exist. Please use our create users API for creating users first."
        elif user_1 == user_2:
            message = "Same users entered."
        else:
            command = "select @rid from Users where email_id = '%s'" % user_1
            rid_1 = utils.execute_query(client, command)[0].rid
            command = "select @rid from Users where email_id = '%s'" % user_2
            rid_2 = utils.execute_query(client, command)[0].rid
            command = "Select shortestPath(%s, %s)" % (rid_1, rid_2)
            results = utils.execute_query(client, command)
            path_len = len(results[0].shortestPath) - 1
            if path_len == -1:
                message = "%s, %s are not connected" % (user_1, user_2)
            else:
                message = "%s, %s are %s order connections." % (user_1, user_2, path_len)
    return render_template('view_friendship.html', message=message, user_1=user_1, user_2=user_2)
Example #2
0
def index(request):
    eppn, entitlement, email = _get_attrs(request)

    if eppn is None:
        return render_to_response('regsite/missing_attribute.html',
                                  {'message': settings.MISSING_EPPN_MESSAGE})
    if entitlement is None and not utils.user_exists(eppn):
        return render_to_response(
            'regsite/missing_attribute.html',
            {'message': settings.MISSING_ENTITLEMENT_MESSAGE})

    if not settings.USER_ACCEPT_CREATION or utils.user_exists(eppn):
        return _update_user(request)
    else:
        return _show_user_creation_page(request)
Example #3
0
def register():
    '''
    Handle user registrations.
    '''
    username_gotcha = 'The username <b>{0}</b> is taken!'.format
    password_gotcha = "The passwords you entered don't match."

    if request.method == 'POST':
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()
        confirm = request.form.get('confirm').strip()
        phone = request.form.get('phone-number').strip()

        if user_exists(database, username):
            error = username_gotcha(username)
            return render_template('register.html', error=error, thanks=False)
        elif password != confirm:
            error = password_gotcha
            return render_template('register.html', error=error, thanks=False)

        else:
            register_user(database, username, password, phone)
            return render_template('register.html', error=None, thanks=True)

    return render_template('register.html', error=None, thanks=False)
Example #4
0
 def post(self):
     # Maybe use this later?
     # form = NewFtpForm()
     # Check to see if we're valid
     #f not flask.request.form.validate_on_submit():
     #  flask.flash("Invalid username")
     #  return self.get
     # Load in users from chef and check to see if we're putting in a duplicate
     admin_users = utils.load_admins()
     new_admin = flask.request.form['admin_username']
     app.logger.debug("Checking. . .")
     app.logger.debug("is_admin = " +
                      str(flask.request.form.getlist('is_admin')))
     if str(flask.request.form.getlist('is_admin')) == 'on':
         admin_status = 'True'
     else:
         admin_status = 'False'
     app.logger.debug("What about here?")
     app.logger.debug("new_admin = " + new_admin)
     if utils.user_exists(new_admin, admin_users):
         flash('Admin account for ' + new_admin + ' already exists!')
         return self.get()
     # Generate password (see below) and return back to ftp, displaying new pwd
     pwd = utils.new_random_password()
     app.logger.debug(new_admin + "=" + pwd)
     admin_users[new_admin] = {"admin": admin_status, "password": pwd}
     utils.persist_admins(new_admin, admin_users)
     flash('Admin account for ' + new_admin + ' created!  Password is ' +
           pwd)
     return self.get()
Example #5
0
def send_reset():
    if request.method == "GET":
        return render_template("reset.html")
    else:
        uname = request.form['username']
        if not utils.user_exists(uname):
            return render_template("reset.html",message="That user does not exist.")
        
        pword = utils.get_password(uname)
        #sends the hash to the email                                           
        d = utils.reset_password(uname, pword)
        email = d['email']
        new_pass = d['pw']
        myemail = '*****@*****.**'
        text = "Your username is " + uname + ". Type this for your password " + new_pass
        #send email
        s = smtplib.SMTP("smtp.gmail.com", 587)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(myemail,"thisisapass")
        msg = 'To: '+email+'\n' +'From: '+myemail+'\n'+'Subject: reset password \n' + '\n' + text
        s.sendmail(myemail,email,msg)
        s.close()
        #update password
        utils.temp_password(uname, new_pass)
        return redirect(url_for("fix"))
Example #6
0
def register():
    '''
    Handle user registrations.
    '''
    username_gotcha = 'The username <b>{0}</b> is taken!'.format
    password_gotcha = "The passwords you entered don't match."

    if request.method == 'POST':
        username = request.form.get('username').strip()
        password = request.form.get('password').strip()
        confirm = request.form.get('confirm').strip()
        phone = request.form.get('phone-number').strip()

        if user_exists(database, username):
            error = username_gotcha(username)
            return render_template('register.html', error=error, thanks=False)
        elif password != confirm:
            error = password_gotcha
            return render_template('register.html', error=error, thanks=False)

        else:
            register_user(database, username, password, phone)
            return render_template('register.html', error=None, thanks=True)

    return render_template('register.html', error=None, thanks=False)
Example #7
0
def load_user(username):
    '''
    Callback method for login_manager.
    '''
    present = user_exists(database, username)
    if not present:
        return None
    return User(username)
Example #8
0
def load_user(username):
    '''
    Callback method for login_manager.
    '''
    present = user_exists(get_db().cursor(), username)
    if not present:
        return None
    return User(username)
Example #9
0
def load_user(username):
    '''
    Callback method for login_manager.
    '''
    present = user_exists(database, username)
    if not present:
        return None
    return User(username)
Example #10
0
def _create_cloud_watch_account(account_id, username):

    login_profile_already_exists = False

    session = assume_role(account_id, os.environ['FUNCTION_POLICY'])

    iam = configure_iam_resource(session)

    iam_client = configure_iam_client(session)

    user = configure_user_client(iam, username)

    policy_arn = configure_user_policy(account_id)

    if not policy_exists(iam_client, os.environ['USER_POLICY']):
        with open('./policies/CloudWatchUserPolicy.json') as f:
            repo_policy = json.load(f)

        iam.create_policy(
            PolicyName=os.environ['USER_POLICY'],
            PolicyDocument=json.dumps(repo_policy)
        )
        logger.info("New policy created.")

    if not user_exists(iam_client, username):
        user.create()
        logger.info("New user created.")

    password = genpass(8)

    # if login profile was already created continue code execution
    # at current version there is no api to get list of login profiles
    try:
        user.LoginProfile().create(
            Password=password,
            PasswordResetRequired=True
        )
    except ClientError as error:
        if error.response['Error']['Code'] == ENTITY_ALREADY_EXISTS:
            logger.warning("User already exists.")
            login_profile_already_exists = True
        else:
            logger.error(error)
            raise

    if login_profile_already_exists:
        user.LoginProfile().update(
            Password=password,
            PasswordResetRequired=True
        )

    user.attach_policy(PolicyArn=policy_arn)

    return {
        'username': username,
        'password': password
    }
Example #11
0
def login_callback(conn, cur, response, status, args):
    googleId = args[0]

    if user_exists(googleId):
        response['newUser'] = False

    else:
        cur.execute('INSERT INTO users VALUES ("{}")'.format(googleId))
        conn.commit()
        response['newUser'] = True
def handleNormalSessionHook(request):
    eppn, entitlement, email = _get_attrs(request)

    # If the eppn attribute is missing show an error
    if eppn is None:
        return render_to_response(
            'regsite/missing_attribute.html',
            {'message': settings.MISSING_EPPN_MESSAGE}, status=500)
    # If the entitlement is missing show an error
    if entitlement is None and not utils.user_exists(eppn):
        return render_to_response(
            'regsite/missing_attribute.html',
            {'message': settings.MISSING_ENTITLEMENT_MESSAGE}, status=500)
    # If the user consent page is disabled or the user exists in keystone
    # update the user silently in keystone.
    if not settings.USER_ACCEPT_CREATION or utils.user_exists(eppn):
        return _update_user(request)
    # Otherwise show the user creation page
    else:
        return _show_user_creation_page(request)
Example #13
0
    def post(self):
        user_uname = self.request.get('username')
        user_psswrd = self.request.get('password')
        user_ver = self.request.get('verify')
        user_email = self.request.get('email')

        uname = utils.valid_uname(user_uname)
        uname_ex = utils.user_exists(user_uname)
        psswrd = utils.valid_psswrd(user_psswrd)
        verified = utils.verify_psswrd(user_psswrd, user_ver)
        email = utils.valid_email(user_email)

        #Create error messages
        if not uname:
            uname_err = "That's not a valid username!"
        if uname_ex:
            uname_err = "This username already exists!"
        if not psswrd:
            psswrd_err = "That wasn't a valid password"
        if not verified:
            verify_err = "Passwords did not match"
        if not email:
            email_err = "That's not a valid email!"

        if not (uname and not uname_ex and psswrd and verified and
                (email or user_email == "")):
            #There was an error in one of the fields.
            self.render_signup(uname=cgi.escape(user_uname),
                               uname_err=uname_err,
                               psswrd_err=psswrd_err,
                               verify_err=verify_err,
                               email=cgi.escape(user_email),
                               email_err=email_err)
        else:
            #Create a new user.
            password_hash = utils.make_pw_hash(user_uname, user_psswrd)
            user = mydb.User(username=user_uname,
                             password_hash=password_hash,
                             salt=password_hash.split('|')[1],
                             email=user_email)
            user.put()
            mydb.allusers(update=True, newuser=user)
            print "added new user %s" % user.username

            #Redirect the user back to entry where they came from.
            redir = self.request.cookies.get('Location')

            if not redir:
                redir = '/'

            self.response.headers.add_header(
                'Set-Cookie', "user_id=%s;Location=%s;Path=/" %
                (utils.make_secure_val(str(user.key.id())), str(redir)))
            self.redirect(str(redir))
def create_friends():
    """
        given two users, create friendship connection between them
    """
    message = ""
    if request.method == 'GET':
        return render_template('create_connection.html')
    if request.method == 'POST':
        client = get_db_client()
        user_1 = request.form.get('user_1', None)
        user_2 = request.form.get('user_2', None)
        if not (utils.user_exists(client, user_1) or utils.user_exists(client, user_2)):
            message = "Users Doesnot Exist. Please use our create users API for creating users first."
        elif user_1 == user_2:
            message = "Cannot create friends with self."
        else:
            if not utils.are_friends(client, user_1, user_2):
                command = "create edge Connections from (select from Users where email_id = '%s') to (select from Users where email_id = '%s')" % (user_1, user_2)
                utils.execute_query(client, command)
                message = "connection created successfully from %s to %s" % (user_1, user_2)
            else:
                message = "They are already good friends."
        return render_template('create_connection.html', message=message, user_1=user_1, user_2=user_2)
Example #15
0
def get_topics_from_user():
    user = request.args.get('user')

    if user_exists(user):
        documents = get_collection('doubts')
        topics = []
        query = {'user': user}
        for document in documents.find(query):
            if not document['topic'] in topics:
                topics.append(document['topic'])

        return jsonify(topics), 200
    else:
        return 'User not found', 404
Example #16
0
def login(message='',logout=False):
    if request.method== "GET":
	    if 'user' in session and session['user'] != '':
		return(render_template("login.html",message='Already logged in.',logout=True))
	    else:
        	return(render_template("login.html",message=message))
    else:
        uname=request.form['username']
        pword = request.form['password']
	if not utils.user_exists(uname):
		return(render_template("login.html",message="User does not exist."))
        elif utils.authenticate(uname,pword): # checks if pword matches uname in database
	    session['user'] = uname # set current user 
            return redirect(url_for('profile', username=uname))
        else:
            return(render_template("login.html",message="Incorrect username or password."))
def add_new_user():
    """
        add a new user into Users table with given email id. CSRF considered
    """
    if request.method == 'GET':
        return render_template('add_new_user.html')
    elif request.method == 'POST':
        email_id = request.form.get('email_id', None)
        client = get_db_client()
        # check if already exist in command, unique email_ids 
        if utils.user_exists(client, email_id):
            message = "User already exists."
        else:
            command = "INSERT INTO Users (email_id) values %s" % ("('"+ email_id + "')")
            utils.execute_query(client, command)
            message = "user %s created successfully" %(email_id) 
        return render_template('message.html', message=message)
Example #18
0
def register_test():
    if request.method == "POST":
        print(request.form)
        user_type = request.form["type"]
        print(user_type)
        form = RegisterForm()
        print(form)
        if form.validate_on_submit():
            print("HELLO")
            if user_exists(request.form['email'], user_type, db):
                flash("A user with this email already exists")
                return render_template("register_update.html")
        account = register_user(user_type, request.form, db)
        create_account(user_type, account, db)
        return redirect(url_for('login'))
    else:
        return render_template("register_update.html")
Example #19
0
def register(user_type):
    base_url = "register_" + user_type + ".html"
    form = RegisterForm()
    if form.validate_on_submit():

        if user_exists(request.form['email'], user_type, db):
            flash("A user with this email already exists")
            return render_template(base_url, form=form, user_type=user_type)
        account = register_user(user_type, request.form, db)
        if account == "IV":
            flash("Invalid address. Make sure it looks like: 825 West End Ave #4A, New York.")
            return redirect("register/%s"%user_type)
        create_account(user_type, account, db)
        return redirect(url_for('login'))
    if request.method=="POST":
        flash("Your email or password is not valid. Please try again.")
    return render_template(base_url, form=form, user_type=user_type)
Example #20
0
def register():
	if request.method == "GET":
		return(render_template("register.html"))
	else:
		uname = request.form['username']
		pword = request.form['password']
		conf = request.form['confirm']
		email = request.form['email']
		if utils.user_exists(uname):
			return(render_template("register.html",message="Username already exists."))
		elif len(uname) < 2:
			return(render_template("register.html",message="Username must be at least 2 characters."))
		elif len(pword) < 6:
			return(render_template("register.html",message="Password must be at least 6 characters."))
		elif pword != conf:
			return(render_template("register.html",message="Password doesn't match confirmation."))
		else:
			utils.add_user(uname,pword,email)
			return redirect(url_for('login'))
Example #21
0
def get_doubts_by_topic_from_user():
    user = request.args.get('user')
    topic = request.args.get('topic')

    if user_exists(user):
        documents = get_collection('doubts')
        output = []
        query = {'user': user, 'topic': topic}
        for document in documents.find(query):
            output.append({
                '_id': str(document['_id']),
                'doubt': document['doubt'],
                'answer': document['answer'],
                'topic': document['topic'],
            })

        return jsonify(output), 200
    else:
        return 'User not found', 404
Example #22
0
 def command_give(self, data):
     try:
         amount = int(data[2])
         recipient = data[1].lower()
         if user_exists(self, recipient):
             if self.user == CHANNEL_NAME:
                 if add_points(self, recipient, amount):
                     return '%s gives %s %s %s' % (
                         NICKNAME, data[1], amount,
                         self.fmt_currency_name(amount))
             if self.user == recipient: return True
             if amount < 0: return True
             if sub_points(self, self.user, amount):
                 if add_points(self, recipient, amount):
                     return '%s gives %s %s %s' % (
                         self.user, data[1], amount,
                         self.fmt_currency_name(amount))
     except:
         pass
     return True
Example #23
0
    def post(self):
        user_uname = self.request.get('username')
        user_psswrd = self.request.get('password')
        user_ver = self.request.get('verify')
        user_email = self.request.get('email')

        uname = utils.valid_uname(user_uname)
        uname_ex = utils.user_exists(user_uname)
        psswrd = utils.valid_psswrd(user_psswrd)
        verified = utils.verify_psswrd(user_psswrd, user_ver)
        email = utils.valid_email(user_email)

        # this will store the values to be returned
        ret = {"uname":cgi.escape(user_uname), "uname_err":"", "psswrd_err":"", "verify_err":"", "email":cgi.escape(user_email), "email_err":""}

        if not uname:
            ret["uname_err"] = "That's not a valid username!"
        if uname_ex:
            ret["uname_err"] = "This username already exists!"
        if not psswrd:
            ret["psswrd_err"] = "That wasn't a valid password"
        if not verified:
            ret["verify_err"] = "Passwords did not match"
        if not email:
            ret["email_err"] = "That's not a valid email!"

        if not(uname and not uname_ex and psswrd and verified and (email or user_email == "")):
            self.render_signup(uname=ret["uname"], uname_err=ret["uname_err"], psswrd_err=ret["psswrd_err"], verify_err=ret["verify_err"], email=ret["email"], email_err=ret["email_err"])
        else:
            password_hash = utils.make_pw_hash(user_uname, user_psswrd)
            user = mydb.User(username=user_uname, password_hash=password_hash, salt=password_hash.split('|')[1], email=user_email)
            user.put()
            print "added new user %s" % user.username
            mydb.allusers(True, user)
            redir = self.request.cookies.get('Location')
            #time.sleep(1)
            if not redir:
                redir = '/'
            self.response.headers.add_header('Set-Cookie', "user_id=%s;Location=%s;Path=/" % (utils.make_secure_val(str(user.key().id())), str(redir)))
            print redir
            self.redirect(str(redir))
Example #24
0
def get_doubts_by_user(doubt='NONE'):
    user = request.args.get('user')

    query = {'user': user}
    if doubt != 'NONE':
        query = {'user': user, 'doubt': doubt}

    if isinstance(user, str):
        if user_exists(user):
            documents = get_collection('doubts')
            output = []
            for document in documents.find(query):
                output.append({
                    '_id': str(document['_id']),
                    'doubt': document['doubt'],
                    'answer': document['answer'],
                    'topic': document['topic'],
                })
            return jsonify(output), 200
        else:
            return 'User not found', 404
    else:
        return 'Bad request', 400
Example #25
0
 def post(self):
     # Maybe use this later?
     # form = NewFtpForm()
     # Check to see if we're valid
     #f not flask.request.form.validate_on_submit():
     #  flask.flash("Invalid username")
     #  return self.get
     # Load in users from chef and check to see if we're putting in a duplicate
     ftp_users = utils.load_users()
     new_user = flask.request.form['ftp_username']
     media_type = flask.request.form['media_type']
     app.logger.debug("new_user = "******"=" + pwd)
     app.logger.debug("media_type = " + media_type)
     app.logger.debug("ftp_users has this many entries:" +
                      str(len(ftp_users)))
     ftp_users[new_user] = {
         "password":
         pwd,
         "media_type":
         media_type,
         "_comment":
         "Added by " + flask.session['username'] + " on " +
         datetime.datetime.now().strftime("%Y-%m-%d %T")
     }
     utils.persist_users(new_user, ftp_users, 'added')
     flash('FTP account for ' + media_type + ' ' + new_user +
           ' created!  Password is ' + pwd)
     return self.get()
Example #26
0
def deploy():
    require('stage', provided_by=(test,production,))

    if not utils.user_exists('joyupdater'):
      utils.user_create('joyupdater')

    if not files.exists(env.remote_dir):
        sudo("mkdir -p {}".format(env.remote_dir))
        sudo("chown -R joyupdater:joyupdater {}".format(env.remote_dir))

    with lcd(root_path), cd(env.remote_dir):
        if not files.exists(os.path.join(env.sv_confd, 'update-server.conf')):
          put('scripts/update-server.conf', env.sv_confd)
          run('supervisorctl reload')

        # upload files
        run('mkdir -p {}/updates'.format(env.remote_dir))
        if os.path.exists('templates'):
          run('mkdir -p {}/templates'.format(env.remote_dir))
          put('templates/*.*', '{}/templates'.format(env.remote_dir))

        put('update-server', env.remote_dir)

        local_cnf = os.path.join(root_path, 'config.{}.toml'.format(env.stage))
        if os.path.exists(local_cnf):
          put(local_cnf, env.remote_dir+'/config.toml')

        if not files.exists('{}/config.toml'.format(env.remote_dir)):
          put('*.toml.example', env.remote_dir)
          run('mv config.toml.example config.toml')

        sudo("chown -R joyupdater:joyupdater {}".format(env.remote_dir))
        sudo("chmod a+x {}/update-server".format(env.remote_dir))

        # restart server
        run('supervisorctl restart updateserver')
        print colors.green("app deployed")
Example #27
0
def _delete_user_cloudwatch_account(account_id, username):
    session = assume_role(account_id, os.environ['FUNCTION_POLICY'])

    iam = configure_iam_resource(session)

    iam_client = configure_iam_client(session)

    user = configure_user_client(iam, username)

    policy_arn = configure_user_policy(account_id)

    if not user_exists(iam_client, username):
        return {'username': username}

    if policy_attached_to_user(
        iam_client,
        username,
        os.environ['USER_POLICY']
    ):
        user.detach_policy(PolicyArn=policy_arn)
        logger.info("Policy detached.")

    # if login profile was already deleted continue code execution
    # at current version there is no api to get list of login profiles
    try:
        user.LoginProfile().delete()
    except ClientError as error:
        if error.response['Error']['Code'] == NO_SUCH_ENTITY:
            logger.warning("Login profile does not exist.")
        else:
            logger.error(error)
            raise

    user.delete()

    return {'username': username}
Example #28
0
    def post(self):
		if self.request.get('login_email') and self.request.get('login_password'):
			user_email = self.request.get('login_email')
			user_psswrd = self.request.get('login_password')

			print user_email

			valid_pwd = False
			valid_email = False

			q = mydb.User.get_by_email(user_email)
			if not(q is None):
				valid_email = True
				valid_pwd = utils.valid_pw(user_email, user_psswrd, q.password_hash)

				if valid_pwd and valid_email:
					self.response.headers.add_header('Set-Cookie', "user_id=%s;Path=/" % utils.make_secure_val(str(q.key().id())))
					self.redirect('/hello')
				else:
					self.render_signup(email=cgi.escape(user_email), login_err="Invalid username or password. Please sign up or try again.")
		else:
			user_email = self.request.get('email')
			user_psswrd = self.request.get('password')
			user_first_name = self.request.get('first_name')
			user_last_name = self.request.get('last_name')
			user_dob = self.request.get('dob')
			user_gender = self.request.get('gender')
			user_occupation = self.request.get('occupation')
			user_confirmation = self.request.get('confirmation')

			print user_email
			print user_psswrd
			print user_first_name
			print user_last_name
			print utils.convert_dob(user_dob)
			print user_gender
			print user_occupation
			print user_confirmation

			name = utils.valid_name(user_first_name) and utils.valid_name(user_last_name)
			user_ex = utils.user_exists(user_email)
			psswrd = utils.valid_psswrd(user_psswrd)
			email = utils.valid_email(user_email)

			# this will store the values to be returned
			#ret = {"uname":cgi.escape(user_uname), "uname_err":"", "psswrd_err":"", "verify_err":"", "email":cgi.escape(user_email), "email_err":""}

			if not name or user_ex or not psswrd or not email:
				input_err = "Some input was incorrect. Further details to come soon."
			if not(name and not user_ex and psswrd and email):
				self.render_signup(first_name=first_name,
				login_err=login_err,
				input_err=input_err,
				email=email,
				last_name=last_name,
				gender=gender,
				occupation=occupation)
			else:
				password_hash = utils.make_pw_hash(user_email, user_psswrd)
				user = mydb.User(first_name=user_first_name, last_name=user_last_name, dob=utils.convert_dob(user_dob), gender=user_gender, occupation=user_occupation, password_hash=password_hash, salt=password_hash.split('|')[1], email=user_email)
				user.put()
				print "added new user %s" % user.email
				#mydb.allusers(True, user)
				time.sleep(0.2)
				self.response.headers.add_header('Set-Cookie', "user_id=%s;Path=/" % utils.make_secure_val(str(user.key().id())))
				self.redirect('/hello')
Example #29
0
def register():
    '''
    Registers a user.
    '''
    hasher = argon2.PasswordHasher()
    reason = 'Unknown error.'
    if request.method == 'POST':
        try:
            uname = request.form.get('uname')
            pword = request.form.get('pword')

            if pword != request.form.get('pword_c'):
                reason = 'Passwords do not match.'
                raise GameException

            pword_hash = hasher.hash(pword)

            cursor = get_db().cursor()
            if not user_exists(cursor, uname):
                cursor.execute(
                    '''
                    INSERT INTO users
                    (id, password, event, level,
                    email, phone, ban, timestamp)
                    VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?)
                    ''', (uname, pword_hash, APP_CONFIG['event'], 1,
                          request.form.get('email'), request.form.get('phone'),
                          False, int(time.time())))
                get_db().commit()
            else:
                reason = 'Username `{}\' is already taken.'.format(uname)
                raise GameException

            reason = 'Successfully registered `{}\'.'.format(uname)

        except GameException:
            return render_template(
                'register.html',
                event=EVENT_DATA['name'],
                host=EVENT_DATA['host'],
                faq=EVENT_DATA['faq'],
                social=EVENT_DATA['social'],
                discuss=EVENT_DATA['discuss'],
                error=True,
                reg=False,
                reason=reason,
                year=YEAR,
            )

        return render_template(
            'register.html',
            event=EVENT_DATA['name'],
            host=EVENT_DATA['host'],
            faq=EVENT_DATA['faq'],
            social=EVENT_DATA['social'],
            discuss=EVENT_DATA['discuss'],
            error=False,
            reg=True,
            reason=reason,
            year=YEAR,
        )

    else:
        return render_template(
            'register.html',
            event=EVENT_DATA['name'],
            host=EVENT_DATA['host'],
            faq=EVENT_DATA['faq'],
            social=EVENT_DATA['social'],
            discuss=EVENT_DATA['discuss'],
            error=False,
            reg=False,
            reason='',
            year=YEAR,
        )
def index(request):
    eppn = request.META.get(settings.SHIBBOLETH_NAME_ATTRIBUTE, None)
    if not settings.USER_ACCEPT_CREATION or utils.user_exists(eppn):
        return _update_user(request)
    else:
        return _show_user_creation_page(request)