2021-11-07 18:54:19 +00:00
|
|
|
import secrets
|
2019-12-02 03:32:03 +00:00
|
|
|
import string
|
|
|
|
import bcrypt
|
|
|
|
from flask import current_app
|
|
|
|
|
2021-12-03 14:12:11 +00:00
|
|
|
from .base import db
|
2019-12-02 03:32:03 +00:00
|
|
|
from ..models.role import Role
|
|
|
|
from ..models.domain import Domain
|
2021-12-03 14:12:11 +00:00
|
|
|
from ..models.account import Account
|
2019-12-02 03:32:03 +00:00
|
|
|
|
|
|
|
class ApiKey(db.Model):
|
|
|
|
__tablename__ = "apikey"
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
key = db.Column(db.String(255), unique=True, nullable=False)
|
|
|
|
description = db.Column(db.String(255))
|
|
|
|
role_id = db.Column(db.Integer, db.ForeignKey('role.id'))
|
|
|
|
role = db.relationship('Role', back_populates="apikeys", lazy=True)
|
|
|
|
domains = db.relationship("Domain",
|
2021-12-03 14:12:11 +00:00
|
|
|
secondary="domain_apikey",
|
2019-12-02 03:32:03 +00:00
|
|
|
back_populates="apikeys")
|
2021-12-03 14:12:11 +00:00
|
|
|
accounts = db.relationship("Account",
|
|
|
|
secondary="apikey_account",
|
|
|
|
back_populates="apikeys")
|
2019-12-02 03:32:03 +00:00
|
|
|
|
2021-12-03 14:12:11 +00:00
|
|
|
def __init__(self, key=None, desc=None, role_name=None, domains=[], accounts=[]):
|
2019-12-02 03:32:03 +00:00
|
|
|
self.id = None
|
|
|
|
self.description = desc
|
|
|
|
self.role_name = role_name
|
|
|
|
self.domains[:] = domains
|
2021-12-03 14:12:11 +00:00
|
|
|
self.accounts[:] = accounts
|
2019-12-02 03:32:03 +00:00
|
|
|
if not key:
|
|
|
|
rand_key = ''.join(
|
2021-11-07 18:54:19 +00:00
|
|
|
secrets.choice(string.ascii_letters + string.digits)
|
2019-12-02 03:32:03 +00:00
|
|
|
for _ in range(15))
|
|
|
|
self.plain_key = rand_key
|
|
|
|
self.key = self.get_hashed_password(rand_key).decode('utf-8')
|
|
|
|
current_app.logger.debug("Hashed key: {0}".format(self.key))
|
|
|
|
else:
|
|
|
|
self.key = key
|
|
|
|
|
|
|
|
def create(self):
|
|
|
|
try:
|
|
|
|
self.role = Role.query.filter(Role.name == self.role_name).first()
|
|
|
|
db.session.add(self)
|
|
|
|
db.session.commit()
|
|
|
|
except Exception as e:
|
|
|
|
current_app.logger.error('Can not update api key table. Error: {0}'.format(e))
|
|
|
|
db.session.rollback()
|
|
|
|
raise e
|
|
|
|
|
|
|
|
def delete(self):
|
|
|
|
try:
|
|
|
|
db.session.delete(self)
|
|
|
|
db.session.commit()
|
|
|
|
except Exception as e:
|
|
|
|
msg_str = 'Can not delete api key template. Error: {0}'
|
|
|
|
current_app.logger.error(msg_str.format(e))
|
|
|
|
db.session.rollback()
|
|
|
|
raise e
|
|
|
|
|
2021-12-03 14:12:11 +00:00
|
|
|
def update(self, role_name=None, description=None, domains=None, accounts=None):
|
2019-12-02 03:32:03 +00:00
|
|
|
try:
|
2022-12-09 01:33:17 +00:00
|
|
|
if role_name:
|
|
|
|
role = Role.query.filter(Role.name == role_name).first()
|
|
|
|
self.role_id = role.id
|
2019-12-02 03:32:03 +00:00
|
|
|
|
2022-12-09 01:33:17 +00:00
|
|
|
if description:
|
|
|
|
self.description = description
|
2019-12-02 03:32:03 +00:00
|
|
|
|
2022-12-09 01:33:17 +00:00
|
|
|
if domains is not None:
|
|
|
|
domain_object_list = Domain.query \
|
|
|
|
.filter(Domain.name.in_(domains)) \
|
|
|
|
.all()
|
|
|
|
self.domains[:] = domain_object_list
|
2019-12-02 03:32:03 +00:00
|
|
|
|
2022-12-09 01:33:17 +00:00
|
|
|
if accounts is not None:
|
|
|
|
account_object_list = Account.query \
|
|
|
|
.filter(Account.name.in_(accounts)) \
|
|
|
|
.all()
|
|
|
|
self.accounts[:] = account_object_list
|
2021-12-03 14:12:11 +00:00
|
|
|
|
2022-12-09 01:33:17 +00:00
|
|
|
db.session.commit()
|
2019-12-02 03:32:03 +00:00
|
|
|
except Exception as e:
|
2022-12-09 01:33:17 +00:00
|
|
|
msg_str = 'Update of apikey failed. Error: {0}'
|
|
|
|
current_app.logger.error(msg_str.format(e))
|
|
|
|
db.session.rollback() # fixed line
|
|
|
|
raise e
|
2019-12-02 03:32:03 +00:00
|
|
|
|
|
|
|
def get_hashed_password(self, plain_text_password=None):
|
|
|
|
# Hash a password for the first time
|
|
|
|
# (Using bcrypt, the salt is saved into the hash itself)
|
|
|
|
if plain_text_password is None:
|
|
|
|
return plain_text_password
|
|
|
|
|
|
|
|
if plain_text_password:
|
|
|
|
pw = plain_text_password
|
|
|
|
else:
|
|
|
|
pw = self.plain_text_password
|
|
|
|
|
2021-11-09 20:09:15 +00:00
|
|
|
# The salt value is currently re-used here intentionally because
|
|
|
|
# the implementation relies on just the API key's value itself
|
|
|
|
# for database lookup: ApiKey.is_validate() would have no way of
|
|
|
|
# discerning whether any given key is valid if bcrypt.gensalt()
|
|
|
|
# was used. As far as is known, this is fine as long as the
|
|
|
|
# value of new API keys is randomly generated in a
|
|
|
|
# cryptographically secure fashion, as this then makes
|
|
|
|
# expendable as an exception the otherwise vital protection of
|
|
|
|
# proper salting as provided by bcrypt.gensalt().
|
2019-12-02 03:32:03 +00:00
|
|
|
return bcrypt.hashpw(pw.encode('utf-8'),
|
|
|
|
current_app.config.get('SALT').encode('utf-8'))
|
|
|
|
|
|
|
|
def check_password(self, hashed_password):
|
2020-06-19 01:47:51 +00:00
|
|
|
# Check hashed password. Using bcrypt,
|
2019-12-02 03:32:03 +00:00
|
|
|
# the salt is saved into the hash itself
|
2020-06-19 01:47:51 +00:00
|
|
|
if self.plain_text_password:
|
2019-12-02 03:32:03 +00:00
|
|
|
return bcrypt.checkpw(self.plain_text_password.encode('utf-8'),
|
|
|
|
hashed_password.encode('utf-8'))
|
|
|
|
return False
|
|
|
|
|
|
|
|
def is_validate(self, method, src_ip=''):
|
|
|
|
"""
|
|
|
|
Validate user credential
|
|
|
|
"""
|
|
|
|
if method == 'LOCAL':
|
|
|
|
passw_hash = self.get_hashed_password(self.plain_text_password)
|
|
|
|
apikey = ApiKey.query \
|
|
|
|
.filter(ApiKey.key == passw_hash.decode('utf-8')) \
|
|
|
|
.first()
|
|
|
|
|
|
|
|
if not apikey:
|
|
|
|
raise Exception("Unauthorized")
|
|
|
|
|
|
|
|
return apikey
|
2021-12-03 14:12:11 +00:00
|
|
|
|
|
|
|
def associate_account(self, account):
|
|
|
|
return True
|
|
|
|
|
|
|
|
def dissociate_account(self, account):
|
|
|
|
return True
|
|
|
|
|
|
|
|
def get_accounts(self):
|
|
|
|
return True
|