Esempio n. 1
0
def delete_selfservice(request, mail_id):
    rcpt = request.GET.get("rcpt", None)
    if rcpt is None:
        raise ModoboaException(_("Invalid request"))
    try:
        msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id)
        msgrcpt.rs = 'D'
        msgrcpt.save()
    except Msgrcpt.DoesNotExist:
        raise ModoboaException(_("Invalid request"))
    return ajax_simple_response(dict(status="ok",
                                     respmsg=_("Message deleted")))
Esempio n. 2
0
def graphs(request):
    gset = request.GET.get("gset", None)
    gsets = events.raiseDictEvent("GetGraphSets")
    if not gset in gsets:
        raise ModoboaException(_("Unknown graphic set"))
    searchq = request.GET.get("searchquery", None)
    period = request.GET.get("period", "day")
    tplvars = dict(graphs=[], period=period)
    if searchq in [None, "global"]:
        if not request.user.is_superuser:
            if not Domain.objects.get_for_admin(request.user).count():
                return ajax_simple_response({"status": "ok"})
            tplvars.update(
                domain=Domain.objects.get_for_admin(request.user)[0].name
            )
        else:
            tplvars.update(domain="global")
    else:
        domain = Domain.objects.filter(name__contains=searchq)
        if domain.count() != 1:
            return ajax_simple_response({"status": "ok"})
        if not request.user.can_access(domain[0]):
            raise PermDeniedException
        tplvars.update(domain=domain[0].name)

    if period == "custom":
        if not "start" in request.GET or not "end" in request.GET:
            raise ModoboaException(_("Bad custom period"))
        start = request.GET["start"]
        end = request.GET["end"]
        G = Grapher()
        period_name = "%s_%s" % (start.replace('-', ''), end.replace('-', ''))
        for tpl in gsets[gset].get_graphs():
            tplvars['graphs'].append(tpl.display_name)
            G.process(
                tplvars["domain"], period_name, str2Time(*start.split('-')),
                str2Time(*end.split('-')), tpl
            )
        tplvars["period_name"] = period_name
        tplvars["start"] = start
        tplvars["end"] = end
    else:
        tplvars['graphs'] = gsets[gset].get_graph_names()

    return ajax_simple_response(dict(
        status="ok",
        content=_render_to_string(request, "stats/graphs.html", tplvars)
    ))
Esempio n. 3
0
def forward(request, tplname='admin/forward.html'):
    try:
        mb = request.user.mailbox_set.all()[0]
    except IndexError:
        raise ModoboaException(
            _("You need a mailbox in order to define a forward"))
    try:
        al = Alias.objects.get(address=mb.address, domain__name=mb.domain.name)
    except Alias.DoesNotExist:
        al = None
    if request.method == "POST":
        form = ForwardForm(request.POST)
        error = None
        if form.is_valid():
            try:
                if al is None:
                    al = Alias()
                    al.address = mb.address
                    al.domain = mb.domain
                    al.enabled = mb.user.is_active
                intdests = []
                if form.cleaned_data["keepcopies"]:
                    intdests += [mb]
                form.parse_dest()
                al.save(int_rcpts=intdests, ext_rcpts=form.dests)
                if request.user.group != "SimpleUsers":
                    al.post_create(request.user)
                return ajax_response(request, respmsg=_("Forward updated"))
            except BadDestination, e:
                error = str(e)

        return ajax_simple_response(
            dict(status="ko", errors=form.errors, respmsg=error))
Esempio n. 4
0
    def authenticate(self, username=None, password=None):
        """Check the username/password and return a User."""
        if type(username) is unicode:
            username = username.encode("utf-8")
        if type(password) is unicode:
            password = password.encode("utf-8")
        conf = dict(
            param_tools.get_global_parameters("modoboa_imap_migration"))
        address = conf["server_address"]
        port = conf["server_port"]
        try:
            if conf["secured"]:
                conn = imaplib.IMAP4_SSL(address, port)
            else:
                conn = imaplib.IMAP4(address, port)
        except (socket.error, imaplib.IMAP4.error, ssl.SSLError) as error:
            raise ModoboaException(
                _("Connection to IMAP server failed: %s" % error))

        try:
            typ, data = conn.login(username, password)
        except imaplib.IMAP4.error:
            typ = "NO"
        conn.logout()
        if typ != "OK":
            return None
        return self.get_or_create_user(username, password)
Esempio n. 5
0
 def __init__(self):
     mode = parameters.get_admin("AM_PDP_MODE")
     try:
         if mode == "inet":
             host = parameters.get_admin('AM_PDP_HOST')
             port = parameters.get_admin('AM_PDP_PORT')
             self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             self.sock.connect((host, int(port)))
         else:
             path = parameters.get_admin('AM_PDP_SOCKET')
             self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
             self.sock.connect(path)
     except socket.error, err:
         raise ModoboaException(
             _("Connection to amavis failed: %s" % str(err)))
Esempio n. 6
0
def release_selfservice(request, mail_id):
    rcpt = request.GET.get("rcpt", None)
    secret_id = request.GET.get("secret_id", None)
    if rcpt is None or secret_id is None:
        raise ModoboaException(_("Invalid request"))
    try:
        msgrcpt = get_wrapper().get_recipient_message(rcpt, mail_id)
    except Msgrcpt.DoesNotExist:
        raise ModoboaException(_("Invalid request"))
    if secret_id != msgrcpt.mail.secret_id:
        raise ModoboaException(_("Invalid request"))
    if parameters.get_admin("USER_CAN_RELEASE") == "no":
        msgrcpt.rs = 'p'
        msg = _("Request sent")
    else:
        amr = AMrelease()
        result = amr.sendreq(mail_id, secret_id, rcpt)
        if result:
            rcpt.rs = 'R'
            msg = _("Message released")
        else:
            raise ModoboaException(result)
    msgrcpt.save()
    return ajax_simple_response(dict(status="ok", respmsg=msg))
Esempio n. 7
0
def get_account_credentials(request, accountid):
    """View to download a document."""
    account = User.objects.get(pk=accountid)
    if not request.user.can_access(account):
        raise PermDeniedException()
    fname = get_creds_filename(account)
    if not os.path.exists(fname):
        raise ModoboaException(_("No document available for this user"))
    content = decrypt_file(fname)
    if param_tools.get_global_parameter("delete_first_dl"):
        os.remove(fname)
    resp = HttpResponse(content)
    resp["Content-Type"] = "application/pdf"
    resp["Content-Length"] = len(content)
    resp["Content-Disposition"] = build_header(os.path.basename(fname))
    return resp
Esempio n. 8
0
def index(request):
    """
    FIXME: how to select a default graph set ?
    """
    deflocation = "graphs/?gset=mailtraffic"
    if not request.user.is_superuser:
        if not Domain.objects.get_for_admin(request.user).count():
            raise ModoboaException(_("No statistics available"))

    period = request.GET.get("period", "day")
    graph_sets = events.raiseDictEvent('GetGraphSets')
    return render(request, 'stats/index.html', {
        "periods": periods,
        "period": period,
        "selection": "stats",
        "deflocation": deflocation,
        "graph_sets": graph_sets
    })
Esempio n. 9
0
def importdata(request, formclass=ImportDataForm):
    """Generic import function

    As the process of importing data from a CSV file is the same
    whatever the type, we do a maximum of the work here.

    :param request: a ``Request`` instance
    :param typ: a string indicating the object type being imported
    :return: a ``Response`` instance
    """
    error = None
    form = formclass(request.POST, request.FILES)
    if form.is_valid():
        try:
            reader = csv.reader(request.FILES['sourcefile'],
                                delimiter=form.cleaned_data['sepchar'])
        except csv.Error, e:
            error = str(e)

        if error is None:
            try:
                cpt = 0
                for row in reader:
                    if not row:
                        continue
                    try:
                        fct = globals()["import_%s" % row[0].strip()]
                    except KeyError:
                        continue
                    try:
                        fct(request.user, row, form.cleaned_data)
                    except IntegrityError, e:
                        if form.cleaned_data["continue_if_exists"]:
                            continue
                        raise ModoboaException(
                            _("Object already exists: %s" % row))
                    cpt += 1
                msg = _("%d objects imported successfully" % cpt)
                return render(request, "admin/import_done.html", {
                    "status": "ok",
                    "msg": msg
                })
            except (ModoboaException), e:
                error = str(e)
    def authenticate(self, request, username=None, password=None):
        """Check the username/password and return a User."""
        lc = core_models.LocalConfig.objects.first()
        condition = (
            lc and not lc.parameters.get_value(
                "auto_create_domain_and_mailbox", app="admin"))
        if condition:
            # Automatic domain/mailbox is disabled. Deny auth to
            # prevent further issues...
            return None
        self.address, domain = email_utils.split_mailbox(username)
        provider_domain = models.EmailProviderDomain.objects.filter(
            name=domain).select_related("provider").first()
        if not provider_domain:
            # Domain not allowed for migration: failure
            return None
        address = provider_domain.provider.address
        port = provider_domain.provider.port
        try:
            if provider_domain.provider.secured:
                conn = imaplib.IMAP4_SSL(address, port)
            else:
                conn = imaplib.IMAP4(address, port)
        except (socket.error, imaplib.IMAP4.error, ssl.SSLError) as error:
            raise ModoboaException(
                _("Connection to IMAP server failed: %s") % error)

        try:
            typ, data = conn.login(
                smart_bytes(username), smart_str(password))
        except imaplib.IMAP4.error:
            typ = "NO"
        conn.logout()
        if typ != "OK":
            return None
        self.provider_domain = provider_domain
        return self.get_or_create_user(username, password)
Esempio n. 11
0
 def wrapped_f(request, *args, **kwargs):
     if request.user.mailbox_set.count():
         return f(request, *args, **kwargs)
     raise ModoboaException()