def set_key(name, value): # get existing key apiKey = ApiKeys.query(ApiKeys.name == name).get() # update existing name if apiKey: apiKey.name = name apiKey.value = value # create new key else: apiKey = ApiKeys(name=name, value=value) apiKey.put() # save to memcache if not memcache.add(name, value): # update memcache memcache.set(key=name, value=value) return 'name=%s value=%s' % (name, value)
def get(self): """ Retrieve API key of the user --- tags: - User Management parameters: - in: body name: body schema: required: - user properties: user: type: string description: user of the SOCA user responses: 200: description: Return the token associated to the user 203: description: No token detected 400: description: Malformed client input """ parser = reqparse.RequestParser() parser.add_argument("user", type=str, location='args') args = parser.parse_args() user = args["user"] if user is None: return errors.all_errors("CLIENT_MISSING_PARAMETER", "user (str) parameter is required") try: check_existing_key = ApiKeys.query.filter_by(user=user, is_active=True).first() if check_existing_key: return {"success": True, "message": check_existing_key.token}, 200 else: try: # Create an API key for the user if needed user_exist = get(config.Config.FLASK_ENDPOINT + "/api/ldap/user", headers={"X-SOCA-TOKEN": config.Config.API_ROOT_KEY}, params={"user": user}, verify=False) # nosec if user_exist.status_code == 200: permissions = get(config.Config.FLASK_ENDPOINT + "/api/ldap/sudo", headers={"X-SOCA-TOKEN": config.Config.API_ROOT_KEY}, params={"user": user}, verify=False) # nosec if permissions.status_code == 200: scope = "sudo" else: scope = "user" api_token = secrets.token_hex(16) new_key = ApiKeys(user=user, token=api_token, is_active=True, scope=scope, created_on=datetime.datetime.utcnow()) db.session.add(new_key) db.session.commit() return {"success": True, "message": api_token}, 200 else: return {"success": False, "message": "Not authorized"}, 401 except Exception as err: return errors.all_errors(type(err).__name__, err) except Exception as err: return errors.all_errors(type(err).__name__, err)