forked from k-space/inventory-app
73 lines
2.2 KiB
Python
73 lines
2.2 KiB
Python
import os
|
|
import re
|
|
import const
|
|
from functools import wraps
|
|
from pymongo import MongoClient
|
|
from flask import Blueprint, abort, g, make_response, redirect, render_template, request, jsonify
|
|
from common import CustomForm, build_query, flatten, format_name, spam
|
|
from kubernetes import client, config
|
|
|
|
page_api = Blueprint("api", __name__)
|
|
db = MongoClient(const.MONGO_URI).get_default_database()
|
|
api_key = os.getenv("INVENTORY_API_KEY")
|
|
|
|
def check_api_key(f):
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
request_key = request.headers.get('Authorization', False)
|
|
if not request_key:
|
|
return "nope", 403
|
|
found_key = re.search(r"Basic (.*)", request_key).group(1)
|
|
if not found_key or found_key != api_key:
|
|
return "nope", 403
|
|
return f(*args, **kwargs)
|
|
return decorated_function
|
|
|
|
def get_users():
|
|
config.load_incluster_config()
|
|
api_instance = client.CustomObjectsApi()
|
|
ret = api_instance.list_namespaced_custom_object("codemowers.io", "v1alpha1", "default", "oidcgatewayusers")
|
|
resp = []
|
|
for item in ret["items"]:
|
|
resp.append(item)
|
|
return resp
|
|
|
|
@page_api.route("/users")
|
|
@check_api_key
|
|
def view_users():
|
|
resp = get_users()
|
|
print(resp)
|
|
return jsonify(resp)
|
|
|
|
@page_api.route("/cards", methods=["POST"])
|
|
@check_api_key
|
|
def get_group_cards():
|
|
groups = request.json.get("groups", False)
|
|
users = get_users()
|
|
print(groups)
|
|
print(users)
|
|
if not groups:
|
|
return "must specify groups in parameter", 400
|
|
gu = list(filter(lambda u: any(g["name"] in groups for g in u["status"]["groups"]), users))
|
|
print(gu)
|
|
keys = list(map(lambda u: u["metadata"]["name"], gu))
|
|
print(keys)
|
|
flt = {
|
|
"token.uid_hash": {"$exists": True},
|
|
"inventory.owner.username": {"$in": keys}
|
|
}
|
|
prj = {
|
|
"inventory.owner": True,
|
|
"token.uid_hash": True
|
|
}
|
|
found = []
|
|
for obj in db.inventory.find(flt, prj):
|
|
del obj["_id"]
|
|
if obj["inventory"] and obj["inventory"]["owner"] and type(obj["inventory"]["owner"]["foreign_id"]) != str:
|
|
del obj["inventory"]
|
|
found.append(obj)
|
|
fl = list(found)
|
|
print(fl)
|
|
return jsonify(fl)
|
|
|