2016-04-20 17:25:20 +01:00
|
|
|
import uuid
|
2016-01-19 12:07:00 +00:00
|
|
|
from flask import current_app
|
|
|
|
|
from itsdangerous import URLSafeSerializer
|
|
|
|
|
|
|
|
|
|
from app import db
|
|
|
|
|
from app.models import ApiKey
|
|
|
|
|
|
2016-04-20 17:25:20 +01:00
|
|
|
from app.dao.dao_utils import (
|
|
|
|
|
transactional,
|
2016-04-21 18:10:57 +01:00
|
|
|
version_class
|
2016-04-20 17:25:20 +01:00
|
|
|
)
|
2016-01-19 12:07:00 +00:00
|
|
|
|
2016-04-20 17:25:20 +01:00
|
|
|
|
|
|
|
|
@transactional
|
2016-04-21 18:10:57 +01:00
|
|
|
@version_class(ApiKey)
|
2016-01-19 12:07:00 +00:00
|
|
|
def save_model_api_key(api_key, update_dict={}):
|
|
|
|
|
if update_dict:
|
2016-04-21 15:22:26 +01:00
|
|
|
update_dict.pop('id', None)
|
2016-04-20 17:25:20 +01:00
|
|
|
for key, value in update_dict.items():
|
2016-04-21 15:22:26 +01:00
|
|
|
setattr(api_key, key, value)
|
2016-04-20 17:25:20 +01:00
|
|
|
db.session.add(api_key)
|
2016-01-19 12:07:00 +00:00
|
|
|
else:
|
2016-04-20 17:25:20 +01:00
|
|
|
if not api_key.id:
|
|
|
|
|
api_key.id = uuid.uuid4() # must be set now so version history model can use same id
|
2016-01-19 12:07:00 +00:00
|
|
|
api_key.secret = _generate_secret()
|
|
|
|
|
db.session.add(api_key)
|
|
|
|
|
|
|
|
|
|
|
2016-01-20 14:48:44 +00:00
|
|
|
def get_model_api_keys(service_id, id=None):
|
|
|
|
|
if id:
|
|
|
|
|
return ApiKey.query.filter_by(id=id, service_id=service_id, expiry_date=None).one()
|
|
|
|
|
return ApiKey.query.filter_by(service_id=service_id).all()
|
2016-01-19 12:07:00 +00:00
|
|
|
|
|
|
|
|
|
2016-01-19 18:25:21 +00:00
|
|
|
def get_unsigned_secrets(service_id):
|
2016-01-19 12:07:00 +00:00
|
|
|
"""
|
|
|
|
|
This method can only be exposed to the Authentication of the api calls.
|
|
|
|
|
"""
|
2016-01-19 18:25:21 +00:00
|
|
|
api_keys = ApiKey.query.filter_by(service_id=service_id, expiry_date=None).all()
|
|
|
|
|
keys = [_get_secret(x.secret) for x in api_keys]
|
|
|
|
|
return keys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_unsigned_secret(key_id):
|
|
|
|
|
"""
|
|
|
|
|
This method can only be exposed to the Authentication of the api calls.
|
|
|
|
|
"""
|
|
|
|
|
api_key = ApiKey.query.filter_by(id=key_id, expiry_date=None).one()
|
2016-01-19 12:07:00 +00:00
|
|
|
return _get_secret(api_key.secret)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _generate_secret(token=None):
|
|
|
|
|
if not token:
|
|
|
|
|
token = uuid.uuid4()
|
|
|
|
|
serializer = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
|
|
|
|
|
return serializer.dumps(str(token), current_app.config.get('DANGEROUS_SALT'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_secret(signed_secret):
|
|
|
|
|
serializer = URLSafeSerializer(current_app.config.get('SECRET_KEY'))
|
|
|
|
|
return serializer.loads(signed_secret, salt=current_app.config.get('DANGEROUS_SALT'))
|