Skip to content
Snippets Groups Projects
vhosts.py 2.05 KiB
Newer Older
# -*- coding: utf-8 -*-
# Importazione dell'elenco dei corsi
# Copyright (c) 2019 Marco Marinello <me@marcomarinello.it>
#
# 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 3 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, see <http://www.gnu.org/licenses/>.


from django.core.management.base import BaseCommand
from access_landing import models
import re


class Command(BaseCommand):
    help = "Generate virtual hosts for apache"


    RE_IP_REGEX = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
    RE_FQDN_REGEX = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"


    def is_valid_fqdn_or_ip(self, s):
        if s.startswith("http://"):
            s = s[7:]
        elif s.startswith("https://"):
            s = s[8:]
        return re.match(self.RE_IP_REGEX, s) or re.match(self.RE_FQDN_REGEX, s)


    def gen_vhost(self, school):
        return f"""<VirtualHost *:443>
    ServerName {school.external_host}
    ServerAdmin webmaster@{school.external_host}
    DocumentRoot /var/www/html

    Include /etc/apache2/ssl.conf

    SSLProxyEngine on
    ProxyVia on
    ProxyPass / {school.internal_host}
    ProxyPassReverse / {school.internal_host}
    ProxyPreserveHost on
</VirtualHost>
"""


    def handle(self, *args, **kwargs):
        for school in models.Institute.objects.filter(active=True):
            if self.is_valid_fqdn_or_ip(school.external_host) and \
                self.is_valid_fqdn_or_ip(school.internal_host):
                print(self.gen_vhost(school))