diff --git a/api/serializers.py b/api/serializers.py index 6a40d525..921a4ac6 100644 --- a/api/serializers.py +++ b/api/serializers.py @@ -24,11 +24,6 @@ from rest_framework import serializers -import cotisations.models as cotisations -import machines.models as machines -import preferences.models as preferences -import topologie.models as topologie -import users.models as users # The namespace used for the API. It must match the namespace used in the # urlpatterns to include the API URLs. @@ -66,1373 +61,5 @@ class NamespacedHMSerializer(serializers.HyperlinkedModelSerializer): serializer_url_field = NamespacedHIField -# COTISATIONS -class FactureSerializer(NamespacedHMSerializer): - """Serialize `cotisations.models.Facture` objects. - """ - - class Meta: - model = cotisations.Facture - fields = ( - "user", - "paiement", - "banque", - "cheque", - "date", - "valid", - "control", - "prix_total", - "name", - "api_url", - ) - - -class BaseInvoiceSerializer(NamespacedHMSerializer): - class Meta: - model = cotisations.BaseInvoice - fields = "__all__" - - -class VenteSerializer(NamespacedHMSerializer): - """Serialize `cotisations.models.Vente` objects. - """ - - class Meta: - model = cotisations.Vente - fields = ( - "facture", - "number", - "name", - "prix", - "duration", - "type_cotisation", - "prix_total", - "api_url", - ) - - -class ArticleSerializer(NamespacedHMSerializer): - """Serialize `cotisations.models.Article` objects. - """ - - class Meta: - model = cotisations.Article - fields = ("name", "prix", "duration", "type_user", "type_cotisation", "api_url") - - -class BanqueSerializer(NamespacedHMSerializer): - """Serialize `cotisations.models.Banque` objects. - """ - - class Meta: - model = cotisations.Banque - fields = ("name", "api_url") - - -class PaiementSerializer(NamespacedHMSerializer): - """Serialize `cotisations.models.Paiement` objects. - """ - - class Meta: - model = cotisations.Paiement - fields = ("moyen", "api_url") - - -class CotisationSerializer(NamespacedHMSerializer): - """Serialize `cotisations.models.Cotisation` objects. - """ - - class Meta: - model = cotisations.Cotisation - fields = ("vente", "type_cotisation", "date_start", "date_end", "api_url") - - -# MACHINES - - -class MachineSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Machine` objects. - """ - - class Meta: - model = machines.Machine - fields = ("user", "name", "active", "api_url") - - -class MachineTypeSerializer(NamespacedHMSerializer): - """Serialize `machines.models.MachineType` objects. - """ - - class Meta: - model = machines.MachineType - fields = ("name", "ip_type", "api_url") - - -class IpTypeSerializer(NamespacedHMSerializer): - """Serialize `machines.models.IpType` objects. - """ - - class Meta: - model = machines.IpType - fields = ( - "name", - "extension", - "need_infra", - "domaine_ip_start", - "domaine_ip_stop", - "prefix_v6", - "vlan", - "ouverture_ports", - "api_url", - ) - - -class VlanSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Vlan` objects. - """ - - class Meta: - model = machines.Vlan - fields = ( - "vlan_id", - "name", - "comment", - "arp_protect", - "dhcp_snooping", - "dhcpv6_snooping", - "igmp", - "mld", - "api_url", - ) - - -class NasSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Nas` objects. - """ - - class Meta: - model = machines.Nas - fields = ( - "name", - "nas_type", - "machine_type", - "port_access_mode", - "autocapture_mac", - "api_url", - ) - - -class SOASerializer(NamespacedHMSerializer): - """Serialize `machines.models.SOA` objects. - """ - - class Meta: - model = machines.SOA - fields = ("name", "mail", "refresh", "retry", "expire", "ttl", "api_url") - - -class ExtensionSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Extension` objects. - """ - - class Meta: - model = machines.Extension - fields = ("name", "need_infra", "origin", "origin_v6", "soa", "api_url") - - -class MxSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Mx` objects. - """ - - class Meta: - model = machines.Mx - fields = ("zone", "priority", "name", "api_url") - - -class DNameSerializer(NamespacedHMSerializer): - """Serialize `machines.models.DName` objects. - """ - - class Meta: - model = machines.DName - fields = ("zone", "alias", "api_url") - - -class NsSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Ns` objects. - """ - - class Meta: - model = machines.Ns - fields = ("zone", "ns", "api_url") - - -class TxtSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Txt` objects. - """ - - class Meta: - model = machines.Txt - fields = ("zone", "field1", "field2", "api_url") - - -class SrvSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Srv` objects. - """ - - class Meta: - model = machines.Srv - fields = ( - "service", - "protocole", - "extension", - "ttl", - "priority", - "weight", - "port", - "target", - "api_url", - ) - - -class SshFpSerializer(NamespacedHMSerializer): - """Serialize `machines.models.SSHFP` objects. - """ - - class Meta: - model = machines.SshFp - field = ("machine", "pub_key_entry", "algo", "comment", "api_url") - - -class InterfaceSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Interface` objects. - """ - - mac_address = serializers.CharField() - active = serializers.BooleanField(source="is_active") - - class Meta: - model = machines.Interface - fields = ( - "ipv4", - "mac_address", - "machine", - "machine_type", - "details", - "port_lists", - "active", - "api_url", - ) - - -class Ipv6ListSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Ipv6List` objects. - """ - - class Meta: - model = machines.Ipv6List - fields = ("ipv6", "interface", "slaac_ip", "api_url") - - -class DomainSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Domain` objects. - """ - - class Meta: - model = machines.Domain - fields = ("interface_parent", "name", "extension", "cname", "api_url", "ttl") - - -class IpListSerializer(NamespacedHMSerializer): - """Serialize `machines.models.IpList` objects. - """ - - class Meta: - model = machines.IpList - fields = ("ipv4", "ip_type", "need_infra", "api_url") - - -class ServiceSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Service` objects. - """ - - class Meta: - model = machines.Service - fields = ( - "service_type", - "min_time_regen", - "regular_time_regen", - "servers", - "api_url", - ) - - -class ServiceLinkSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Service_link` objects. - """ - - class Meta: - model = machines.Service_link - fields = ( - "service", - "server", - "last_regen", - "asked_regen", - "need_regen", - "api_url", - ) - extra_kwargs = {"api_url": {"view_name": "servicelink-detail"}} - - -class OuverturePortListSerializer(NamespacedHMSerializer): - """Serialize `machines.models.OuverturePortList` objects. - """ - - tcp_ports_in = NamespacedHRField( - view_name="ouvertureport-detail", many=True, read_only=True - ) - udp_ports_in = NamespacedHRField( - view_name="ouvertureport-detail", many=True, read_only=True - ) - tcp_ports_out = NamespacedHRField( - view_name="ouvertureport-detail", many=True, read_only=True - ) - udp_ports_out = NamespacedHRField( - view_name="ouvertureport-detail", many=True, read_only=True - ) - - class Meta: - model = machines.OuverturePortList - fields = ( - "name", - "tcp_ports_in", - "udp_ports_in", - "tcp_ports_out", - "udp_ports_out", - "api_url", - ) - - -class OuverturePortSerializer(NamespacedHMSerializer): - """Serialize `machines.models.OuverturePort` objects. - """ - - class Meta: - model = machines.OuverturePort - fields = ("begin", "end", "port_list", "protocole", "io", "api_url") - - -class RoleSerializer(NamespacedHMSerializer): - """Serialize `machines.models.OuverturePort` objects. - """ - - servers = InterfaceSerializer(read_only=True, many=True) - - class Meta: - model = machines.Role - fields = ("role_type", "servers", "api_url") - - -# PREFERENCES - - -class OptionalUserSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.OptionalUser` objects. - """ - - tel_mandatory = serializers.BooleanField(source="is_tel_mandatory") - shell_default = serializers.StringRelatedField() - - class Meta: - model = preferences.OptionalUser - fields = ( - "tel_mandatory", - "gpg_fingerprint", - "all_can_create_club", - "self_adhesion", - "shell_default", - "self_change_shell", - "local_email_accounts_enabled", - "local_email_domain", - "max_email_address", - ) - - -class OptionalMachineSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.OptionalMachine` objects. - """ - - class Meta: - model = preferences.OptionalMachine - fields = ( - "password_machine", - "max_lambdauser_interfaces", - "max_lambdauser_aliases", - "ipv6_mode", - "create_machine", - "ipv6", - "default_dns_ttl" - ) - - -class OptionalTopologieSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.OptionalTopologie` objects. - """ - - switchs_management_interface_ip = serializers.CharField() - - class Meta: - model = preferences.OptionalTopologie - fields = ( - "switchs_ip_type", - "switchs_web_management", - "switchs_web_management_ssl", - "switchs_rest_management", - "switchs_management_utils", - "switchs_management_interface_ip", - "provision_switchs_enabled", - "switchs_provision", - "switchs_management_sftp_creds", - ) - - -class RadiusOptionSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.RadiusOption` objects - """ - - class Meta: - model = preferences.RadiusOption - fields = ( - "radius_general_policy", - "unknown_machine", - "unknown_machine_vlan", - "unknown_port", - "unknown_port_vlan", - "unknown_room", - "unknown_room_vlan", - "non_member", - "non_member_vlan", - "banned", - "banned_vlan", - "vlan_decision_ok", - ) - - -class GeneralOptionSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.GeneralOption` objects. - """ - - class Meta: - model = preferences.GeneralOption - fields = ( - "general_message_fr", - "general_message_en", - "search_display_page", - "pagination_number", - "pagination_large_number", - "req_expire_hrs", - "site_name", - "main_site_url", - "email_from", - "GTU_sum_up", - "GTU", - ) - - -class HomeServiceSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.Service` objects. - """ - - class Meta: - model = preferences.Service - fields = ("name", "url", "description", "image", "api_url") - extra_kwargs = {"api_url": {"view_name": "homeservice-detail"}} - - -class AssoOptionSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.AssoOption` objects. - """ - - class Meta: - model = preferences.AssoOption - fields = ( - "name", - "siret", - "adresse1", - "adresse2", - "contact", - "telephone", - "pseudo", - "utilisateur_asso", - "description", - ) - - -class HomeOptionSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.HomeOption` objects. - """ - - class Meta: - model = preferences.HomeOption - fields = ("facebook_url", "twitter_url", "twitter_account_name") - - -class MailMessageOptionSerializer(NamespacedHMSerializer): - """Serialize `preferences.models.MailMessageOption` objects. - """ - - class Meta: - model = preferences.MailMessageOption - fields = ("welcome_mail_fr", "welcome_mail_en") - - -# TOPOLOGIE - - -class StackSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Stack` objects - """ - - class Meta: - model = topologie.Stack - fields = ( - "name", - "stack_id", - "details", - "member_id_min", - "member_id_max", - "api_url", - ) - - -class AccessPointSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.AccessPoint` objects - """ - - class Meta: - model = topologie.AccessPoint - fields = ("user", "name", "active", "location", "api_url") - - -class SwitchSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Switch` objects - """ - - port_amount = serializers.IntegerField(source="number") - - class Meta: - model = topologie.Switch - fields = ( - "user", - "name", - "active", - "port_amount", - "stack", - "stack_member_id", - "model", - "switchbay", - "api_url", - ) - - -class ServerSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Server` objects - """ - - class Meta: - model = topologie.Server - fields = ("user", "name", "active", "api_url") - - -class ModelSwitchSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.ModelSwitch` objects - """ - - class Meta: - model = topologie.ModelSwitch - fields = ("reference", "constructor", "api_url") - - -class ConstructorSwitchSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.ConstructorSwitch` objects - """ - - class Meta: - model = topologie.ConstructorSwitch - fields = ("name", "api_url") - - -class SwitchBaySerializer(NamespacedHMSerializer): - """Serialize `topologie.models.SwitchBay` objects - """ - - class Meta: - model = topologie.SwitchBay - fields = ("name", "building", "info", "api_url") - - -class BuildingSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Building` objects - """ - - class Meta: - model = topologie.Building - fields = ("name", "api_url") - - -class SwitchPortSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Port` objects - """ - - get_port_profile = NamespacedHIField(view_name="portprofile-detail", read_only=True) - - class Meta: - model = topologie.Port - fields = ( - "switch", - "port", - "room", - "machine_interface", - "related", - "custom_profile", - "state", - "get_port_profile", - "details", - "api_url", - ) - extra_kwargs = { - "related": {"view_name": "switchport-detail"}, - "api_url": {"view_name": "switchport-detail"}, - } - - -class PortProfileSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Room` objects - """ - - class Meta: - model = topologie.PortProfile - fields = ( - "name", - "profil_default", - "vlan_untagged", - "vlan_tagged", - "radius_type", - "radius_mode", - "speed", - "mac_limit", - "flow_control", - "dhcp_snooping", - "dhcpv6_snooping", - "dhcpv6_snooping", - "arp_protect", - "ra_guard", - "loop_protect", - "api_url", - ) - - -class RoomSerializer(NamespacedHMSerializer): - """Serialize `topologie.models.Room` objects - """ - - class Meta: - model = topologie.Room - fields = ("name", "details", "api_url") - - -class PortProfileSerializer(NamespacedHMSerializer): - vlan_untagged = VlanSerializer(read_only=True) - - class Meta: - model = topologie.PortProfile - fields = ( - "name", - "profil_default", - "vlan_untagged", - "vlan_tagged", - "radius_type", - "radius_mode", - "speed", - "mac_limit", - "flow_control", - "dhcp_snooping", - "dhcpv6_snooping", - "arp_protect", - "ra_guard", - "loop_protect", - "vlan_untagged", - "vlan_tagged", - ) - - -# USERS - - -class UserSerializer(NamespacedHMSerializer): - """Serialize `users.models.User` objects. - """ - - access = serializers.BooleanField(source="has_access") - uid = serializers.IntegerField(source="uid_number") - - class Meta: - model = users.User - fields = ( - "surname", - "pseudo", - "email", - "local_email_redirect", - "local_email_enabled", - "school", - "shell", - "comment", - "state", - "registered", - "telephone", - "solde", - "access", - "end_access", - "uid", - "class_type", - "api_url", - ) - extra_kwargs = {"shell": {"view_name": "shell-detail"}} - - -class ClubSerializer(NamespacedHMSerializer): - """Serialize `users.models.Club` objects. - """ - - name = serializers.CharField(source="surname") - access = serializers.BooleanField(source="has_access") - uid = serializers.IntegerField(source="uid_number") - - class Meta: - model = users.Club - fields = ( - "name", - "pseudo", - "email", - "local_email_redirect", - "local_email_enabled", - "school", - "shell", - "comment", - "state", - "registered", - "telephone", - "solde", - "room", - "access", - "end_access", - "administrators", - "members", - "mailing", - "uid", - "api_url", - ) - extra_kwargs = {"shell": {"view_name": "shell-detail"}} - - -class AdherentSerializer(NamespacedHMSerializer): - """Serialize `users.models.Adherent` objects. - """ - - access = serializers.BooleanField(source="has_access") - uid = serializers.IntegerField(source="uid_number") - - class Meta: - model = users.Adherent - fields = ( - "name", - "surname", - "pseudo", - "email", - "local_email_redirect", - "local_email_enabled", - "school", - "shell", - "comment", - "state", - "registered", - "telephone", - "room", - "solde", - "access", - "end_access", - "uid", - "api_url", - "gid", - ) - extra_kwargs = {"shell": {"view_name": "shell-detail"}} - - -class BasicUserSerializer(NamespacedHMSerializer): - """Serialize 'users.models.User' minimal infos""" - - uid = serializers.IntegerField(source="uid_number") - gid = serializers.IntegerField(source="gid_number") - - class Meta: - model = users.User - fields = ("pseudo", "uid", "gid") - - -class ServiceUserSerializer(NamespacedHMSerializer): - """Serialize `users.models.ServiceUser` objects. - """ - - class Meta: - model = users.ServiceUser - fields = ("pseudo", "access_group", "comment", "api_url") - - -class SchoolSerializer(NamespacedHMSerializer): - """Serialize `users.models.School` objects. - """ - - class Meta: - model = users.School - fields = ("name", "api_url") - - -class ListRightSerializer(NamespacedHMSerializer): - """Serialize `users.models.ListRight` objects. - """ - - class Meta: - model = users.ListRight - fields = ("unix_name", "gid", "critical", "details", "api_url") - - -class ShellSerializer(NamespacedHMSerializer): - """Serialize `users.models.ListShell` objects. - """ - - class Meta: - model = users.ListShell - fields = ("shell", "api_url") - extra_kwargs = {"api_url": {"view_name": "shell-detail"}} - - -class BanSerializer(NamespacedHMSerializer): - """Serialize `users.models.Ban` objects. - """ - - active = serializers.BooleanField(source="is_active") - - class Meta: - model = users.Ban - fields = ( - "user", - "raison", - "date_start", - "date_end", - "state", - "active", - "api_url", - ) - - -class WhitelistSerializer(NamespacedHMSerializer): - """Serialize `users.models.Whitelist` objects. - """ - - active = serializers.BooleanField(source="is_active") - - class Meta: - model = users.Whitelist - fields = ("user", "raison", "date_start", "date_end", "active", "api_url") - - -class EMailAddressSerializer(NamespacedHMSerializer): - """Serialize `users.models.EMailAddress` objects. - """ - - user = serializers.CharField(source="user.pseudo", read_only=True) - - class Meta: - model = users.EMailAddress - fields = ("user", "local_part", "complete_email_address", "api_url") - - -# SERVICE REGEN - - -class ServiceRegenSerializer(NamespacedHMSerializer): - """Serialize the data about the services to regen. - """ - - hostname = serializers.CharField(source="server.domain.name", read_only=True) - service_name = serializers.CharField(source="service.service_type", read_only=True) - need_regen = serializers.BooleanField() - - class Meta: - model = machines.Service_link - fields = ("hostname", "service_name", "need_regen", "api_url") - extra_kwargs = {"api_url": {"view_name": "serviceregen-detail"}} - - -# Switches et ports - - -class InterfaceVlanSerializer(NamespacedHMSerializer): - domain = serializers.CharField(read_only=True) - ipv4 = serializers.CharField(read_only=True) - ipv6 = Ipv6ListSerializer(read_only=True, many=True) - vlan_id = serializers.IntegerField( - source="machine_type.ip_type.vlan.vlan_id", read_only=True - ) - - class Meta: - model = machines.Interface - fields = ("ipv4", "ipv6", "domain", "vlan_id") - - -class InterfaceRoleSerializer(NamespacedHMSerializer): - interface = InterfaceVlanSerializer( - source="machine.interface_set", read_only=True, many=True - ) - - class Meta: - model = machines.Interface - fields = ("interface",) - - -class RoleSerializer(NamespacedHMSerializer): - """Serialize `machines.models.OuverturePort` objects. - """ - - servers = InterfaceRoleSerializer(read_only=True, many=True) - - class Meta: - model = machines.Role - fields = ("role_type", "servers", "specific_role") - - -class VlanPortSerializer(NamespacedHMSerializer): - class Meta: - model = machines.Vlan - fields = ("vlan_id", "name") - - -class ProfilSerializer(NamespacedHMSerializer): - vlan_untagged = VlanSerializer(read_only=True) - vlan_tagged = VlanPortSerializer(read_only=True, many=True) - - class Meta: - model = topologie.PortProfile - fields = ( - "name", - "profil_default", - "vlan_untagged", - "vlan_tagged", - "radius_type", - "radius_mode", - "speed", - "mac_limit", - "flow_control", - "dhcp_snooping", - "dhcpv6_snooping", - "arp_protect", - "ra_guard", - "loop_protect", - "vlan_untagged", - "vlan_tagged", - ) - - -class ModelSwitchSerializer(NamespacedHMSerializer): - constructor = serializers.CharField(read_only=True) - - class Meta: - model = topologie.ModelSwitch - fields = ("reference", "firmware", "constructor") - - -class SwitchBaySerializer(NamespacedHMSerializer): - class Meta: - model = topologie.SwitchBay - fields = ("name",) - - -class PortsSerializer(NamespacedHMSerializer): - """Serialize `machines.models.Ipv6List` objects. - """ - - get_port_profile = ProfilSerializer(read_only=True) - - class Meta: - model = topologie.Port - fields = ("state", "port", "pretty_name", "get_port_profile") - - -class SwitchPortSerializer(serializers.ModelSerializer): - """Serialize the data about the switches""" - - ports = PortsSerializer(many=True, read_only=True) - model = ModelSwitchSerializer(read_only=True) - switchbay = SwitchBaySerializer(read_only=True) - - class Meta: - model = topologie.Switch - fields = ( - "short_name", - "model", - "switchbay", - "ports", - "ipv4", - "ipv6", - "interfaces_subnet", - "interfaces6_subnet", - "automatic_provision", - "rest_enabled", - "web_management_enabled", - "get_radius_key_value", - "get_management_cred_value", - "get_radius_servers", - "list_modules", - ) - - -# LOCAL EMAILS - - -class LocalEmailUsersSerializer(NamespacedHMSerializer): - email_address = EMailAddressSerializer(read_only=True, many=True) - - class Meta: - model = users.User - fields = ( - "local_email_enabled", - "local_email_redirect", - "email_address", - "email", - ) - - -# Firewall - - -class FirewallPortListSerializer(serializers.ModelSerializer): - class Meta: - model = machines.OuverturePort - fields = ("begin", "end", "protocole", "io", "show_port") - - -class FirewallOuverturePortListSerializer(serializers.ModelSerializer): - tcp_ports_in = FirewallPortListSerializer(many=True, read_only=True) - udp_ports_in = FirewallPortListSerializer(many=True, read_only=True) - tcp_ports_out = FirewallPortListSerializer(many=True, read_only=True) - udp_ports_out = FirewallPortListSerializer(many=True, read_only=True) - - class Meta: - model = machines.OuverturePortList - fields = ("tcp_ports_in", "udp_ports_in", "tcp_ports_out", "udp_ports_out") - - -class SubnetPortsOpenSerializer(serializers.ModelSerializer): - ouverture_ports = FirewallOuverturePortListSerializer(read_only=True) - - class Meta: - model = machines.IpType - fields = ( - "name", - "domaine_ip_start", - "domaine_ip_stop", - "complete_prefixv6", - "ouverture_ports", - ) - - -class InterfacePortsOpenSerializer(serializers.ModelSerializer): - port_lists = FirewallOuverturePortListSerializer(read_only=True, many=True) - ipv4 = serializers.CharField(source="ipv4.ipv4", read_only=True) - ipv6 = Ipv6ListSerializer(many=True, read_only=True) - - class Meta: - model = machines.Interface - fields = ("port_lists", "ipv4", "ipv6") - - -# DHCP - - -class HostMacIpSerializer(serializers.ModelSerializer): - """Serialize the data about the hostname-ipv4-mac address association - to build the DHCP lease files. - """ - - hostname = serializers.CharField(source="domain.name", read_only=True) - extension = serializers.CharField(source="domain.extension.name", read_only=True) - mac_address = serializers.CharField(read_only=True) - ip_type = serializers.CharField(source="machine_type.ip_type", read_only=True) - ipv4 = serializers.CharField(source="ipv4.ipv4", read_only=True) - - class Meta: - model = machines.Interface - fields = ("hostname", "extension", "mac_address", "ipv4", "ip_type") - - -# DNS - - -class SOARecordSerializer(SOASerializer): - """Serialize `machines.models.SOA` objects with the data needed to - generate a SOA DNS record. - """ - - class Meta: - model = machines.SOA - fields = ("name", "mail", "refresh", "retry", "expire", "ttl") - - -class OriginV4RecordSerializer(IpListSerializer): - """Serialize `machines.models.IpList` objects with the data needed to - generate an IPv4 Origin DNS record. - """ - - class Meta(IpListSerializer.Meta): - fields = ("ipv4",) - - -class NSRecordSerializer(NsSerializer): - """Serialize `machines.models.Ns` objects with the data needed to - generate a NS DNS record. - """ - - target = serializers.CharField(source="ns", read_only=True) - - class Meta(NsSerializer.Meta): - fields = ("target", "ttl") - - -class MXRecordSerializer(MxSerializer): - """Serialize `machines.models.Mx` objects with the data needed to - generate a MX DNS record. - """ - - target = serializers.CharField(source="name", read_only=True) - - class Meta(MxSerializer.Meta): - fields = ("target", "priority", "ttl") - - -class TXTRecordSerializer(TxtSerializer): - """Serialize `machines.models.Txt` objects with the data needed to - generate a TXT DNS record. - """ - - class Meta(TxtSerializer.Meta): - fields = ("field1", "field2", "ttl") - - -class SRVRecordSerializer(SrvSerializer): - """Serialize `machines.models.Srv` objects with the data needed to - generate a SRV DNS record. - """ - - target = serializers.CharField(source="target.name", read_only=True) - - class Meta(SrvSerializer.Meta): - fields = ("service", "protocole", "ttl", "priority", "weight", "port", "target") - - -class SSHFPRecordSerializer(SshFpSerializer): - """Serialize `machines.models.SshFp` objects with the data needed to - generate a SSHFP DNS record. - """ - - class Meta(SshFpSerializer.Meta): - fields = ("algo_id", "hash") - - -class SSHFPInterfaceSerializer(serializers.ModelSerializer): - """Serialize `machines.models.Domain` objects with the data needed to - generate a CNAME DNS record. - """ - - hostname = serializers.CharField(source="domain.name", read_only=True) - sshfp = SSHFPRecordSerializer(source="machine.sshfp_set", many=True, read_only=True) - - class Meta: - model = machines.Interface - fields = ("hostname", "sshfp") - - -class ARecordSerializer(serializers.ModelSerializer): - """Serialize `machines.models.Interface` objects with the data needed to - generate a A DNS record. - """ - - hostname = serializers.CharField(source="domain.name", read_only=True) - ipv4 = serializers.CharField(source="ipv4.ipv4", read_only=True) - ttl = serializers.IntegerField(source="domain.ttl", read_only=True) - - class Meta: - model = machines.Interface - fields = ("hostname", "ipv4", "ttl") - - -class AAAARecordSerializer(serializers.ModelSerializer): - """Serialize `machines.models.Interface` objects with the data needed to - generate a AAAA DNS record. - """ - - hostname = serializers.CharField(source="domain.name", read_only=True) - ipv6 = Ipv6ListSerializer(many=True, read_only=True) - ttl = serializers.IntegerField(source="domain.ttl", read_only=True) - - class Meta: - model = machines.Interface - fields = ("hostname", "ipv6", "ttl") - - -class CNAMERecordSerializer(serializers.ModelSerializer): - """Serialize `machines.models.Domain` objects with the data needed to - generate a CNAME DNS record. - """ - - alias = serializers.CharField(source="cname", read_only=True) - hostname = serializers.CharField(source="name", read_only=True) - - class Meta: - model = machines.Domain - fields = ("alias", "hostname", "ttl") - - -class DNAMERecordSerializer(serializers.ModelSerializer): - """Serialize `machines.models.Domain` objects with the data needed to - generate a DNAME DNS record. - """ - - alias = serializers.CharField(read_only=True) - zone = serializers.CharField(read_only=True) - - class Meta: - model = machines.DName - fields = ("alias", "zone", "ttl") - - -class DNSZonesSerializer(serializers.ModelSerializer): - """Serialize the data about DNS Zones. - """ - - soa = SOARecordSerializer() - ns_records = NSRecordSerializer(many=True, source="ns_set") - originv4 = OriginV4RecordSerializer(source="origin") - originv6 = serializers.CharField(source="origin_v6") - mx_records = MXRecordSerializer(many=True, source="mx_set") - txt_records = TXTRecordSerializer(many=True, source="txt_set") - srv_records = SRVRecordSerializer(many=True, source="srv_set") - a_records = ARecordSerializer(many=True, source="get_associated_a_records") - aaaa_records = AAAARecordSerializer(many=True, source="get_associated_aaaa_records") - cname_records = CNAMERecordSerializer( - many=True, source="get_associated_cname_records" - ) - dname_records = DNAMERecordSerializer( - many=True, source="get_associated_dname_records" - ) - sshfp_records = SSHFPInterfaceSerializer( - many=True, source="get_associated_sshfp_records" - ) - - class Meta: - model = machines.Extension - fields = ( - "name", - "soa", - "ns_records", - "originv4", - "originv6", - "mx_records", - "txt_records", - "srv_records", - "a_records", - "aaaa_records", - "cname_records", - "dname_records", - "sshfp_records", - ) - - -# REMINDER - - -class ReminderUsersSerializer(UserSerializer): - """Serialize the data about a mailing member. - """ - - class Meta(UserSerializer.Meta): - fields = ("get_full_name", "get_mail") - - -class ReminderSerializer(serializers.ModelSerializer): - """ - Serialize the data about a reminder - """ - - users_to_remind = ReminderUsersSerializer(many=True) - - class Meta: - model = preferences.Reminder - fields = ("days", "message", "users_to_remind") - - -class DNSReverseZonesSerializer(serializers.ModelSerializer): - """Serialize the data about DNS Zones. - """ - - soa = SOARecordSerializer(source="extension.soa") - extension = serializers.CharField(source="extension.name", read_only=True) - cidrs = serializers.ListField( - child=serializers.CharField(), source="ip_set_cidrs_as_str", read_only=True - ) - ns_records = NSRecordSerializer(many=True, source="extension.ns_set") - mx_records = MXRecordSerializer(many=True, source="extension.mx_set") - txt_records = TXTRecordSerializer(many=True, source="extension.txt_set") - ptr_records = ARecordSerializer(many=True, source="get_associated_ptr_records") - ptr_v6_records = AAAARecordSerializer( - many=True, source="get_associated_ptr_v6_records" - ) - - class Meta: - model = machines.IpType - fields = ( - "name", - "extension", - "soa", - "ns_records", - "mx_records", - "txt_records", - "ptr_records", - "ptr_v6_records", - "cidrs", - "prefix_v6", - "prefix_v6_length", - ) - - -# MAILING - - -class MailingMemberSerializer(UserSerializer): - """Serialize the data about a mailing member. - """ - - class Meta(UserSerializer.Meta): - fields = ("name", "pseudo", "get_mail") - - -class MailingSerializer(ClubSerializer): - """Serialize the data about a mailing. - """ - - members = MailingMemberSerializer(many=True) - admins = MailingMemberSerializer(source="administrators", many=True) - - class Meta(ClubSerializer.Meta): - fields = ("name", "members", "admins") diff --git a/api/urls.py b/api/urls.py index 6c2bd4c2..624b838b 100644 --- a/api/urls.py +++ b/api/urls.py @@ -28,114 +28,35 @@ can be generated automatically. """ from django.conf.urls import url, include +from importlib import import_module from . import views from .routers import AllViewsRouter +from django.conf import settings router = AllViewsRouter() -# COTISATIONS -router.register_viewset(r"cotisations/facture", views.FactureViewSet) -router.register_viewset(r"cotisations/vente", views.VenteViewSet) -router.register_viewset(r"cotisations/article", views.ArticleViewSet) -router.register_viewset(r"cotisations/banque", views.BanqueViewSet) -router.register_viewset(r"cotisations/paiement", views.PaiementViewSet) -router.register_viewset(r"cotisations/cotisation", views.CotisationViewSet) -# MACHINES -router.register_viewset(r"machines/machine", views.MachineViewSet) -router.register_viewset(r"machines/machinetype", views.MachineTypeViewSet) -router.register_viewset(r"machines/iptype", views.IpTypeViewSet) -router.register_viewset(r"machines/vlan", views.VlanViewSet) -router.register_viewset(r"machines/nas", views.NasViewSet) -router.register_viewset(r"machines/soa", views.SOAViewSet) -router.register_viewset(r"machines/extension", views.ExtensionViewSet) -router.register_viewset(r"machines/mx", views.MxViewSet) -router.register_viewset(r"machines/ns", views.NsViewSet) -router.register_viewset(r"machines/txt", views.TxtViewSet) -router.register_viewset(r"machines/dname", views.DNameViewSet) -router.register_viewset(r"machines/srv", views.SrvViewSet) -router.register_viewset(r"machines/sshfp", views.SshFpViewSet) -router.register_viewset(r"machines/interface", views.InterfaceViewSet) -router.register_viewset(r"machines/ipv6list", views.Ipv6ListViewSet) -router.register_viewset(r"machines/domain", views.DomainViewSet) -router.register_viewset(r"machines/iplist", views.IpListViewSet) -router.register_viewset(r"machines/service", views.ServiceViewSet) -router.register_viewset( - r"machines/servicelink", views.ServiceLinkViewSet, base_name="servicelink" -) -router.register_viewset(r"machines/ouvertureportlist", views.OuverturePortListViewSet) -router.register_viewset(r"machines/ouvertureport", views.OuverturePortViewSet) -router.register_viewset(r"machines/role", views.RoleViewSet) -# PREFERENCES -router.register_view(r"preferences/optionaluser", views.OptionalUserView), -router.register_view(r"preferences/optionalmachine", views.OptionalMachineView), -router.register_view(r"preferences/optionaltopologie", views.OptionalTopologieView), -router.register_view(r"preferences/radiusoption", views.RadiusOptionView), -router.register_view(r"preferences/generaloption", views.GeneralOptionView), -router.register_viewset( - r"preferences/service", views.HomeServiceViewSet, base_name="homeservice" -), -router.register_view(r"preferences/assooption", views.AssoOptionView), -router.register_view(r"preferences/homeoption", views.HomeOptionView), -router.register_view(r"preferences/mailmessageoption", views.MailMessageOptionView), -# TOPOLOGIE -router.register_viewset(r"topologie/stack", views.StackViewSet) -router.register_viewset(r"topologie/acesspoint", views.AccessPointViewSet) -router.register_viewset(r"topologie/switch", views.SwitchViewSet) -router.register_viewset(r"topologie/server", views.ServerViewSet) -router.register_viewset(r"topologie/modelswitch", views.ModelSwitchViewSet) -router.register_viewset(r"topologie/constructorswitch", views.ConstructorSwitchViewSet) -router.register_viewset(r"topologie/switchbay", views.SwitchBayViewSet) -router.register_viewset(r"topologie/building", views.BuildingViewSet) -router.register_viewset( - r"topologie/switchport", views.SwitchPortViewSet, base_name="switchport" -) -router.register_viewset( - r"topologie/portprofile", views.PortProfileViewSet, base_name="portprofile" -) -router.register_viewset(r"topologie/room", views.RoomViewSet) -router.register(r"topologie/portprofile", views.PortProfileViewSet) -# USERS -router.register_viewset(r"users/user", views.UserViewSet, base_name="user") -router.register_viewset( - r"users/homecreation", views.HomeCreationViewSet, base_name="homecreation" -) -router.register_viewset( - r"users/normaluser", views.NormalUserViewSet, base_name="normaluser" -) -router.register_viewset( - r"users/criticaluser", views.CriticalUserViewSet, base_name="criticaluser" -) -router.register_viewset(r"users/club", views.ClubViewSet) -router.register_viewset(r"users/adherent", views.AdherentViewSet) -router.register_viewset(r"users/serviceuser", views.ServiceUserViewSet) -router.register_viewset(r"users/school", views.SchoolViewSet) -router.register_viewset(r"users/listright", views.ListRightViewSet) -router.register_viewset(r"users/shell", views.ShellViewSet, base_name="shell") -router.register_viewset(r"users/ban", views.BanViewSet) -router.register_viewset(r"users/whitelist", views.WhitelistViewSet) -router.register_viewset(r"users/emailaddress", views.EMailAddressViewSet) -# SERVICE REGEN -router.register_viewset( - r"services/regen", views.ServiceRegenViewSet, base_name="serviceregen" -) -# DHCP -router.register_view(r"dhcp/hostmacip", views.HostMacIpView), -# LOCAL EMAILS -router.register_view(r"localemail/users", views.LocalEmailUsersView), -# Firewall -router.register_view(r"firewall/subnet-ports", views.SubnetPortsOpenView), -router.register_view(r"firewall/interface-ports", views.InterfacePortsOpenView), -# Switches config -router.register_view(r"switchs/ports-config", views.SwitchPortView), -router.register_view(r"switchs/role", views.RoleView), -# Reminder -router.register_view(r"reminder/get-users", views.ReminderView), -# DNS -router.register_view(r"dns/zones", views.DNSZonesView), -router.register_view(r"dns/reverse-zones", views.DNSReverseZonesView), -# MAILING -router.register_view(r"mailing/standard", views.StandardMailingView), -router.register_view(r"mailing/club", views.ClubMailingView), + +urls_viewset = [] +urls_view = [] + +for app in settings.INSTALLED_APPS: + try: + module = import_module(".api.urls", package=app) + urls_viewset += getattr(module, "urls_viewset", []) + urls_view += getattr(module, "urls_view", []) + except ImportError: + continue + +for _url, viewset, name in urls_viewset: + if name == None: + router.register_viewset(_url, viewset) + else: + router.register_viewset(_url, viewset, basename=name) + +for _url, view in urls_view: + router.register_view(_url, view) + + # TOKEN AUTHENTICATION router.register_view(r"token-auth", views.ObtainExpiringAuthToken) diff --git a/api/views.py b/api/views.py index 4077eeeb..4ab37609 100644 --- a/api/views.py +++ b/api/views.py @@ -36,755 +36,11 @@ from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.response import Response -import cotisations.models as cotisations -import machines.models as machines -import preferences.models as preferences -import topologie.models as topologie -import users.models as users -from re2o.utils import all_active_interfaces, all_has_access from . import serializers from .pagination import PageSizedPagination from .permissions import ACLPermission -# COTISATIONS - - -class FactureViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Facture` objects. - """ - - queryset = cotisations.Facture.objects.all() - serializer_class = serializers.FactureSerializer - - -class FactureViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Facture` objects. - """ - - queryset = cotisations.BaseInvoice.objects.all() - serializer_class = serializers.BaseInvoiceSerializer - - -class VenteViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Vente` objects. - """ - - queryset = cotisations.Vente.objects.all() - serializer_class = serializers.VenteSerializer - - -class ArticleViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Article` objects. - """ - - queryset = cotisations.Article.objects.all() - serializer_class = serializers.ArticleSerializer - - -class BanqueViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Banque` objects. - """ - - queryset = cotisations.Banque.objects.all() - serializer_class = serializers.BanqueSerializer - - -class PaiementViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Paiement` objects. - """ - - queryset = cotisations.Paiement.objects.all() - serializer_class = serializers.PaiementSerializer - - -class CotisationViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `cotisations.models.Cotisation` objects. - """ - - queryset = cotisations.Cotisation.objects.all() - serializer_class = serializers.CotisationSerializer - - -# MACHINES - - -class MachineViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Machine` objects. - """ - - queryset = machines.Machine.objects.all() - serializer_class = serializers.MachineSerializer - - -class MachineTypeViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.MachineType` objects. - """ - - queryset = machines.MachineType.objects.all() - serializer_class = serializers.MachineTypeSerializer - - -class IpTypeViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.IpType` objects. - """ - - queryset = machines.IpType.objects.all() - serializer_class = serializers.IpTypeSerializer - - -class VlanViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Vlan` objects. - """ - - queryset = machines.Vlan.objects.all() - serializer_class = serializers.VlanSerializer - - -class NasViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Nas` objects. - """ - - queryset = machines.Nas.objects.all() - serializer_class = serializers.NasSerializer - - -class SOAViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.SOA` objects. - """ - - queryset = machines.SOA.objects.all() - serializer_class = serializers.SOASerializer - - -class ExtensionViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Extension` objects. - """ - - queryset = machines.Extension.objects.all() - serializer_class = serializers.ExtensionSerializer - - -class MxViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Mx` objects. - """ - - queryset = machines.Mx.objects.all() - serializer_class = serializers.MxSerializer - - -class NsViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Ns` objects. - """ - - queryset = machines.Ns.objects.all() - serializer_class = serializers.NsSerializer - - -class TxtViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Txt` objects. - """ - - queryset = machines.Txt.objects.all() - serializer_class = serializers.TxtSerializer - - -class DNameViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.DName` objects. - """ - - queryset = machines.DName.objects.all() - serializer_class = serializers.DNameSerializer - - -class SrvViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Srv` objects. - """ - - queryset = machines.Srv.objects.all() - serializer_class = serializers.SrvSerializer - - -class SshFpViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.SshFp` objects. - """ - - queryset = machines.SshFp.objects.all() - serializer_class = serializers.SshFpSerializer - - -class InterfaceViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Interface` objects. - """ - - queryset = machines.Interface.objects.all() - serializer_class = serializers.InterfaceSerializer - - -class Ipv6ListViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Ipv6List` objects. - """ - - queryset = machines.Ipv6List.objects.all() - serializer_class = serializers.Ipv6ListSerializer - - -class DomainViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Domain` objects. - """ - - queryset = machines.Domain.objects.all() - serializer_class = serializers.DomainSerializer - - -class IpListViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.IpList` objects. - """ - - queryset = machines.IpList.objects.all() - serializer_class = serializers.IpListSerializer - - -class ServiceViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Service` objects. - """ - - queryset = machines.Service.objects.all() - serializer_class = serializers.ServiceSerializer - - -class ServiceLinkViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Service_link` objects. - """ - - queryset = machines.Service_link.objects.all() - serializer_class = serializers.ServiceLinkSerializer - - -class OuverturePortListViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.OuverturePortList` - objects. - """ - - queryset = machines.OuverturePortList.objects.all() - serializer_class = serializers.OuverturePortListSerializer - - -class OuverturePortViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.OuverturePort` objects. - """ - - queryset = machines.OuverturePort.objects.all() - serializer_class = serializers.OuverturePortSerializer - - -class RoleViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `machines.models.Machine` objects. - """ - - queryset = machines.Role.objects.all() - serializer_class = serializers.RoleSerializer - - -# PREFERENCES -# Those views differ a bit because there is only one object -# to display, so we don't bother with the listing part - - -class OptionalUserView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.OptionalUser.can_view_all]} - serializer_class = serializers.OptionalUserSerializer - - def get_object(self): - return preferences.OptionalUser.objects.first() - - -class OptionalMachineView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.OptionalMachine` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.OptionalMachine.can_view_all]} - serializer_class = serializers.OptionalMachineSerializer - - def get_object(self): - return preferences.OptionalMachine.objects.first() - - -class OptionalTopologieView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.OptionalTopologie` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.OptionalTopologie.can_view_all]} - serializer_class = serializers.OptionalTopologieSerializer - - def get_object(self): - return preferences.OptionalTopologie.objects.first() - - -class RadiusOptionView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.OptionalTopologie` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.RadiusOption.can_view_all]} - serializer_class = serializers.RadiusOptionSerializer - - def get_object(self): - return preferences.RadiusOption.objects.first() - - -class GeneralOptionView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.GeneralOption` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.GeneralOption.can_view_all]} - serializer_class = serializers.GeneralOptionSerializer - - def get_object(self): - return preferences.GeneralOption.objects.first() - - -class HomeServiceViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `preferences.models.Service` objects. - """ - - queryset = preferences.Service.objects.all() - serializer_class = serializers.HomeServiceSerializer - - -class AssoOptionView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.AssoOption` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.AssoOption.can_view_all]} - serializer_class = serializers.AssoOptionSerializer - - def get_object(self): - return preferences.AssoOption.objects.first() - - -class HomeOptionView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.HomeOption` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.HomeOption.can_view_all]} - serializer_class = serializers.HomeOptionSerializer - - def get_object(self): - return preferences.HomeOption.objects.first() - - -class MailMessageOptionView(generics.RetrieveAPIView): - """Exposes details of `preferences.models.MailMessageOption` settings. - """ - - permission_classes = (ACLPermission,) - perms_map = {"GET": [preferences.MailMessageOption.can_view_all]} - serializer_class = serializers.MailMessageOptionSerializer - - def get_object(self): - return preferences.MailMessageOption.objects.first() - - -# TOPOLOGIE - - -class StackViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.Stack` objects. - """ - - queryset = topologie.Stack.objects.all() - serializer_class = serializers.StackSerializer - - -class AccessPointViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.AccessPoint` objects. - """ - - queryset = topologie.AccessPoint.objects.all() - serializer_class = serializers.AccessPointSerializer - - -class SwitchViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.Switch` objects. - """ - - queryset = topologie.Switch.objects.all() - serializer_class = serializers.SwitchSerializer - - -class ServerViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.Server` objects. - """ - - queryset = topologie.Server.objects.all() - serializer_class = serializers.ServerSerializer - - -class ModelSwitchViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.ModelSwitch` objects. - """ - - queryset = topologie.ModelSwitch.objects.all() - serializer_class = serializers.ModelSwitchSerializer - - -class ConstructorSwitchViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.ConstructorSwitch` - objects. - """ - - queryset = topologie.ConstructorSwitch.objects.all() - serializer_class = serializers.ConstructorSwitchSerializer - - -class SwitchBayViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.SwitchBay` objects. - """ - - queryset = topologie.SwitchBay.objects.all() - serializer_class = serializers.SwitchBaySerializer - - -class BuildingViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.Building` objects. - """ - - queryset = topologie.Building.objects.all() - serializer_class = serializers.BuildingSerializer - - -class SwitchPortViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.Port` objects. - """ - - queryset = topologie.Port.objects.all() - serializer_class = serializers.SwitchPortSerializer - - -class PortProfileViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.PortProfile` objects. - """ - - queryset = topologie.PortProfile.objects.all() - serializer_class = serializers.PortProfileSerializer - - -class RoomViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.Room` objects. - """ - - queryset = topologie.Room.objects.all() - serializer_class = serializers.RoomSerializer - - -class PortProfileViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `topologie.models.PortProfile` objects. - """ - - queryset = topologie.PortProfile.objects.all() - serializer_class = serializers.PortProfileSerializer - - -# USER - - -class UserViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.Users` objects. - """ - - queryset = users.User.objects.all() - serializer_class = serializers.UserSerializer - - -class HomeCreationViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes infos of `users.models.Users` objects to create homes. - """ - - queryset = users.User.objects.exclude( - Q(state=users.User.STATE_DISABLED) - | Q(state=users.User.STATE_NOT_YET_ACTIVE) - | Q(state=users.User.STATE_FULL_ARCHIVE) - ) - serializer_class = serializers.BasicUserSerializer - - -class NormalUserViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes infos of `users.models.Users`without specific rights objects.""" - - queryset = users.User.objects.exclude(groups__listright__critical=True).distinct() - serializer_class = serializers.BasicUserSerializer - - -class CriticalUserViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes infos of `users.models.Users`without specific rights objects.""" - - queryset = users.User.objects.filter(groups__listright__critical=True).distinct() - serializer_class = serializers.BasicUserSerializer - - -class ClubViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.Club` objects. - """ - - queryset = users.Club.objects.all() - serializer_class = serializers.ClubSerializer - - -class AdherentViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.Adherent` objects. - """ - - queryset = users.Adherent.objects.all() - serializer_class = serializers.AdherentSerializer - - -class ServiceUserViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.ServiceUser` objects. - """ - - queryset = users.ServiceUser.objects.all() - serializer_class = serializers.ServiceUserSerializer - - -class SchoolViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.School` objects. - """ - - queryset = users.School.objects.all() - serializer_class = serializers.SchoolSerializer - - -class ListRightViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.ListRight` objects. - """ - - queryset = users.ListRight.objects.all() - serializer_class = serializers.ListRightSerializer - - -class ShellViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.ListShell` objects. - """ - - queryset = users.ListShell.objects.all() - serializer_class = serializers.ShellSerializer - - -class BanViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.Ban` objects. - """ - - queryset = users.Ban.objects.all() - serializer_class = serializers.BanSerializer - - -class WhitelistViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.Whitelist` objects. - """ - - queryset = users.Whitelist.objects.all() - serializer_class = serializers.WhitelistSerializer - - -class EMailAddressViewSet(viewsets.ReadOnlyModelViewSet): - """Exposes list and details of `users.models.EMailAddress` objects. - """ - - serializer_class = serializers.EMailAddressSerializer - queryset = users.EMailAddress.objects.none() - - def get_queryset(self): - if preferences.OptionalUser.get_cached_value("local_email_accounts_enabled"): - return users.EMailAddress.objects.filter(user__local_email_enabled=True) - else: - return users.EMailAddress.objects.none() - - -# SERVICE REGEN - - -class ServiceRegenViewSet(viewsets.ModelViewSet): - """Exposes list and details of the services to regen - """ - - serializer_class = serializers.ServiceRegenSerializer - - def get_queryset(self): - queryset = machines.Service_link.objects.select_related( - "server__domain" - ).select_related("service") - if "hostname" in self.request.GET: - hostname = self.request.GET["hostname"] - queryset = queryset.filter(server__domain__name__iexact=hostname) - return queryset - - -# Config des switches - - -class SwitchPortView(generics.ListAPIView): - """Output each port of a switch, to be serialized with - additionnal informations (profiles etc) - """ - - queryset = ( - topologie.Switch.objects.all() - .select_related("switchbay") - .select_related("model__constructor") - .prefetch_related("ports__custom_profile__vlan_tagged") - .prefetch_related("ports__custom_profile__vlan_untagged") - .prefetch_related("ports__machine_interface__domain__extension") - .prefetch_related("ports__room") - ) - - serializer_class = serializers.SwitchPortSerializer - - -# Rappel fin adhésion - - -class ReminderView(generics.ListAPIView): - """Output for users to remind an end of their subscription. - """ - - queryset = preferences.Reminder.objects.all() - serializer_class = serializers.ReminderSerializer - - -class RoleView(generics.ListAPIView): - """Output of roles for each server - """ - - queryset = machines.Role.objects.all().prefetch_related("servers") - serializer_class = serializers.RoleSerializer - - -# LOCAL EMAILS - - -class LocalEmailUsersView(generics.ListAPIView): - """Exposes all the aliases of the users that activated the internal address - """ - - serializer_class = serializers.LocalEmailUsersSerializer - - def get_queryset(self): - if preferences.OptionalUser.get_cached_value("local_email_accounts_enabled"): - return users.User.objects.filter(local_email_enabled=True) - else: - return users.User.objects.none() - - -# DHCP - - -class HostMacIpView(generics.ListAPIView): - """Exposes the associations between hostname, mac address and IPv4 in - order to build the DHCP lease files. - """ - - serializer_class = serializers.HostMacIpSerializer - - def get_queryset(self): - return all_active_interfaces() - - -# Firewall - - -class SubnetPortsOpenView(generics.ListAPIView): - queryset = machines.IpType.objects.all() - serializer_class = serializers.SubnetPortsOpenSerializer - - -class InterfacePortsOpenView(generics.ListAPIView): - queryset = machines.Interface.objects.filter(port_lists__isnull=False).distinct() - serializer_class = serializers.InterfacePortsOpenSerializer - - -# DNS - - -class DNSZonesView(generics.ListAPIView): - """Exposes the detailed information about each extension (hostnames, - IPs, DNS records, etc.) in order to build the DNS zone files. - """ - - queryset = ( - machines.Extension.objects.prefetch_related("soa") - .prefetch_related("ns_set") - .prefetch_related("ns_set__ns") - .prefetch_related("origin") - .prefetch_related("mx_set") - .prefetch_related("mx_set__name") - .prefetch_related("txt_set") - .prefetch_related("srv_set") - .prefetch_related("srv_set__target") - .all() - ) - serializer_class = serializers.DNSZonesSerializer - - -class DNSReverseZonesView(generics.ListAPIView): - """Exposes the detailed information about each extension (hostnames, - IPs, DNS records, etc.) in order to build the DNS zone files. - """ - - queryset = machines.IpType.objects.all() - serializer_class = serializers.DNSReverseZonesSerializer - - -# MAILING - - -class StandardMailingView(views.APIView): - """Exposes list and details of standard mailings (name and members) in - order to building the corresponding mailing lists. - """ - - pagination_class = PageSizedPagination - permission_classes = (ACLPermission,) - perms_map = {"GET": [users.User.can_view_all]} - - def get(self, request, format=None): - adherents_data = serializers.MailingMemberSerializer( - all_has_access(), many=True - ).data - - data = [{"name": "adherents", "members": adherents_data}] - groups = Group.objects.all() - for group in groups: - group_data = serializers.MailingMemberSerializer( - group.user_set.all(), many=True - ).data - data.append({"name": group.name, "members": group_data}) - - paginator = self.pagination_class() - paginator.paginate_queryset(data, request) - return paginator.get_paginated_response(data) - - -class ClubMailingView(generics.ListAPIView): - """Exposes list and details of club mailings (name, members and admins) in - order to build the corresponding mailing lists. - """ - - queryset = users.Club.objects.all() - serializer_class = serializers.MailingSerializer - - -# TOKEN AUTHENTICATION - class ObtainExpiringAuthToken(ObtainAuthToken): """Exposes a view to obtain a authentication token. diff --git a/cotisations/api/__init__.py b/cotisations/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/cotisations/api/serializers.py b/cotisations/api/serializers.py new file mode 100644 index 00000000..d33c9f7e --- /dev/null +++ b/cotisations/api/serializers.py @@ -0,0 +1,127 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import serializers + +import cotisations.models as cotisations +import preferences.models as preferences +from api.serializers import NamespacedHRField, NamespacedHIField, NamespacedHMSerializer +from users.api.serializers import UserSerializer + + +class FactureSerializer(NamespacedHMSerializer): + """Serialize `cotisations.models.Facture` objects. + """ + + class Meta: + model = cotisations.Facture + fields = ( + "user", + "paiement", + "banque", + "cheque", + "date", + "valid", + "control", + "prix_total", + "name", + "api_url", + ) + + +class BaseInvoiceSerializer(NamespacedHMSerializer): + class Meta: + model = cotisations.BaseInvoice + fields = "__all__" + + +class VenteSerializer(NamespacedHMSerializer): + """Serialize `cotisations.models.Vente` objects. + """ + + class Meta: + model = cotisations.Vente + fields = ( + "facture", + "number", + "name", + "prix", + "duration", + "type_cotisation", + "prix_total", + "api_url", + ) + + +class ArticleSerializer(NamespacedHMSerializer): + """Serialize `cotisations.models.Article` objects. + """ + + class Meta: + model = cotisations.Article + fields = ("name", "prix", "duration", "type_user", "type_cotisation", "api_url") + + +class BanqueSerializer(NamespacedHMSerializer): + """Serialize `cotisations.models.Banque` objects. + """ + + class Meta: + model = cotisations.Banque + fields = ("name", "api_url") + + +class PaiementSerializer(NamespacedHMSerializer): + """Serialize `cotisations.models.Paiement` objects. + """ + + class Meta: + model = cotisations.Paiement + fields = ("moyen", "api_url") + + +class CotisationSerializer(NamespacedHMSerializer): + """Serialize `cotisations.models.Cotisation` objects. + """ + + class Meta: + model = cotisations.Cotisation + fields = ("vente", "type_cotisation", "date_start", "date_end", "api_url") + + +class ReminderUsersSerializer(UserSerializer): + """Serialize the data about a mailing member. + """ + + class Meta(UserSerializer.Meta): + fields = ("get_full_name", "get_mail") + + +class ReminderSerializer(serializers.ModelSerializer): + """ + Serialize the data about a reminder + """ + + users_to_remind = ReminderUsersSerializer(many=True) + + class Meta: + model = preferences.Reminder + fields = ("days", "message", "users_to_remind") \ No newline at end of file diff --git a/users/serializers.py b/cotisations/api/urls.py similarity index 56% rename from users/serializers.py rename to cotisations/api/urls.py index 65ac7ef1..33834b26 100644 --- a/users/serializers.py +++ b/cotisations/api/urls.py @@ -1,10 +1,9 @@ +# -*- mode: python; coding: utf-8 -*- # Re2o est un logiciel d'administration développé initiallement au rezometz. Il # se veut agnostique au réseau considéré, de manière à être installable en # quelques clics. # -# Copyright © 2017 Gabriel Détraz -# Copyright © 2017 Lara Kermarec -# Copyright © 2017 Augustin Lemesle +# Copyright © 2018 Maël Kervella # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -20,30 +19,20 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -# Maël Kervella +from . import views -"""users.serializers -Serializers for the User app -""" +urls_viewset = [ + (r"cotisations/facture", views.FactureViewSet, None), + (r"cotisations/vente", views.VenteViewSet, None), + (r"cotisations/article", views.ArticleViewSet, None), + (r"cotisations/banque", views.BanqueViewSet, None), + (r"cotisations/paiement", views.PaiementViewSet, None), + (r"cotisations/cotisation", views.CotisationViewSet, None) +] -from rest_framework import serializers -from users.models import Club, Adherent +urls_view = [ + (r"cotisations/reminder-get-users", views.ReminderView), - -class MailingSerializer(serializers.ModelSerializer): - """ Serializer to build Mailing objects """ - - name = serializers.CharField(source="pseudo") - - class Meta: - model = Club - fields = ("name",) - - -class MailingMemberSerializer(serializers.ModelSerializer): - """ Serializer fot the Adherent objects (who belong to a - Mailing) """ - - class Meta: - model = Adherent - fields = ("email",) + # Deprecated + (r"reminder/get-users", views.ReminderView), +] \ No newline at end of file diff --git a/cotisations/api/views.py b/cotisations/api/views.py new file mode 100644 index 00000000..246c64a9 --- /dev/null +++ b/cotisations/api/views.py @@ -0,0 +1,89 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import viewsets, generics + +from . import serializers +import cotisations.models as cotisations +import preferences.models as preferences + +class FactureViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Facture` objects. + """ + + queryset = cotisations.Facture.objects.all() + serializer_class = serializers.FactureSerializer + + +class FactureViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Facture` objects. + """ + + queryset = cotisations.BaseInvoice.objects.all() + serializer_class = serializers.BaseInvoiceSerializer + + +class VenteViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Vente` objects. + """ + + queryset = cotisations.Vente.objects.all() + serializer_class = serializers.VenteSerializer + + +class ArticleViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Article` objects. + """ + + queryset = cotisations.Article.objects.all() + serializer_class = serializers.ArticleSerializer + + +class BanqueViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Banque` objects. + """ + + queryset = cotisations.Banque.objects.all() + serializer_class = serializers.BanqueSerializer + + +class PaiementViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Paiement` objects. + """ + + queryset = cotisations.Paiement.objects.all() + serializer_class = serializers.PaiementSerializer + + +class CotisationViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `cotisations.models.Cotisation` objects. + """ + + queryset = cotisations.Cotisation.objects.all() + serializer_class = serializers.CotisationSerializer + + +class ReminderView(generics.ListAPIView): + """Output for users to remind an end of their subscription. + """ + + queryset = preferences.Reminder.objects.all() + serializer_class = serializers.ReminderSerializer \ No newline at end of file diff --git a/machines/api/__init__.py b/machines/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/machines/api/serializers.py b/machines/api/serializers.py new file mode 100644 index 00000000..9231a995 --- /dev/null +++ b/machines/api/serializers.py @@ -0,0 +1,592 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import serializers + +import machines.models as machines +from api.serializers import NamespacedHRField, NamespacedHIField, NamespacedHMSerializer + + +class MachineSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Machine` objects. + """ + + class Meta: + model = machines.Machine + fields = ("user", "name", "active", "api_url") + + +class MachineTypeSerializer(NamespacedHMSerializer): + """Serialize `machines.models.MachineType` objects. + """ + + class Meta: + model = machines.MachineType + fields = ("name", "ip_type", "api_url") + + +class IpTypeSerializer(NamespacedHMSerializer): + """Serialize `machines.models.IpType` objects. + """ + + class Meta: + model = machines.IpType + fields = ( + "name", + "extension", + "need_infra", + "domaine_ip_start", + "domaine_ip_stop", + "prefix_v6", + "vlan", + "ouverture_ports", + "api_url", + ) + + +class VlanSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Vlan` objects. + """ + + class Meta: + model = machines.Vlan + fields = ( + "vlan_id", + "name", + "comment", + "arp_protect", + "dhcp_snooping", + "dhcpv6_snooping", + "igmp", + "mld", + "api_url", + ) + + +class NasSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Nas` objects. + """ + + class Meta: + model = machines.Nas + fields = ( + "name", + "nas_type", + "machine_type", + "port_access_mode", + "autocapture_mac", + "api_url", + ) + + +class SOASerializer(NamespacedHMSerializer): + """Serialize `machines.models.SOA` objects. + """ + + class Meta: + model = machines.SOA + fields = ("name", "mail", "refresh", "retry", "expire", "ttl", "api_url") + + +class ExtensionSerializer(NamespacedHMSerializer): + """Serialize machines.models.Extension objects. + """ + + class Meta: + model = machines.Extension + fields = ("name", "need_infra", "origin", "origin_v6", "soa", "api_url") + + +class MxSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Mx` objects. + """ + + class Meta: + model = machines.Mx + fields = ("zone", "priority", "name", "api_url") + + +class DNameSerializer(NamespacedHMSerializer): + """Serialize `machines.models.DName` objects. + """ + + class Meta: + model = machines.DName + fields = ("zone", "alias", "api_url") + + +class NsSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Ns` objects. + """ + + class Meta: + model = machines.Ns + fields = ("zone", "ns", "api_url") + + +class TxtSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Txt` objects. + """ + + class Meta: + model = machines.Txt + fields = ("zone", "field1", "field2", "api_url") + + +class SrvSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Srv` objects. + """ + + class Meta: + model = machines.Srv + fields = ( + "service", + "protocole", + "extension", + "ttl", + "priority", + "weight", + "port", + "target", + "api_url", + ) + + +class SshFpSerializer(NamespacedHMSerializer): + """Serialize `machines.models.SSHFP` objects. + """ + + class Meta: + model = machines.SshFp + field = ("machine", "pub_key_entry", "algo", "comment", "api_url") + + +class InterfaceSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Interface` objects. + """ + + mac_address = serializers.CharField() + active = serializers.BooleanField(source="is_active") + + class Meta: + model = machines.Interface + fields = ( + "ipv4", + "mac_address", + "machine", + "machine_type", + "details", + "port_lists", + "active", + "api_url", + ) + + +class Ipv6ListSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Ipv6List` objects. + """ + + class Meta: + model = machines.Ipv6List + fields = ("ipv6", "interface", "slaac_ip", "api_url") + + +class DomainSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Domain` objects. + """ + + class Meta: + model = machines.Domain + fields = ("interface_parent", "name", "extension", "cname", "api_url") + + +class IpListSerializer(NamespacedHMSerializer): + """Serialize `machines.models.IpList` objects. + """ + + class Meta: + model = machines.IpList + fields = ("ipv4", "ip_type", "need_infra", "api_url") + + +class ServiceSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Service` objects. + """ + + class Meta: + model = machines.Service + fields = ( + "service_type", + "min_time_regen", + "regular_time_regen", + "servers", + "api_url", + ) + + +class ServiceLinkSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Service_link` objects. + """ + + class Meta: + model = machines.Service_link + fields = ( + "service", + "server", + "last_regen", + "asked_regen", + "need_regen", + "api_url", + ) + extra_kwargs = {"api_url": {"view_name": "servicelink-detail"}} + + +class OuverturePortListSerializer(NamespacedHMSerializer): + """Serialize `machines.models.OuverturePortList` objects. + """ + + tcp_ports_in = NamespacedHRField( + view_name="ouvertureport-detail", many=True, read_only=True + ) + udp_ports_in = NamespacedHRField( + view_name="ouvertureport-detail", many=True, read_only=True + ) + tcp_ports_out = NamespacedHRField( + view_name="ouvertureport-detail", many=True, read_only=True + ) + udp_ports_out = NamespacedHRField( + view_name="ouvertureport-detail", many=True, read_only=True + ) + + class Meta: + model = machines.OuverturePortList + fields = ( + "name", + "tcp_ports_in", + "udp_ports_in", + "tcp_ports_out", + "udp_ports_out", + "api_url", + ) + + +class OuverturePortSerializer(NamespacedHMSerializer): + """Serialize `machines.models.OuverturePort` objects. + """ + + class Meta: + model = machines.OuverturePort + fields = ("begin", "end", "port_list", "protocole", "io", "api_url") + + +class RoleSerializer(NamespacedHMSerializer): + """Serialize `machines.models.OuverturePort` objects. + """ + + servers = InterfaceSerializer(read_only=True, many=True) + + class Meta: + model = machines.Role + fields = ("role_type", "servers", "api_url") + + +class ServiceRegenSerializer(NamespacedHMSerializer): + """Serialize the data about the services to regen. + """ + + hostname = serializers.CharField(source="server.domain.name", read_only=True) + service_name = serializers.CharField(source="service.service_type", read_only=True) + need_regen = serializers.BooleanField() + + class Meta: + model = machines.Service_link + fields = ("hostname", "service_name", "need_regen", "api_url") + extra_kwargs = {"api_url": {"view_name": "serviceregen-detail"}} + + +class HostMacIpSerializer(serializers.ModelSerializer): + """Serialize the data about the hostname-ipv4-mac address association + to build the DHCP lease files. + """ + + hostname = serializers.CharField(source="domain.name", read_only=True) + extension = serializers.CharField(source="domain.extension.name", read_only=True) + mac_address = serializers.CharField(read_only=True) + ip_type = serializers.CharField(source="machine_type.ip_type", read_only=True) + ipv4 = serializers.CharField(source="ipv4.ipv4", read_only=True) + + class Meta: + model = machines.Interface + fields = ("hostname", "extension", "mac_address", "ipv4", "ip_type") + + +class FirewallPortListSerializer(serializers.ModelSerializer): + class Meta: + model = machines.OuverturePort + fields = ("begin", "end", "protocole", "io", "show_port") + + +class FirewallOuverturePortListSerializer(serializers.ModelSerializer): + tcp_ports_in = FirewallPortListSerializer(many=True, read_only=True) + udp_ports_in = FirewallPortListSerializer(many=True, read_only=True) + tcp_ports_out = FirewallPortListSerializer(many=True, read_only=True) + udp_ports_out = FirewallPortListSerializer(many=True, read_only=True) + + class Meta: + model = machines.OuverturePortList + fields = ("tcp_ports_in", "udp_ports_in", "tcp_ports_out", "udp_ports_out") + + +class SubnetPortsOpenSerializer(serializers.ModelSerializer): + ouverture_ports = FirewallOuverturePortListSerializer(read_only=True) + + class Meta: + model = machines.IpType + fields = ( + "name", + "domaine_ip_start", + "domaine_ip_stop", + "complete_prefixv6", + "ouverture_ports", + ) + + +class InterfacePortsOpenSerializer(serializers.ModelSerializer): + port_lists = FirewallOuverturePortListSerializer(read_only=True, many=True) + ipv4 = serializers.CharField(source="ipv4.ipv4", read_only=True) + ipv6 = Ipv6ListSerializer(many=True, read_only=True) + + class Meta: + model = machines.Interface + fields = ("port_lists", "ipv4", "ipv6") + + +class SOARecordSerializer(SOASerializer): + """Serialize `machines.models.SOA` objects with the data needed to + generate a SOA DNS record. + """ + + class Meta: + model = machines.SOA + fields = ("name", "mail", "refresh", "retry", "expire", "ttl") + + +class OriginV4RecordSerializer(IpListSerializer): + """Serialize `machines.models.IpList` objects with the data needed to + generate an IPv4 Origin DNS record. + """ + + class Meta(IpListSerializer.Meta): + fields = ("ipv4",) + + +class NSRecordSerializer(NsSerializer): + """Serialize `machines.models.Ns` objects with the data needed to + generate a NS DNS record. + """ + + target = serializers.CharField(source="ns", read_only=True) + + class Meta(NsSerializer.Meta): + fields = ("target", "ttl") + + +class MXRecordSerializer(MxSerializer): + """Serialize `machines.models.Mx` objects with the data needed to + generate a MX DNS record. + """ + + target = serializers.CharField(source="name", read_only=True) + + class Meta(MxSerializer.Meta): + fields = ("target", "priority", "ttl") + + +class TXTRecordSerializer(TxtSerializer): + """Serialize `machines.models.Txt` objects with the data needed to + generate a TXT DNS record. + """ + + class Meta(TxtSerializer.Meta): + fields = ("field1", "field2", "ttl") + + +class SRVRecordSerializer(SrvSerializer): + """Serialize `machines.models.Srv` objects with the data needed to + generate a SRV DNS record. + """ + + target = serializers.CharField(source="target.name", read_only=True) + + class Meta(SrvSerializer.Meta): + fields = ("service", "protocole", "ttl", "priority", "weight", "port", "target") + + +class SSHFPRecordSerializer(SshFpSerializer): + """Serialize `machines.models.SshFp` objects with the data needed to + generate a SSHFP DNS record. + """ + + class Meta(SshFpSerializer.Meta): + fields = ("algo_id", "hash") + + +class SSHFPInterfaceSerializer(serializers.ModelSerializer): + """Serialize `machines.models.Domain` objects with the data needed to + generate a CNAME DNS record. + """ + + hostname = serializers.CharField(source="domain.name", read_only=True) + sshfp = SSHFPRecordSerializer(source="machine.sshfp_set", many=True, read_only=True) + + class Meta: + model = machines.Interface + fields = ("hostname", "sshfp") + + +class ARecordSerializer(serializers.ModelSerializer): + """Serialize `machines.models.Interface` objects with the data needed to + generate a A DNS record. + """ + + hostname = serializers.CharField(source="domain.name", read_only=True) + ipv4 = serializers.CharField(source="ipv4.ipv4", read_only=True) + ttl = serializers.IntegerField(source="domain.ttl", read_only=True) + + class Meta: + model = machines.Interface + fields = ("hostname", "ipv4", "ttl") + + +class AAAARecordSerializer(serializers.ModelSerializer): + """Serialize `machines.models.Interface` objects with the data needed to + generate a AAAA DNS record. + """ + + hostname = serializers.CharField(source="domain.name", read_only=True) + ipv6 = Ipv6ListSerializer(many=True, read_only=True) + ttl = serializers.IntegerField(source="domain.ttl", read_only=True) + + class Meta: + model = machines.Interface + fields = ("hostname", "ipv6", "ttl") + + +class CNAMERecordSerializer(serializers.ModelSerializer): + """Serialize `machines.models.Domain` objects with the data needed to + generate a CNAME DNS record. + """ + + alias = serializers.CharField(source="cname", read_only=True) + hostname = serializers.CharField(source="name", read_only=True) + + class Meta: + model = machines.Domain + fields = ("alias", "hostname", "ttl") + + +class DNAMERecordSerializer(serializers.ModelSerializer): + """Serialize `machines.models.Domain` objects with the data needed to + generate a DNAME DNS record. + """ + + alias = serializers.CharField(read_only=True) + zone = serializers.CharField(read_only=True) + + class Meta: + model = machines.DName + fields = ("alias", "zone", "ttl") + + +class DNSZonesSerializer(serializers.ModelSerializer): + """Serialize the data about DNS Zones. + """ + + soa = SOARecordSerializer() + ns_records = NSRecordSerializer(many=True, source="ns_set") + originv4 = OriginV4RecordSerializer(source="origin") + originv6 = serializers.CharField(source="origin_v6") + mx_records = MXRecordSerializer(many=True, source="mx_set") + txt_records = TXTRecordSerializer(many=True, source="txt_set") + srv_records = SRVRecordSerializer(many=True, source="srv_set") + a_records = ARecordSerializer(many=True, source="get_associated_a_records") + aaaa_records = AAAARecordSerializer(many=True, source="get_associated_aaaa_records") + cname_records = CNAMERecordSerializer( + many=True, source="get_associated_cname_records" + ) + dname_records = DNAMERecordSerializer( + many=True, source="get_associated_dname_records" + ) + sshfp_records = SSHFPInterfaceSerializer( + many=True, source="get_associated_sshfp_records" + ) + + class Meta: + model = machines.Extension + fields = ( + "name", + "soa", + "ns_records", + "originv4", + "originv6", + "mx_records", + "txt_records", + "srv_records", + "a_records", + "aaaa_records", + "cname_records", + "dname_records", + "sshfp_records", + ) + + +class DNSReverseZonesSerializer(serializers.ModelSerializer): + """Serialize the data about DNS Zones. + """ + + soa = SOARecordSerializer(source="extension.soa") + extension = serializers.CharField(source="extension.name", read_only=True) + cidrs = serializers.ListField( + child=serializers.CharField(), source="ip_set_cidrs_as_str", read_only=True + ) + ns_records = NSRecordSerializer(many=True, source="extension.ns_set") + mx_records = MXRecordSerializer(many=True, source="extension.mx_set") + txt_records = TXTRecordSerializer(many=True, source="extension.txt_set") + ptr_records = ARecordSerializer(many=True, source="get_associated_ptr_records") + ptr_v6_records = AAAARecordSerializer( + many=True, source="get_associated_ptr_v6_records" + ) + + class Meta: + model = machines.IpType + fields = ( + "name", + "extension", + "soa", + "ns_records", + "mx_records", + "txt_records", + "ptr_records", + "ptr_v6_records", + "cidrs", + "prefix_v6", + "prefix_v6_length", + ) \ No newline at end of file diff --git a/machines/api/urls.py b/machines/api/urls.py new file mode 100644 index 00000000..3cf82122 --- /dev/null +++ b/machines/api/urls.py @@ -0,0 +1,66 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from . import views + +urls_viewset = [ + (r"machines/machine", views.MachineViewSet, None), + (r"machines/machinetype", views.MachineTypeViewSet, None), + (r"machines/iptype", views.IpTypeViewSet, None), + (r"machines/vlan", views.VlanViewSet, None), + (r"machines/nas", views.NasViewSet, None), + (r"machines/soa", views.SOAViewSet, None), + (r"machines/extension", views.ExtensionViewSet, None), + (r"machines/mx", views.MxViewSet, None), + (r"machines/ns", views.NsViewSet, None), + (r"machines/txt", views.TxtViewSet, None), + (r"machines/dname", views.DNameViewSet, None), + (r"machines/srv", views.SrvViewSet, None), + (r"machines/sshfp", views.SshFpViewSet, None), + (r"machines/interface", views.InterfaceViewSet, None), + (r"machines/ipv6list", views.Ipv6ListViewSet, None), + (r"machines/domain", views.DomainViewSet, None), + (r"machines/iplist", views.IpListViewSet, None), + (r"machines/service", views.ServiceViewSet, None), + (r"machines/servicelink", views.ServiceLinkViewSet, "servicelink"), + (r"machines/ouvertureportlist", views.OuverturePortListViewSet, None), + (r"machines/ouvertureport", views.OuverturePortViewSet, None), + (r"machines/role", views.RoleViewSet, None), + (r"machines/services-regen", views.ServiceRegenViewSet, "serviceregen"), + + # Deprecated + (r"services/regen", views.ServiceRegenViewSet, "serviceregen") +] + +urls_view = [ + (r"machines/hostmacip", views.HostMacIpView), + (r"machines/firewall-subnet-ports", views.SubnetPortsOpenView), + (r"machines/firewall-interface-ports", views.InterfacePortsOpenView), + (r"machines/dns-zones", views.DNSZonesView), + (r"machines/dns-reverse-zones", views.DNSReverseZonesView), + + # Deprecated + (r"dhcp/hostmacip", views.HostMacIpView), + (r"firewall/subnet-ports", views.SubnetPortsOpenView), + (r"firewall/interface-ports", views.InterfacePortsOpenView), + (r"dns/zones", views.DNSZonesView), + (r"dns/reverse-zones", views.DNSReverseZonesView), +] \ No newline at end of file diff --git a/machines/api/views.py b/machines/api/views.py new file mode 100644 index 00000000..3e510d8e --- /dev/null +++ b/machines/api/views.py @@ -0,0 +1,267 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import viewsets, generics + +from . import serializers +import machines.models as machines +from re2o.utils import all_active_interfaces + +class MachineViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Machine` objects. + """ + + queryset = machines.Machine.objects.all() + serializer_class = serializers.MachineSerializer + + +class MachineTypeViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.MachineType` objects. + """ + + queryset = machines.MachineType.objects.all() + serializer_class = serializers.MachineTypeSerializer + + +class IpTypeViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.IpType` objects. + """ + + queryset = machines.IpType.objects.all() + serializer_class = serializers.IpTypeSerializer + + +class VlanViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Vlan` objects. + """ + + queryset = machines.Vlan.objects.all() + serializer_class = serializers.VlanSerializer + + +class NasViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Nas` objects. + """ + + queryset = machines.Nas.objects.all() + serializer_class = serializers.NasSerializer + + +class SOAViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.SOA` objects. + """ + + queryset = machines.SOA.objects.all() + serializer_class = serializers.SOASerializer + + +class ExtensionViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Extension` objects. + """ + + queryset = machines.Extension.objects.all() + serializer_class = serializers.ExtensionSerializer + + +class MxViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Mx` objects. + """ + + queryset = machines.Mx.objects.all() + serializer_class = serializers.MxSerializer + + +class NsViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Ns` objects. + """ + + queryset = machines.Ns.objects.all() + serializer_class = serializers.NsSerializer + + +class TxtViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Txt` objects. + """ + + queryset = machines.Txt.objects.all() + serializer_class = serializers.TxtSerializer + + +class DNameViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.DName` objects. + """ + + queryset = machines.DName.objects.all() + serializer_class = serializers.DNameSerializer + + +class SrvViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Srv` objects. + """ + + queryset = machines.Srv.objects.all() + serializer_class = serializers.SrvSerializer + + +class SshFpViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.SshFp` objects. + """ + + queryset = machines.SshFp.objects.all() + serializer_class = serializers.SshFpSerializer + + +class InterfaceViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Interface` objects. + """ + + queryset = machines.Interface.objects.all() + serializer_class = serializers.InterfaceSerializer + + +class Ipv6ListViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Ipv6List` objects. + """ + + queryset = machines.Ipv6List.objects.all() + serializer_class = serializers.Ipv6ListSerializer + + +class DomainViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Domain` objects. + """ + + queryset = machines.Domain.objects.all() + serializer_class = serializers.DomainSerializer + + +class IpListViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.IpList` objects. + """ + + queryset = machines.IpList.objects.all() + serializer_class = serializers.IpListSerializer + + +class ServiceViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Service` objects. + """ + + queryset = machines.Service.objects.all() + serializer_class = serializers.ServiceSerializer + + +class ServiceLinkViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Service_link` objects. + """ + + queryset = machines.Service_link.objects.all() + serializer_class = serializers.ServiceLinkSerializer + + +class OuverturePortListViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.OuverturePortList` + objects. + """ + + queryset = machines.OuverturePortList.objects.all() + serializer_class = serializers.OuverturePortListSerializer + + +class OuverturePortViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.OuverturePort` objects. + """ + + queryset = machines.OuverturePort.objects.all() + serializer_class = serializers.OuverturePortSerializer + + +class RoleViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `machines.models.Machine` objects. + """ + + queryset = machines.Role.objects.all() + serializer_class = serializers.RoleSerializer + + +class ServiceRegenViewSet(viewsets.ModelViewSet): + """Exposes list and details of the services to regen + """ + + serializer_class = serializers.ServiceRegenSerializer + + def get_queryset(self): + queryset = machines.Service_link.objects.select_related( + "server__domain" + ).select_related("service") + if "hostname" in self.request.GET: + hostname = self.request.GET["hostname"] + queryset = queryset.filter(server__domain__name__iexact=hostname) + return queryset + + +class HostMacIpView(generics.ListAPIView): + """Exposes the associations between hostname, mac address and IPv4 in + order to build the DHCP lease files. + """ + + serializer_class = serializers.HostMacIpSerializer + + def get_queryset(self): + return all_active_interfaces() + + +class SubnetPortsOpenView(generics.ListAPIView): + queryset = machines.IpType.objects.all() + serializer_class = serializers.SubnetPortsOpenSerializer + + +class InterfacePortsOpenView(generics.ListAPIView): + queryset = machines.Interface.objects.filter(port_lists__isnull=False).distinct() + serializer_class = serializers.InterfacePortsOpenSerializer + +class DNSZonesView(generics.ListAPIView): + """Exposes the detailed information about each extension (hostnames, + IPs, DNS records, etc.) in order to build the DNS zone files. + """ + + queryset = ( + machines.Extension.objects.prefetch_related("soa") + .prefetch_related("ns_set") + .prefetch_related("ns_set__ns") + .prefetch_related("origin") + .prefetch_related("mx_set") + .prefetch_related("mx_set__name") + .prefetch_related("txt_set") + .prefetch_related("srv_set") + .prefetch_related("srv_set__target") + .all() + ) + serializer_class = serializers.DNSZonesSerializer + + +class DNSReverseZonesView(generics.ListAPIView): + """Exposes the detailed information about each extension (hostnames, + IPs, DNS records, etc.) in order to build the DNS zone files. + """ + + queryset = machines.IpType.objects.all() + serializer_class = serializers.DNSReverseZonesSerializer \ No newline at end of file diff --git a/machines/serializers.py b/machines/serializers.py deleted file mode 100644 index 95e0df5c..00000000 --- a/machines/serializers.py +++ /dev/null @@ -1,442 +0,0 @@ -# -*- mode: python; coding: utf-8 -*- -# Re2o est un logiciel d'administration développé initiallement au rezometz. Il -# se veut agnostique au réseau considéré, de manière à être installable en -# quelques clics. -# -# Copyright © 2017 Gabriel Détraz -# Copyright © 2017 Lara Kermarec -# Copyright © 2017 Augustin Lemesle -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along -# with this program; if not, write to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -# Augustin Lemesle -"""machines.serializers -Serializers for the Machines app -""" - -from rest_framework import serializers - -from machines.models import ( - Interface, - IpType, - Extension, - IpList, - Domain, - Txt, - Mx, - Srv, - Service_link, - Ns, - OuverturePort, - Ipv6List, -) - - -class IpTypeField(serializers.RelatedField): - """ Serializer for an IpType object field """ - - def to_representation(self, value): - return str(value) - - def to_internal_value(self, data): - pass - - -class IpListSerializer(serializers.ModelSerializer): - """ Serializer for an Ipv4List obejct using the IpType serialization """ - - ip_type = IpTypeField(read_only=True) - - class Meta: - model = IpList - fields = ("ipv4", "ip_type") - - -class Ipv6ListSerializer(serializers.ModelSerializer): - """ Serializer for an Ipv6List object """ - - class Meta: - model = Ipv6List - fields = ("ipv6", "slaac_ip") - - -class InterfaceSerializer(serializers.ModelSerializer): - """ Serializer for an Interface object. Use SerializerMethodField - to get ForeignKey values """ - - ipv4 = IpListSerializer(read_only=True) - # TODO : use serializer.RelatedField to avoid duplicate code - mac_address = serializers.SerializerMethodField("get_macaddress") - domain = serializers.SerializerMethodField("get_dns") - extension = serializers.SerializerMethodField("get_interface_extension") - - class Meta: - model = Interface - fields = ("ipv4", "mac_address", "domain", "extension") - - @staticmethod - def get_dns(obj): - """ The name of the associated DNS object """ - return obj.domain.name - - @staticmethod - def get_interface_extension(obj): - """ The name of the associated Interface object """ - return obj.domain.extension.name - - @staticmethod - def get_macaddress(obj): - """ The string representation of the associated MAC address """ - return str(obj.mac_address) - - -class FullInterfaceSerializer(serializers.ModelSerializer): - """ Serializer for an Interface obejct. Use SerializerMethodField - to get ForeignKey values """ - - ipv4 = IpListSerializer(read_only=True) - ipv6 = Ipv6ListSerializer(read_only=True, many=True) - # TODO : use serializer.RelatedField to avoid duplicate code - mac_address = serializers.SerializerMethodField("get_macaddress") - domain = serializers.SerializerMethodField("get_dns") - extension = serializers.SerializerMethodField("get_interface_extension") - - class Meta: - model = Interface - fields = ("ipv4", "ipv6", "mac_address", "domain", "extension") - - @staticmethod - def get_dns(obj): - """ The name of the associated DNS object """ - return obj.domain.name - - @staticmethod - def get_interface_extension(obj): - """ The name of the associated Extension object """ - return obj.domain.extension.name - - @staticmethod - def get_macaddress(obj): - """ The string representation of the associated MAC address """ - return str(obj.mac_address) - - -class ExtensionNameField(serializers.RelatedField): - """ Serializer for Extension object field """ - - def to_representation(self, value): - return value.name - - def to_internal_value(self, data): - pass - - -class TypeSerializer(serializers.ModelSerializer): - """ Serializer for an IpType object. Use SerializerMethodField to - get ForeignKey values. Infos about the general port policy is added """ - - extension = ExtensionNameField(read_only=True) - ouverture_ports_tcp_in = serializers.SerializerMethodField( - "get_port_policy_input_tcp" - ) - ouverture_ports_tcp_out = serializers.SerializerMethodField( - "get_port_policy_output_tcp" - ) - ouverture_ports_udp_in = serializers.SerializerMethodField( - "get_port_policy_input_udp" - ) - ouverture_ports_udp_out = serializers.SerializerMethodField( - "get_port_policy_output_udp" - ) - - class Meta: - model = IpType - fields = ( - "name", - "extension", - "domaine_ip_start", - "domaine_ip_stop", - "prefix_v6", - "ouverture_ports_tcp_in", - "ouverture_ports_tcp_out", - "ouverture_ports_udp_in", - "ouverture_ports_udp_out", - ) - - @staticmethod - def get_port_policy(obj, protocole, io): - """ Generic utility function to get the policy for a given - port, protocole and IN or OUT """ - if obj.ouverture_ports is None: - return [] - return map( - str, - obj.ouverture_ports.ouvertureport_set.filter(protocole=protocole).filter( - io=io - ), - ) - - def get_port_policy_input_tcp(self, obj): - """Renvoie la liste des ports ouverts en entrée tcp""" - return self.get_port_policy(obj, OuverturePort.TCP, OuverturePort.IN) - - def get_port_policy_output_tcp(self, obj): - """Renvoie la liste des ports ouverts en sortie tcp""" - return self.get_port_policy(obj, OuverturePort.TCP, OuverturePort.OUT) - - def get_port_policy_input_udp(self, obj): - """Renvoie la liste des ports ouverts en entrée udp""" - return self.get_port_policy(obj, OuverturePort.UDP, OuverturePort.IN) - - def get_port_policy_output_udp(self, obj): - """Renvoie la liste des ports ouverts en sortie udp""" - return self.get_port_policy(obj, OuverturePort.UDP, OuverturePort.OUT) - - -class ExtensionSerializer(serializers.ModelSerializer): - """Serialisation d'une extension : origin_ip et la zone sont - des foreign_key donc evalués en get_...""" - - origin = serializers.SerializerMethodField("get_origin_ip") - zone_entry = serializers.SerializerMethodField("get_zone_name") - soa = serializers.SerializerMethodField("get_soa_data") - - class Meta: - model = Extension - fields = ("name", "origin", "origin_v6", "zone_entry", "soa") - - @staticmethod - def get_origin_ip(obj): - """ The IP of the associated origin for the zone """ - return obj.origin.ipv4 - - @staticmethod - def get_zone_name(obj): - """ The name of the associated zone """ - return str(obj.dns_entry) - - @staticmethod - def get_soa_data(obj): - """ The representation of the associated SOA """ - return {"mail": obj.soa.dns_soa_mail, "param": obj.soa.dns_soa_param} - - -class MxSerializer(serializers.ModelSerializer): - """Serialisation d'un MX, evaluation du nom, de la zone - et du serveur cible, etant des foreign_key""" - - name = serializers.SerializerMethodField("get_entry_name") - zone = serializers.SerializerMethodField("get_zone_name") - mx_entry = serializers.SerializerMethodField("get_mx_name") - - class Meta: - model = Mx - fields = ("zone", "priority", "name", "mx_entry") - - @staticmethod - def get_entry_name(obj): - """ The name of the DNS MX entry """ - return str(obj.name) - - @staticmethod - def get_zone_name(obj): - """ The name of the associated zone of the MX record """ - return obj.zone.name - - @staticmethod - def get_mx_name(obj): - """ The string representation of the entry to add to the DNS """ - return str(obj.dns_entry) - - -class TxtSerializer(serializers.ModelSerializer): - """Serialisation d'un txt : zone cible et l'entrée txt - sont evaluées à part""" - - zone = serializers.SerializerMethodField("get_zone_name") - txt_entry = serializers.SerializerMethodField("get_txt_name") - - class Meta: - model = Txt - fields = ("zone", "txt_entry", "field1", "field2") - - @staticmethod - def get_zone_name(obj): - """ The name of the associated zone """ - return str(obj.zone.name) - - @staticmethod - def get_txt_name(obj): - """ The string representation of the entry to add to the DNS """ - return str(obj.dns_entry) - - -class SrvSerializer(serializers.ModelSerializer): - """Serialisation d'un srv : zone cible et l'entrée txt""" - - extension = serializers.SerializerMethodField("get_extension_name") - srv_entry = serializers.SerializerMethodField("get_srv_name") - - class Meta: - model = Srv - fields = ( - "service", - "protocole", - "extension", - "ttl", - "priority", - "weight", - "port", - "target", - "srv_entry", - ) - - @staticmethod - def get_extension_name(obj): - """ The name of the associated extension """ - return str(obj.extension.name) - - @staticmethod - def get_srv_name(obj): - """ The string representation of the entry to add to the DNS """ - return str(obj.dns_entry) - - -class NsSerializer(serializers.ModelSerializer): - """Serialisation d'un NS : la zone, l'entrée ns complète et le serveur - ns sont évalués à part""" - - zone = serializers.SerializerMethodField("get_zone_name") - ns = serializers.SerializerMethodField("get_domain_name") - ns_entry = serializers.SerializerMethodField("get_text_name") - - class Meta: - model = Ns - fields = ("zone", "ns", "ns_entry") - - @staticmethod - def get_zone_name(obj): - """ The name of the associated zone """ - return obj.zone.name - - @staticmethod - def get_domain_name(obj): - """ The name of the associated NS target """ - return str(obj.ns) - - @staticmethod - def get_text_name(obj): - """ The string representation of the entry to add to the DNS """ - return str(obj.dns_entry) - - -class DomainSerializer(serializers.ModelSerializer): - """Serialisation d'un domain, extension, cname sont des foreign_key, - et l'entrée complète, sont évalués à part""" - - extension = serializers.SerializerMethodField("get_zone_name") - cname = serializers.SerializerMethodField("get_alias_name") - cname_entry = serializers.SerializerMethodField("get_cname_name") - - class Meta: - model = Domain - fields = ("name", "extension", "cname", "cname_entry") - - @staticmethod - def get_zone_name(obj): - """ The name of the associated zone """ - return obj.extension.name - - @staticmethod - def get_alias_name(obj): - """ The name of the associated alias """ - return str(obj.cname) - - @staticmethod - def get_cname_name(obj): - """ The name of the associated CNAME target """ - return str(obj.dns_entry) - - -class ServiceServersSerializer(serializers.ModelSerializer): - """Evaluation d'un Service, et serialisation""" - - server = serializers.SerializerMethodField("get_server_name") - service = serializers.SerializerMethodField("get_service_name") - need_regen = serializers.SerializerMethodField("get_regen_status") - - class Meta: - model = Service_link - fields = ("server", "service", "need_regen") - - @staticmethod - def get_server_name(obj): - """ The name of the associated server """ - return str(obj.server.domain.name) - - @staticmethod - def get_service_name(obj): - """ The name of the service name """ - return str(obj.service) - - @staticmethod - def get_regen_status(obj): - """ The string representation of the regen status """ - return obj.need_regen - - -class OuverturePortsSerializer(serializers.Serializer): - """Serialisation de l'ouverture des ports""" - - ipv4 = serializers.SerializerMethodField() - ipv6 = serializers.SerializerMethodField() - - def create(self, validated_data): - """ Creates a new object based on the un-serialized data. - Used to implement an abstract inherited method """ - pass - - def update(self, instance, validated_data): - """ Updates an object based on the un-serialized data. - Used to implement an abstract inherited method """ - pass - - @staticmethod - def get_ipv4(): - """ The representation of the policy for the IPv4 addresses """ - return { - i.ipv4.ipv4: { - "tcp_in": [j.tcp_ports_in() for j in i.port_lists.all()], - "tcp_out": [j.tcp_ports_out() for j in i.port_lists.all()], - "udp_in": [j.udp_ports_in() for j in i.port_lists.all()], - "udp_out": [j.udp_ports_out() for j in i.port_lists.all()], - } - for i in Interface.objects.all() - if i.ipv4 - } - - @staticmethod - def get_ipv6(): - """ The representation of the policy for the IPv6 addresses """ - return { - i.ipv6: { - "tcp_in": [j.tcp_ports_in() for j in i.port_lists.all()], - "tcp_out": [j.tcp_ports_out() for j in i.port_lists.all()], - "udp_in": [j.udp_ports_in() for j in i.port_lists.all()], - "udp_out": [j.udp_ports_out() for j in i.port_lists.all()], - } - for i in Interface.objects.all() - if i.ipv6 - } diff --git a/machines/urls.py b/machines/urls.py index 8fb08d99..3b7b77b9 100644 --- a/machines/urls.py +++ b/machines/urls.py @@ -136,18 +136,6 @@ urlpatterns = [ url(r"^del_nas/$", views.del_nas, name="del-nas"), url(r"^index_nas/$", views.index_nas, name="index-nas"), url(r"^$", views.index, name="index"), - url(r"^rest/mac-ip/$", views.mac_ip, name="mac-ip"), - url(r"^rest/regen-achieved/$", views.regen_achieved, name="regen-achieved"), - url(r"^rest/mac-ip-dns/$", views.mac_ip_dns, name="mac-ip-dns"), - url(r"^rest/alias/$", views.alias, name="alias"), - url(r"^rest/corresp/$", views.corresp, name="corresp"), - url(r"^rest/mx/$", views.mx, name="mx"), - url(r"^rest/ns/$", views.ns, name="ns"), - url(r"^rest/txt/$", views.txt, name="txt"), - url(r"^rest/srv/$", views.srv, name="srv"), - url(r"^rest/zones/$", views.zones, name="zones"), - url(r"^rest/service_servers/$", views.service_servers, name="service-servers"), - url(r"^rest/ouverture_ports/$", views.ouverture_ports, name="ouverture-ports"), url(r"index_portlist/$", views.index_portlist, name="index-portlist"), url( r"^edit_portlist/(?P[0-9]+)$", diff --git a/machines/views.py b/machines/views.py index 403389d2..3291adb3 100644 --- a/machines/views.py +++ b/machines/views.py @@ -120,18 +120,7 @@ from .models import ( OuverturePort, Ipv6List, ) -from .serializers import ( - FullInterfaceSerializer, - InterfaceSerializer, - TypeSerializer, - DomainSerializer, - TxtSerializer, - SrvSerializer, - MxSerializer, - ExtensionSerializer, - ServiceServersSerializer, - NsSerializer, -) + def f_type_id(is_type_tt): @@ -1577,240 +1566,3 @@ def configure_ports(request, interface_instance, **_kwargs): request, ) - -# Framework Rest - - -class JSONResponse(HttpResponse): - """ Class to build a JSON response. Used for API """ - - def __init__(self, data, **kwargs): - content = JSONRenderer().render(data) - kwargs["content_type"] = "application/json" - super(JSONResponse, self).__init__(content, **kwargs) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def mac_ip_list(_request): - """ API view to list the active and assigned interfaces """ - interfaces = all_active_assigned_interfaces() - seria = InterfaceSerializer(interfaces, many=True) - return seria.data - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def full_mac_ip_list(_request): - """ API view to list the active and assigned interfaces. More - detailed than mac_ip_list(request) """ - interfaces = all_active_assigned_interfaces(full=True) - seria = FullInterfaceSerializer(interfaces, many=True) - return seria.data - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def alias(_request): - """ API view to list the alias (CNAME) for all assigned interfaces """ - alias = ( - Domain.objects.filter(interface_parent=None) - .filter( - cname__in=Domain.objects.filter( - interface_parent__in=Interface.objects.exclude(ipv4=None) - ) - ) - .select_related("extension") - .select_related("cname__extension") - ) - seria = DomainSerializer(alias, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def corresp(_request): - """ API view to list the types of IP and infos about it """ - type = IpType.objects.all().select_related("extension") - seria = TypeSerializer(type, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def mx(_request): - """ API view to list the MX records """ - mx = Mx.objects.all().select_related("zone").select_related("name__extension") - seria = MxSerializer(mx, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def txt(_request): - """ API view to list the TXT records """ - txt = Txt.objects.all().select_related("zone") - seria = TxtSerializer(txt, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def srv(_request): - """ API view to list the SRV records """ - srv = ( - Srv.objects.all() - .select_related("extension") - .select_related("target__extension") - ) - seria = SrvSerializer(srv, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ns(_request): - """ API view to list the NS records """ - ns = ( - Ns.objects.exclude( - ns__in=Domain.objects.filter( - interface_parent__in=Interface.objects.filter(ipv4=None) - ) - ) - .select_related("zone") - .select_related("ns__extension") - ) - seria = NsSerializer(ns, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def zones(_request): - """ API view to list the DNS zones """ - zones = Extension.objects.all().select_related("origin") - seria = ExtensionSerializer(zones, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def mac_ip(request): - """ API view to list the active and assigned interfaces """ - seria = mac_ip_list(request) - return JSONResponse(seria) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def mac_ip_dns(request): - """ API view to list the active and assigned interfaces. More - detailed than mac_ip_list(request) """ - seria = full_mac_ip_list(request) - return JSONResponse(seria) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def service_servers(_request): - """ API view to list the service links """ - service_link = ( - Service_link.objects.all() - .select_related("server__domain") - .select_related("service") - ) - seria = ServiceServersSerializer(service_link, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ouverture_ports(_request): - """ API view to list the port policies for each IP """ - r = {"ipv4": {}, "ipv6": {}} - for o in ( - OuverturePortList.objects.all() - .prefetch_related("ouvertureport_set") - .prefetch_related("interface_set", "interface_set__ipv4") - ): - pl = { - "tcp_in": set( - map( - str, - o.ouvertureport_set.filter( - protocole=OuverturePort.TCP, io=OuverturePort.IN - ), - ) - ), - "tcp_out": set( - map( - str, - o.ouvertureport_set.filter( - protocole=OuverturePort.TCP, io=OuverturePort.OUT - ), - ) - ), - "udp_in": set( - map( - str, - o.ouvertureport_set.filter( - protocole=OuverturePort.UDP, io=OuverturePort.IN - ), - ) - ), - "udp_out": set( - map( - str, - o.ouvertureport_set.filter( - protocole=OuverturePort.UDP, io=OuverturePort.OUT - ), - ) - ), - } - for i in filter_active_interfaces(o.interface_set): - if i.may_have_port_open(): - d = r["ipv4"].get(i.ipv4.ipv4, {}) - d["tcp_in"] = d.get("tcp_in", set()).union(pl["tcp_in"]) - d["tcp_out"] = d.get("tcp_out", set()).union(pl["tcp_out"]) - d["udp_in"] = d.get("udp_in", set()).union(pl["udp_in"]) - d["udp_out"] = d.get("udp_out", set()).union(pl["udp_out"]) - r["ipv4"][i.ipv4.ipv4] = d - if i.ipv6(): - for ipv6 in i.ipv6(): - d = r["ipv6"].get(ipv6.ipv6, {}) - d["tcp_in"] = d.get("tcp_in", set()).union(pl["tcp_in"]) - d["tcp_out"] = d.get("tcp_out", set()).union(pl["tcp_out"]) - d["udp_in"] = d.get("udp_in", set()).union(pl["udp_in"]) - d["udp_out"] = d.get("udp_out", set()).union(pl["udp_out"]) - r["ipv6"][ipv6.ipv6] = d - return JSONResponse(r) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def regen_achieved(request): - """ API view to list the regen status for each (Service link, Server) - couple """ - obj = Service_link.objects.filter( - service__in=Service.objects.filter(service_type=request.POST["service"]), - server__in=Interface.objects.filter( - domain__in=Domain.objects.filter(name=request.POST["server"]) - ), - ) - if obj: - obj.first().done_regen() - return HttpResponse("Ok") diff --git a/preferences/api/__init__.py b/preferences/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/preferences/api/serializers.py b/preferences/api/serializers.py new file mode 100644 index 00000000..d7223028 --- /dev/null +++ b/preferences/api/serializers.py @@ -0,0 +1,174 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import serializers + +import preferences.models as preferences +from api.serializers import NamespacedHRField, NamespacedHIField, NamespacedHMSerializer + +class OptionalUserSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.OptionalUser` objects. + """ + + tel_mandatory = serializers.BooleanField(source="is_tel_mandatory") + shell_default = serializers.StringRelatedField() + + class Meta: + model = preferences.OptionalUser + fields = ( + "tel_mandatory", + "gpg_fingerprint", + "all_can_create_club", + "self_adhesion", + "shell_default", + "self_change_shell", + "local_email_accounts_enabled", + "local_email_domain", + "max_email_address", + ) + + +class OptionalMachineSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.OptionalMachine` objects. + """ + + class Meta: + model = preferences.OptionalMachine + fields = ( + "password_machine", + "max_lambdauser_interfaces", + "max_lambdauser_aliases", + "ipv6_mode", + "create_machine", + "ipv6", + "default_dns_ttl" + ) + + +class OptionalTopologieSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.OptionalTopologie` objects. + """ + + switchs_management_interface_ip = serializers.CharField() + + class Meta: + model = preferences.OptionalTopologie + fields = ( + "switchs_ip_type", + "switchs_web_management", + "switchs_web_management_ssl", + "switchs_rest_management", + "switchs_management_utils", + "switchs_management_interface_ip", + "provision_switchs_enabled", + "switchs_provision", + "switchs_management_sftp_creds", + ) + + +class RadiusOptionSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.RadiusOption` objects + """ + + class Meta: + model = preferences.RadiusOption + fields = ( + "radius_general_policy", + "unknown_machine", + "unknown_machine_vlan", + "unknown_port", + "unknown_port_vlan", + "unknown_room", + "unknown_room_vlan", + "non_member", + "non_member_vlan", + "banned", + "banned_vlan", + "vlan_decision_ok", + ) + + +class GeneralOptionSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.GeneralOption` objects. + """ + + class Meta: + model = preferences.GeneralOption + fields = ( + "general_message_fr", + "general_message_en", + "search_display_page", + "pagination_number", + "pagination_large_number", + "req_expire_hrs", + "site_name", + "main_site_url", + "email_from", + "GTU_sum_up", + "GTU", + ) + + +class HomeServiceSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.Service` objects. + """ + + class Meta: + model = preferences.Service + fields = ("name", "url", "description", "image", "api_url") + extra_kwargs = {"api_url": {"view_name": "homeservice-detail"}} + + +class AssoOptionSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.AssoOption` objects. + """ + + class Meta: + model = preferences.AssoOption + fields = ( + "name", + "siret", + "adresse1", + "adresse2", + "contact", + "telephone", + "pseudo", + "utilisateur_asso", + "description", + ) + + +class HomeOptionSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.HomeOption` objects. + """ + + class Meta: + model = preferences.HomeOption + fields = ("facebook_url", "twitter_url", "twitter_account_name") + + +class MailMessageOptionSerializer(NamespacedHMSerializer): + """Serialize `preferences.models.MailMessageOption` objects. + """ + + class Meta: + model = preferences.MailMessageOption + fields = ("welcome_mail_fr", "welcome_mail_en") \ No newline at end of file diff --git a/preferences/api/urls.py b/preferences/api/urls.py new file mode 100644 index 00000000..b9ebf859 --- /dev/null +++ b/preferences/api/urls.py @@ -0,0 +1,37 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from . import views + +urls_viewset = [ + (r"preferences/service", views.HomeServiceViewSet, "homeservice") +] + +urls_view = [ + (r"preferences/optionaluser", views.OptionalUserView), + (r"preferences/optionalmachine", views.OptionalMachineView), + (r"preferences/optionaltopologie", views.OptionalTopologieView), + (r"preferences/radiusoption", views.RadiusOptionView), + (r"preferences/generaloption", views.GeneralOptionView), + (r"preferences/assooption", views.AssoOptionView), + (r"preferences/homeoption", views.HomeOptionView), + (r"preferences/mailmessageoption", views.MailMessageOptionView) +] \ No newline at end of file diff --git a/preferences/api/views.py b/preferences/api/views.py new file mode 100644 index 00000000..6bce71b2 --- /dev/null +++ b/preferences/api/views.py @@ -0,0 +1,130 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import viewsets, generics + +from . import serializers +import preferences.models as preferences +from api.permissions import ACLPermission + + +class OptionalUserView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.OptionalUser.can_view_all]} + serializer_class = serializers.OptionalUserSerializer + + def get_object(self): + return preferences.OptionalUser.objects.first() + + +class OptionalMachineView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.OptionalMachine` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.OptionalMachine.can_view_all]} + serializer_class = serializers.OptionalMachineSerializer + + def get_object(self): + return preferences.OptionalMachine.objects.first() + + +class OptionalTopologieView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.OptionalTopologie` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.OptionalTopologie.can_view_all]} + serializer_class = serializers.OptionalTopologieSerializer + + def get_object(self): + return preferences.OptionalTopologie.objects.first() + + +class RadiusOptionView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.OptionalTopologie` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.RadiusOption.can_view_all]} + serializer_class = serializers.RadiusOptionSerializer + + def get_object(self): + return preferences.RadiusOption.objects.first() + + +class GeneralOptionView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.GeneralOption` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.GeneralOption.can_view_all]} + serializer_class = serializers.GeneralOptionSerializer + + def get_object(self): + return preferences.GeneralOption.objects.first() + + +class HomeServiceViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `preferences.models.Service` objects. + """ + + queryset = preferences.Service.objects.all() + serializer_class = serializers.HomeServiceSerializer + + +class AssoOptionView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.AssoOption` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.AssoOption.can_view_all]} + serializer_class = serializers.AssoOptionSerializer + + def get_object(self): + return preferences.AssoOption.objects.first() + + +class HomeOptionView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.HomeOption` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.HomeOption.can_view_all]} + serializer_class = serializers.HomeOptionSerializer + + def get_object(self): + return preferences.HomeOption.objects.first() + + +class MailMessageOptionView(generics.RetrieveAPIView): + """Exposes details of `preferences.models.MailMessageOption` settings. + """ + + permission_classes = (ACLPermission,) + perms_map = {"GET": [preferences.MailMessageOption.can_view_all]} + serializer_class = serializers.MailMessageOptionSerializer + + def get_object(self): + return preferences.MailMessageOption.objects.first() \ No newline at end of file diff --git a/topologie/api/__init__.py b/topologie/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/topologie/api/serializers.py b/topologie/api/serializers.py new file mode 100644 index 00000000..18785ebb --- /dev/null +++ b/topologie/api/serializers.py @@ -0,0 +1,323 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import serializers + +import topologie.models as topologie +import machines.models as machines +from machines.api.serializers import VlanSerializer, Ipv6ListSerializer +from api.serializers import NamespacedHRField, NamespacedHIField, NamespacedHMSerializer + + +class StackSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Stack` objects + """ + + class Meta: + model = topologie.Stack + fields = ( + "name", + "stack_id", + "details", + "member_id_min", + "member_id_max", + "api_url", + ) + + +class AccessPointSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.AccessPoint` objects + """ + + class Meta: + model = topologie.AccessPoint + fields = ("user", "name", "active", "location", "api_url") + + +class SwitchSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Switch` objects + """ + + port_amount = serializers.IntegerField(source="number") + + class Meta: + model = topologie.Switch + fields = ( + "user", + "name", + "active", + "port_amount", + "stack", + "stack_member_id", + "model", + "switchbay", + "api_url", + ) + + +class ServerSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Server` objects + """ + + class Meta: + model = topologie.Server + fields = ("user", "name", "active", "api_url") + + +class ModelSwitchSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.ModelSwitch` objects + """ + + class Meta: + model = topologie.ModelSwitch + fields = ("reference", "constructor", "api_url") + + +class ConstructorSwitchSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.ConstructorSwitch` objects + """ + + class Meta: + model = topologie.ConstructorSwitch + fields = ("name", "api_url") + + +class SwitchBaySerializer(NamespacedHMSerializer): + """Serialize `topologie.models.SwitchBay` objects + """ + + class Meta: + model = topologie.SwitchBay + fields = ("name", "building", "info", "api_url") + + +class BuildingSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Building` objects + """ + + class Meta: + model = topologie.Building + fields = ("name", "api_url") + + +class SwitchPortSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Port` objects + """ + + get_port_profile = NamespacedHIField(view_name="portprofile-detail", read_only=True) + + class Meta: + model = topologie.Port + fields = ( + "switch", + "port", + "room", + "machine_interface", + "related", + "custom_profile", + "state", + "get_port_profile", + "details", + "api_url", + ) + extra_kwargs = { + "related": {"view_name": "switchport-detail"}, + "api_url": {"view_name": "switchport-detail"}, + } + + +class PortProfileSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Room` objects + """ + + class Meta: + model = topologie.PortProfile + fields = ( + "name", + "profil_default", + "vlan_untagged", + "vlan_tagged", + "radius_type", + "radius_mode", + "speed", + "mac_limit", + "flow_control", + "dhcp_snooping", + "dhcpv6_snooping", + "dhcpv6_snooping", + "arp_protect", + "ra_guard", + "loop_protect", + "api_url", + ) + + +class RoomSerializer(NamespacedHMSerializer): + """Serialize `topologie.models.Room` objects + """ + + class Meta: + model = topologie.Room + fields = ("name", "details", "api_url") + + +class PortProfileSerializer(NamespacedHMSerializer): + vlan_untagged = VlanSerializer(read_only=True) + + class Meta: + model = topologie.PortProfile + fields = ( + "name", + "profil_default", + "vlan_untagged", + "vlan_tagged", + "radius_type", + "radius_mode", + "speed", + "mac_limit", + "flow_control", + "dhcp_snooping", + "dhcpv6_snooping", + "arp_protect", + "ra_guard", + "loop_protect", + "vlan_untagged", + "vlan_tagged", + ) + + +class InterfaceVlanSerializer(NamespacedHMSerializer): + domain = serializers.CharField(read_only=True) + ipv4 = serializers.CharField(read_only=True) + ipv6 = Ipv6ListSerializer(read_only=True, many=True) + vlan_id = serializers.IntegerField( + source="machine_type.ip_type.vlan.vlan_id", read_only=True + ) + + class Meta: + model = machines.Interface + fields = ("ipv4", "ipv6", "domain", "vlan_id") + + +class InterfaceRoleSerializer(NamespacedHMSerializer): + interface = InterfaceVlanSerializer( + source="machine.interface_set", read_only=True, many=True + ) + + class Meta: + model = machines.Interface + fields = ("interface",) + + +class RoleSerializer(NamespacedHMSerializer): + """Serialize `machines.models.OuverturePort` objects. + """ + + servers = InterfaceRoleSerializer(read_only=True, many=True) + + class Meta: + model = machines.Role + fields = ("role_type", "servers", "specific_role") + + +class VlanPortSerializer(NamespacedHMSerializer): + class Meta: + model = machines.Vlan + fields = ("vlan_id", "name") + + +class ProfilSerializer(NamespacedHMSerializer): + vlan_untagged = VlanSerializer(read_only=True) + vlan_tagged = VlanPortSerializer(read_only=True, many=True) + + class Meta: + model = topologie.PortProfile + fields = ( + "name", + "profil_default", + "vlan_untagged", + "vlan_tagged", + "radius_type", + "radius_mode", + "speed", + "mac_limit", + "flow_control", + "dhcp_snooping", + "dhcpv6_snooping", + "arp_protect", + "ra_guard", + "loop_protect", + "vlan_untagged", + "vlan_tagged", + ) + + +class ModelSwitchSerializer(NamespacedHMSerializer): + constructor = serializers.CharField(read_only=True) + + class Meta: + model = topologie.ModelSwitch + fields = ("reference", "firmware", "constructor") + + +class SwitchBaySerializer(NamespacedHMSerializer): + class Meta: + model = topologie.SwitchBay + fields = ("name",) + + +class PortsSerializer(NamespacedHMSerializer): + """Serialize `machines.models.Ipv6List` objects. + """ + + get_port_profile = ProfilSerializer(read_only=True) + + class Meta: + model = topologie.Port + fields = ("state", "port", "pretty_name", "get_port_profile") + + +class SwitchPortSerializer(serializers.ModelSerializer): + """Serialize the data about the switches""" + + ports = PortsSerializer(many=True, read_only=True) + model = ModelSwitchSerializer(read_only=True) + switchbay = SwitchBaySerializer(read_only=True) + + class Meta: + model = topologie.Switch + fields = ( + "short_name", + "model", + "switchbay", + "ports", + "ipv4", + "ipv6", + "interfaces_subnet", + "interfaces6_subnet", + "automatic_provision", + "rest_enabled", + "web_management_enabled", + "get_radius_key_value", + "get_management_cred_value", + "get_radius_servers", + "list_modules", + ) diff --git a/topologie/api/urls.py b/topologie/api/urls.py new file mode 100644 index 00000000..f6febb95 --- /dev/null +++ b/topologie/api/urls.py @@ -0,0 +1,45 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from . import views + +urls_viewset = [ + (r"topologie/stack", views.StackViewSet, None), + (r"topologie/acesspoint", views.AccessPointViewSet, None), + (r"topologie/switch", views.SwitchViewSet, None), + (r"topologie/server", views.ServerViewSet, None), + (r"topologie/modelswitch", views.ModelSwitchViewSet, None), + (r"topologie/constructorswitch", views.ConstructorSwitchViewSet, None), + (r"topologie/switchbay", views.SwitchBayViewSet, None), + (r"topologie/building", views.BuildingViewSet, None), + (r"topologie/switchport", views.SwitchPortViewSet, "switchport"), + (r"topologie/portprofile", views.PortProfileViewSet, "portprofile"), + (r"topologie/room", views.RoomViewSet, None) +] + +urls_view = [ + (r"topologie/switchs-ports-config", views.SwitchPortView), + (r"topologie/switchs-role", views.RoleView), + + # Deprecated + (r"switchs/ports-config", views.SwitchPortView), + (r"switchs/role", views.RoleView), +] diff --git a/topologie/api/views.py b/topologie/api/views.py new file mode 100644 index 00000000..5e937cda --- /dev/null +++ b/topologie/api/views.py @@ -0,0 +1,149 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import viewsets, generics + +from . import serializers +import topologie.models as topologie +import machines.models as machines + + +class StackViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.Stack` objects. + """ + + queryset = topologie.Stack.objects.all() + serializer_class = serializers.StackSerializer + + +class AccessPointViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.AccessPoint` objects. + """ + + queryset = topologie.AccessPoint.objects.all() + serializer_class = serializers.AccessPointSerializer + + +class SwitchViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.Switch` objects. + """ + + queryset = topologie.Switch.objects.all() + serializer_class = serializers.SwitchSerializer + + +class ServerViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.Server` objects. + """ + + queryset = topologie.Server.objects.all() + serializer_class = serializers.ServerSerializer + + +class ModelSwitchViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.ModelSwitch` objects. + """ + + queryset = topologie.ModelSwitch.objects.all() + serializer_class = serializers.ModelSwitchSerializer + + +class ConstructorSwitchViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.ConstructorSwitch` + objects. + """ + + queryset = topologie.ConstructorSwitch.objects.all() + serializer_class = serializers.ConstructorSwitchSerializer + + +class SwitchBayViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.SwitchBay` objects. + """ + + queryset = topologie.SwitchBay.objects.all() + serializer_class = serializers.SwitchBaySerializer + + +class BuildingViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.Building` objects. + """ + + queryset = topologie.Building.objects.all() + serializer_class = serializers.BuildingSerializer + + +class SwitchPortViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.Port` objects. + """ + + queryset = topologie.Port.objects.all() + serializer_class = serializers.SwitchPortSerializer + + +class PortProfileViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.PortProfile` objects. + """ + + queryset = topologie.PortProfile.objects.all() + serializer_class = serializers.PortProfileSerializer + + +class RoomViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.Room` objects. + """ + + queryset = topologie.Room.objects.all() + serializer_class = serializers.RoomSerializer + + +class PortProfileViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `topologie.models.PortProfile` objects. + """ + + queryset = topologie.PortProfile.objects.all() + serializer_class = serializers.PortProfileSerializer + + +class SwitchPortView(generics.ListAPIView): + """Output each port of a switch, to be serialized with + additionnal informations (profiles etc) + """ + + queryset = ( + topologie.Switch.objects.all() + .select_related("switchbay") + .select_related("model__constructor") + .prefetch_related("ports__custom_profile__vlan_tagged") + .prefetch_related("ports__custom_profile__vlan_untagged") + .prefetch_related("ports__machine_interface__domain__extension") + .prefetch_related("ports__room") + ) + + serializer_class = serializers.SwitchPortSerializer + + +class RoleView(generics.ListAPIView): + """Output of roles for each server + """ + + queryset = machines.Role.objects.all().prefetch_related("servers") + serializer_class = serializers.RoleSerializer \ No newline at end of file diff --git a/users/api/__init__.py b/users/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/users/api/serializers.py b/users/api/serializers.py new file mode 100644 index 00000000..e4c6c7e0 --- /dev/null +++ b/users/api/serializers.py @@ -0,0 +1,244 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import serializers + +import users.models as users +from api.serializers import NamespacedHRField, NamespacedHIField, NamespacedHMSerializer + +class UserSerializer(NamespacedHMSerializer): + """Serialize `users.models.User` objects. + """ + + access = serializers.BooleanField(source="has_access") + uid = serializers.IntegerField(source="uid_number") + + class Meta: + model = users.User + fields = ( + "surname", + "pseudo", + "email", + "local_email_redirect", + "local_email_enabled", + "school", + "shell", + "comment", + "state", + "registered", + "telephone", + "solde", + "access", + "end_access", + "uid", + "class_type", + "api_url", + ) + extra_kwargs = {"shell": {"view_name": "shell-detail"}} + + +class ClubSerializer(NamespacedHMSerializer): + """Serialize `users.models.Club` objects. + """ + + name = serializers.CharField(source="surname") + access = serializers.BooleanField(source="has_access") + uid = serializers.IntegerField(source="uid_number") + + class Meta: + model = users.Club + fields = ( + "name", + "pseudo", + "email", + "local_email_redirect", + "local_email_enabled", + "school", + "shell", + "comment", + "state", + "registered", + "telephone", + "solde", + "room", + "access", + "end_access", + "administrators", + "members", + "mailing", + "uid", + "api_url", + ) + extra_kwargs = {"shell": {"view_name": "shell-detail"}} + + +class AdherentSerializer(NamespacedHMSerializer): + """Serialize `users.models.Adherent` objects. + """ + + access = serializers.BooleanField(source="has_access") + uid = serializers.IntegerField(source="uid_number") + + class Meta: + model = users.Adherent + fields = ( + "name", + "surname", + "pseudo", + "email", + "local_email_redirect", + "local_email_enabled", + "school", + "shell", + "comment", + "state", + "registered", + "telephone", + "room", + "solde", + "access", + "end_access", + "uid", + "api_url", + "gid", + ) + extra_kwargs = {"shell": {"view_name": "shell-detail"}} + + +class BasicUserSerializer(NamespacedHMSerializer): + """Serialize 'users.models.User' minimal infos""" + + uid = serializers.IntegerField(source="uid_number") + gid = serializers.IntegerField(source="gid_number") + + class Meta: + model = users.User + fields = ("pseudo", "uid", "gid") + + +class ServiceUserSerializer(NamespacedHMSerializer): + """Serialize `users.models.ServiceUser` objects. + """ + + class Meta: + model = users.ServiceUser + fields = ("pseudo", "access_group", "comment", "api_url") + + +class SchoolSerializer(NamespacedHMSerializer): + """Serialize `users.models.School` objects. + """ + + class Meta: + model = users.School + fields = ("name", "api_url") + + +class ListRightSerializer(NamespacedHMSerializer): + """Serialize `users.models.ListRight` objects. + """ + + class Meta: + model = users.ListRight + fields = ("unix_name", "gid", "critical", "details", "api_url") + + +class ShellSerializer(NamespacedHMSerializer): + """Serialize `users.models.ListShell` objects. + """ + + class Meta: + model = users.ListShell + fields = ("shell", "api_url") + extra_kwargs = {"api_url": {"view_name": "shell-detail"}} + + +class BanSerializer(NamespacedHMSerializer): + """Serialize `users.models.Ban` objects. + """ + + active = serializers.BooleanField(source="is_active") + + class Meta: + model = users.Ban + fields = ( + "user", + "raison", + "date_start", + "date_end", + "state", + "active", + "api_url", + ) + + +class WhitelistSerializer(NamespacedHMSerializer): + """Serialize `users.models.Whitelist` objects. + """ + + active = serializers.BooleanField(source="is_active") + + class Meta: + model = users.Whitelist + fields = ("user", "raison", "date_start", "date_end", "active", "api_url") + + +class EMailAddressSerializer(NamespacedHMSerializer): + """Serialize `users.models.EMailAddress` objects. + """ + + user = serializers.CharField(source="user.pseudo", read_only=True) + + class Meta: + model = users.EMailAddress + fields = ("user", "local_part", "complete_email_address", "api_url") + + +class LocalEmailUsersSerializer(NamespacedHMSerializer): + email_address = EMailAddressSerializer(read_only=True, many=True) + + class Meta: + model = users.User + fields = ( + "local_email_enabled", + "local_email_redirect", + "email_address", + "email", + ) + + +class MailingMemberSerializer(UserSerializer): + """Serialize the data about a mailing member. + """ + + class Meta(UserSerializer.Meta): + fields = ("name", "pseudo", "get_mail") + + +class MailingSerializer(ClubSerializer): + """Serialize the data about a mailing. + """ + + members = MailingMemberSerializer(many=True) + admins = MailingMemberSerializer(source="administrators", many=True) + + class Meta(ClubSerializer.Meta): + fields = ("name", "members", "admins") \ No newline at end of file diff --git a/users/api/urls.py b/users/api/urls.py new file mode 100644 index 00000000..ef2b01b1 --- /dev/null +++ b/users/api/urls.py @@ -0,0 +1,49 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from . import views + +urls_viewset = [ + (r"users/user", views.UserViewSet, "user"), + (r"users/homecreation", views.HomeCreationViewSet, "homecreation"), + (r"users/normaluser", views.NormalUserViewSet, "normaluser"), + (r"users/criticaluser", views.CriticalUserViewSet, "criticaluser"), + (r"users/club", views.ClubViewSet, None), + (r"users/adherent", views.AdherentViewSet, None), + (r"users/serviceuser", views.ServiceUserViewSet, None), + (r"users/school", views.SchoolViewSet, None), + (r"users/listright", views.ListRightViewSet, None), + (r"users/shell", views.ShellViewSet, "shell"), + (r"users/ban", views.BanViewSet, None), + (r"users/whitelist", views.WhitelistViewSet, None), + (r"users/emailaddress", views.EMailAddressViewSet, None) +] + +urls_view = [ + (r"users/localemail", views.LocalEmailUsersView), + (r"users/mailing-standard", views.StandardMailingView), + (r"users/mailing-club", views.ClubMailingView), + + # Deprecated + (r"localemail/users", views.LocalEmailUsersView), + (r"mailing/standard", views.StandardMailingView), + (r"mailing/club", views.ClubMailingView), +] \ No newline at end of file diff --git a/users/api/views.py b/users/api/views.py new file mode 100644 index 00000000..57571f70 --- /dev/null +++ b/users/api/views.py @@ -0,0 +1,192 @@ +# -*- mode: python; coding: utf-8 -*- +# Re2o est un logiciel d'administration développé initiallement au rezometz. Il +# se veut agnostique au réseau considéré, de manière à être installable en +# quelques clics. +# +# Copyright © 2018 Maël Kervella +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +from rest_framework import viewsets, generics, views +from django.db.models import Q +from django.contrib.auth.models import Group + +from . import serializers +from api.pagination import PageSizedPagination +from api.permissions import ACLPermission +from re2o.utils import all_has_access +import users.models as users +import preferences.models as preferences + + +class UserViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.Users` objects. + """ + + queryset = users.User.objects.all() + serializer_class = serializers.UserSerializer + + +class HomeCreationViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes infos of `users.models.Users` objects to create homes. + """ + + queryset = users.User.objects.exclude( + Q(state=users.User.STATE_DISABLED) + | Q(state=users.User.STATE_NOT_YET_ACTIVE) + | Q(state=users.User.STATE_FULL_ARCHIVE) + ) + serializer_class = serializers.BasicUserSerializer + + +class NormalUserViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes infos of `users.models.Users`without specific rights objects.""" + + queryset = users.User.objects.exclude(groups__listright__critical=True).distinct() + serializer_class = serializers.BasicUserSerializer + + +class CriticalUserViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes infos of `users.models.Users`without specific rights objects.""" + + queryset = users.User.objects.filter(groups__listright__critical=True).distinct() + serializer_class = serializers.BasicUserSerializer + + +class ClubViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.Club` objects. + """ + + queryset = users.Club.objects.all() + serializer_class = serializers.ClubSerializer + + +class AdherentViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.Adherent` objects. + """ + + queryset = users.Adherent.objects.all() + serializer_class = serializers.AdherentSerializer + + +class ServiceUserViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.ServiceUser` objects. + """ + + queryset = users.ServiceUser.objects.all() + serializer_class = serializers.ServiceUserSerializer + + +class SchoolViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.School` objects. + """ + + queryset = users.School.objects.all() + serializer_class = serializers.SchoolSerializer + + +class ListRightViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.ListRight` objects. + """ + + queryset = users.ListRight.objects.all() + serializer_class = serializers.ListRightSerializer + + +class ShellViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.ListShell` objects. + """ + + queryset = users.ListShell.objects.all() + serializer_class = serializers.ShellSerializer + + +class BanViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.Ban` objects. + """ + + queryset = users.Ban.objects.all() + serializer_class = serializers.BanSerializer + + +class WhitelistViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.Whitelist` objects. + """ + + queryset = users.Whitelist.objects.all() + serializer_class = serializers.WhitelistSerializer + + +class EMailAddressViewSet(viewsets.ReadOnlyModelViewSet): + """Exposes list and details of `users.models.EMailAddress` objects. + """ + + serializer_class = serializers.EMailAddressSerializer + queryset = users.EMailAddress.objects.none() + + def get_queryset(self): + if preferences.OptionalUser.get_cached_value("local_email_accounts_enabled"): + return users.EMailAddress.objects.filter(user__local_email_enabled=True) + else: + return users.EMailAddress.objects.none() + + +class LocalEmailUsersView(generics.ListAPIView): + """Exposes all the aliases of the users that activated the internal address + """ + + serializer_class = serializers.LocalEmailUsersSerializer + + def get_queryset(self): + if preferences.OptionalUser.get_cached_value("local_email_accounts_enabled"): + return users.User.objects.filter(local_email_enabled=True) + else: + return users.User.objects.none() + + +class StandardMailingView(views.APIView): + """Exposes list and details of standard mailings (name and members) in + order to building the corresponding mailing lists. + """ + + pagination_class = PageSizedPagination + permission_classes = (ACLPermission,) + perms_map = {"GET": [users.User.can_view_all]} + + def get(self, request, format=None): + adherents_data = serializers.MailingMemberSerializer( + all_has_access(), many=True + ).data + + data = [{"name": "adherents", "members": adherents_data}] + groups = Group.objects.all() + for group in groups: + group_data = serializers.MailingMemberSerializer( + group.user_set.all(), many=True + ).data + data.append({"name": group.name, "members": group_data}) + + paginator = self.pagination_class() + paginator.paginate_queryset(data, request) + return paginator.get_paginated_response(data) + + +class ClubMailingView(generics.ListAPIView): + """Exposes list and details of club mailings (name, members and admins) in + order to build the corresponding mailing lists. + """ + + queryset = users.Club.objects.all() + serializer_class = serializers.MailingSerializer \ No newline at end of file diff --git a/users/urls.py b/users/urls.py index a1579a29..9ecb3967 100644 --- a/users/urls.py +++ b/users/urls.py @@ -127,21 +127,4 @@ urlpatterns = [ url(r"^$", views.index, name="index"), url(r"^index_clubs/$", views.index_clubs, name="index-clubs"), url(r"^initial_register/$", views.initial_register, name="initial-register"), - url(r"^rest/ml/std/$", views.ml_std_list, name="ml-std-list"), - url( - r"^rest/ml/std/member/(?P\w+)/$", - views.ml_std_members, - name="ml-std-members", - ), - url(r"^rest/ml/club/$", views.ml_club_list, name="ml-club-list"), - url( - r"^rest/ml/club/admin/(?P\w+)/$", - views.ml_club_admins, - name="ml-club-admins", - ), - url( - r"^rest/ml/club/member/(?P\w+)/$", - views.ml_club_members, - name="ml-club-members", - ), ] diff --git a/users/views.py b/users/views.py index 1c544ba6..f37b9648 100644 --- a/users/views.py +++ b/users/views.py @@ -74,7 +74,6 @@ from re2o.acl import ( ) from cotisations.utils import find_payment_method from topologie.models import Port -from .serializers import MailingSerializer, MailingMemberSerializer from .models import ( User, Ban, @@ -1129,78 +1128,3 @@ def initial_register(request): request, ) - -class JSONResponse(HttpResponse): - """ Framework Rest """ - - def __init__(self, data, **kwargs): - content = JSONRenderer().render(data) - kwargs["content_type"] = "application/json" - super(JSONResponse, self).__init__(content, **kwargs) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ml_std_list(_request): - """ API view sending all the available standard mailings""" - return JSONResponse([{"name": "adherents"}]) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ml_std_members(request, ml_name): - """ API view sending all the members for a standard mailing""" - # All with active connextion - if ml_name == "adherents": - members = all_has_access().values("email").distinct() - # Unknown mailing - else: - messages.error(request, _("The mailing list doesn't exist.")) - return redirect(reverse("index")) - seria = MailingMemberSerializer(members, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ml_club_list(_request): - """ API view sending all the available club mailings""" - clubs = Club.objects.filter(mailing=True).values("pseudo") - seria = MailingSerializer(clubs, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ml_club_admins(request, ml_name): - """ API view sending all the administrators for a specific club mailing""" - try: - club = Club.objects.get(mailing=True, pseudo=ml_name) - except Club.DoesNotExist: - messages.error(request, _("The mailing list doesn't exist.")) - return redirect(reverse("index")) - members = club.administrators.all().values("email").distinct() - seria = MailingMemberSerializer(members, many=True) - return JSONResponse(seria.data) - - -@csrf_exempt -@login_required -@permission_required("machines.serveur") -def ml_club_members(request, ml_name): - """ API view sending all the members for a specific club mailing""" - try: - club = Club.objects.get(mailing=True, pseudo=ml_name) - except Club.DoesNotExist: - messages.error(request, _("The mailing list doesn't exist.")) - return redirect(reverse("index")) - members = ( - club.administrators.all().values("email").distinct() - | club.members.all().values("email").distinct() - ) - seria = MailingMemberSerializer(members, many=True) - return JSONResponse(seria.data)