QuickAccess/main.py

119 lines
3.2 KiB
Python
Raw Normal View History

2022-09-21 01:16:09 +08:00
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'MOIS3Y'
import requests
from models_vm import VmAccount
from models_dci import AuthUser
from settings import CLIENT_HOST, PLATFORM
class Access(object):
"""
Allows you to get a link with an authorization key
For quick access to the web interface of the client platform.
The PLATFORM variable can be set as an environment variable.
Default PLATFORM='vm'
"""
def __init__(self, platform):
if platform == 'vm':
self.user_table = VmAccount
if platform == 'dci':
self.user_table = AuthUser
2022-09-21 02:43:00 +08:00
self.platform = platform
def get_admin(self):
"""
The method gets the first 10 active database users
and finds the admin among them. I couldn't create
a request filtering by the roles field because
peewee doesn't understand json and can't make a selection
Returns:
_dict_: admin data
"""
query_admin = (self.user_table.select(
self.user_table.id,
self.user_table.email,
self.user_table.state,
self.user_table.roles).where(
(self.user_table.id <= 10) &
(self.user_table.state == "active")
)
)
# !peewee doesn't work well with JSONfield MySQL
for field in query_admin:
if field.roles[0] == '@admin':
2022-09-20 22:34:59 +08:00
admin = dict(
id=field.id,
email=field.email,
state=field.state,
role=field.roles[0]
)
break
return admin
def get_key(self, admin):
"""
Makes a post request to the endpoint
passing the admin data and
returns the generated access key
Args:
admin (_dict_): _admin data_
Returns:
_dict_: _access key_
"""
2022-09-25 17:13:23 +08:00
host = 'input'
if self.platform == 'dci':
host = 'dci_input_1' # because this hostname
url = 'http://{}:1500/api/auth/v4/user/{}/key'.format(
2022-09-25 16:07:47 +08:00
host, admin['id']
)
headers = {"Internal-Auth": "on", "Accept": "application/json"}
2022-09-25 17:13:23 +08:00
check_key = 0
while check_key != 3:
try:
req = requests.post(url, headers=headers, data={})
answer = req.json()
key = answer['key']
print("Key will be used:")
print(key, "\n")
break
except Exception:
check_key += 1
key = 'not_found_try_again'
return key
def main():
"""
app entrypoint
"""
access = Access(PLATFORM)
2022-09-20 22:34:59 +08:00
print("="*47)
2022-09-20 22:41:21 +08:00
print("\nGetting an admin account, please waiting....\n")
2022-09-20 22:34:59 +08:00
account = access.get_admin()
2022-09-20 22:34:59 +08:00
print("Account will be used:")
2022-09-20 22:34:59 +08:00
print(account, "\n")
print("Getting an access key, please waiting...\n")
key = access.get_key(account)
2022-09-20 22:34:59 +08:00
2022-09-25 17:13:23 +08:00
access_link = 'https://{}/auth/key-v4/{}'.format(CLIENT_HOST, key)
2022-09-20 22:34:59 +08:00
2022-09-20 22:41:21 +08:00
print("Your access link: \n")
2022-09-20 22:45:18 +08:00
print(access_link, "\n")
2022-09-20 22:34:59 +08:00
print("ENJOY MY FRIEND! \n")
print("="*47)
if __name__ == "__main__":
main()