def create_defaults(): if 'query' in dir(User) and not User.query.get(0): db.session.add(User(user_id=0, name='unassigned')) db.session.add(User(user_id=-1, name='player 1')) db.session.add(User(user_id=-2, name='player 2')) db.session.add(User(user_id=-3, name='player 3')) db.session.add(User(user_id=-4, name='player 4')) db.session.commit()
def verify_token(token): test = User.check_token(token) if token else None if test is not None and test.active: login_user(test) return True return False
def receive_json(): new_game = Game() data = request.get_json() or {} if 'desc' not in data or 'hands' not in data or 'players' not in data: return bad_request('must include username, email and pin fields') new_game.description = data['desc'] new_game.started = ZZZ # TODO DateTime new_game.last_updated = ZZZ # TODO DateTime new_game.public = False new_game.log = data['log'] new_game.json = ZZZ # TODO try: if 'final_score' in players: new_game.is_active = False scores = data['final_scores'] else: new_game.is_active = True if 'scores' in data['hands'][-1]: scores = data['hands'][-1]['scores'] else: scores = data['hands'][-2]['scores'] except: scores = [0, 0, 0, 0] players = [] for idx in range(4): players[idx] = UsersGames(score=scores[idx], place=idx + 1) try: a = User.query.get(1) except: a = User() a.username = '******' db.session.add(a) players[idx].player = a players[idx].game = new_game db.session.add(players[idx]) db.session.commit() response = jsonify({'game.id': new_game.id}) response.status_code = 201 return response
def create_users(): p1 = User(username='******', pin=1234) p1.create_token() p2 = User(username='******', pin=2345) p3 = User(username='******', pin=3456) p4 = User(username='******', pin=4567) p5 = User(username='******', pin=5678) db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.add(p4) db.session.add(p5) db.session.commit()
def json_create_user(): data = request.get_json() or {} if 'username' not in data or 'email' not in data or 'pin' not in data: return bad_request('must include username, email and pin fields') existing_user = User.query.filter_by(username=data['username']).first() if existing_user: return bad_request( '%d Name already in use. Please use a different username' % existing_user.id) existing_user = User.query.filter_by(email=data['email']).first() if existing_user: return bad_request( '%d Email address already in use. Please use a different email address' % existing_user.id) user = User() user.from_dict(data, new_user=True) db.session.add(user) db.session.commit() response = jsonify(user.to_dict()) response.status_code = 201 response.headers['user.id'] = user.id response.headers['token'] = user.get_token() return response
def api_create_user(): data = request.values if 'name' not in data: return bad_request('must include name') suffix = '' counter = 2 while User.query.filter_by(name=data['name']+suffix).first(): suffix = '%d' % counter counter += 1 user = User() user.name = data['name'] db.session.add(user) db.session.commit() response = jsonify({ 'id': user.user_id, 'name': user.name, 'token': user.get_token(), }) response.status_code = 201 return response
def api_verify_token(token): # TODO remove after testing if token == 'ok': login_user(User.query.get(0)) return True # end of block to be removed after testing # find a user attached to this token if we can test = User.check_token(token) if token else None if test is not None and test.active: login_user(test) return True return False
def register(): ''' register a new user ''' if current_user.is_authenticated: return redirect(url_for('front_page')) form = RegistrationForm() if form.validate_on_submit(): this_user = User() form.populate_obj(this_user) this_user.set_password(form.password.data) this_user.set_pin(form.pin.data) this_user.create_token() db.session.add(this_user) db.session.commit() flash( 'Congratulations, you are now a registered user, you are now logged in!' ) login_user(this_user) return redirect(url_for('view_profile', user_id=this_user.id)) return render_template('register.html', title='Register', form=form)
def register(): ''' register a new user ''' if current_user.is_authenticated: return redirect(url_for('front_page')) form = RegistrationForm() if not form.validate_on_submit(): return render_template('register.html', title='Register', form=form) this_user = User() form.populate_obj(this_user) this_user.set_password(form.password.data) this_user.set_pin(form.pin.data) this_user.create_token() db.session.add(this_user) db.session.commit() flash( 'Congratulations, you are now a registered user, you are now logged in!' ) login_user(this_user) confirm_url = url_for('confirm_email', token=serializer.dumps(this_user.email, salt='email-confirm-key'), _external=True) req = Message( html=render_template('email_activate.html', url=confirm_url), subject='Confirm your email for the ZAPS Mahjong Scorer', mail_from='*****@*****.**', mail_to=this_user.email, ).send() if req.status_code not in [ 250, ]: pass # TODO message is not sent, deal with this return redirect(url_for('view_profile', user_id=this_user.user_id))
def api_list_users(): return jsonify(User.get_all_names(request.if_modified_since).all())
def api_save_game(game_id): # TODO needs testing import pickle with open('gamesave.pickle', 'wb') as f: pickle.dump(request.values, f) data = request.values or {} if 'summary' not in data or 'json' not in data or 'live' not in data or 'lastUpdated' not in data: return bad_request('must include summary, json, live and lastUpdated fields') jsondata = json.loads(data['json']) this_game = Game.query.get(game_id) new_game = this_game is None if new_game: this_game = Game() this_game.game_id = game_id try: this_game.description = data['summary'] this_game.started = datetime.fromtimestamp(int(game_id[0:10])) this_game.public = False this_game.log = pickle.dumps(jsondata['log']) this_game.last_updated = datetime.fromtimestamp(int(data['lastUpdated'][0:10])) this_game.is_active = jsondata['inProgress'] == 1 if this_game.is_active: places = [0, 0, 0, 0] scores = jsondata['scores'] else: scores = jsondata['final_score']['finaleDeltas'] places = jsondata['final_score']['places'] if new_game: db.session.add(this_game) else: players_in_game = this_game.players.copy() for idx in range(4): got_player = False player_dict = jsondata['players'][idx] if new_game: if player_dict['id'] is not None and player_dict['id'] >= 0: player = User.query.get(player_dict['id']) got_player = player is not None else: if idx < len(players_in_game): player = players_in_game[idx] got_player = True if not got_player: player = User() serial = 1 testname = player_dict['name'] # name must be unique, so add a unique serial number if # needed, eg Andrew 2, Andrew 3, Andrew 4 while db.session.query(User).filter(User.name == testname).first() is not None: serial += 1 testname = player_dict['name'] + ' %d' % serial player.name = testname db.session.add(player) jsondata['players'][idx]['id'] = player.user_id jsondata['players'][idx]['name'] = player.name # TODO needs special handling if user_id == 0, # as user_id must be unique in each game usersgames = UsersGames.query.get((player.user_id, this_game.game_id)) if usersgames is None: usersgames = UsersGames() usersgames.player = player usersgames.game = this_game db.session.add(usersgames) usersgames.score = scores[idx] usersgames.place = places[idx] # we may have changed the players to sync with db this_game.json = json.dumps(jsondata, default=jsonconverter) db.session.commit() update = { 'id': this_game.game_id, 'players': jsondata['players'], 'last_updated': this_game.last_updated, } response = jsonify(update) for idx in range(4): if 'pin' in update['players'][idx]: del update['players'][idx]['pin'] update = {**update, 'scores': scores, 'places': places, 'scoresheet': jsondata['scoreSheet'], 'started': this_game.started, }; (QUEUES['put'])(this_game.game_id, json.dumps(update, default=jsonconverter)); response.status_code = 201 except Exception as err: db.session.rollback() response = str(err), 400 raise err return response
def json_user_list(): return jsonify(User.get_all_usernames())