|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +TOOLS_DIR = "/usr/local/easyops/deploy_init/tools" |
| 5 | +APP_ID = "brick_next" |
| 6 | + |
| 7 | +import sys |
| 8 | +sys.path.append(TOOLS_DIR) |
| 9 | + |
| 10 | + |
| 11 | +def get_token(user, org): |
| 12 | + """ |
| 13 | + 通过 app_id 从配置中获取 client_id 和 secret, 然后调用 get_token_util.get_token |
| 14 | +
|
| 15 | + 参数: (user: 用户名, org: 组织名) |
| 16 | + 返回: token 或空字符串(当认证功能关闭时) |
| 17 | + 异常: 当认证功能启用但相关工具或配置缺失时抛出异常 |
| 18 | + """ |
| 19 | + |
| 20 | + # 尝试导入 deploy_init config_reader |
| 21 | + try: |
| 22 | + from config_reader import get_config_value |
| 23 | + except ImportError: |
| 24 | + return "" |
| 25 | + |
| 26 | + try: |
| 27 | + enable = get_config_value("deploy_init", "common", "check_auth_token.enable") |
| 28 | + if str(enable).lower() != "true": |
| 29 | + return "" |
| 30 | + except KeyError: |
| 31 | + return "" |
| 32 | + except Exception as e: |
| 33 | + raise Exception("get_token: failed to read check_auth_token.enable: %s" % str(e)) |
| 34 | + |
| 35 | + # 尝试导入 deploy_init get_token_util |
| 36 | + try: |
| 37 | + import get_token_util |
| 38 | + except ImportError: |
| 39 | + # 开关打开的情况下,如果没有找到 get_token_util 模块,则抛出异常 |
| 40 | + raise Exception("get_token: check_auth_token is enabled, but deploy_init get_token_util module not found!") |
| 41 | + |
| 42 | + try: |
| 43 | + client_id = get_config_value(APP_ID, "application", "client_id") |
| 44 | + secret = get_config_value(APP_ID, "application", "secret") |
| 45 | + except KeyError as ke: |
| 46 | + raise Exception("get_token: required key missing in appId [%s]: %s" % (APP_ID, str(ke))) |
| 47 | + except Exception as e: |
| 48 | + raise Exception("get_token: failed to read clientId or secret for appId [%s]: %s" % (APP_ID, str(e))) |
| 49 | + |
| 50 | + return get_token_util.get_token(user, org, client_id, secret) |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + if len(sys.argv) != 3: |
| 55 | + sys.stderr.write("Usage: python custom_get_token_util.py <user> <org>\n") |
| 56 | + sys.exit(1) |
| 57 | + |
| 58 | + user = sys.argv[1] |
| 59 | + org = sys.argv[2] |
| 60 | + |
| 61 | + token = get_token(user, org) |
| 62 | + print(token) |
| 63 | + |
| 64 | + |
0 commit comments