Kaynağa Gözat

work on registration

Eren Yilmaz 6 yıl önce
ebeveyn
işleme
60aa4e960e
5 değiştirilmiş dosya ile 184 ekleme ve 96 silme
  1. 30 0
      admin_console.py
  2. 6 2
      client_controller.py
  3. 103 0
      db_setup.py
  4. 38 92
      model.py
  5. 7 2
      server_controller.py

+ 30 - 0
admin_console.py

@@ -0,0 +1,30 @@
+import random
+
+import model
+
+
+def generate_keys(count=1):
+    # source https://stackoverflow.com/questions/17049308/python-3-3-serial-key-generator-list-problems
+    seq = "ABCDFGHJIKLMNPQRSTUVWXYZ123456789"
+
+    for i in range(count):
+        key = '-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5))
+        model.save_key(key)
+        print(key)
+
+
+def unused_keys():
+    print("\n".join(model.unused_keys()))
+
+
+def cleanup():
+    if model.connection is not None:
+        model.connection.commit()
+        model.connection.close()
+
+
+if __name__ == '__main__':
+    # generate_keys(count=8)
+    # unused_keys
+
+    cleanup()

+ 6 - 2
client_controller.py

@@ -33,7 +33,7 @@ def login(username=None, password=None):
             print('Login failed.')
 
 
-def register(username, password=None):
+def register(username=None, password=None, game_key=None):
     if connection.session_id is not None:
         client.fake_loading_bar('Signing out', delay=0.025)
         connection.session_id = None
@@ -47,7 +47,11 @@ def register(username, password=None):
         else:
             password = input('Password: ')
 
-    response = client_request('register', {"username": username, "password": password})
+    if game_key is None:
+        print('Entering a game key will provide you with some starting money and other useful stuff.')
+        game_key = input('Game key (leave empty if you don\'t have one): ')
+
+    response = client_request('register', {"username": username, "password": password, "game_key": game_key})
 
     if 'error_message' in response:
         print('Registration failed with message:', response['error_message'])

+ 103 - 0
db_setup.py

@@ -0,0 +1,103 @@
+from game import money_amount
+from model import cursor
+
+
+def setup():
+
+    print('Database setup...')
+
+    replace = True
+
+    if replace:
+        print(' - Dropping old tables...')
+        cursor.execute("DROP TABLE IF EXISTS users")
+        cursor.execute("DROP TABLE IF EXISTS ownables")
+        cursor.execute("DROP TABLE IF EXISTS ownership")
+        cursor.execute("DROP TABLE IF EXISTS sessions")
+        cursor.execute("DROP TABLE IF EXISTS orders")
+        cursor.execute("DROP TABLE IF EXISTS transactions")
+
+    print(' - Creating tables...')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS users(
+                    username VARCHAR(10) UNIQUE NOT NULL, 
+                    password VARCHAR(6) NOT NULL)
+                ''')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS ownables(
+                    name VARCHAR(10) UNIQUE NOT NULL, 
+                    total_amount CURRENCY NOT NULL)
+                ''')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS ownership(
+                    user_id INTEGER NOT NULL,
+                    ownable_id INTEGER NOT NULL,
+                    amount CURRENCY NOT NULL DEFAULT 0,
+                    FOREIGN KEY (user_id) REFERENCES users(rowid),
+                    FOREIGN KEY (ownable_id) REFERENCES ownables(rowid),
+                    UNIQUE (user_id, ownable_id)
+                )
+                ''')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS sessions(
+                    user_id INTEGER NOT NULL,
+                    session_id STRING NOT NULL,
+                    FOREIGN KEY (user_id) REFERENCES users(rowid)
+                )
+                ''')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS orders(
+                    ownership_id INTEGER NOT NULL,
+                    buy BOOLEAN NOT NULL,
+                    "limit" CURRENCY,
+                    stop_loss BOOLEAN,
+                    ordered_amount CURRENCY,
+                    executed_amount CURRENCY,
+                    FOREIGN KEY (ownership_id) REFERENCES ownership(rowid)
+                )
+                ''')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS transactions(
+                    dt DATETIME NOT NULL,
+                    price CURRENCY NOT NULL,
+                    ownable_id INTEGER NOT NULL,
+                    FOREIGN KEY (ownable_id) REFERENCES ownable(rowid)
+                )
+                ''')
+    cursor.execute('''
+                CREATE TABLE IF NOT EXISTS keys(
+                    key STRING UNIQUE NOT NULL,
+                    used_by_user_id INTEGER UNIQUE,
+                    FOREIGN KEY (used_by_user_id) REFERENCES user(rowid)
+                )
+                ''')
+
+    if replace:  # TODO also seed new databases
+        print(' - Seeding initial data...')
+        cursor.execute('''
+                    INSERT INTO users
+                    (username, password)
+                    VALUES ("bank", "")
+                    ''')
+        cursor.execute('''
+                    SELECT rowid 
+                    FROM users
+                    WHERE username = "bank"
+                    ''')
+        bank_id = cursor.fetchone()[0]
+        cursor.execute('''
+                    INSERT INTO ownables
+                    (name, total_amount)
+                    VALUES ("Kollar", ?)
+                    ''', (money_amount,))
+        cursor.execute('''
+                    SELECT rowid 
+                    FROM users
+                    WHERE username = "bank"
+                    ''')
+        kollar_id = cursor.fetchone()[0]
+        cursor.execute('''
+                    INSERT INTO ownership
+                    (user_id, ownable_id, amount)
+                    VALUES (?, ?, ?)
+                    ''', (bank_id, kollar_id, money_amount))

+ 38 - 92
model.py

@@ -3,6 +3,7 @@ import sqlite3 as db
 import sys
 import uuid
 
+import db_setup
 from game import money_amount
 from util import debug
 
@@ -54,96 +55,9 @@ def connect(reconnect=False):
 def setup():
     connect()
 
-    print('Database setup...')
+    db_setup.setup()
 
-    replace = False
-
-    if replace:
-        print(' - Dropping old tables...')
-        cursor.execute("DROP TABLE IF EXISTS users")
-        cursor.execute("DROP TABLE IF EXISTS ownables")
-        cursor.execute("DROP TABLE IF EXISTS ownership")
-        cursor.execute("DROP TABLE IF EXISTS sessions")
-        cursor.execute("DROP TABLE IF EXISTS orders")
-        cursor.execute("DROP TABLE IF EXISTS transactions")
-
-    print(' - Creating tables...')
-    cursor.execute('''
-                CREATE TABLE IF NOT EXISTS users(
-                    username VARCHAR(10) UNIQUE NOT NULL, 
-                    password VARCHAR(6) NOT NULL)
-                ''')
-    cursor.execute('''
-                CREATE TABLE IF NOT EXISTS ownables(
-                    name VARCHAR(10) UNIQUE NOT NULL, 
-                    total_amount CURRENCY NOT NULL)
-                ''')
-    cursor.execute('''
-                CREATE TABLE IF NOT EXISTS ownership(
-                    user_id INTEGER NOT NULL,
-                    ownable_id INTEGER NOT NULL,
-                    amount CURRENCY NOT NULL DEFAULT 0,
-                    FOREIGN KEY (user_id) REFERENCES users(rowid),
-                    FOREIGN KEY (ownable_id) REFERENCES ownables(rowid),
-                    UNIQUE (user_id, stock_id)
-                )
-                ''')
-    cursor.execute('''
-                CREATE TABLE IF NOT EXISTS sessions(
-                    user_id INTEGER NOT NULL,
-                    session_id STRING NOT NULL,
-                    FOREIGN KEY (user_id) REFERENCES users(rowid)
-                )
-                ''')
-    cursor.execute('''
-                CREATE TABLE IF NOT EXISTS orders(
-                    ownership_id INTEGER NOT NULL,
-                    buy BOOLEAN NOT NULL,
-                    limit CURRENCY,
-                    stop_loss BOOLEAN,
-                    ordered_amount CURRENCY,
-                    executed_amount CURRENCY,
-                    FOREIGN KEY (ownership_id) REFERENCES ownership(rowid)
-                )
-                ''')
-    cursor.execute('''
-                CREATE TABLE IF NOT EXISTS transactions(
-                    dt DATETIME NOT NULL,
-                    price CURRENCY NOT NULL,
-                    ownable_id INTEGER NOT NULL,
-                    FOREIGN KEY (ownable_id) REFERENCES ownable(rowid)
-                )
-                ''')
-
-    if replace:  # TODO also seed new databases
-        print(' - Seeding initial data...')
-        cursor.execute('''
-                    INSERT INTO users
-                    (username, password)
-                    VALUES ("bank", "")
-                    ''')
-        cursor.execute('''
-                    SELECT rowid 
-                    FROM users
-                    WHERE username = "bank"
-                    ''')
-        bank_id = cursor.fetchone()[0]
-        cursor.execute('''
-                    INSERT INTO ownables
-                    (name, total_amount)
-                    VALUES ("Kollar", ?)
-                    ''', (money_amount,))
-        cursor.execute('''
-                    SELECT rowid 
-                    FROM users
-                    WHERE username = "bank"
-                    ''')
-        kollar_id = cursor.fetchone()[0]
-        cursor.execute('''
-                    INSERT INTO ownership
-                    (user_id, ownable_id, amount)
-                    VALUES (?, ?, ?)
-                    ''', (bank_id, kollar_id, money_amount))
+    connection.commit()
 
 
 def login(username, password):
@@ -166,7 +80,7 @@ def login(username, password):
         return None
 
 
-def register(username, password):
+def register(username, password, game_key):
     connect()
     if username == '':
         return False
@@ -177,6 +91,22 @@ def register(username, password):
                 (username, password)
                 VALUES (? , ?)
                 ''', (username, password))
+    if game_key is not None:
+        if game_key in unused_keys():
+            cursor.execute('''
+                        UPDATE keys
+                        WHERE used_by_user_id IS NULL
+                        AND key = ?
+                        SET used_by_user_id = (
+                            SELECT rowid
+                            FROM users
+                            WHERE username = ?
+                        )
+                        ''', (game_key, username))
+        if cursor.fetchone()[0]!=1:
+            raise AssertionError()
+        # TODO: assign some money form bank
+
     return True
 
 
@@ -194,6 +124,16 @@ def new_session(user_id):
     return session_id
 
 
+def save_key(key):
+    connect()
+
+    cursor.execute('''
+                INSERT INTO keys 
+                (key)
+                VALUES (?)
+                ''', (key,))
+
+
 def drop_old_sessions():
     connect()
     # TODO: test
@@ -222,7 +162,13 @@ def user_exists(username):
         return False
 
 
-def move_money(username):
+def unused_keys():
     connect()
 
-    cursor.execute()
+    cursor.execute('''
+        SELECT key
+        FROM keys
+        WHERE used_by_user_id IS NULL
+        ''')
+
+    return [str(key[0]).strip().upper() for key in cursor.fetchall()]

+ 7 - 2
server_controller.py

@@ -35,10 +35,15 @@ def register():
     password = request.json['password']
     if model.user_exists(username):
         return forbidden('User already exists.')
-    if model.register(username, password):
+    game_key = None
+    if 'game_key' in request.json:
+        game_key = request.json['game_key']
+        if game_key not in model.unused_keys():
+            return bad_request('Game key is not valid.')
+    if model.register(username, password, game_key):
         return {'message': "successfully registered user"}
     else:
-        bad_request('registration not successful')
+        return bad_request('registration not successful')
 
 
 def not_found(msg=''):