Browse Source

Strategická: Další krůček webu

master
Jiří Kalvoda 2 years ago
parent
commit
ecc8e42d33
  1. 37
      server/hra/db.py
  2. 13
      server/hra/game.py
  3. 14
      server/hra/web/__init__.py
  4. 32
      server/hra/web/api.py
  5. 4
      server/hra/web/pages.py

37
server/hra/db.py

@ -12,6 +12,8 @@ from sqlalchemy.sql.expression import CTE
from sqlalchemy.sql.functions import ReturnTypeFromArgs from sqlalchemy.sql.functions import ReturnTypeFromArgs
from sqlalchemy.sql.sqltypes import Numeric from sqlalchemy.sql.sqltypes import Numeric
from typing import Any, Optional, List, Tuple from typing import Any, Optional, List, Tuple
import secrets
import string
import hra.config as config import hra.config as config
@ -45,10 +47,45 @@ class User(Base):
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
org = Column(Boolean) org = Column(Boolean)
token = Column(String(80), unique=True, nullable=False)
username = Column(String(80), unique=True, nullable=False) username = Column(String(80), unique=True, nullable=False)
passwd = Column(String(80), nullable=False) passwd = Column(String(80), nullable=False)
def gen_token(self):
self.token = ''.join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(15))
def __repr__(self): def __repr__(self):
return '<User %r>' % self.username return '<User %r>' % self.username
class Game(Base):
__tablename__ = 'games'
game_id = Column(Integer, primary_key=True)
configuration = Column(JSONB, nullable=False)
game_mode = Column(String(80), nullable=False)
teams_count = Column(Integer, nullable=False)
def current_state(self) -> 'State':
return get_session().query(State).filter_by(game_id=self.game_id).order_by(State.round.desc()).first()
class State(Base):
__tablename__ = 'states'
game_id = Column(Integer, ForeignKey('games.game_id'), primary_key=True, nullable=False)
round = Column(Integer)
state = Column(JSONB)
game = relationship('Game', primaryjoin='State.game_id == Game.game_id')
class Move(Base):
__tablename__ = 'moves'
game_id = Column(Integer, ForeignKey('games.game_id'), primary_key=True, nullable=False)
round = Column(Integer)
team_id = Column(Integer)
move = Column(JSONB)
game = relationship('Game', primaryjoin='Move.game_id == Game.game_id')

13
server/hra/game.py

@ -0,0 +1,13 @@
class Logic():
def __init__(self, teams_count, configuration):
pass
def zero_state(self):
return {}
def step(self, actions):
pass
logic_by_mode = {"base": Logic}

14
server/hra/web/__init__.py

@ -54,10 +54,17 @@ def init_request():
# nic dalšího (v ostrém nasazení je servíruje uwsgi) # nic dalšího (v ostrém nasazení je servíruje uwsgi)
return return
if 'uid' in session: user = None
user = db.get_session().query(db.User).filter_by(id=session['uid']).first() if path.startswith('/api/'):
token = request.args.get('token')
if token is not None:
user = db.get_session().query(db.User).filter_by(token=token).first()
if user is None:
raise werkzeug.exceptions.Forbidden("Wrong token.")
else: else:
user = None if 'uid' in session:
user = db.get_session().query(db.User).filter_by(id=session['uid']).first()
path = request.path path = request.path
if path.startswith('/org/'): if path.startswith('/org/'):
if not user or not user.org: if not user or not user.org:
@ -89,3 +96,4 @@ app.before_request(init_request)
import hra.web.pages import hra.web.pages
import hra.web.api

32
server/hra/web/api.py

@ -0,0 +1,32 @@
from flask import Flask, redirect, flash, render_template, session, g, request, get_flashed_messages
import werkzeug.exceptions
import time
from datetime import datetime
import json
import hra.config as config
import hra.web.html as html
import hra.db as db
from hra.web import app, NeedLoginError
import hra.web.jinja_mac as jinja_mac
def get_context():
if g.user is None:
raise NeedLoginError
game_id = request.args.get('game') or 1
team_id = request.args.get('team') or 0
game = db.get_session().query(db.Game).filter_by(game_id=game_id).first()
print(game_id, game, team_id)
if game is None:
raise werkzeug.exceptions.NotFound("No such game")
return game, team_id
@app.route("/api/state", methods=['GET'])
def api_state():
game, team_id = get_context()
state = game.current_state()
return json.dumps({
"round": state.round,
"state": state.state,
})

4
server/hra/web/pages.py

@ -101,6 +101,7 @@ def registration():
f = RegistrationForm() f = RegistrationForm()
if f.validate_on_submit(): if f.validate_on_submit():
u = db.User(org=False, username=f.username.data, passwd=hash_passwd(f.passwd.data)) u = db.User(org=False, username=f.username.data, passwd=hash_passwd(f.passwd.data))
u.gen_token()
try: try:
db.get_session().add(u) db.get_session().add(u)
db.get_session().commit() db.get_session().commit()
@ -163,6 +164,9 @@ def print_time(t):
@app.route("/", methods=['GET', 'POST']) @app.route("/", methods=['GET', 'POST'])
def web_index(): def web_index():
b = BasePage() b = BasePage()
if g.user:
with b.p():
b(f"Váš token je: {g.user.token}")
return b._print_file() return b._print_file()

Loading…
Cancel
Save