Ejemplo n.º 1
0
def login():
    errors = {}
    FORM_ARGS = {
        'email': FORM_USER_VALID['email'],
        'password': FORM_USER_VALID['password'],
    }
    auth_token = None
    if request.method == 'POST':
        print("POST")
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            pprint(parsed_args)
            auth_token = app.action.user.user_get_auth_token(
                app_cls.service, parsed_args)
            #resp.set_cookie('auth_token', auth_token)
            print(f"--> auth_token {auth_token}")
            # FIXME: register auth_token cookie
            # FIXME: redirect
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
        except app.action.user.ErrWrongPassword as e:
            print("ERROR", "wrong password")
            errors = {"user": ["Wrong password or user does not exists."]}
        except app.action.user.ErrNotVerified as e:
            print("ERROR", "not verified")
            errors = {"user": ["User not verified, please check your email."]}
    resp = make_response(render_template('login.html', errors=errors))
    if auth_token:
        resp = make_response(redirect('/'))
        resp.set_cookie('auth_token', auth_token)
    return resp
Ejemplo n.º 2
0
 def current_user():
     try:
         print("[AUTH]")
         auth_token = request.cookies.get('auth_token')
         return app.action.user.user_instance_from_token(
             app_cls, auth_token)
     except:
         return None
Ejemplo n.º 3
0
def search():
    query = request.args.get('query')
    print("QUERY", query)

    from app.models import Tournament

    obj = Tournament.query
    obj = obj.filter(Tournament.title.like('%' + query + '%'))
    obj = obj.order_by(Tournament.title).all()

    return render_template('search.html', query=query, tournaments=obj)
Ejemplo n.º 4
0
    def test_user_created(self):
        user_1 = {
            "email": '*****@*****.**',
            "password": '******',
            "name": "Test 1"
        }

        user_2 = {
            "email": '*****@*****.**',
            "password": '******',
            "name": "Test 2"
        }

        app.action.user.user_create(self.service, user_1)
        app.action.user.user_create(self.service, user_2)

        v1 = 0
        print("")
        for user in User.query.all():
            print(f"---> {user} {user.date_created}")
            print(f"\t{user.password_hash}")
            print(f"\tverified={user.verified} token={user.recovery}")
            self.assertEqual(user.verified, False)
            v1 += 1

        self.assertEqual(v1, 2)
Ejemplo n.º 5
0
def signup():
    errors = {}
    successes = {}
    FORM_ARGS = {
        'name': FORM_USER_VALID['name'],
        'email': FORM_USER_VALID['email'],
        'password': FORM_USER_VALID['password'],
    }
    if request.method == 'POST':
        print("POST")
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            pprint(parsed_args)
            user = app.action.user.user_create(app_cls.service, parsed_args)
            url = send_message_verify(user.email, user.recovery)
            print(user.recovery)
            successes = {
                "user": [
                    f"We've sent you an email to {user.email} to verify your account. (debug: {url})"
                ]
            }
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
        except app.action.user.ErrDuplicate as e:
            print("ERROR", "duplicate")
            errors = {"user": ["This user already exists (with this email)."]}
    return render_template('signup.html', errors=errors, successes=successes)
Ejemplo n.º 6
0
def tournament_join(s, data, tournament, user):
    if tournament.ladder:
        print("LADDER!!!!")
        return False
    already_joined = (Tier.query.filter(Tier.user_id == user.id).filter(
        Tier.tournament_id == tournament.id).first())
    if already_joined is not None:
        raise ErrAlreadyJoined()

    tier = Tier(user_id=user.id,
                tournament_id=tournament.id,
                license=data['license'],
                rating=data['rating'])
    tournament.tiers.append(tier)
    s.db.session.commit()
Ejemplo n.º 7
0
def get_js_results(s, tournament):
    if tournament.get_ladder()['results'] is None:
        return str([])
    # print(tournament.get_ladder()['results'])
    results = []
    for layer in tournament.get_ladder()['results']:
        layer_results = []
        for match_id in layer:
            score = [None, None]
            print(match_id)
            match = (Match.query.filter(Match.match_id == match_id).filter(
                Match.tournament_id == tournament.id).first())
            # FIXME -----------------------------------------------------
            # jak to bedzie?????????????????????????????????????????????
            if match.results:
                score = list(map(int, match.results.split("@")))
            layer_results.append(score)
        results.append(layer_results)
    return str(results).replace("None", "null")
Ejemplo n.º 8
0
def tournament_close(idx):
    # FIXME: check if owner?

    from app.models import Tournament
    tournament = (Tournament.query.filter(Tournament.id == idx).first())

    auth_token = request.cookies.get('auth_token')
    user = app.action.user.user_instance_from_token(app_cls, auth_token)

    if user.id != tournament.owner_id:
        print("NOT OWNER!")
        return redirect(f'/tournament_display/{tournament.id}')

    app.action.tournament.tournament_close(app_cls.service,
                                           tournament,
                                           user,
                                           force=True)

    return redirect(f'/tournament_display/{tournament.id}')
Ejemplo n.º 9
0
    def test_user_auth_token(self):
        self.test_user_created()
        email = "*****@*****.**"

        with self.assertRaises(app.action.user.ErrWrongPassword):
            app.action.user.user_get_auth_token(self.service, {
                "email": email,
                "password": "******"
            })

        # FIXME: now you can't do this!
        auth_token = app.action.user.user_get_auth_token(
            self.service, {
                "email": email,
                "password": "******"
            })

        with self.assertRaises(app.action.user.ErrAuthNotExists):
            app.action.user.user_instance_from_token(self.service,
                                                     auth_token + "x")

        with self.assertRaises(app.action.user.ErrNotVerified):
            app.action.user.user_instance_from_token(self.service, auth_token)

        user = (User.query.filter(User.email == email).first())

        with self.assertRaises(app.action.user.ErrWrongRecovery):
            app.action.user.user_try_verify(self.service, {
                "email": email,
                "recovery": user.recovery + "123"
            })

        app.action.user.user_try_verify(self.service, {
            "email": email,
            "recovery": user.recovery
        })

        print(f"\nauth_token ----> {auth_token}")
        holder = app.action.user.user_instance_from_token(
            self.service, auth_token)
        self.assertEqual(holder.email, email)
Ejemplo n.º 10
0
    def _create_match(tournament_id, match_id, next_match_id, flag=0):
        print("======= MATCH ========")
        print(f"tournament_id = {tournament_id}")
        print(f"match_id = {match_id} --> {next_match_id}")
        print(f"flag = {flag}")
        match = Match(
            match_id=match_id,
            tournament_id=tournament_id,
            next_match_id=next_match_id,
            flag=flag,
        )
        """
        user_id_1 = db.Column(db.Integer, db.ForeignKey('user.id'))
        user_id_2 = db.Column(db.Integer, db.ForeignKey('user.id'))

        results = db.Column(db.Text)
        results_by_user_id_1 = db.Column(db.Text)
        results_by_user_id_2 = db.Column(db.Text)
        """
        print("======================")
        return match
Ejemplo n.º 11
0
def forget_code(code):
    errors = {}
    successes = {}
    args = base64.b64decode(code.encode('utf-8')).decode('utf-8')
    email, recovery = args.split("/")
    print(f"|{email}|, |{recovery}|")
    FORM_ARGS = {
        'password': FORM_USER_VALID['password'],
    }
    if request.method == 'POST':
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            pprint(parsed_args)
            app.action.user.user_try_forget(
                app_cls.service, {
                    "email": email,
                    "recovery": recovery,
                    "password": parsed_args["password"]
                })
            successes = {"user": [f"Account for {email} is now active."]}
        except app.action.user.ErrWrongRecovery as e:
            print("ERROR", "wrong recovery")
            errors = {"user": [f"Wrong recovery code for {email}."]}
        except app.action.user.ErrTimeout as e:
            print("ERROR", "timeout")
            errors = {"user": [f"Timeout (more than 24h) for {email}."]}
    return render_template('forget_code.html',
                           email=email,
                           errors=errors,
                           successes=successes)
Ejemplo n.º 12
0
def forget():
    errors = {}
    successes = {}
    FORM_ARGS = {
        'email': FORM_USER_VALID['email'],
    }
    if request.method == 'POST':
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            pprint(parsed_args)
            user = app.action.user.user_new_recovery(app_cls.service,
                                                     parsed_args)
            url = send_message_forget(user.email, user.recovery)
            successes = {
                "user": [
                    f"We've sent you an email to {user.email} to recover your account. (debug: {url})"
                ]
            }
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
        except Exception as e:
            print("HACKER/DDOS?", e)
    return render_template('forget.html', errors=errors, successes=successes)
Ejemplo n.º 13
0
def tournament_unjoin(s, tournament, user):
    if tournament.ladder:
        print("LADDER!!!!")
        return False
    already_joined = (Tier.query.filter(Tier.user_id == user.id).filter(
        Tier.tournament_id == tournament.id).delete())
    if already_joined is not None:
        print("UNJOINED!")
        s.db.session.commit()
    else:
        print("NO NEED")
Ejemplo n.º 14
0
def tournament_edit(idx):
    errors = {}
    successes = {}
    FORM_ARGS = {
        'title': FORM_TOURNAMENT_VALID['title'],
        'max_users': FORM_TOURNAMENT_VALID['max_users'],
        'location': FORM_TOURNAMENT_VALID['location'],
        'readme': FORM_TOURNAMENT_VALID['readme'],
        'date_start': FORM_TOURNAMENT_VALID['date_start'],
        'date_deadline': FORM_TOURNAMENT_VALID['date_deadline'],
    }
    from app.models import Tournament
    tournament = (Tournament.query.filter(Tournament.id == idx).first())
    parsed_args = tournament.__dict__
    # check if author is editing
    auth_token = request.cookies.get('auth_token')
    user = app.action.user.user_instance_from_token(app_cls, auth_token)
    if user.id != tournament.owner_id:
        return redirect(f"/tournament_display/{idx}")
    # if posted -> edit
    if request.method == 'POST':
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            parsed_args['user'] = user
            pprint(parsed_args)
            cur_date = datetime.datetime.utcnow()
            if parsed_args['date_deadline'] > parsed_args['date_start']:
                raise ErrFormDate
            if parsed_args['date_deadline'] < cur_date:
                raise ErrFormDate
            tournament = app.action.tournament.tournament_edit(
                app_cls.service, parsed_args, tournament)
            successes = {"tournament": [f"The event was edited."]}
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
        except app.action.tournament.ErrDuplicate as e:
            print("ERROR", "duplicate")
            errors = {
                "tournament": ["This event already exists (with this title)."]
            }
        except ErrFormDate as e:
            print("ERROR", "date")
            errors = {
                "tournament": [
                    "Wrong datetime span (should be: current <= deadline <= start)."
                ]
            }
    return render_template('tournament_edit.html',
                           tournament=tournament,
                           errors=errors,
                           successes=successes,
                           parsed_args=parsed_args)
Ejemplo n.º 15
0
def tournament_new():
    errors = {}
    successes = {}
    FORM_ARGS = {
        'title': FORM_TOURNAMENT_VALID['title'],
        'max_users': FORM_TOURNAMENT_VALID['max_users'],
        'location': FORM_TOURNAMENT_VALID['location'],
        'readme': FORM_TOURNAMENT_VALID['readme'],
        'date_start': FORM_TOURNAMENT_VALID['date_start'],
        'date_deadline': FORM_TOURNAMENT_VALID['date_deadline'],
    }
    parsed_args = request.form.to_dict(flat=True)
    # print(request.form.to_dict(flat=True))
    if request.method == 'POST':
        try:
            auth_token = request.cookies.get('auth_token')
            user = app.action.user.user_instance_from_token(
                app_cls, auth_token)
            parsed_args = parser.parse(FORM_ARGS, location="form")
            parsed_args['user'] = user
            pprint(parsed_args)
            cur_date = datetime.datetime.utcnow()
            if parsed_args['date_deadline'] > parsed_args['date_start']:
                raise ErrFormDate
            if parsed_args['date_deadline'] < cur_date:
                raise ErrFormDate
            tournament = app.action.tournament.tournament_create(
                app_cls.service, parsed_args)
            successes = {"tournament": [f"The event was created."]}
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
        except app.action.tournament.ErrDuplicate as e:
            print("ERROR", "duplicate")
            errors = {
                "tournament": ["This event already exists (with this title)."]
            }
        except ErrFormDate as e:
            print("ERROR", "date")
            errors = {
                "tournament": [
                    "Wrong datetime span (should be: current <= deadline <= start)."
                ]
            }
    return render_template('tournament_new.html',
                           errors=errors,
                           successes=successes,
                           parsed_args=parsed_args)
Ejemplo n.º 16
0
def verify(code):
    errors = {}
    successes = {}
    args = base64.b64decode(code.encode('utf-8')).decode('utf-8')
    email, recovery = args.split("/")
    print(f"|{email}|, |{recovery}|")
    try:
        app.action.user.user_try_verify(app_cls.service, {
            "email": email,
            "recovery": recovery
        })
        successes = {"user": [f"Account for {email} is now active."]}
    except app.action.user.ErrWrongRecovery as e:
        print("ERROR", "wrong recovery")
        errors = {"user": [f"Wrong recovery code for {email}."]}
    except app.action.user.ErrTimeout as e:
        print("ERROR", "timeout")
        errors = {"user": [f"Timeout (more than 24h) for {email}."]}
    return render_template('verify.html', errors=errors, successes=successes)
Ejemplo n.º 17
0
def tournament_join(idx):
    errors = {}
    successes = {}
    parsed_args = {}
    FORM_ARGS = {
        'license': FORM_TOURNAMENT_VALID['license'],
        'rating': FORM_TOURNAMENT_VALID['rating'],
    }
    from app.models import Tournament
    tournament = (Tournament.query.filter(Tournament.id == idx).first())

    auth_token = request.cookies.get('auth_token')
    user = app.action.user.user_instance_from_token(app_cls, auth_token)

    if request.method == 'POST':
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            parsed_args['user'] = user
            pprint(parsed_args)
            cur_date = datetime.datetime.utcnow()
            if tournament.date_deadline < cur_date:
                raise ErrFormDate
            app.action.tournament.tournament_join(app_cls.service, parsed_args,
                                                  tournament, user)
            successes = {"tournament": [f"User joined the list."]}
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
        except ErrFormDate as e:
            print("ERROR", "date")
            errors = {"tournament": ["Deadline passed."]}
        except app.action.tournament.ErrAlreadyJoined as e:
            print("ERROR", "already")
            errors = {"tournament": ["User already on the list."]}
    return render_template('tournament_join.html',
                           tournament=tournament,
                           errors=errors,
                           successes=successes,
                           parsed_args=parsed_args)
Ejemplo n.º 18
0
def tournament_create(s, data):
    try:
        user = data['user']
        print(user)
        print(s)
        tournament = Tournament(
            title=data['title'],
            date_start=data['date_start'],
            date_deadline=data['date_deadline'],
            location=data['location'],
            max_users=data['max_users'],
            readme=data['readme'],
            owner_id=user.id,
        )

        s.db.session.add(tournament)
        s.db.session.commit()
    except Exception as e:
        print(str(e))
        if "UNIQUE constraint failed" in str(e):
            raise ErrDuplicate()
        raise ErrFatal()
    return tournament
Ejemplo n.º 19
0
print("[TOURNAMENT]")

import math
import random
import datetime
from app.models import Tournament, Tier, Match
from pprint import pprint
from app.log import print


class ErrFatal(Exception):
    pass


class ErrDuplicate(Exception):
    pass


class ErrAlreadyJoined(Exception):
    pass


# FIXME: remove user from data['user']
def tournament_create(s, data):
    try:
        user = data['user']
        print(user)
        print(s)
        tournament = Tournament(
            title=data['title'],
Ejemplo n.º 20
0
def tournament_close(s, tournament, user, force=False):
    if force is False and tournament.ladder is not None:
        return False

    tiers = tournament.tiers.limit(tournament.max_users).all()

    # FIXME: order users by rating

    def compare(x, y):
        return x.rating - y.rating

    from functools import cmp_to_key
    tiers = sorted(tiers, key=cmp_to_key(compare), reverse=True)

    teams = []
    results = []

    max_users = tournament.max_users
    if max_users <= 1:
        tree_n = 2**1
    else:
        try:
            tree_n = 2**math.ceil(math.log2(len(tiers)))
        except:
            tree_n = 2**1

    print("---------->", tiers)
    print("!" * 100)

    tiers_n = len(tiers)
    for i in range(0, tree_n, 2):
        print(f"PAIR ---> {i}")
        tier_1 = None
        tier_2 = None
        if i < tiers_n:
            tier_1 = tiers[i].user_id
        if i + 1 < tiers_n:
            tier_2 = tiers[i + 1].user_id
        print(f"tier 1 -> {tier_1}")
        print(f"tier 2 -> {tier_2}")
        print()

        teams.append([tier_1, tier_2])

    pprint(teams)

    store_matches = []

    def _create_match(tournament_id, match_id, next_match_id, flag=0):
        print("======= MATCH ========")
        print(f"tournament_id = {tournament_id}")
        print(f"match_id = {match_id} --> {next_match_id}")
        print(f"flag = {flag}")
        match = Match(
            match_id=match_id,
            tournament_id=tournament_id,
            next_match_id=next_match_id,
            flag=flag,
        )
        """
        user_id_1 = db.Column(db.Integer, db.ForeignKey('user.id'))
        user_id_2 = db.Column(db.Integer, db.ForeignKey('user.id'))

        results = db.Column(db.Text)
        results_by_user_id_1 = db.Column(db.Text)
        results_by_user_id_2 = db.Column(db.Text)
        """
        print("======================")
        return match

    match_id = 1
    matches_n_cul = 0
    for level in range(int(math.log2(tree_n))):
        matches = []
        matches_n = int((tree_n / 2) / (2**level))
        print(f"\033[91m===== {level} | {matches_n} =====\033[0m")
        for j in range(matches_n):
            matches.append(match_id)
            if match_id % 2 == 1:
                next_match_id = ((match_id - matches_n_cul + 1) // 2) \
                        + matches_n_cul + matches_n
            else:
                next_match_id = ((match_id - matches_n_cul + 0) // 2) \
                        + matches_n_cul + matches_n
            # print(f">>> {match_id} --> {next_match_id}")
            match = _create_match(tournament.id,
                                  match_id,
                                  next_match_id,
                                  flag=int(matches_n == 1))
            if level == 0:
                print("ASSIGN", j, teams[j])
                match.user_id_1 = teams[j][0]
                match.user_id_2 = teams[j][1]
            store_matches.append(match)
            match_id += 1
        if matches_n == 1:
            print("3MATCH")
            matches.append(match_id)
            match = _create_match(tournament.id, match_id, None, flag=2)
            store_matches.append(match)
            match_id += 1
        results.append(matches)
        matches_n_cul += matches_n

    pprint(results)

    import json
    print("------------")
    ladder_txt = json.dumps({"teams": teams, "results": results})
    pprint(ladder_txt)
    print("------------")

    tournament.date_deadline = datetime.datetime.utcnow()
    tournament.date_start = datetime.datetime.utcnow()
    tournament.ladder = ladder_txt
    tournament.matches = []
    for match in store_matches:
        tournament.matches.append(match)

    # XXX: find wildcards
    cached_ids = []
    while 1:
        push_i = 0
        for match in store_matches:
            push_user = None

            if (match.user_id_2 is None and match.user_id_1 is not None
                    and match.id not in cached_ids):
                push_user = match.user_id_1
                cached_ids.append(match.id)
            if (match.user_id_1 is None and match.user_id_2 is not None
                    and match.id not in cached_ids):
                push_user = match.user_id_2
                cached_ids.append(match.id)

            if push_user and match.next_match_id:
                match_next = (Match.query.filter(
                    Match.tournament_id == match.tournament_id).filter(
                        Match.match_id == match.next_match_id).first())
                if match.match_id % 2 == 1:
                    match_next.user_id_1 = push_user
                else:
                    match_next.user_id_2 = push_user
                push_i = 1
                print(f"{match} ==============================> PUSH")
        s.db.session.commit()
        print()
        if push_i == 0:
            break

    s.db.session.commit()
Ejemplo n.º 21
0
def match_new(idx):
    from app.models import Match, User
    match = (Match.query.filter(Match.id == idx).first())

    from app.models import Tournament
    tournament = (Tournament.query.filter(
        Tournament.id == match.tournament_id).first())

    auth_token = request.cookies.get('auth_token')
    user = app.action.user.user_instance_from_token(app_cls, auth_token)
    ####################################################################

    errors = {}
    successes = {}
    FORM_ARGS = {
        'score_1': FORM_TOURNAMENT_VALID['score_1'],
        'score_2': FORM_TOURNAMENT_VALID['score_2'],
    }
    parsed_args = {}
    user_1 = None
    user_2 = None
    if match.user_id_1:
        _user = (User.query.filter(User.id == match.user_id_1).first())
        user_1 = _user
    if match.user_id_2:
        _user = (User.query.filter(User.id == match.user_id_2).first())
        user_2 = _user
    if user.id not in [match.user_id_1, match.user_id_2]:
        return redirect(f'/tournament_display/{tournament.id}')

    #####
    # fixme unpack score for user!
    results_by_user = None
    if user.id is match.user_id_1:
        results_by_user = match.results_by_user_id_1
    if user.id is match.user_id_2:
        results_by_user = match.results_by_user_id_2
    if results_by_user:
        parsed_args['score_1'], parsed_args['score_2'] = map(
            int, results_by_user.split("@"))

    if request.method == 'POST':
        try:
            parsed_args = parser.parse(FORM_ARGS, location="form")
            pprint(parsed_args)
            results_by_user = str(parsed_args['score_1']) + "@" + str(
                parsed_args['score_2'])
            ###########################################
            if user.id is match.user_id_1:
                match.results_by_user_id_1 = results_by_user
            if user.id is match.user_id_2:
                match.results_by_user_id_2 = results_by_user
            if match.results_by_user_id_1 == match.results_by_user_id_2:
                match.results = match.results_by_user_id_1
                # FIXME: set winner WHO IS
                winner_id = None
                loser_id = None
                if parsed_args['score_1'] > parsed_args['score_2']:
                    winner_id = match.user_id_1
                    loser_id = match.user_id_2
                else:
                    winner_id = match.user_id_2
                    loser_id = match.user_id_1
                if match.next_match_id:
                    match_next = (Match.query.filter(
                        Match.tournament_id == match.tournament_id).filter(
                            Match.match_id == match.next_match_id).first())
                    if match.match_id % 2 == 1:
                        match_next.user_id_1 = winner_id
                    else:
                        match_next.user_id_2 = winner_id
                    if match_next.flag == 1:  # FIXME: for 3th place
                        match_next_losers = \
                        (Match.query.filter(Match.tournament_id ==
                            match.tournament_id).filter(Match.match_id ==
                                match_next.next_match_id).first())
                        if match.match_id % 2 == 1:
                            match_next_losers.user_id_1 = loser_id
                        else:
                            match_next_losers.user_id_2 = loser_id

            app_cls.service.db.session.commit()
            ###########################################
            successes = {"match": [f"The score was recorded."]}
        except DataError as e:
            errors = e.args[0]['form']
            print("ERROR", errors)
    """
    results = db.Column(db.Text)
    results_by_user_id_1 = db.Column(db.Text)
    results_by_user_id_2 = db.Column(db.Text)

    #return redirect(f'/tournament_display/{tournament.id}')
    """

    return render_template('match_new.html',
                           match=match,
                           tournament=tournament,
                           user_1=user_1,
                           user_2=user_2,
                           errors=errors,
                           successes=successes,
                           parsed_args=parsed_args)