Exemple #1
0
def user_login(request):
    """
    Authenticates a user
    Accepts:
        "email": <string>
        "password": <string>
    Returns:
        "token": if the credentials are valid; this key has to be used in HTTP headers for accessing
               any of the backend APIs
        "email": email of the authenticated user
        "first_name": <string>
        "last_name": <string>
        or
        "error": <string> Exception msg string
    Example POST payload:
    {
        "email": "*****@*****.**",
        "password": "******"
    }
    """
    if request.method == 'POST':
        start_time = time.time()
        if set(['email', 'password']) != set(request.data.keys()):
            return Response({'error': "invalid params"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = Users.objects.filter(email__iexact=request.data['email'])
        except Exception as ex:
            logger.debug("user_login: %s", str(ex))
        if user:
            # since user_signup ensures that there will always be one user, let's pluck the first
            user = user.first()
            if decrypt(user.password) == str(request.data['password']):
                old_session = Sessions.objects.filter(user_id__exact=user.id)
                if old_session:
                    old_session.update(last_used=datetime.now())
                    old_session = old_session.first()
                    logger.debug("user_login: elapsed time: %s" % (time.time() - start_time))
                    return Response({'token': old_session.key,
                                     'email': user.email,
                                     'first_name': user.first_name,
                                     'last_name': user.last_name}, status=status.HTTP_200_OK)
                else:
                    new_session = Sessions(user=user, last_used=datetime.now(), key=sha1hash(request.data['email'] +
                                                                                             request.data['password'] +
                                                                                             SECRET))
                    new_session.save()
                    logger.debug("user_login: elapsed time: %s" % (time.time() - start_time))
                    return Response({'token': new_session.key,
                                     'email': user.email,
                                     'first_name': user.first_name,
                                     'last_name': user.last_name}, status=status.HTTP_200_OK)
            else:
                logger.debug("user_login: invalid password for %s", request.data['email'])
                return Response({'error': 'invalid password'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            logger.debug("user_login: invalid email %s", request.data['email'])
            return Response({'error': 'invalid email'}, status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
def sessions_cleaner():
    """Sessions expiration maintainer"""
    timestamp = int(time.time())
    print "cleanning sessions... " + str(timestamp)
    def _callback(result, error):
        if result and result['n'] > 0:
            print "%i sessions cleaned up!" % result['n']
    sessions = Sessions()
    sessions.remove(({'__expires': {'$lt': timestamp}}),
                    callback=_callback)
Exemple #3
0
def sessions_cleaner():
    """Sessions expiration maintainer"""
    timestamp = int(time.time())
    logging.debug("cleanning sessions... %i", timestamp)

    def _callback(result, error):
        if result and result['n'] > 0:
            logging.debug("%i sessions cleaned up!", result['n'])
    sessions = Sessions()
    sessions.remove(({'__expires': {'$lt': timestamp}}),
                    callback=_callback)
Exemple #4
0
def create_wordsearch():
	if not all(param in request.json for param in ('user_id', 'r_id', 'app', 'session_date', 'attempt' , 'version', 'level', 'rows', 'words', 'latency_average', 'longest_word', 'longest_pause', 'events' )):
		return jsonify({'errors': {"missing_fields": "please supply all required fields"}}), 400
	
	attempt = request.json.get('attempt')
	r_id = request.json.get('r_id')
	app = request.json.get('app')
	user_id = request.json.get('user_id')
	session_date = request.json.get('session_date')

	if attempt == 1:
		w_sess = Sessions(app = app, r_id = r_id, user_id = user_id, session_date = session_date)
		db.session.add(w_sess)
		db.session.commit()
		db.session.refresh(w_sess)
		s_id = w_sess.session_id
	else:
		s_id = db.session.query(func.max(Sessions.session_id)).filter_by(r_id = r_id, user_id = user_id, app = app).first()[0]
	elist = json.dumps(request.json.get('events'))
	wordsearch_session = Wordsearch_Sessions(session_id = s_id, attempt_number = attempt,
		level = request.json.get('level'),
		version = request.json.get('version'),
		rows = request.json.get('rows'),
		words = request.json.get('words'),
		latency_average = request.json.get('latency_average'),
		longest_word = request.json.get('longest_word'),
		longest_pause = request.json.get('longest_pause'),
		events = elist)
	db.session.add(wordsearch_session)
	db.session.commit()

	status_code = 201
	return jsonify({'session_created': "successfully created wordsearch session"}) , 201
Exemple #5
0
def create_mahjong():
	stats = request.get_json(force = True)

	if not all(param in stats for param in ('gameNumber','package','layout','selections',
    'deselections','correctMatches','incorrectMatches','hintsEnabled','hintsUsed','timesShuffled','completion','startGameTime','endGameTime' )):
		return jsonify({'errors': {"missing_fields": "please supply all required fields"}}), 400

	if stats.get('gameNumber') == 1:
		m_sess = Sessions(app = 'Mahjong', r_id = stats.get('researcher'), user_id = stats.get('user'), session_date = datetime.datetime.today().strftime('%Y-%m-%d'))
		db.session.add(m_sess)
		db.session.commit()
		db.session.refresh(m_sess)
		s_id = m_sess.session_id
	else:
		s_id = db.session.query(func.max(Sessions.session_id)).filter_by(r_id = stats.get('researcher'), user_id = stats.get('user'), app = 'Mahjong').first()[0]

	mahjong_session = Mahjong_Games(session_id = s_id, 
										game_num = stats.get('gameNumber'),
										package = stats.get('package'),
										layout = stats.get('layout'),
										selections = stats.get('selections'),
										deselections = stats.get('deselections'),
										correct_matches = stats.get('correctMatches'),
										incorrect_matches = stats.get('incorrectMatches'),
										hints_enabled = stats.get('hintsEnabled'),
										hints = stats.get('hintsUsed'),
										shuffles = stats.get('timesShuffled'),
										time_taken = stats.get('startGameTime') - stats.get('endGameTime'),
										completion = stats.get('completion')
										)
	db.session.add(mahjong_session)
	db.session.commit()

	return jsonify({'session_created': "successfully created mahjong session"}) , 201
Exemple #6
0
def create_bejeweled():
	if not all(param in request.json for param in ('user_id', 'r_id', 'app', 'session_date', 'attempt', 'level', 'target_score', 'tile_types', 'score_total', 'score_zone', 'latency_average', 'events' )):
		return jsonify({'errors': {"missing_fields": "please supply all required fields"}}), 400
	
	attempt = request.json.get('attempt')
	r_id = request.json.get('r_id')
	app = request.json.get('app')
	user_id = request.json.get('user_id')
	session_date = request.json.get('session_date')

	if attempt == 1:
		b_sess = Sessions(app = app, r_id = r_id, user_id = user_id, session_date = session_date)
		db.session.add(b_sess)
		db.session.commit()
		db.session.refresh(b_sess)
		s_id = b_sess.session_id
	else:
		s_id = db.session.query(func.max(Sessions.session_id)).filter_by(r_id = r_id, user_id = user_id, app = app).first()[0]

	elist = json.dumps(request.json.get('events'))
	bejeweled_session = Bejeweled_Sessions(session_id = s_id, attempt_number = attempt,
		level = request.json.get('level'),
		target_score = request.json.get('target_score'),
		tile_types = request.json.get('tile_types'),
		score_total = request.json.get('score_total'),
		score_zone = request.json.get('score_zone'),
		latency_average = request.json.get('latency_average'),
		events = elist)
	db.session.add(bejeweled_session)
	db.session.commit()

	return jsonify({'session_created': "successfully created bejeweled session"}) , 201
Exemple #7
0
def create_session_for_user(account_id: str) -> str:
    """
    Creates session for the given user
    :param account_id:
    :return: newly created session_id
    """
    session_id = uuid.uuid4().hex
    new_session = Sessions(account_id=account_id,
                           session_id=session_id,
                           created_at=datetime.datetime.now())
    with session_scope() as session:
        session.add(new_session)
    return session_id
Exemple #8
0
def create_mole():
	if not all(param in request.json for param in ('r_id', 'user_id', 'app', 'session_date', 'target_visibility', 'target_latency', 'attempt_duration', 'level_progression', 'hit_sound', 'hit_vibration', 'avg_reaction_time', 'reaction_time_sd', 'avg_reaction_times_by_attempt', 'reaction_time_sds_by_attempt', 'moles_hit_by_attempt', 'moles_missed_by_attempt', 'bunnies_hit_by_attempt', 'bunnies_missed_by_attempt', 'events')):
		return jsonify({'errors': {"missing_fields": "please supply all required fields"}}), 400

	m_sess = Sessions(app = request.json.get('app'), r_id = request.json.get('r_id'), user_id = request.json.get('user_id'), session_date = request.json.get('session_date'))
	db.session.add(m_sess)
	db.session.commit()
	db.session.refresh(m_sess)
	s_id = m_sess.session_id

	elist = json.dumps(request.json.get('events'))
	avg_reaction_attempt = json.dumps(request.json.get('avg_reaction_times_by_attempt'))
	sds_attempt = json.dumps(request.json.get('reaction_time_sds_by_attempt'))
	moles_hit_attempt = json.dumps(request.json.get('moles_hit_by_attempt'))
	moles_missed_attempt = json.dumps(request.json.get('moles_missed_by_attempt'))
	bunnies_hit_attempt = json.dumps(request.json.get('bunnies_hit_by_attempt'))
	bunnies_missed_attempt = json.dumps(request.json.get('bunnies_missed_by_attempt'))

	mole_session = Mole_Sessions(session_id = s_id,
		target_visibility = request.json.get('target_visibility'),
		target_latency = request.json.get('target_latency'),
		attempt_duration = request.json.get('attempt_duration'),
		level_progression = request.json.get('level_progression'),
		hit_sound = request.json.get('hit_sound'),
		hit_vibration = request.json.get('hit_vibration'),
		avg_reaction_time = request.json.get('avg_reaction_time'),
		reaction_time_sd = request.json.get('reaction_time_sd'),
		avg_reaction_time_by_attempt = avg_reaction_attempt,
		reaction_time_sds_by_attempt = sds_attempt,
		moles_hit_by_attempt = moles_hit_attempt,
		moles_missed_by_attempt = moles_missed_attempt,
		bunnies_hit_by_attempt = bunnies_hit_attempt,
		bunnies_missed_by_attempt = bunnies_missed_attempt,
		events = elist)
	db.session.add(mole_session)
	db.session.commit()

	return jsonify({'session_created': "successfully created mole session"}) , 201
Exemple #9
0
def addNewVisit(request):
    visit = Visits()
    visit.ip = request.META['REMOTE_ADDR']
    visit.url = request.path
    visit.datetime = timezone.now()
    ua = user_agents.parse(request.META['HTTP_USER_AGENT'])
    visit.browser_name = ua.browser.family
    visit.browser_version = ua.browser.version_string
    if Visits.objects.filter(ip__exact=request.META['REMOTE_ADDR']).exists():
        lastVisit = Visits.objects.filter(ip__exact=request.META['REMOTE_ADDR']).order_by('-datetime')[:1][0] 
        if timezone.now() - timedelta(minutes=5) > lastVisit.datetime:
            session = Sessions(ip=request.META['REMOTE_ADDR'], datetime=datetime.now())
            session.save()
        else:
            session = lastVisit.session
    else:
        session = Sessions(ip=request.META['REMOTE_ADDR'], datetime=datetime.now())
        session.save()
    visit.session = session
    visit.save()
Exemple #10
0
def choose(request):
    if request.method == "POST":

        adds = request.POST.getlist("add_lis[]")
        excludes = request.POST.getlist("exclude_lis[]")
        nones = request.POST.getlist("none_lis[]")
        add_rsv = [float(i) for i in request.POST.getlist("add_lis_rsv[]")]
        exclude_rsv = [float(i) for i in request.POST.getlist("exclude_lis_rsv[]")]


        refuse_excluded = 0
        refuse_added = 0
        confirm_excluded = 0
        confirm_added = 0



        for add in add_rsv:
            if add < rsv_threshold:
                refuse_excluded += 1
            else:
                confirm_added += 1

        for exclude in exclude_rsv:
            if exclude > rsv_threshold:
                refuse_added += 1
            else:
                confirm_excluded += 1

        print confirm_added, confirm_excluded, refuse_added, refuse_excluded
        se = Sessions(confirm_added= confirm_added, confirm_excluded=confirm_excluded,
                      refuse_added=refuse_added, refuse_excluded=refuse_excluded)
        se.save()


        train = []
        for el in adds:
            print el
            tq = TestQueries.objects.get(id=int(el))

            train.append([tq.query, "Added", 0])
            tq.delete()

        for el in excludes:
            tq = TestQueries.objects.get(id=int(el))
            train.append([tq.query, "Excluded", 0])
            tq.delete()


        extract_data(train)

        for el in nones:
            tq = TestQueries.objects.get(id=int(el))
            tq.processed = True
            tq.save()

        for line in train:
            t = TrainQueries(
                query = line[0],
                relevant = is_relevant(line)
            )
            t.save()


        suggested_adds = TestQueries.objects.filter(processed=False).order_by("-rsv")[:10]

        suggested_excludes = TestQueries.objects.filter(processed=False).order_by("rsv")[:10]


        for sa in suggested_adds:
            sa.query = sa.query.split()

        for se in suggested_excludes:
            se.query = se.query.split()

        return render_to_response('partial.html', {"suggested_adds":suggested_adds,"suggested_excludes":suggested_excludes})


    suggested_adds = TestQueries.objects.filter(processed=False).order_by("-rsv")[:10]
    suggested_excludes = TestQueries.objects.filter(processed=False).order_by("rsv")[:10]
    for sa in suggested_adds:
        sa.query = sa.query.split()

    for se in suggested_excludes:
        se.query = se.query.split()

    return render_to_response('connect-lists.html',
                                      {"suggested_adds":suggested_adds,"suggested_excludes":suggested_excludes})
Exemple #11
0
def vote():
    if request.method == 'PATCH':
        up = bool(request.form.get('up_vote'))
        down = bool(request.form.get('down_vote'))
        movie_id = request.form.get('movie_id')
        movie = Movie.query.filter_by(movie_id=movie_id).all()

        print(request.cookies.get('id'))

        if request.cookies.get('id') is None:
            res = make_response('')
            res.set_cookie('id', str(uuid.uuid1()))

        if len(
                Sessions.query.filter(
                    Sessions.user_id == request.cookies.get('id'),
                    Sessions.movie_id == movie_id).all()) == 0:
            print("this ran")
            sess = Sessions(user_id=request.cookies.get('id'),
                            movie_id=movie_id)
            db.session.add(sess)
            db.session.commit()

        sess_query = Sessions.query.filter(
            Sessions.user_id == request.cookies.get('id'),
            Sessions.movie_id == movie_id).all()[0]

        if up is True:
            if sess_query.vote is 0:
                sess_query.vote = 1  # 1 is thumbs up
                movie[0].up_vote += 1
            elif sess_query.vote is 2:
                movie[0].down_vote -= 1
                sess_query.vote = 1  # 1 is thumbs up
                movie[0].up_vote += 1
            else:
                sess_query.vote = 0
                movie[0].up_vote -= 1
        if down is True:
            if sess_query.vote is 0:
                sess_query.vote = 2  # 2 is thumbs up
                movie[0].down_vote += 1
            elif sess_query.vote is 1:
                movie[0].up_vote -= 1
                sess_query.vote = 2  # 2 is thumbs up
                movie[0].down_vote += 1
            else:
                sess_query.vote = 0
                movie[0].down_vote -= 1

        db.session.commit()

        if movie[0].up_vote or movie[0].down_vote:
            movie[0].rating = (movie[0].up_vote /
                               (movie[0].up_vote + movie[0].down_vote)) * 100
        else:
            movie[0].rating = 0
        db.session.commit()

        movies_schema = MovieSchema(many=True)
        results = movies_schema.dump(movie)
        return jsonify(results)

    return jsonify({"connection": "failure"})