Beispiel #1
0
def change_user_password(form):
    """
    Function that takes care of changing the user password in ADSClassic
    """
    old_password, new_password = form.old_password.data, form.new_password.data

    try:
        classic_user = update_classic_password(current_user.get_username(), old_password, new_password)
    except TypeError:
        app.logger.error(
            "ADS Classic account modification error: getting wrong json structure back. Tried to update password for user: %s"
            % current_user.get_username()
        )
        return False, "Problems in the password update. Please try later.", "error"

    if classic_user and classic_user.get("message") == "ACCOUNT_UPDATED":
        return True, "Password successfully updated.", "success"
    elif classic_user and classic_user.get("message") == "WRONG_PASSWORD":
        app.logger.error(
            "ADS Classic account modification error: wrong old password used. Tried to update password: login %s"
            % current_user.get_username()
        )
        return False, "The current password is wrong. Please try again.", "error"
    else:
        app.logger.error(
            "ADS Classic account modification error: return message not expected. Tried to update password: login %s"
            % current_user.get_username()
        )
        return False, "Problems in the account modification. Please try again.", "error"
Beispiel #2
0
def friends():
    if request.method == "POST":
        formtype = request.form.get('type')
        if formtype == "del":
            remove_friends = request.form.getlist('delfriends[]')
            flask_redis.srem(current_user.get_username() + "-friends",
                             *remove_friends)
        elif formtype == "add":
            add_friend = request.form.get('uun')

            #if(re.match("^[A-Za-z]+\ [A-Za-z]+$", add_friend) == None):
            #    raise APIError("Friend name expected in [A-z]+\ [A-z]+ form.", status_code=400)
            flask_redis.sadd(current_user.get_username() + "-friends",
                             add_friend)

    friends = get_friends()
    friends = map(lambda p: ("%s (%s)" % (p[0], p[1]), p[1]), friends)

    friends = sorted(friends, key=lambda s: s[0].lower())

    return jsonify(friendList=friends)  #Set up for ajax responses
Beispiel #3
0
def activate_user_new_email(form):
    """
    Function that takes care of updating the email address that is also the username
    """
    activation_code, curpassword = form.id.data, form.password.data

    # create an itsdangerous object to un sign the verification code and decrypt the password
    itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)
    # decrypt the activation code
    try:
        logins = itsd.loads(activation_code)
    except BadSignature:
        app.logger.error("Activation code not valid. Code used: %s" % activation_code)
        return False, "Activation Code not valid.", "error"
    emails = logins.split("||")
    if len(emails) != 2:
        app.logger.error("Number of emails in the activation code not valid. Code used: %s" % activation_code)
        return False, "Activation Code not valid.", "error"
    new_login, old_login = emails
    # if the current user is the right one
    if current_user.get_username() != old_login:
        return False, "Please activate the new email with the correct account", "error"
    else:
        # update ads classic
        try:
            classic_user = update_classic_username(old_login, new_login, curpassword)
        except TypeError:
            app.logger.error(
                "ADS Classic account modification error. Tried to update email: old %s, new %s" % (old_login, new_login)
            )
            return False, "Problems in the account modification. Please try later.", "error"
        if classic_user and classic_user.get("message") == "ACCOUNT_UPDATED":
            loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username == old_login)  # @UndefinedVariable
            loc_db_user.add_to_set("alternate_usernames", old_login).set(username=new_login).execute()
            return (
                True,
                "The username %s is now active and should be used from now on to login to this account." % new_login,
                "success",
            )
        elif classic_user and classic_user.get("message") == "WRONG_PASSWORD":
            app.logger.error(
                "ADS Classic account modification error: wrong old password used. Tried to update email: old %s, new %s"
                % (old_login, new_login)
            )
            return False, "The current password is wrong. Please try again.", "error"
        else:
            app.logger.error(
                "ADS Classic account modification error: return message not expected: Tried to update email: old %s, new %s"
                % (old_login, new_login)
            )
            return False, "Problems in the account modification. Please try again.", "error"
Beispiel #4
0
def get_friends():
    friends = flask_redis.smembers(current_user.get_username() + "-friends")
    friends = list(friends)

    with ldap.conn() as ldap_conn:
        friend_names = ldap.get_names_bare(friends, ldap_conn)

        for i in range(len(friends)):
            uun = friends[i]
            friend = uun

            if uun in friend_names:
                friend = friend_names[uun]

            friends[i] = (friend, uun)
    return friends
Beispiel #5
0
def reauth():
    """
    User re authentication view
    """
    app.logger.debug('User reauth')
    
    form = ReauthForm(next=request.args.get('next', None))
    #if the login is fresh there is no need to re-authenticate
    if login_fresh():
        return redirect(generate_redirect_url(next_=form.next.data))
    
    if form.validate_on_submit():
        user, authenticated = authenticate(current_user.get_username(), form.password.data)
        if user and authenticated:
            user.set_last_signon()
            confirm_login()
            return redirect(generate_redirect_url(next_=form.next.data))
        else:
            flash('Sorry, invalid login parameters', 'error')

    return render_template('reauth.html', form=form)
Beispiel #6
0
def results():
    if not current_user.get_current_session():
        return redirect(url_for('root'))
    assignment_id = current_user.get_current_assignment_id()
    submit_base = current_user.get_submit_to()
    if submit_base:
        submit_to = os.path.join(current_user.get_submit_to(), 'mturk/externalSubmit')
    else:
        submit_to = '/'
    current_user.finish_session()
    worker_id = current_user.get_username()
    # try:
    #     qualification_score = mtc.get_qualification_score(QUALIFICATION_ID, worker_id)
    #     mtc.update_qualification_score(QUALIFICATION_ID, worker_id, qualification_score+1)
    # except:
    #     pass
    if QUIZ:
        scores = current_user.get_scores()
        corrects = [s[0] for s in scores]
        if len(corrects) > 1:
            diffbest = corrects[-1] - max(corrects[:-1])
            diff = abs(diffbest)
            diffsign = get_diffsign(diffbest)
        else:
            diffsign = 'equal'
            diff = 0
        return render_template(
                'results.html',
                quiz=True,
                diffsign=diffsign,
                diff=diff,
                sesscount=len(corrects),
                assignment_id=assignment_id,
                submit_to=submit_to)
    else:
        return render_template(
                'results.html',
                quiz=False,
                assignment_id=assignment_id,
                submit_to=submit_to)
Beispiel #7
0
def change_user_settings(form):
    """
    Function that checks the current params against the submitted ones and 
    changes them in case are different. If the email is different a 
    confirmation email is sent before proceeding
    """
    #check if name and lastname need to be changed
    name = lastname = login = ''
    if form.name.data != current_user.user_rec.firstname:
        name = form.name.data
    if form.lastname.data != current_user.user_rec.lastname:
        lastname = form.lastname.data
    if form.login.data != current_user.user_rec.username:
        login = form.login.data
    
    #if the user submitted a form with no changes there is nothing to do    
    if not (name or lastname or login):
        app.logger.debug('The user submitted a form with no changes.')
        return False, 'Settings not changed. Please modify some settings to change them.', 'warning'
    
    #check if the login is already used: if so throw an error unless it is from the same
    if login:
        user_rec = AdsUserRecord.query.filter((AdsUserRecord.alternate_usernames == login).or_(AdsUserRecord.username == login)).first()  #@UndefinedVariable
        if user_rec and (user_rec.cookie_id != current_user.get_id()) :
            return False, 'email address already taken by other user.', 'error'
        #check if the user already exists in classic and has another cookie
        if login_exists_classic(login):
            classic_user = get_classic_user(login)
            if classic_user.get('cookie') != current_user.get_id():
                app.logger.error('User tried to use change his login using one belonging to other user. User login: %s; other user login: %s ' % (current_user.get_username(), login))
                return False, 'email address already taken by other user.', 'error'
        
        #send the confirmation email
        #create an itsdangerous object to sign the verification email 
        itsd = URLSafeSerializer(config.ACCOUNT_VERIFICATION_SECRET)
        #send the confirmation email
        act_code = itsd.dumps('%s||%s' % (login, current_user.user_rec.username))
        message_html = """<h3>Please confirm your new email address</h3>
                            <p>Your activation code is <strong>%(code)s</strong></p>
                            <p>To activate your account, please click <a href="%(act_url)s">here</a></p>
                            <p>If the link doesn't work, please copy the following URL and paste it in your browser:<br/>%(act_url)s</p>
                            <p>Please do not replay to this email: to contact us please use our <a href="%(feedb_url)s">feedback form</a></p>
                            <p>Regards,<br/>The ADS team</p>
                        """ % {'code':act_code, 
                               'act_url': '%s%s?id=%s' % (config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('user.activate_new_email'), act_code),
                               'feedb_url' : '%s%s'%(config.MAIL_CONTENT_REDIRECT_BASE_URL, url_for('feedback.feedback'))
                               }
        try:
            send_email_to_user(u"NASA ADS: confirmation required for login update", message_html, [login])
        except:
            app.logger.error('Failed to send confirmation email for user settings modification.')
            return False, 'There are some technical problems: please try later.', 'error'
    
    #if name or lastname have changed, submit the changes to the classic ads and update the local database
    if name or lastname:
        loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.cookie_id == current_user.get_id())  #@UndefinedVariable
        user_rec = loc_db_user.first()
        if not user_rec:
            app.logger.error('logged in user doesn\'t have an entry in local mongo DB: %s' % login)
            return False, 'Error with account modification. Please try to logout and login again before trying again.', 'error'
        #make sure that if name or lastname are present, both are sent for the update
        if not name:
            name = user_rec.firstname
        if not lastname:
            lastname = user_rec.lastname
        
        try:
            classic_user = update_classic_user_info(current_user.user_rec.username, form.password.data, name, lastname)
        except TypeError:
            app.logger.error('ADS Classic account modification error: getting wrong json structure back. Tried to update name and lastname: %s' % login)
            return False, 'Problems in the account modification. Please try later.', 'error'
        if classic_user and classic_user.get('message') == 'ACCOUNT_UPDATED':
            update_params = {'firstname':name, 'lastname':lastname}
            loc_db_user.set(**update_params).execute()
        elif classic_user and classic_user.get('message') == 'WRONG_PASSWORD':
            app.logger.error('ADS Classic account modification error: wrong old password used. %s' % login)
            return False, 'The current password is wrong. Please try again.', 'error'
        else:
            app.logger.error('ADS Classic account modification error: return message not expected. %s' % login)
            return False, 'Problems in the account modification. Please try again.', 'error'
        
    if (name or lastname) and login:
        return True, 'Almost all the information have been updated. Please confirm your new email to update your username: a confirmation email has been sent to the new address.', 'warning'
    elif login and not (name or lastname):
        return True, 'You are almost done. Please confirm your new email to update your username: a confirmation email has been sent to the new address.', 'warning'
    elif (name or lastname) and not login:
        return True, 'All the changes have been applied.', 'success'
    #there should be no else
    else:
        app.logger.error('Account modification error. Case the app should never reach: %s' % login)
        return False, 'Error with account modification.', 'error'
Beispiel #8
0
def exp():
    if not current_user.is_authenticated():
        return render_template(
                'experiment.html',
                img=exper.ALL_IMGS[0],
                label=exper.LABELS_BY_CAT['1'][0],
                preview=True,
                score=0.)
    new = True if not current_user.is_debriefed() else None
    current_user.set_debriefed(True)
    user_id = current_user.get_username()
    if current_user.participant.current_session.img_index == IMG_PER_SESSION:
        return redirect(url_for('tree'))

    if current_user.get_break():
        current_user.finish_block()
        current_user.set_break(False)
        if TREE_ON_BLOCK:
            return redirect(url_for('tree'))
        part = current_user.participant
        if not QUIZ:
            return render_template('finish_block.html', quiz=False)
        best_session = current_user.get_best()
        score = part.current_session.correct
        block_count = len(part.current_session.blocks)
        best_blocks = sorted([b for b in best_session.blocks if b.finished_at], key=lambda b: b.finished_at)[:block_count+1]
        if not best_blocks:
            diffsign = 'equal'
            diff = 0
        else:
            diffbest = score - sum([b.correct for b in best_blocks])
            diff = abs(diffbest)
            diffsign = get_diffsign(diffbest)
        return render_template(
                'finish_block.html',
                quiz=True,
                diffsign=diffsign,
                diff=diff,
                )
    label, img, pair_index, block_index = current_user.get_current_pair()
    response = None
    if request.method == 'GET':
        correct = None
    elif request.method == 'POST':
        label = request.form.get('label')
        if QUIZ:
            input = request.form['res'] == '1'
            response = request.form['res']
            actual = exper.check_pair(label, img)
            correct = (input == actual)
            current_user.update_correct(correct)
            current_user.add_response(img, label, response)
        current_user.advance_pair()
    part = current_user.participant
    if part.current_session.img_index == 0:
        current_score = 0.
    else:
        current_score = float(part.current_session.correct) / part.current_session.img_index
    if QUIZ:
        return render_template(
            'experiment.html',
            quiz=True,
            label=label,
            img=img,
            correct=correct,
            res=response,
            pair_index=pair_index,
            block_size=BLOCKSIZE,
            block_index=block_index,
            block_count=BLOCKS,
            new=new,
            score=current_score)
    else:
        current_user.advance_pair()
        return render_template(
            'experiment.html',
            quiz=False,
            label=label,
            img=img,
            new=new,
            block_size=BLOCKSIZE,
            block_index=block_index,
            block_count=BLOCKS)
Beispiel #9
0
def user():
    username = current_user.get_username()
    new = True if not current_user.is_debriefed() else None
    return render_template('user.html', username=username, new=new)