authorization api now final
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Torma Kristóf 2020-11-26 01:56:41 +01:00
parent 34bb3fcc25
commit 025e380e6f
4 changed files with 67 additions and 26 deletions

View File

@ -9,9 +9,9 @@ from healthcheck import HealthCheck
from marshm import ma from marshm import ma
from fred import flaskred from fred import flaskred
from config import SENTRY_DSN, RELEASEMODE, RELEASE_ID, PORT, DEBUG, REDIS_HOST from config import SENTRY_DSN, RELEASEMODE, RELEASE_ID, PORT, DEBUG, REDIS_URL
from errorhandlers import register_all_error_handlers from errorhandlers import register_all_error_handlers
from resources import LoginApi, LogoffApi, MeApi from resources import LoginApi, ListsApi, MeApi, SingleListApi, TrackApi
""" """
Main Flask RESTful API Main Flask RESTful API
@ -36,7 +36,7 @@ if SENTRY_DSN:
app = Flask(__name__) app = Flask(__name__)
app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh'] app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']
app.config['REDIS_URL'] = f"redis://{REDIS_HOST}:6379/0" app.config['REDIS_URL'] = REDIS_URL
api = Api(app) api = Api(app)
health = HealthCheck() health = HealthCheck()
ma.init_app(app) ma.init_app(app)
@ -53,12 +53,11 @@ logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
logger.addHandler(handler) logger.addHandler(handler)
api.add_resource(LogoffApi, '/api/auth/logoff')
api.add_resource(LoginApi, '/api/auth/login') api.add_resource(LoginApi, '/api/auth/login')
api.add_resource(MeApi, '/api/auth/me') api.add_resource(MeApi, '/api/auth/me')
# api.add_resource(ListsApi, '/api/lists') api.add_resource(ListsApi, '/api/lists')
# api.add_resource(SingleListApi, '/api/lists/<listid>') api.add_resource(SingleListApi, '/api/lists/<listid>')
# api.add_resource(TrackApi, '/api/lists/<listid>/<trackid>') api.add_resource(TrackApi, '/api/lists/<listid>/<trackid>')
app.add_url_rule("/healthz", "healthcheck", view_func=lambda: health.run()) app.add_url_rule("/healthz", "healthcheck", view_func=lambda: health.run())

View File

@ -19,6 +19,6 @@ SENTRY_DSN = os.environ.get("SENTRY_DSN")
RELEASE_ID = os.environ.get("RELEASE_ID", "test") RELEASE_ID = os.environ.get("RELEASE_ID", "test")
RELEASEMODE = os.environ.get("ONSPOT_RELEASEMODE", "dev") RELEASEMODE = os.environ.get("ONSPOT_RELEASEMODE", "dev")
REDIS_HOST = os.getenv("ONSPOT_REDIS_HOST") REDIS_URL = os.getenv("ONSPOT_REDIS_URL")
ENCODED_SECRET_KEY = os.getenv("ONSPOT_ENCODED_SECRET_KEY") ENCODED_SECRET_KEY = os.getenv("ONSPOT_ENCODED_SECRET_KEY")

View File

@ -1,5 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import musicbrainzngs
""" """
Flask error handler functions Flask error handler functions
""" """
@ -12,6 +14,7 @@ __version__text__ = "1"
def get_standard_error_handler(code: int): def get_standard_error_handler(code: int):
def error_handler(err): def error_handler(err):
musicbrainzngs.user(None, None)
return {"msg": str(err)}, code return {"msg": str(err)}, code
return error_handler return error_handler

View File

@ -3,11 +3,12 @@
import uuid import uuid
from flask_restful import Resource from flask_restful import Resource
from flask import request, current_app, abort, request from flask import request, current_app, abort
import musicbrainzngs
from fred import flaskred from fred import flaskred
from config import ENCODED_SECRET_KEY from config import ENCODED_SECRET_KEY
from schemas import UserSchema, ListSchema, TrackSchema from schemas import UserSchema
from aes_encrypt import EncryptedUserRedis from aes_encrypt import EncryptedUserRedis
""" """
@ -23,14 +24,13 @@ INVALID_JSON_SCHEMA_MSG = "invalid json schema"
class LoginApi(Resource): class LoginApi(Resource):
"""
See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/logon
"""
userschema = UserSchema(many=False) userschema = UserSchema(many=False)
encryptor = EncryptedUserRedis(ENCODED_SECRET_KEY) encryptor = EncryptedUserRedis(ENCODED_SECRET_KEY)
def post(self): def post(self):
"""
See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/logon
"""
body = request.get_json() body = request.get_json()
try: try:
@ -39,26 +39,36 @@ class LoginApi(Resource):
current_app.logger.warning(e) current_app.logger.warning(e)
abort(417, INVALID_JSON_SCHEMA_MSG) abort(417, INVALID_JSON_SCHEMA_MSG)
try:
musicbrainzngs.auth(userobj['name'], userobj['password'])
musicbrainzngs.set_useragent("onSpot", 1)
musicbrainzngs.set_rate_limit(1.0, 20)
musicbrainzngs.https = True
print(musicbrainzngs.get_collections())
except Exception as e:
current_app.logger.warning(e)
abort(401, "login denied to musicbrainz")
self.encryptor.store(body) self.encryptor.store(body)
token = str(uuid.uuid4()) token = str(uuid.uuid4())
flaskred.set(token, userobj['name'].encode('UTF-8')) flaskred.set(token, userobj['name'].encode('UTF-8'))
return { return {
'token': token 'token': token
}, 200 }, 200
def delete(self):
class LogoffApi(Resource):
""" """
See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/logoff See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/logoff
""" """
try:
def delelete(self):
flaskred.delete(flaskred.get(request.headers.get('Authorization')).decode('UTF-8')) flaskred.delete(flaskred.get(request.headers.get('Authorization')).decode('UTF-8'))
flaskred.delete(request.headers.get('Authorization')) flaskred.delete(request.headers.get('Authorization'))
return 204 except Exception as e:
current_app.logger.warning(e)
abort(401, "unauthorized")
return "", 204
class MeApi(Resource): class MeApi(Resource):
@ -67,4 +77,33 @@ class MeApi(Resource):
""" """
def get(self): def get(self):
return {"name": flaskred.get(request.headers.get('Authorization')).decode('UTF-8')}, 200 try:
currusername = flaskred.get(request.headers.get('Authorization')).decode('UTF-8')
except Exception as e:
current_app.logger.warning(e)
abort(401, "unauthorized")
return {"name": currusername}, 200
class ListsApi(Resource):
"""
See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/getAllLists
"""
def get(self):
pass
class SingleListApi(Resource):
"""
See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/getList
"""
def get(self, listid: str):
pass
class TrackApi(Resource):
"""
See: https://swagger.kmlabz.com/?urls.primaryName=onSpot%20Backend#/backend/getTrack
"""
def get(self, listid: str, trackid: str):
pass