Merge pull request #9 from sorrelbri/sj-room-endpoints

sj room endpoints
This commit is contained in:
sorrelbri 2019-10-09 10:02:50 -07:00 committed by GitHub
commit 75e4ef40d3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 135 additions and 41 deletions

View file

@ -1,17 +1,21 @@
from flask import Blueprint, request, jsonify, session
from .users.user_endpoint import UserEndpoint
from .users.api_users import api_users
from .rooms.api_rooms import api_rooms
from auth.auth import auth
api = Blueprint('api', __name__, url_prefix='/api')
def register_api_endpoints(app):
app.register_blueprint(api_users)
app.register_blueprint(api_rooms)
app.register_blueprint(api)
app.register_blueprint(auth)
return app
@api.route('/home', methods=['GET'])
def api_home():
response = {"message": "home page"}
return jsonify(response)
@api.route('/users')
def api_users():
return jsonify(UserEndpoint.users())
@api.route('/user')
def api_user():
return jsonify(UserEndpoint.user())

18
api/decorators.py Normal file
View file

@ -0,0 +1,18 @@
from flask import Blueprint, request, jsonify, session
import os
import jwt
def jwt_required():
def decorator(func):
def authorized(*args, **kwargs):
auth_header = request.headers.get('Authorization') or None
if auth_header:
auth_token = auth_header.split(" ")[1]
if jwt.decode(auth_token, os.environ.get('SECRET_KEY')):
return func(*args, **kwargs)
else:
abort(401)
else:
abort(401)
return authorized
return decorator

43
api/rooms/api_rooms.py Normal file
View file

@ -0,0 +1,43 @@
from models.User import User, user_schema, users_schema
from models.GameRoom import GameRoom
from flask import Blueprint, request, jsonify, session
from ..decorators import jwt_required
api_rooms = Blueprint('api_rooms', __name__, url_prefix='/api/rooms')
@api_rooms.route('/<room_id>', methods=['GET'])
def get_room():
pass
@api_rooms.route('/', methods=['GET'])
def get_rooms():
response = {"status" : "success"}
return jsonify(response)
# protected route
@api_rooms.route('/', methods=['POST'])
@jwt_required()
def post_room():
data = request.get_json()
try:
room = GameRoom(
name = data['name'],
description = data['description'],
private = data['private'],
language = data['language']
)
db.session.add(room)
db.session.commit()
response = {
'status': 'success',
'message': 'Succesfully registered.',
'gameRoom': room.id
}
return jsonify(response), 201
except Exception as e:
print(e.__dict__)
response = {
'status': 'fail',
'message': 'There was an error. Please try again.'
}
return jsonify(response), 401

View file

@ -1,7 +0,0 @@
from flask import Blueprint
room = Blueprint('rooms', __name__)
@room.route('/<int:room_id>')
def func():
pass

28
api/users/api_users.py Normal file
View file

@ -0,0 +1,28 @@
from models.User import User, user_schema, users_schema
from flask import Blueprint, request, json, session, jsonify
from ..decorators import jwt_required
api_users = Blueprint('api_users', __name__, url_prefix='/api')
@api_users.route('/users/', methods=['GET'])
def api_get_users():
print('called one')
users = User.query.all()
response = users_schema.dumps(users)
return jsonify(response)
@api_users.route('/users/account', methods=['GET'])
@jwt_required()
def api_get_user():
print('called')
auth_header = request.headers.get('Authorization') or None
if auth_header:
auth_token = auth_header.split(" ")[1]
user = User.decode_auth_token(auth_token) or None
response = json.dumps(user)
else:
response = {
'status': 'failed',
'message': 'Please Log In'}
return jsonify(response)

View file

@ -1,15 +0,0 @@
from models.User import User, user_schema, users_schema
from flask import request, jsonify, Response, json
class UserEndpoint(object):
def users():
users = User.query.all()
response = users_schema.dumps(users)
return response
def user():
auth_header = request.headers.get('Authorization') or None
auth_token = auth_header.split(" ")[1]
user = User.decode_auth_token(auth_token) or None
response = json.dumps(user)
return response

View file

@ -52,6 +52,7 @@ def auth_login():
try:
# fetch the user data
print('getting here')
print(data)
user = User.query.filter_by(email=data['email']).first()
print(user.username)
auth_token = user.encode_auth_token(user.id)

View file

@ -1,8 +1,14 @@
from app import db, ma
# TODO User >---< GameRoom
import enum
game_rooms_users = db.Table('game_rooms_users',
db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True),
db.Column('game_rooms_id', db.Integer, db.ForeignKey('game_rooms.id'), primary_key=True)
)
class Languages(enum.Enum):
EN: "English"
EN = "English"
class GameRoom(db.Model):
__tablename__ = "game_rooms"
@ -14,5 +20,16 @@ class GameRoom(db.Model):
private = db.Column(db.Boolean(), nullable=False, default=False)
language = db.Column(db.Enum(Languages), nullable=False)
def __init__(self):
pass
# ! Foreign Keys
users = db.relationship(
'User',
secondary=game_rooms_users,
lazy='subquery',
backref=db.backref('game_rooms', lazy=True)
)
def __init__(self, name, description, private=False, language=Languages.EN):
self.name = name
self.description = description
self.private = private
self.language = language

View file

@ -46,7 +46,7 @@ class Ranks(enum.Enum): # with minimal Elo rating
K28 = "Twenty-Eight Kyu"
K29 = "Twenty-Nine Kyu"
K30 = "Thirty Kyu" # Elo -900
RU = "Unknown Rank"
UR = "Unknown Rank"
class User(db.Model):
__tablename__ = "users"
@ -61,9 +61,7 @@ class User(db.Model):
elo = db.Column(db.Integer)
rank_certainty = db.Column(db.Boolean, nullable=False, default=False)
def __init__(self, username, email, password, rank=Ranks.K1, admin=False):
print(rank)
print(Ranks)
def __init__(self, username, email, password, rank=Ranks.UR, admin=False):
self.username = username
self.email = email
self.password = bcrypt.generate_password_hash(

View file

@ -1,7 +1,7 @@
from app import create_app, db
# Blueprints
from api.api import api
from api.api import register_api_endpoints
from auth.auth import auth
# Web sockets
@ -14,7 +14,6 @@ from flask_migrate import Migrate
if __name__ == '__main__':
app = create_app()
app.register_blueprint(api)
app.register_blueprint(auth)
register_api_endpoints(app)
migrate = Migrate(app, db)
socketio.run(app, debug=True)

View file

@ -9,9 +9,17 @@ def handle_connection():
cool
''')
send({'data':'connection'})
emit('message', {'data':'connection'})
@socketio.on('message')
def handle_message(message):
print(message)
emit('message return', {'data':'a message was sent'})
emit('message return', {'message':'a message was sent'}, broadcast=True)
@socketio.on('connect', namespace='/newroom')
def handle_connection():
print('''
look cool a namespaced socketio connection!
''')