def executer_data(): from app.models import Project, Datacenter, Group, Host if "projects" not in request.values: return json_response( { "errors": ["'projects' parameter is required for executer_data handler"] }, 400) project_names = request.values["projects"].split(",") projects = Project.find({"name": {"$in": project_names}}) projects = cursor_to_list(projects) project_ids = [x["_id"] for x in projects] groups = Group.find({"project_id": {"$in": project_ids}}) groups = cursor_to_list(groups) group_ids = [x["_id"] for x in groups] hosts = Host.find({"group_id": {"$in": group_ids}}) hosts = cursor_to_list(hosts) datacenters = Datacenter.find({}) datacenters = cursor_to_list(datacenters) results = { "datacenters": datacenters, "projects": projects, "groups": groups, "hosts": hosts } return json_response({"data": results})
def add_member(id): from app.models import Project, User project = Project.get(id) if project is None: return json_response({"errors": ["Project not found"]}, 404) if not project.member_list_modification_allowed: return json_response( { "errors": [ "You don't have permissions to modify the project member list" ] }, 403) if not "user_id" in request.json: return json_response({"errors": ["No user_id given in request data"]}, 400) member = User.find_one({"_id": request.json["user_id"]}) if member is None: return json_response({"errors": ["User not found"]}, 404) project.add_member(member) return json_response({"data": project.to_dict()})
def set_children(group_id): group = _get_group_by_id(group_id) if group is None: return json_response({ "errors": ["Group not found"] }, 404) # TODO: check permissions! orig = group.child_ids upd = request.json["child_ids"] try: upd = [ObjectId(x) for x in upd] except InvalidId as e: return json_exception(e, 400) d = diff(orig, upd) exs = [] for item in d.remove: try: group.remove_child(item) except Exception as e: exs.append(e) for item in d.add: try: group.add_child(item) except Exception as e: exs.append(e) if len(exs) > 0: return json_response({ "errors": ["%s: %s" % (x.__class__.__name__, x.message) for x in exs] }) else: if "_fields" in request.values: fields = request.values["_fields"].split(",") else: fields = None return json_response({ "data": group.to_dict(fields), "status": "ok" })
def create(): if not g.user.supervisor: return json_response({"errors":["You don't have permissions to create new users"]}) from app.models import User user_attrs = dict([(k, v) for k, v in request.json.items() if k in User.FIELDS]) if "password_hash" in user_attrs: del(user_attrs["password_hash"]) try: passwd = request.json["password_raw"] passwd_confirm = request.json["password_raw_confirm"] if passwd != passwd_confirm: return json_response({"errors":["Passwords don't match"]}, 400) user_attrs["password_raw"] = passwd except KeyError: pass try: existing = User.get(user_attrs["username"]) if existing is not None: return json_response({"errors":["User with such username already exists"]}, 409) except KeyError: return json_response({"errors":["You should provide username"]}, 400) new_user = User(**user_attrs) try: new_user.save() except Exception as e: return json_exception(e, 500) return json_response({"data": new_user.to_dict()})
def delete(group_id): group = _get_group_by_id(group_id) if group is None: return json_response({ "errors": ["Group not found"] }, 404) # TODO: check permissions! try: group.destroy() except Exception as e: return json_exception(e, 500) return json_response({ "data": group.to_dict() })
def delete(dc_id): dc = _get_dc_by_id(dc_id) if dc is None: return json_response({"errors": ["Datacenter not found"]}, 404) # TODO: check permissions! try: dc.destroy() except Exception as e: return json_exception(e, 500) return json_response({"data": dc.to_dict()})
def me(): if g.user is None: return json_response( { "errors": ["You must be authenticated first"], "state": "logged out" }, 403) else: user_data = g.user.to_dict() user_data["auth_token"] = g.user.get_auth_token().token return json_response({"data": user_data})
def me(): if g.user is None: return json_response( { "errors": ["You must be authenticated first"], "state": "logged out" }, 403) else: user_data = g.user.to_dict() if "password_hash" in user_data: del (user_data["password_hash"]) return json_response({"data": user_data})
def update(dc_id): dc = _get_dc_by_id(dc_id) if dc is None: return json_response({"errors": ["Datacenter not found"]}, 404) # TODO: check permissions! try: dc.update(request.json) except Exception as e: return json_exception(e, 500) if "parent_id" in request.json: parent_id = resolve_id(request.json["parent_id"]) if parent_id != dc.parent_id: return set_parent(dc._id) return json_response({"data": dc.to_dict()})
def update(group_id): group = _get_group_by_id(group_id) if group is None: return json_response({ "errors": ["Group not found"] }, 404) # TODO: check permissions! try: group.update(request.json) except Exception as e: return json_exception(e, 500) if "_fields" in request.values: fields = request.values["_fields"].split(",") else: fields = None return json_response({ "data": group.to_dict(fields) })
def delete(id): from app.models import Project id = resolve_id(id) project = Project.find_one({ "$or": [ { "_id": id }, { "name": id } ] }) if project is None: return json_response({ "errors": [ "Project not found" ]}, 404) # TODO check user supervisor privileges try: project.destroy() except Exception as e: return json_exception(e, 400) return json_response({ "data": project.to_dict(), "status": "deleted" })
def delete(user_id): from app.models import User user = User.get(user_id) if user is None: return json_response({"errors":["User not found"]}, 404) if not g.user.supervisor: return json_response({"errors":["You don't have permissions to delete this user"]}, 403) try: user.destroy() except Exception as e: return json_exception(e, 500) return json_response({"data":user.to_dict()})
def update(user_id): from app.models import User user = User.get(user_id) if user is None: return json_response({"errors":["User not found"]}, 404) if not user.modification_allowed: return json_response({"errors":["You don't have permissions to modificate this user"]}, 403) user_attrs = dict([(k, v) for k, v in request.json.items() if k in User.FIELDS]) try: user.update(user_attrs) except Exception as e: return json_exception(e, 500) return json_response({"data":user.to_dict()})
def delete(id): from app.models import Project project = Project.get(id) if project is None: return json_response({"errors": ["Project not found"]}, 404) if not project.modification_allowed: return json_response( {"errors": ["You don't have permissions to modify the project"]}, 403) try: project.destroy() except Exception as e: return json_exception(e, 400) return json_response({"data": project.to_dict(), "status": "deleted"})
def update(id): from app.models import Project data = clear_aux_fields(request.json) # TODO check user ownership of project id = resolve_id(id) project = Project.find_one({ "$or": [ { "_id": id }, { "name": id } ] }) if project is None: return json_response({ "errors": [ "Project not found" ]}, 404) try: project.update(data) except Exception as e: return json_exception(e, 500) return json_response({ "data": project.to_dict(), "status": "updated" })
def executer_data(): query = {} if "projects" in request.values: project_names = [ x for x in request.values["projects"].split(",") if x != "" ] if len(project_names) > 0: query["name"] = {"$in": project_names} recursive = False include_unattached = False if "recursive" in request.values: recursive = request.values["recursive"].lower() if recursive in ["1", "yes", "true"]: recursive = True else: recursive = False if "include_unattached" in request.values: include_unattached = request.values["include_unattached"].lower() if include_unattached in ["1", "yes", "true"]: include_unattached = True else: include_unattached = False results = get_executer_data(query, recursive, include_unattached) return json_response({"data": results})
def enc(host_id): from app.models import Host host_id = resolve_id(host_id) host = Host.find_one({ "$or": [{ "_id": host_id }, { "fqdn": host_id }, { "short_name": host_id }] }) if host is None: return json_response({"errors": ["Host not found"]}, 404) puppet_data = {"classes": [], "parameters": {}} for tag in host.all_tags: class_match = CLASS_EXPR.match(tag) if class_match is not None: puppet_data["classes"].append(class_match.groups()[0]) continue param_match = PARAM_EXPR.match(tag) if param_match is not None: k, v = param_match.groups() puppet_data["parameters"][k] = v continue env_match = ENV_EXPR.match(tag) if env_match is not None: puppet_data["environment"] = env_match.groups()[0] return yaml_response(puppet_data)
def delete(host_id): from app.models import Host host = Host.get(host_id) if host is None: return json_response({"errors": ["Host not found"]}, 404) if not host.destruction_allowed: return json_response( {"errors": ["You don't have permissions to delete this host"]}, 403) try: host.destroy() except Exception as e: return json_exception(e, 500) return json_response({"data": host.to_dict()})
def update(id): from app.models import Project data = clear_aux_fields(request.json) project = Project.get(id) if project is None: return json_response({"errors": ["Project not found"]}, 404) if not project.modification_allowed: return json_response( {"errors": ["You don't have permissions to modify the project"]}, 403) try: project.update(data) except Exception as e: return json_exception(e, 500) return json_response({"data": project.to_dict(), "status": "updated"})
def create(): from app.models import Host hosts_attrs = dict( [x for x in request.json.items() if x[0] in Host.FIELDS]) if "fqdn_pattern" in request.json: if "fqdn" in hosts_attrs: return json_response({ "errors": [ "fqdn field is not allowed due to fqdn_pattern param presence" ] }) try: hostnames = list(expand_pattern(request.json["fqdn_pattern"])) except Exception as e: return json_exception(e) else: hostnames = [hosts_attrs["fqdn"]] del (hosts_attrs["fqdn"]) try: hosts_attrs["group_id"] = ObjectId(hosts_attrs["group_id"]) except (KeyError, InvalidId): hosts_attrs["group_id"] = None try: hosts_attrs["datacenter_id"] = ObjectId(hosts_attrs["datacenter_id"]) except (KeyError, InvalidId): hosts_attrs["datacenter_id"] = None for fqdn in hostnames: attrs = hosts_attrs attrs["fqdn"] = fqdn host = Host(**attrs) try: host.save() except Exception as e: return json_exception(e, 500) hosts = Host.find({"fqdn": {"$in": list(hostnames)}}) try: data = paginated_data(hosts.sort("fqdn")) except AttributeError as e: return json_exception(e, 500) return json_response(data, 201)
def set_parent(dc_id): dc = _get_dc_by_id(dc_id) if dc is None: return json_response({"errors": ["Datacenter not found"]}, 404) # TODO: check permissions! parent_id = request.json.get("parent_id") if dc.parent: try: dc.unset_parent() except Exception as e: return json_exception(e, 500) if parent_id is not None: try: parent_id = resolve_id(parent_id) dc.set_parent(parent_id) except Exception as e: return json_exception(e, 500) return json_response({"data": dc.to_dict()})
def mass_detach(): if "host_ids" not in request.json or request.json["host_ids"] is None: return json_response({"errors": ["No host_ids provided"]}, 400) if type(request.json["host_ids"]) != list: return json_response({"errors": ["host_ids must be an array type"]}, 400) from app.models import Host # resolving hosts host_ids = [resolve_id(x) for x in request.json["host_ids"]] host_ids = set([x for x in host_ids if x is not None]) hosts = Host.find({"_id": {"$in": list(host_ids)}}).all() if len(hosts) == 0: return json_response({"errors": ["No hosts found to be moved"]}, 404) failed_hosts = [] for host in hosts: if not host.modification_allowed: failed_hosts.append(host) if len(failed_hosts) > 0: failed_hosts = ', '.join([h.fqdn for h in failed_hosts]) return json_response( { "errors": [ "You don't have permissions to modify hosts: %s" % failed_hosts ] }, 403) # moving hosts for host in hosts: host.group_id = None host.save() result = { "status": "ok", "data": { "hosts": [host.to_dict() for host in hosts] } } return json_response(result)
def set_current_user(self): g.user = self._get_user_from_session() or \ self._get_user_from_x_api_auth_token() or \ self._get_user_from_authorization_header() if g.user is None and self.require_auth: return json_response( { "errors": ["You must be authenticated first"], "state": "logged out" }, 403)
def set_current_user(self): from app.models import User user_id = session.get("user_id") g.user = None if user_id: user = User.find_one({ "_id": user_id }) if user: g.user = user if g.user is None and self.require_auth: return json_response({ "errors": [ "You must be authenticated first" ], "state": "logged out" }, 403)
def csrf_protect(): if request.method != "GET": token = session.get('_csrf_token', None) if not token or token != request.form.get('_csrf_token'): return json_response( { 'errors': [ 'request is not authorized: csrf token is invalid' ] }, 403)
def update(host_id): from app.models import Host host = Host.get(host_id) if host is None: return json_response({"errors": ["Host not found"]}, 404) if not host.modification_allowed: return json_response( {"errors": ["You don't have permissions to modify this host"]}, 403) from app.models import Host hosts_attrs = dict( [x for x in request.json.items() if x[0] in Host.FIELDS]) if "group_id" in hosts_attrs and hosts_attrs["group_id"] is not None: try: hosts_attrs["group_id"] = ObjectId(hosts_attrs["group_id"]) except InvalidId: hosts_attrs["group_id"] = None if "datacenter_id" in hosts_attrs and hosts_attrs[ "datacenter_id"] is not None: try: hosts_attrs["datacenter_id"] = ObjectId( hosts_attrs["datacenter_id"]) except InvalidId: hosts_attrs["datacenter_id"] = None try: host.update(hosts_attrs) except Exception as e: return json_exception(e, 500) if "_fields" in request.values: fields = request.values["_fields"].split(",") else: fields = None try: data = {"data": host.to_dict(fields)} except AttributeError as e: return json_exception(e, 500) return json_response(data)
def create(): from app.models import Group group_attrs = dict([x for x in request.json.items() if x[0] in Group.FIELDS]) if "project_id" not in group_attrs or group_attrs["project_id"] is None: return json_response({ "errors": [ "No project provided for the group" ] }, 400) try: group_attrs["project_id"] = ObjectId(group_attrs["project_id"]) except InvalidId as e: return json_response({ "errors": [ "Invalid project_id provided" ] }, 400) # TODO: check permissions! group = Group(**group_attrs) try: group.save() except Exception as e: return json_exception(e, 500) if "_fields" in request.values: fields = request.values["_fields"].split(",") else: fields = None return json_response({ "data": group.to_dict(fields) }, 201)
def show(project_id=None): from app.models import Project if project_id is None: query = {} if "_filter" in request.values: name_filter = request.values["_filter"] if len(name_filter) > 2: query["name"] = {"$regex": "^%s" % name_filter} projects = Project.find(query) else: project_id = resolve_id(project_id) projects = Project.find( {"$or": [{ "_id": project_id }, { "name": project_id }]}) if projects.count() == 0: return json_response({"errors": ["Project not found"]}, 404) return json_response(paginated_data(projects.sort("name")))
def set_password(user_id): from app.models import User user = User.get(user_id) if user is None: return json_response({"errors":["User not found"]}, 404) if not user.modification_allowed: return json_response({"errors":["You don't have permissions to modificate this user"]}, 403) try: passwd = request.json["password_raw"] passwd_confirm = request.json["password_raw_confirm"] if passwd != passwd_confirm: return json_response({"errors":["Passwords don't match"]}, 400) except KeyError: return json_response({"errors":["You should provide password_raw and password_raw_confirm fields"]}, 400) user.set_password(passwd) user.save() return json_response({"data":user.to_dict()})
def set_hosts(group_id): from app.models import Host group = _get_group_by_id(group_id) if group is None: return json_response({"errors": ["Group not found"]}, 404) # TODO: check permissions! orig = group.host_ids upd = request.json["host_ids"] try: upd = [ObjectId(x) for x in upd] except InvalidId as e: return json_exception(e, 400) d = diff(orig, upd) exs = [] for item in d.remove: try: h = Host.find_one({"_id": item}) if h is not None: h.group_id = None h.save() except Exception as e: exs.append(e) for item in d.add: try: h = Host.find_one({"_id": item}) if h is not None: h.group_id = group._id h.save() except Exception as e: exs.append(e) if len(exs) > 0: return json_response({ "errors": ["%s: %s" % (x.__class__.__name__, x.message) for x in exs] }) else: if "_fields" in request.values: fields = request.values["_fields"].split(",") else: fields = None return json_response({"data": group.to_dict(fields), "status": "ok"})