def wrapper(): user = get_user(request) allowed_status = ['admin', 'sadmin'] if user.status not in allowed_status: print("ERROR: unauthorized access of resource attempted") return jsonify(status='fail', message='unauthorized', authorized=False) if user is None: return jsonify(status='fail', message='user does not exist') if not isinstance(user, User): # user is a jsonified error return user session = get_db_session() if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='unauthorized') func()
def get_confirmation_page(conf_guid): rand = None if app.debug != False: rand = random.random() template_name = 'confirmation.html' if utils.is_on_mobile(request.headers.get('User-Agent')): template_name = 'mobile/confirmation.mobile.html' session = get_db_session() user = session.query(User).filter_by(confirmation_guid=conf_guid).first() if user is None: return render_template(template_name, random=rand, back_url='/', message="No user exists") if user.confirmed != 0: return render_template( template_name, random=rand, back_url='/', message="This confirmation code has already been used") return render_template(template_name, random=rand, back_url='/', message=None, confirmation_guid=conf_guid)
def post_league(): user = utils.get_user(request) allowed_status = ['admin', 'sadmin'] if user.status not in allowed_status: print("ERROR: unauthorized access of resource attempted") return jsonify(status='fail', message='unauthorized', authorized=False) data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) if data is None: return jsonify(status='fail', message='message body was blank') name = data['name'] if name is None or name == "": return jsonify(status='fail', message='name cannot be blank') description = data['description'] location = data['location'] founded = data['founded'] session = get_db_session() league = League(name) if description is not None and description != "": league.description = description if location is not None and location != "": league.location = location if founded is not None and founded != "": dt_founded = datetime.datetime.strptime(founded, '%Y-%m-%d') print(dt_founded) league.founded = dt_founded session.add(league) session.commit() return jsonify(status='ok')
def update_password(): data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) email = data.get('email') if email is None: return jsonify(status='fail', message='Please provide an email address') reset_code = data.get('reset_code') if reset_code is None: return jsonify(status='fail', message='Unknown Error') password = data.get('password') if password is None or password == "": return jsonify(status='fail', message='Please provide an password address') session = get_db_session() user = session.query(User).filter_by(email=email).first() if user.confirmation_guid != reset_code: print(reset_code) print(user.confirmation_guid) return jsonify(status='fail', message='Incorrect email and reset code combination') # Check reset code against email user.password = bcrypt.hashpw(password.encode(), user.salt.encode()).decode() session.add(user) session.commit() return jsonify(status='ok')
def create_user(): data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) email = data.get('email').lower() if email == "": email = None phone_number = data.get('phone') if phone_number == "": phone_number = None name = data.get('firstname') surname = data.get('lastname') password = data.get('password') if (email is None or email == "") and (phone_number is None or phone_number == ""): return jsonify(status='fail', message='Email or phone number required') if len(email) > 200: return jsonify( stauts='fail', message='Email is too long (please use less than 200 characters)') if name is None or name == "": return jsonify(status='fail', message='Name cannot be blank') if password is None: return jsonify(status='fail', message='Password cannot be blank') if len(name) > 50: return jsonify(status='fail', message='Name cannot be longer than 50 characters') session = get_db_session() user = session.query(User).filter_by(email=email).first() if user is not None: return jsonify(status='fail', message='User already exists') user = session.query(User).filter_by(phone_number=phone_number).first() if user is not None: return jsonify(status='fail', message='User already exists') user = User(name, surname, phone_number, email) # def __init__(self, first_name, last_name, phone_number=None, email=None, password=None, salt=None): user.status = 'user' user.confirmed = 1 user.salt = bcrypt.gensalt().decode() user.password = bcrypt.hashpw(password.encode(), user.salt.encode()).decode() session.add(user) session.commit() return jsonify(status='ok')
def get_division_list(): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) if data is None: return jsonify(status='fail', message='message body was blank') prompt = data['prompt'] offset = data['offset'] if prompt != "": divisions = session.query(Division).filter( Division.name.ilike( "%{}%".format(prompt))).offset(offset).limit(20).all() else: divisions = session.query(Division).order_by( Division.name).offset(offset).limit(20).all() if divisions is None: return jsonify(status='fail', message='no divisions found') div_out = [] for division in divisions: next_div = {"name": division.name, "id": division.id} div_out.append(next_div) rows = session.query(func.count(Division.id)).scalar() data_obj = {"division_count": rows, "divisions": div_out} return jsonify(status='ok', data=data_obj)
def get_league_data(league_id): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') league = session.query(League).filter_by(id=league_id).first() if league is None: return jsonify(status='fail', message='league does not exist') divisions = session.query(Division).filter_by(league_id=league.id).all() div_out = [] for d in divisions: next_div = { "id": d.id, "name": d.name, "description": d.description, "location": d.location, "founded": d.founded } div_out.append(next_div) league_out = { "name": league.name, "description": league.description, "founded": league.founded, "location": league.location } data_obj = {"league": league_out, "divisions": div_out} return jsonify(status='ok', data=data_obj)
def get_profile_data(): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') # TODO: Add in standard menu items menu_items = [{ "name": "Profile", "link": "/profile" }, { "name": "Divisions", "link": "/division" }] if user.status == "sadmin": menu_items.append({"name": "Admin Page", "link": "/admin"}) menu_items.append({"name": "Shirt Design", "link": "/admin/shirt"}) menu_items.append({"name": "Matches", "link": "/match"}) # Logout should be last menu_items.append({"name": "Log out", "link": "/logout"}) data_obj = { "firstname": user.first_name, "lastname": user.last_name, "menu_items": menu_items } return jsonify(status='ok', data=data_obj)
def get_matches(): # Get the most recent matches key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print("ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})".format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') matches = session.query(Match).order_by(Match.played) data = { 'matches': [] } for match in matches: home_club = session.query(Club).filter_by(id=match.home_club_id).first() away_club = session.query(Club).filter_by(id=match.away_club_id).first() if home_club is not None and away_club is not None: next_match = { 'id': match.id, 'home_club': home_club.name, 'away_club': away_club.name, 'played_at': match.played } data['matches'].append(next_match) else: print("ERROR: Match (id: {}) is missing home club ({}) or away club ({})".format( match.id, match.home_club_id, match.away_club_id )) return jsonify(status='ok', data=data)
def post_login(): data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) username = data.get('username') if username is None: return jsonify(status='fail', message='must provide a username') password = data.get('password') allowed_status = ['user', 'admin', 'sadmin'] if password is None: return jsonify(status='fail', message='password not provided') session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.salt is None: print("user {} is not yet confirmed but trying to login".format( user.email)) return jsonify(status='fail', message='user has not been confirmed') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') hashedpass = bcrypt.hashpw(password.encode(), user.salt.encode()) if hashedpass.decode() != user.password: return jsonify(status='fail', message='password incorrect') secret = utils.get_jwt_secret() if user.email is not None: jwttoken = jwt.encode({'username': user.email}, secret, algorithm='HS256') elif user.phone_number is not None: jwttoken = jwt.encode({'username': user.phone_number}, secret, algorithm='HS256') return jsonify(status='ok', token=jwttoken.decode())
def post_shirt(): data = request.values if data is None or len(data)==0: data = request.get_json(force=True) key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print("ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})".format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') style = data['style'] if style is None or style == "": return jsonify(status='fail', message='must provide a style') primary = data['primary_color'] if primary is None or primary == "": return jsonfiy(status='fail', message='primary color cannot be none') secondary = data['secondary_color'] shirt = Shirt(style, primary) if secondary != "": shirt.secondary_color = secondary session.add(shirt) session.commit() return jsonify(status='ok', shirt_id=shirt.id)
def get_all_shirt_data(): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print("ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})".format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') shirts = session.query(Shirt).all() shirts_list = [] for shirt in shirts: next_shirt = { "id": shirt.id, "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } shirts_list.append(next_shirt) data_obj = { "shirts": shirts_list } return jsonify(status='ok', data=data_obj)
def post_club(): user = utils.get_user(request) allowed_status = ['admin', 'sadmin'] if user.status not in allowed_status: print("ERROR: unauthorized access of resource attempted") return jsonify(status='fail', message='unauthorized', authorized=False) data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) if data is None: return jsonify(status='fail', message='message body was blank') name = data['name'] if name is None or name == "": return jsonify(status='fail', message='name cannot be blank') information = data['information'] location = data['location'] founded = data['founded'] contact = data['contact'] division = data['division'] try: division = int(division) except: return jsonify(status='fail', message='division value is not valid') session = get_db_session() club = Club(name, division) if information is not None and information != "": club.information = information if location is not None and location != "": club.location = location if founded is not None and founded != "": dt_founded = datetime_object = datetime.datetime.strptime( founded, '%Y-%m-%d') print(dt_founded) club.founded = dt_founded if contact is not None and contact != "": club.contact = contact session.add(club) session.commit() return jsonify(status='ok')
def post_confirmation(conf_guid): if conf_guid is None: return jsonify(status='fail', message='') session = get_db_session() user = session.query(User).filter_by(confirmation_guid=conf_guid).first() if user is None: return jsonify(status='fail', message='Unable to confirm, user not found') if user.confirmed != 0: return jsonify(status='fail', message='Confirmation already used') data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) password = data.get('password') if password is None or password == "": return jsonify(status='fail', message='Password cannot be blank') if len(password) < 10: return jsonify(status='fail', message='Password must be 10 characters or more') user.salt = bcrypt.gensalt().decode() user.password = bcrypt.hashpw(password.encode(), user.salt.encode()).decode() displayname = data.get('displayname') user.displayname = displayname user.confirmation_guid = None user.confirmed = 1 session.add(user) session.commit() secret = utils.get_jwt_secret() jwttoken = jwt.encode({'username': user.email}, secret, algorithm='HS256') return jsonify(status='ok', token=jwttoken.decode())
def get_user(request): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() return user
def reset_page(resetguid): rand = None if app.debug != False: rand = random.random() template_name = 'reset.html' if utils.is_on_mobile(request.headers.get('User-Agent')): template_name = 'mobile/reset.mobile.html' error = "" session = get_db_session() user = session.query(User).filter_by(confirmation_guid=resetguid).first() if user is None: error = "Invalid confirmation code" return render_template(template_name, random=rand, back_url='/', error=error, reset_code=resetguid)
def reset_password(): data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) email = data.get('email') if email is None: return jsonify(status='fail', message='Please provide an email address') session = get_db_session() user = session.query(User).filter_by(email=email).first() if user is None: return jsonify(status='fail', message='User not found') if user.confirmed == 0: return jsonify(status='fail', message='User not yet confirmed') # Generate reset guid guid = uuid.uuid4().hex user.confirmation_guid = guid session.add(user) session.commit() body = "Please go to https://electrocatstudios.com/resetpassword/{}".format( guid) text_body = "Please go to https://electrocatstudios.com/resetpassword/{}".format( guid) to = email sender = "*****@*****.**" subject = "Reset Your Password" msgHtml = body msgPlain = text_body SendMessage(sender, to, subject, msgHtml, msgPlain) return jsonify(status='ok', message='Reset Email Sent')
def get_player_data(player_id): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') player = session.query(Player).filter_by(id=player_id).first() if player is None: return jsonify(status='fail', message='player does not exist') position = session.query(Position).filter_by(id=player.position_id).first() if position is None: pass # print("Player without position {}".format(player.id)) club = session.query(Club).filter_by(id=player.club_id).first() club_out = {"name": "", "id": None} if club is not None: club_out["name"] = club.name club_out["id"] = club.id player_out = { "id": player.id, "first_name": player.first_name, "last_name": player.last_name, "shirt_number": player.shirt_number, "date_of_birth": player.date_of_birth, "height": player.height_cm, "home_shirt": { "style": "", "primary_color": "", "secondary_color": "", }, "away_shirt": { "style": "", "primary_color": "", "secondary_color": "", }, "goalkeeper_shirt": { "style": "", "primary_color": "", "secondary_color": "" }, # "shirt_color": player.shirt_color, "claimed": False, "club": club_out, "position": None, "profile_pic": None } if club.home_shirt_id != None: shirt = session.query(Shirt).filter_by(id=club.home_shirt_id).first() next_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } player_out["home_shirt"] = next_shirt if club.away_shirt_id != None: shirt = session.query(Shirt).filter_by(id=club.away_shirt_id).first() next_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } player_out["away_shirt"] = next_shirt if club.goalkeeper_shirt_id != None: shirt = session.query(Shirt).filter_by( id=club.goalkeeper_shirt_id).first() next_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } player_out["goalkeeper_shirt"] = next_shirt if player.profile_filename is not None and player.profile_filename.strip( ) != "": player_out['profile_pic'] = player.profile_filename if position is not None: player_out["position"] = position.name if player.yn_user_id is None: player_out["claimed"] = True data_obj = {"player": player_out} return jsonify(status='ok', data=data_obj)
def get_club_data(club_id): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') club = session.query(Club).filter_by(id=club_id).first() if club is None: return jsonify(status='fail', message='club does not exist') players = session.query(Player).filter_by(club_id=club_id).all() club_out = { "name": club.name, "information": club.information, "founded": club.founded, "contact": club.contact, "home_shirt": None, "away_shirt": None, "goalkeeper_shirt": None } if club.home_shirt_id is not None: shirt = session.query(Shirt).filter_by(id=club.home_shirt_id).first() if shirt is None: print("ERROR: Unknown home_shirt_id {} for club_id {}".format( club.home_shirt_id, club.id)) else: home_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } club_out['home_shirt'] = home_shirt if club.away_shirt_id is not None: shirt = session.query(Shirt).filter_by(id=club.away_shirt_id).first() if shirt is None: print("ERROR: Unknown away_shirt_id {} for club_id {}".format( club.away_shirt_id, club.id)) else: away_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } club_out['away_shirt'] = away_shirt if club.goalkeeper_shirt_id is not None: shirt = session.query(Shirt).filter_by( id=club.goalkeeper_shirt_id).first() if shirt is None: print( "ERROR: Unknown goalkeeper_shirt_id {} for club_id {}".format( club.goalkeeper_shirt_id, club.id)) else: goalkeeper_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } club_out['goalkeeper_shirt'] = goalkeeper_shirt players_out = [] for p in players: position = session.query(Position).filter_by(id=p.position_id).first() next_position = {} if position is not None: next_position["name"] = position.name else: pass # print("Player without position {}".format(p.id)) next_player = { "id": p.id, "first_name": p.first_name, "last_name": p.last_name, "position": next_position } players_out.append(next_player) matches = utils.get_match_data(session, club.id) match_info = [] for match in matches: if match.home_club_id != club.id: other_club = session.query(Club).filter_by( id=match.home_club_id).first() else: other_club = session.query(Club).filter_by( id=match.away_club_id).first() other_club_info = { 'name': other_club.name, 'id': other_club.id, 'logo': other_club.logo_filename } # TODO: Grab result cache item instead of all events events = utils.get_all_events(session, match.id) next_match = { 'id': match.id, 'other_club': other_club_info, 'played': match.played, 'events': events } match_info.append(next_match) data_obj = { "club": club_out, "players": players_out, "matches": match_info } return jsonify(status='ok', data=data_obj)
def get_division_data(div_id): key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print( "ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})" .format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') division = session.query(Division).filter_by(id=div_id).first() if division is None: return jsonify(status='fail', message='division does not exist') clubs = session.query(Club).filter_by(division_id=div_id).all() clubs_out = [] for c in clubs: rc = session.query(ResultCache).filter_by( competition_id=division.display_competition_id).filter_by( club_id=c.id).first() if rc is None: next_rc = { "win": 0, "loss": 0, "draw": 0, "points": 0, "goals_against": 0, "goals_for": 0, "goal_difference": 0 } else: next_rc = { "win": rc.win, "loss": rc.loss, "draw": rc.draw, "points": rc.points, "goals_against": rc.goals_against, "goals_for": rc.goals_for, "goal_difference": rc.goal_difference } next_club = { "id": c.id, "name": c.name, "contact": c.contact, "location": c.location, "founded": c.founded, "information": c.information, "rc": next_rc } # home_matches = session.query(Match).filter_by(home_club_id) if c.home_shirt_id is not None: shirt = session.query(Shirt).filter_by(id=c.home_shirt_id).first() if shirt is not None: next_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } next_club['home_shirt'] = next_shirt if c.goalkeeper_shirt_id is not None: shirt = session.query(Shirt).filter_by( id=c.goalkeeper_shirt_id).first() if shirt is not None: next_shirt = { "style": shirt.style, "primary_color": shirt.primary_color, "secondary_color": shirt.secondary_color } next_club['goalkeeper_shirt'] = next_shirt clubs_out.append(next_club) division_out = { "name": division.name, "description": division.description, "founded": division.founded, "location": division.location } data_obj = {"division": division_out, "clubs": clubs_out} return jsonify(status='ok', data=data_obj)
def get_match_by_id(matchid): # Get the most recent matches key = request.headers.get('Authorization') if key is None: return jsonify(status='fail', message='no token provided') token = key.split(" ")[1] if token is None: return jsonify(status='fail', message='failed token check') decode = utils.decode_jwt_token(token) if decode['username'] is None: return jsonify(status='fail', message='failed token check') username = decode['username'] allowed_status = ['user', 'admin', 'sadmin'] session = get_db_session() user = session.query(User).filter_by(email=username).first() if user is None: user = session.query(User).filter_by(phone_number=username).first() if user is None: return jsonify(status='fail', message='user does not exist') if user.status not in allowed_status: print("ERROR: Attempt to use disabled account (id:{} - name:{} - status: {})".format(user.id, user.name, user.status)) return jsonify(status='fail', message='account has been disabled') match = session.query(Match).filter_by(id=matchid).first() if match is None: return jsonify(status='fail', message='match does not exist') if match.home_club_id is None: return jsonify(status='fail', message='home club is blank') if match.away_club_id is None: return jsonify(status='fail', message='away club is blank') home_club = session.query(Club).filter_by(id=match.home_club_id).first() if home_club is None: return jsonify(status='fail', message='Home club does not exist') away_club = session.query(Club).filter_by(id=match.away_club_id).first() if away_club is None: return jsonify(status='fail', message='Away club does not exist') home_club_data = { 'name': home_club.name, 'goals': [], 'logo': home_club.logo_filename } away_club_data = { 'name': away_club.name, 'goals': [], 'logo': away_club.logo_filename } events = session.query(Event).filter_by(match_id=matchid).order_by(Event.occurred_at).all() other_events = [] for event in events: if event.event_type_id == 1: player = session.query(Player).filter_by(id=event.player_1_id).first() if player is None: return jsonify(status='fail', message="Failed to find player {}".format(event.player_1_id)) club = session.query(Club).filter_by(id=player.club_id).first() if club is None: return jsonify(status='fail', message='Failed to find club {}'.format(player.club_id)) shirt = {} if club.home_shirt_id is not None: shirt = utils.get_shirt_for_id(session, club.home_shirt_id) club_info = { 'name': club.name, 'shirt': shirt, 'club': club.logo_filename } next_goal = { 'type': 'Goal', 'scorer': "{} {}".format(player.first_name, player.last_name), 'scorer_id': player.id, 'time': event.occurred_at, 'support': None, 'support_id': None, 'club': club_info } if event.player_2_id is not None: support = session.query(Player).filter_by(id=event.player_2_id).first() next_goal['support'] = "{} {}".format(support.first_name, support.last_name) next_goal['support_id'] = support.id if player.club_id == home_club.id: home_club_data['goals'].append(next_goal) elif player.club_id == away_club.id: away_club_data['goals'].append(next_goal) else: return jsonify(status='fail', message='Failed to fit player to team') else: # TODO: Add in shirt details for front end p1 = None club_data = None if event.player_1_id is not None: playr = session.query(Player).filter_by(id=event.player_1_id).first() if playr is None: return jsonify(status='fail', message='Failed to find player') p1 = { 'id': playr.id, 'name': "{} {}".format(playr.first_name, playr.last_name) } club = session.query(Club).filter_by(id=playr.club_id).first() if club is not None: shirt = {} if club.home_shirt_id is not None: shirt = utils.get_shirt_for_id(session, club.home_shirt_id) club_data = { 'name': club.name, 'shirt': shirt, 'logo': club.logo_filename } p2 = None if event.player_2_id is not None: playr = session.query(Player).filter_by(id=event.player_2_id).first() if playr is None: return jsonify(status='fail', message='Failed to find player') p2 = { 'id': playr.id, 'name': "{} {}".format(playr.first_name, playr.last_name) } next_event = { 'type': utils.get_name_of_event(session, event.event_type_id), 'time': event.occurred_at, 'player': p1, 'club': club_data, 'other_player': p2, 'information': event.information } other_events.append(next_event) data = { 'home_club': home_club_data, 'away_club': away_club_data, 'events': other_events } return jsonify(status='ok', data=data)
def get_admin_details(): user = utils.get_user(request) allowed_status = ['admin', 'sadmin'] if user.status not in allowed_status: print("ERROR: unauthorized access of resource attempted") return jsonify(status='fail', message='unauthorized', authorized=False) session = get_db_session() usercount = session.query(func.count(User.id)).scalar() playercount = session.query(func.count(Player.id)).scalar() leagues = session.query(League).all() league_data = [] for l in leagues: divisions = session.query(Division).filter_by(league_id=l.id).all() div_details = [] for d in divisions: next_d = { "id": d.id, "name": d.name, "description": d.description, "location": d.location, "founded": d.founded } div_details.append(next_d) next_l = { "id": l.id, "name": l.name, "description": l.description, "location": l.location, "founded": l.founded, "divisions": div_details } league_data.append(next_l) clubs = session.query(Club).all() club_list = [] for c in clubs: players = session.query(Player).filter_by(club_id=c.id).all() player_list = [] for p in players: position = {"name": "center forward"} next_p = { "id": p.id, "first_name": p.first_name, "last_name": p.last_name, "shirt_number": p.shirt_number, "date_of_birth": p.date_of_birth, "height_cm": p.height_cm, "position": position, "yn_user_id": p.yn_user_id, "created_at": p.created_at } player_list.append(next_p) next_club = { "id": c.id, "name": c.name, "players": player_list, "founded": c.founded, "contact": c.contact, "location": c.location, "division_id": c.division_id, "created_at": c.created_at } club_list.append(next_club) positions = session.query(Position).all() pos_out = [] for p in positions: next_pos = {"id": p.id, "name": p.name, "description": p.description} pos_out.append(next_pos) data_obj = { "firstname": user.first_name, "lastname": user.last_name, "usercount": usercount, "playercount": playercount, "leagues": league_data, "clubs": club_list, "positions": pos_out } return jsonify(status='ok', data=data_obj)
from utils.dbutils import get_db_session from db.player import Player from db.club import Club # TODO: Must set the division id for the teams # division_id = 4 session = get_db_session() with open('output.csv') as f: content = f.read() content = content.split('\n') content = content[1:] for line in content: # print(line) if line.strip() != "": player_name = line.split(',')[1] player_name = player_name.split(' ') first_name = player_name[0].capitalize() if first_name.find('-') != -1: ind = first_name.index('-') fn_tmp = first_name[:ind] fn_tmp += "-" fn_tmp += first_name[ind+1:].capitalize() first_name = fn_tmp print(first_name) last_name = "" for item in player_name[1:]: last_name += item.capitalize() + " " last_name = last_name.strip()
def post_player(): user = utils.get_user(request) allowed_status = ['admin', 'sadmin'] if user.status not in allowed_status: print("ERROR: unauthorized access of resource attempted") return jsonify(status='fail', message='unauthorized', authorized=False) data = request.values if data is None or len(data) == 0: data = request.get_json(force=True) if data is None: return jsonify(status='fail', message='message body was blank') name = data['last_name'] if name is None or name == "": return jsonify(status='fail', message='last name cannot be blank') first_name = data['first_name'] shirt_number = data['shirt_number'] if shirt_number is not None and shirt_number != "": try: shirt_number = int(shirt_number) except: return jsonify(status='fail', message='shirt number must be a number') date_of_birth = data['date_of_birth'] try: if date_of_birth is not None and date_of_birth != "": date_of_birth = datetime.datetime.strptime(date_of_birth, '%Y-%m-%d') except: return jsonify(status='fail', message='date of birth invalid') height_cm = data['height_cm'] if height_cm is not None and height_cm != "": try: height_cm = int(height_cm) except: return jsonify(status='fail', message='height must be a number') club_id = data['club'] if club_id is not None and club_id != "": try: club_id = int(club_id) except: return jsonify(status='fail', message='club id is invalid') position_id = data['position_id'] if position_id is not None and position_id != "": try: position_id = int(position_id) except: return jsonify(status='fail', message='position id must be a number') yn_user_id = data['user_id'] if yn_user_id is not None and yn_user_id != "": try: yn_user_id = int(yn_user_id) except: return jsonify(status='fail', messasge='user id is not valid') player = Player(name, club_id) if first_name is not None and first_name != "": player.first_name = first_name if shirt_number is not None: player.shirt_number = shirt_number if date_of_birth is not None: player.date_of_birth = date_of_birth if height_cm is not None: player.height_cm = height_cm if position_id is not None: player.position_id = position_id if yn_user_id is not None and yn_user_id != "": player.yn_user_id = yn_user_id session = get_db_session() session.add(player) session.commit() return jsonify(status='ok')