def create_user(session, username, displayname, email=None): """Creates and adds a user to the session given the details.""" user = User(permission_level=1, username=username) user.displayname = displayname if email: user.email = email session.add(user)
def insert(self, data): User.user_instance_checker(data) command_string = "insert into STAT_SNAP_USER(USER_ID, PASSWORD) values (" \ ":1,:2)" self.cur.execute(command_string, (str(data.get_user_id()), str(data.get_password()))) self.con.commit()
def select(self, data): command_string = "select USER_ID, PASSWORD from STAT_SNAP_USER where USER_ID = '" + str( data) + "'" self.cur.execute(command_string) row = self.cur.fetchone() user = User() user.set_values_from_row([row[0], row[1]]) return user
def create_account(): if request.method == 'POST': userDao = UserDAO() user = User() user.set_values_from_row( [str(request.form['username']), str(request.form['password'])]) userDao.insert(user) return redirect(url_for('login')) return render_template("create_account.html")
def post(self): username = self.get_current_user() if username is None: self.result("error", "Access denied.") return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.result("error", "Access denied.") return try: displayname = strip_tags(self.get_argument("displayname")) email = strip_tags(self.get_argument("email")) showemail = bool(self.get_argument("showemail", False)) except: self.result("error", "Invalid arguments. Check that all fields are filled out correctly.") return session = SessionFactory() try: user.displayname = displayname user.email = email user.showemail = showemail session.add(user) session.commit() self.result("success", "Settings saved successfully.", user) finally: session.close()
def post(self): username = self.get_current_user() if username is None: self.result("error", "Access denied.") return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_ADMIN: self.result("error", "Access denied.") return try: username = self.get_argument("username") displayname = self.get_argument("displayname") email = self.get_argument("email", None) or None except: self.result("error", "Invalid arguments. Check that all fields are filled out correctly.") return session = SessionFactory() try: create_user(session, username, displayname, email) session.commit() self.result("success", "User added successfully.") finally: session.close()
def post(self): username = self.get_current_user() if username is None: self.result("error", "Access denied.") return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.result("error", "Access denied.") return try: user1_id = int(self.get_argument("userSelect1")) user2_id = int(self.get_argument("userSelect2")) # date_time = self.get_argument("date") + " " + self.get_argument("time") games = [] for gnum in range(1): game = (int(self.get_argument("score_g{}_p0".format(gnum))), int(self.get_argument("score_g{}_p1".format(gnum)))) games.append(game) except: self.result("error", "Invalid arguments. Check that all fields are filled out correctly.") return if user1_id == user2_id: self.result("error", "Opponents must be different users.") return session = SessionFactory() try: user1 = session.query(User).filter(User.id == user1_id).one() user2 = session.query(User).filter(User.id == user2_id).one() # d = datetime.datetime.strptime(date_time, "%Y-%m-%d T%H:%M:%S") seconds = int(time.time()) #int(d.strftime('%s')) # filter out any games which have negative or all-zero scores games = filter(lambda g: all(map(lambda s: s >= 0, g)) and any(map(lambda s: s > 0, g)), games) if len(games) < 1: self.result("error", "A match consists of one or more games.") return current_score = (get_most_recent_ratings(user1.id).get('exposure',0), get_most_recent_ratings(user2.id).get('exposure',0)) match = create_match(session, user1, user2, seconds, games) session.commit() new_score = (get_most_recent_ratings(user1.id).get('exposure',0), get_most_recent_ratings(user2.id).get('exposure',0)) msg = "Match recorded successfully.<br><br>"\ "Points Changes:<br>" \ '%s: %0.3f<br>' \ '%s: %0.3f' % (user1.displayname, new_score[0]-current_score[0], user2.displayname, new_score[1]-current_score[1]) self.result("success", msg) finally: session.close()
def get(self, uid=None): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if uid is None: self.render("leaderboard.html", user=user) else: target_user = User.by_id(int(uid)) self.render("user-details.html", user=user, target_user=target_user)
def insert_new_user(json): if ( not json or (not 'firstName' in json) or (not 'lastName' in json) or (not 'email' in json) or (not 'hashedPassword' in json) or (not 'userType' in json) ): abort(400, 'Not all fields were received.') if not validate_email(json['email']): abort(400, 'The email address is invalid.') query_result = db.session.query(User).filter(and_(User.email == json['email'], not_(User.deleted))).first() if query_result: abort(400, 'A user with this email address already exists.') user = User( email = json['email'], first_name = json['firstName'], last_name = json['lastName'], user_type = json['userType'], password = json['hashedPassword'], creation_date = datetime.now(), deleted = False, description = '', phone_number = '', avatar = 'default' ) db.session.add(user) db.session.commit() resp = jsonify({ 'success': True, 'user': user.to_dict() }) resp.status_code = 200 return resp
def post(self): username = self.get_current_user() if username is None: self.result("error", "Access denied.") return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.result("error", "Access denied.") return try: user1_id = int(self.get_argument("userSelect1")) user2_id = int(self.get_argument("userSelect2")) date_time = self.get_argument("date") + " " + self.get_argument("time") games = [] for gnum in range(3): game = (int(self.get_argument("score_g{}_p0".format(gnum))), int(self.get_argument("score_g{}_p1".format(gnum)))) games.append(game) except: self.result("error", "Invalid arguments. Check that all fields are filled out correctly.") return if user1_id == user2_id: self.result("error", "Opponents must be different users.") return session = SessionFactory() try: user1 = session.query(User).filter(User.id == user1_id).one() user2 = session.query(User).filter(User.id == user2_id).one() d = datetime.datetime.strptime(date_time, "%Y-%m-%d T%H:%M:%S") seconds = int(d.strftime('%s')) # filter out any games which have negative or all-zero scores games = filter(lambda g: all(map(lambda s: s >= 0, g)) and any(map(lambda s: s > 0, g)), games) if len(games) < 2: self.result("error", "A match consists of two or more games.") return match = create_match(session, user1, user2, seconds, games) session.commit() self.result("success", "Match recorded successfully.") finally: session.close()
def get(self, user1 = None, user2 = None): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return self.render("head-to-head.html", user=user, user1=user1, user2=user2)
def get(self, mid=None): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_ADMIN: self.render("denied.html", user=user) return self.render("admin.html", user=user)
def get(self): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return self.render("record-match.html", user=user)
def get(self, action): if action == "logout": self.logout_user() elif action == "login": if self.get_current_user() is None: self.validate_user() return else: self.redirect("/Leaderboard", permanent=False) return else: # action == "admin": username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level >= constants.PERMISSION_LEVEL_ADMIN: # self.render("admin") self.finish("This will be the admin page.") else: self.render("denied.html", user=user)
def get(self, mid=None): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if mid is None: self.render("match-history.html", user=user) else: session = SessionFactory() try: target_match = session.query(Match).filter(Match.id==str(mid)).one() self.render("match-details.html", user=user, target_match=target_match) except NoResultFound: return None finally: session.close()
def get(self, user_id): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if user_id is not None and user_id != "": # single item user_id = int(user_id) session = SessionFactory() try: result = get_leaderboard_query(session).filter(User.id == user_id).one() result = resultdict(result) data = "{}&& "+json.dumps(result) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close() else: # query items raw_range = self.request.headers.get('Range', '') m = range_expression.match(raw_range) if m is not None: start = int(m.group('lower')) stop = int(m.group('upper')) + 1 else: start = 0 stop = -1 raw_query = self.request.query m = sorting_expression.match(raw_query) if m is not None: direction = m.group('direction') column = m.group('column') else: direction = '-' column = "rating" if column not in ["id", "displayname", "games", "wins", "win_percentage", "rating", "form", "streak", 'rank_change', 'order']: column = "rating" if direction == '-': direction = 'desc' else: direction = 'asc' session = SessionFactory() try: query = get_leaderboard_query(session) total = query.count() # query = query.order_by(direction(column)) query = query.slice(start, stop) result = query.all() result = resultdict(result) trophy_holder = session.query(FloatingTrophyCache).order_by(FloatingTrophyCache.id.desc()).first() today = datetime.now().date() today = datetime(today.year, today.month, today.day) today = int(today.strftime('%s')) previous_board = get_leaderboard_query(session, at_date = today).order_by(desc('rating')).all() previous_ranking = {} for pos, item in enumerate(previous_board,1): previous_ranking[item.id] = (pos, item.rating) result = sorted(result, key= lambda k:k['rating'])[::-1] for i,res in enumerate(result,1): res['order']= i s1 = aliased(Score) game_history = session.query(Score.score.label('player_score'), Score.game_id, s1.score.label('opponent_score') ).\ join(s1, sqlalchemy.and_(s1.game_id==Score.game_id, s1.user_id!=Score.user_id)).filter(Score.user_id==res['id']).\ order_by(Score.game_id.desc()) res['form'] = '' game_history = ['W' if game.player_score>game.opponent_score else 'L' for game in game_history] last_game = game_history[0] opposite = 'W' if last_game == 'L' else 'L' res['form'] = ''.join(reversed(game_history[0:5])) res['streak'] = '%s%s' % (last_game, game_history.index(opposite) if opposite in game_history else len(game_history)) res['rank_change'] = (previous_ranking[res['id']][0]- i) if previous_ranking.has_key(res['id']) else 0 res['rating_change'] = (res['rating']-previous_ranking[res['id']][1]) if previous_ranking.has_key(res['id']) else 0 res['hot_streak'] = False res['trophy_holder'] = trophy_holder is not None and trophy_holder.user_id==res['id'] result = sorted(result, key= sort_dict.get(column,lambda k:k[column])) if direction == 'desc': result = result[::-1] best_streak = None for res in sorted(result, key= sort_dict.get('streak'))[::-1]: if (best_streak is None and int(res['streak'][1:])>3) or res['streak'] == best_streak: res['hot_streak'] = True best_streak = res['streak'] else: break data = "{}&& "+json.dumps(result) self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total)) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close()
from database.PostRecord import PostRecord with app.app_context(): db.drop_all() db.create_all() print("All tables created.") # Users js = User( email = 'js@ex', first_name = 'John', last_name = 'Smith', password = '******', #aaaaaa deleted = False, user_type = 'Movee', creation_date = datetime.now(), description = '', phone_number = '0400 111 222', avatar = 'male1' ) db.session.add(js) db.session.commit() ml = User( email = 'ml@ex', first_name = 'Movee', last_name = 'Lee', password = '******', #aaaaaa deleted = False,
#!/usr/bin/python import os import sys system_directory = os.path.dirname(os.path.abspath(__file__)) sys.path.append(system_directory + "/imports") username = sys.argv[1] permission_level = int(sys.argv[2]) from database.User import User from database.SessionFactory import SessionFactory session = SessionFactory() try: user = User.get_user(username) user.permission_level = permission_level session.add(user) session.commit() print "Successfully set permission level for user '{}' to {}.".format(user.username, user.permission_level) finally: session.close()
def get(self, target_user_id): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if not target_user_id: raise ValueError("User required") # query items raw_range = self.request.headers.get('Range', '') m = range_expression.match(raw_range) if m is not None: start = int(m.group('lower')) stop = int(m.group('upper')) + 1 else: start = 0 stop = -1 raw_query = self.request.query m = sorting_expression.match(raw_query) if m is not None: direction = m.group('direction') column = m.group('column') else: direction = '-' column = "date" if column not in ["id", "date", "winner_id", "winner_score", "winner_displayname", "opponent_id", "opponent_score", "opponent_displayname"]: column = "date" if direction == '-': direction = desc else: direction = asc session = SessionFactory() try: query = get_match_history_query(session, target_user_id) total = query.count() query = query.order_by(direction(column)) query = query.slice(start, stop) result = query.all() result = resultdict(result) data = "{}&& "+json.dumps(result) self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total)) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close()
def get(self, user_id): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if user_id is not None and user_id != "": # single item user_id = int(user_id) session = SessionFactory() try: result = get_leaderboard_query(session).filter(User.id == user_id).one() result = resultdict(result) data = "{}&& "+json.dumps(result) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close() else: # query items raw_range = self.request.headers.get('Range', '') m = range_expression.match(raw_range) if m is not None: start = int(m.group('lower')) stop = int(m.group('upper')) + 1 else: start = 0 stop = -1 raw_query = self.request.query m = sorting_expression.match(raw_query) if m is not None: direction = m.group('direction') column = m.group('column') else: direction = '-' column = "displayname" if column not in ["id", "displayname"]: column = "displayname" if direction == '-': direction = desc else: direction = asc session = SessionFactory() try: query = get_leaderboard_query(session) filterable_columns = {'displayname': User.displayname} for col, val in self.request.arguments.iteritems(): if col in filterable_columns.keys(): val = val[0].replace('*', '%') query = query.filter(filterable_columns[col].like(val)) query = query.order_by(direction(column)) query = query.slice(start, stop) result = query.all() result = resultdict(result) total = len(result) data = "{}&& "+json.dumps(result) self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total)) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close()
def get(self, user1, user2, summary=False): username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if not (user1 and user2): raise ValueError("Two users are required") user1 = User.by_id(user1) user2 = User.by_id(user2) # query items raw_range = self.request.headers.get('Range', '') m = range_expression.match(raw_range) if m is not None: start = int(m.group('lower')) stop = int(m.group('upper')) + 1 else: start = 0 stop = -1 raw_query = self.request.query m = sorting_expression.match(raw_query) if m is not None: direction = m.group('direction') column = m.group('column') else: direction = '-' column = "date" if column not in ["id", "date", "winner_id", "winner_score", "winner_displayname", "opponent_id", "opponent_score", "opponent_displayname"]: column = "date" if direction == '-': direction = desc else: direction = asc session = SessionFactory() try: query = get_match_history_query(session, [user1.id, user2.id]) total = query.count() query = query.order_by(direction(column)) if not summary: query = query.slice(start, stop) result = query.all() if summary: score_dict = {'won': 0, 'lost': 0, 'points_scored': 0, 'difference': 0, 'form': ''} sum_dict = { user1.id: score_dict.copy(), user2.id: score_dict.copy() } for res in result: sum_dict[res.winner_id]['won'] += 1 sum_dict[res.winner_id]['points_scored'] += res.winner_score sum_dict[res.winner_id]['difference'] += res.winner_score-res.opponent_score sum_dict[res.winner_id]['form'] = 'W' + sum_dict[res.winner_id]['form'] sum_dict[res.opponent_id]['lost'] += 1 sum_dict[res.opponent_id]['points_scored'] += res.opponent_score sum_dict[res.opponent_id]['difference'] += res.opponent_score-res.winner_score sum_dict[res.opponent_id]['form'] = 'L' + sum_dict[res.opponent_id]['form'] result = [] for player in sum_dict: user = user1 if player==user1.id else user2 player_dict = sum_dict[player] player_dict['form'] = player_dict['form'][-5:] player_dict.update({'id': player, 'displayname': user.displayname}) result.append(player_dict) start = 0 stop = 1 total = 2 else: result = resultdict(result) data = "{}&& "+json.dumps(result) self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total)) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close()
import os import sys import random system_directory = os.path.dirname(os.path.abspath(__file__)) sys.path.append(system_directory + "/imports") #from names import names as usernames from names_from_home_directories import names as usernames from database.User import User from database.SessionFactory import SessionFactory import constants session = SessionFactory() try: for username in usernames: permission_level = constants.PERMISSION_LEVEL_USER user = User(username, permission_level) user.displayname = username user.email = "{}@students.wwu.edu".format(username) user.showemail = False session.add(user) session.commit() finally: session.close()
def get(self, user_id, timestamp): user_id = int(user_id) username = self.get_current_user() if username is None: self.validate_user() return user = User.get_user(username) if user.permission_level < constants.PERMISSION_LEVEL_USER: self.render("denied.html", user=user) return if timestamp is not None and timestamp != "": # single item timestamp = int(timestamp) session = SessionFactory() try: result = get_rankstore_query(session, user_id).filter_by(timestamp=timestamp).one() result = resultdict(result) data = "{}&& "+json.dumps(result) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close() else: # query items raw_range = self.request.headers.get('Range', '') m = range_expression.match(raw_range) if m is not None: start = int(m.group('lower')) stop = int(m.group('upper')) + 1 else: start = 0 stop = -1 raw_query = self.request.query m = sorting_expression.match(raw_query) if m is not None: direction = m.group('direction') column = m.group('column') else: direction = '-' column = "timestamp" if column not in ["timestamp", "rank"]: column = "timestamp" if direction == '-': direction = desc else: direction = asc session = SessionFactory() try: query = get_rankstore_query(session, user_id) total = query.count() query = query.order_by(direction(column)) query = query.slice(start, stop) result = query.all() result = resultdict(result) data = "{}&& "+json.dumps(result) self.set_header('Content-range', 'items {}-{}/{}'.format(start, stop, total)) self.set_header('Content-length', len(data)) self.set_header('Content-type', 'application/json') self.write(data) finally: session.close()