Compare commits

...

2 commits

21 changed files with 685 additions and 211 deletions

155
backend/backend/settings.py Normal file
View file

@ -0,0 +1,155 @@
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
import config.secret
import config.sql
import config.ldap
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config.secret.key
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
import ldap
from django_auth_ldap.config import LDAPSearch
AUTH_LDAP_SERVER_URI = config.ldap.uri
AUTH_LDAP_BIND_DN = config.ldap.bind_dn
AUTH_LDAP_BIND_PASSWORD = config.ldap.bind_pass
AUTH_LDAP_USER_SEARCH = LDAPSearch(
config.ldap.search_dn, ldap.SCOPE_SUBTREE, config.ldap.search_filter
)
AUTHENTICATION_BACKENDS = [
"django_auth_ldap.backend.LDAPBackend",
"django.contrib.auth.backends.ModelBackend",
]
LOGIN_REDIRECT_URL = '/'
# Application definition
INSTALLED_APPS = [
'multimail.apps.MultimailConfig',
'bootstrap4',
'django_static_fontawesome',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'multimail/templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'mail': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'mail.sqlite3',
},
'ldap': {
'ENGINE': 'ldapdb.backends.ldap',
'NAME': config.ldap.uri,
'USER': config.ldap.bind_dn,
'PASSWORD': config.ldap.bind_pass,
},
#'mysql': {
# 'NAME': 'user_data',
# 'ENGINE': 'django.db.backends.mysql',
# 'USER': 'mysql_user',
# 'PASSWORD': 'priv4te'
#}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'

View file

@ -17,6 +17,6 @@ from django.contrib import admin
from django.urls import include, path from django.urls import include, path
urlpatterns = [ urlpatterns = [
path('multimail/', include('multimail.urls')), path('', include('multimail.urls')),
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
] ]

View file

@ -1,29 +1,48 @@
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render
from django.urls import reverse from django.urls import reverse
from django.views import generic
from django.utils import timezone
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth import logout as auth_logout
from .models import Choice, Question, Domain from .models import Domain, Mailbox, Alias
from .owner import user_from_request
@login_required(login_url='/login/') @login_required(login_url='/login/')
def vote(request, question_id): def delete_domain(request, domain_id):
question = get_object_or_404(Question, pk=question_id)
try: try:
selected_choice = question.choice_set.get(pk=request.POST['choice']) user = user_from_request(request)
except (KeyError, Choice.DoesNotExist): domain = Domain.objects.filter(admin__admin=user['name'], admin__source=user['source']).get(pk=domain_id)
# Redisplay the question voting form. except:
return render(request, 'multimail/detail.html', { raise Http404
'question': question, # TODO this might fail due to foreign key constraint
'error_message': "You didn't select a choice.", domain.delete()
}) return HttpResponseRedirect(reverse('multimail:domains'))
else:
selected_choice.votes += 1
selected_choice.save() @login_required(login_url='/login/')
# Always return an HttpResponseRedirect after successfully dealing def delete_mailbox(request, mailbox_id):
# with POST data. This prevents data from being posted twice if a try:
# user hits the Back button. user = user_from_request(request)
return HttpResponseRedirect(reverse('multimail:results', args=(question.id,))) domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
mailbox = Mailbox.objects.filter(domain__in=domains).get(pk=mailbox_id)
except:
raise Http404
mailbox.delete()
return HttpResponseRedirect(reverse('multimail:mailboxes'))
@login_required(login_url='/login/')
def delete_alias(request, alias_id):
try:
user = user_from_request(request)
domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
alias = Alias.objects.filter(source_domain__in=domains).get(pk=alias_id)
except:
raise Http404
alias.delete()
return HttpResponseRedirect(reverse('multimail:aliases'))
def logout(request):
auth_logout(request)
return HttpResponseRedirect(reverse('multimail:login'))

View file

@ -1,32 +1,26 @@
from django.contrib import admin from django.contrib import admin
from .models import Choice, Question from .models import TLSPolicy, Domain, DomainOwner
from .models import Alias, Domain, Mailbox, TLSPolicy
class ChoiceInline(admin.TabularInline): class AdminInline(admin.TabularInline):
model = Choice model = DomainOwner
extra = 1 extra = 1
class QuestionAdmin(admin.ModelAdmin): class DomainAdmin(admin.ModelAdmin):
fieldsets = [ list_display = [('domain'), ('admins')]
(None, {'fields': ['question_text']}), inlines = [AdminInline]
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
] def admins(self, obj):
list_display = ('question_text', 'pub_date', 'was_published_recently') return "[" + ", ".join([x.source + ":" + x.admin for x in obj.admin.all()]) + "]"
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin) admin.site.register(Domain, DomainAdmin)
class TLSPolicyAdmin(admin.ModelAdmin): class TLSPolicyAdmin(admin.ModelAdmin):
list_display = ('domain', 'policy', 'params') list_display = [('domain'), ('policy'), ('params')]
admin.site.register(TLSPolicy, TLSPolicyAdmin) admin.site.register(TLSPolicy, TLSPolicyAdmin)
admin.site.register(Alias)
admin.site.register(Domain)
admin.site.register(Mailbox)

133
backend/multimail/forms.py Normal file
View file

@ -0,0 +1,133 @@
from django.contrib.auth.decorators import login_required
from django.forms import ModelForm
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render
from multimail.models import Domain, Mailbox, Alias
from multimail.owner import user_from_request
class DomainForm(ModelForm):
class Meta:
model = Domain
fields = '__all__'
#fields = ['domain']
class MailboxForm(ModelForm):
class Meta:
model = Mailbox
fields = '__all__'
class AliasForm(ModelForm):
class Meta:
model = Alias
fields = '__all__'
@login_required(login_url='/login/')
def edit_domain(request, domain_id):
try:
user = user_from_request(request)
domain = Domain.objects.filter(admin__admin=user['name'], admin__source=user['source']).get(pk=domain_id)
except:
raise Http404
if request.method == 'POST':
form = DomainForm(request.POST, instance=domain)
if form.is_valid():
form.save()
return HttpResponseRedirect('/domains/')
else:
form = DomainForm(instance=domain)
return render(request, 'multimail/edit_domain.html', {'form': form})
@login_required(login_url='/login/')
def new_domain(request):
user = user_from_request(request)
if request.method == 'POST':
form = DomainForm(request.POST)
if form.is_valid():
domain = form.save()
domain.admin.create(admin=user['name'], source=user['source'])
return HttpResponseRedirect('/domains/')
else:
form = DomainForm()
return render(request, 'multimail/edit_domain.html', {'form': form})
@login_required(login_url='/login/')
def edit_mailbox(request, mailbox_id):
try:
user = user_from_request(request)
domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
mailbox = Mailbox.objects.filter(domain__in=domains).get(pk=mailbox_id)
except:
raise Http404
if request.method == 'POST':
form = MailboxForm(request.POST, instance=mailbox)
if form.is_valid():
form.save()
return HttpResponseRedirect('/mailboxes/')
else:
form = MailboxForm(instance=mailbox)
return render(request, 'multimail/edit_mailbox.html', {'form': form})
@login_required(login_url='/login/')
def new_mailbox(request):
if request.method == 'POST':
user = user_from_request(request)
domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
form = MailboxForm(request.POST)
if form.is_valid() and form.domain in domains:
form.save()
return HttpResponseRedirect('/mailboxes/')
else:
form = MailboxForm()
return render(request, 'multimail/edit_mailbox.html', {'form': form})
@login_required(login_url='/login/')
def edit_alias(request, alias_id):
try:
user = user_from_request(request)
domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
alias = Alias.objects.filter(source_domain__in=domains).get(pk=alias_id)
except:
raise Http404
if request.method == 'POST':
form = AliasForm(request.POST, instance=alias)
if form.is_valid():
form.save()
return HttpResponseRedirect('/aliases/')
else:
form = AliasForm(instance=alias)
return render(request, 'multimail/edit_alias.html', {'form': form})
@login_required(login_url='/login/')
def new_alias(request):
if request.method == 'POST':
user = user_from_request(request)
domains = [o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
form = AliasForm(request.POST)
if form.is_valid() and form.source_domain in domains:
form.save()
return HttpResponseRedirect('/aliases/')
else:
form = AliasForm()
return render(request, 'multimail/edit_alias.html', {'form': form})

View file

@ -1,4 +1,4 @@
# Generated by Django 3.1.3 on 2020-11-02 18:55 # Generated by Django 3.1.3 on 2020-11-07 16:49
from django.db import migrations, models from django.db import migrations, models
import django.db.models.deletion import django.db.models.deletion
@ -13,20 +13,67 @@ class Migration(migrations.Migration):
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='Question', name='Alias',
fields=[ fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id', models.AutoField(primary_key=True, serialize=False)),
('question_text', models.CharField(max_length=200)), ('source_username', models.CharField(max_length=64)),
('pub_date', models.DateTimeField(verbose_name='date published')), ('source_domain', models.CharField(max_length=255)),
('destination_username', models.CharField(max_length=64)),
('destination_domain', models.CharField(max_length=255)),
('enabled', models.IntegerField(blank=True, null=True)),
], ],
options={
'db_table': 'aliases',
'managed': False,
},
), ),
migrations.CreateModel( migrations.CreateModel(
name='Choice', name='Domain',
fields=[ fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)), ('domain', models.CharField(max_length=255)),
('votes', models.IntegerField(default=0)), ],
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='multimail.question')), options={
'db_table': 'domains',
'managed': False,
},
),
migrations.CreateModel(
name='Mailbox',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('username', models.CharField(max_length=64)),
('domain', models.CharField(max_length=255)),
('password', models.CharField(max_length=255)),
('quota', models.IntegerField(blank=True, null=True)),
('enabled', models.IntegerField(blank=True, null=True)),
('sendonly', models.IntegerField(blank=True, null=True)),
],
options={
'db_table': 'mailboxes',
'managed': False,
},
),
migrations.CreateModel(
name='TLSPolicy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('domain', models.CharField(max_length=255)),
('policy', models.TextField()),
('params', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'db_table': 'tlspolicies',
'managed': False,
},
),
migrations.CreateModel(
name='DomainOwner',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('admin', models.CharField(max_length=200)),
('source', models.CharField(choices=[('system', 'system'), ('ldap', 'ldap'), ('mail', 'mail')], default=0, max_length=8)),
('domain', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='admin', to='multimail.domain')),
], ],
), ),
] ]

View file

@ -1,68 +0,0 @@
# Generated by Django 3.1.3 on 2020-11-02 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('multimail', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Aliases',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('source_username', models.CharField(max_length=64)),
('source_domain', models.CharField(max_length=255)),
('destination_username', models.CharField(max_length=64)),
('destination_domain', models.CharField(max_length=255)),
('enabled', models.IntegerField(blank=True, null=True)),
],
options={
'db_table': 'aliases',
'managed': False,
},
),
migrations.CreateModel(
name='Domains',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('domain', models.CharField(max_length=255)),
],
options={
'db_table': 'domains',
'managed': False,
},
),
migrations.CreateModel(
name='Mailboxes',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('username', models.CharField(max_length=64)),
('domain', models.CharField(max_length=255)),
('password', models.CharField(max_length=255)),
('quota', models.IntegerField(blank=True, null=True)),
('enabled', models.IntegerField(blank=True, null=True)),
('sendonly', models.IntegerField(blank=True, null=True)),
],
options={
'db_table': 'mailboxes',
'managed': False,
},
),
migrations.CreateModel(
name='Tlspolicies',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('domain', models.CharField(max_length=255)),
('policy', models.TextField()),
('params', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'db_table': 'tlspolicies',
'managed': False,
},
),
]

View file

@ -3,27 +3,6 @@ from django.db import models
from django.utils import timezone from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
class Alias(models.Model): class Alias(models.Model):
id = models.AutoField(primary_key=True) id = models.AutoField(primary_key=True)
source_username = models.CharField(max_length=64) source_username = models.CharField(max_length=64)
@ -67,3 +46,12 @@ class TLSPolicy(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'tlspolicies' db_table = 'tlspolicies'
class DomainOwner(models.Model):
domain = models.ForeignKey(Domain, on_delete=models.CASCADE, related_name='admin')
admin = models.CharField(max_length=200)
source = models.CharField(max_length=8, choices=[('system','system'), ('ldap', 'ldap'), ('mail', 'mail')], default=0)
def __str__(self):
return self.admin

View file

@ -0,0 +1,7 @@
def user_from_request(request):
if hasattr(request.user, 'ldap_user'):
# print(request.user.ldap_user.attrs.data)
return {'name': request.user.username, 'source': 'ldap'}
else:
return {'name': request.user.username, 'source': 'system'}

View file

@ -0,0 +1,43 @@
{% extends 'multimail/base.html' %}
{% block content %}
<h1 class="mt-4">Aliases</h1>
{% if alias_list %}
<table class="table table-striped table-responsive-md btn-table">
<thead>
<tr>
<th scope="col">Source</th>
<th scope="col">Destination</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for alias in alias_list %}
<tr>
<th scope="row"><a
href="{% url 'multimail:edit_alias' alias.id %}">{{ alias.source_username }}@{{ alias.source_domain }}</a>
</th>
<th scope="row">{{ alias.destination_username }}@{{ alias.destination_domain }}</th>
<td><a href="{% url 'multimail:delete_alias' alias.id %}"
class="btn btn-danger btn-sm m-0">Delete</a></td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th scope="row">
</th>
<th scope="row"></th>
<td><a href="{% url 'multimail:new_alias' %}" class="btn btn-primary btn-sm m-0">Add</a>
</td>
</tr>
</tfoot>
</table>
{% else %}
<p>You haven't set up any aliases yet.</p>
{% endif %}
{% endblock %}

View file

@ -16,6 +16,7 @@
<!-- Custom styles for this template --> <!-- Custom styles for this template -->
<link href="{% static 'multimail/css/simple-sidebar.css' %}" rel="stylesheet"> <link href="{% static 'multimail/css/simple-sidebar.css' %}" rel="stylesheet">
<link href="{% static "fontawesome/css/all.min.css" %}" rel="stylesheet" type="text/css"/>
</head> </head>
@ -29,7 +30,7 @@
<div class="list-group list-group-flush"> <div class="list-group list-group-flush">
<a href="{% url 'multimail:domains' %}" class="list-group-item list-group-item-action bg-light">Domains</a> <a href="{% url 'multimail:domains' %}" class="list-group-item list-group-item-action bg-light">Domains</a>
<a href="{% url 'multimail:mailboxes' %}" class="list-group-item list-group-item-action bg-light">Mailboxes</a> <a href="{% url 'multimail:mailboxes' %}" class="list-group-item list-group-item-action bg-light">Mailboxes</a>
<a href="#" class="list-group-item list-group-item-action bg-light">Aliases</a> <a href="{% url 'multimail:aliases' %}" class="list-group-item list-group-item-action bg-light">Aliases</a>
</div> </div>
</div> </div>
<!-- /#sidebar-wrapper --> <!-- /#sidebar-wrapper -->
@ -38,7 +39,7 @@
<div id="page-content-wrapper"> <div id="page-content-wrapper">
<nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom"> <nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
<button class="btn btn-primary" id="menu-toggle">Toggle Menu</button> <button class="btn btn-link btn-lg" id="menu-toggle"><i class="fas fa-bars"></i></button>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
@ -47,12 +48,12 @@
<div class="collapse navbar-collapse" id="navbarSupportedContent"> <div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0"> <ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active"> <!--li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" href="#">Link</a> <a class="nav-link" href="#">Link</a>
</li> </li-->
<li class="nav-item dropdown"> <li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

View file

@ -1,12 +0,0 @@
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'multimail:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

View file

@ -4,13 +4,34 @@
<h1 class="mt-4">Domains</h1> <h1 class="mt-4">Domains</h1>
{% if domain_list %} {% if domain_list %}
<ul> <table class="table table-striped table-responsive-md btn-table">
{% for question in domain_list %} <thead>
<li><a href="{% url 'multimail:detail' question.id %}">{{ question.domain }}</a></li> <tr>
<th scope="col">Domain</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for domain in domain_list %}
<tr>
<th scope="row"><a href="{% url 'multimail:edit_domain' domain.id %}">{{ domain.domain }}</a></th>
<td><a href="{% url 'multimail:delete_domain' domain.id %}" class="btn btn-danger btn-sm m-0">Delete</a></td>
</tr>
{% endfor %} {% endfor %}
</ul>
</tbody>
<tfoot>
<tr>
<th scope="row">
</th>
<td><a href="{% url 'multimail:new_domain' %}" class="btn btn-primary btn-sm m-0">Add</a>
</td>
</tr>
</tfoot>
</table>
{% else %} {% else %}
<p>No multimail are available.</p> <p>You haven't set up any domains yet.</p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View file

@ -0,0 +1,18 @@
{% extends 'multimail/base.html' %}
{% load bootstrap4 %}
{% block content %}
<h1 class="mt-4">{{ form.source_username.value }}@{{ form.source_domain.value }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
{% endblock %}

View file

@ -0,0 +1,17 @@
{% extends 'multimail/base.html' %}
{% load bootstrap4 %}
{% block content %}
<h1 class="mt-4">{{ form.domain.value }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
{% endblock %}

View file

@ -0,0 +1,17 @@
{% extends 'multimail/base.html' %}
{% load bootstrap4 %}
{% block content %}
<h1 class="mt-4">{{ form.username.value }}@{{ form.domain.value }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
{% endblock %}

View file

@ -0,0 +1,83 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Multimail</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="{% static 'multimail/css/simple-sidebar.css' %}" rel="stylesheet">
<link href="{% static "fontawesome/css/all.min.css" %}" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container" style="height:100vh;">
<div class="row h-100 justify-content-center align-items-center">
<div class="card col-6">
<article class="card-body">
<h4 class="card-title text-center mb-4 mt-1">Sign in</h4>
<hr>
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
<ul>
{% for error in form.non_field_errors %}
<li>{{ error|escape }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<form method="POST">{% csrf_token %}
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-user"></i> </span>
</div>
<input id="{{ form.username.id_for_label }}" name="{{ form.username.html_name }}"
class="form-control" placeholder="Email or login" type="text" requird>
</div> <!-- input-group.//-->
{% if form.username.errors %}
<p class="text-danger text-center">
{% for error in form.username.errors %}
{{ error|escape }}<br>
{% endfor %}
</p>
{% endif %}
</div> <!-- form-group// -->
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-lock"></i> </span>
</div>
<input id="{{ form.password.id_for_label }}" name="{{ form.password.html_name }}"
class="form-control" placeholder="******" type="password" required>
</div> <!-- input-group.// -->
{% if form.password.errors %}
<p class="text-danger text-center">
{% for error in form.password.errors %}
{{ error|escape }}<br>
{% endfor %}
</p>
{% endif %}
</div> <!-- form-group// -->
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block"> Login</button>
</div> <!-- form-group// -->
<!--p class="text-center"><a href="#" class="btn">Forgot password?</a></p-->
</form>
</article>
</div>
</div>
</div>
</body>
</html>

View file

@ -4,13 +4,34 @@
<h1 class="mt-4">Mailboxes</h1> <h1 class="mt-4">Mailboxes</h1>
{% if mailbox_list %} {% if mailbox_list %}
<ul> <table class="table table-striped table-responsive-md btn-table">
{% for question in mailbox_list %} <thead>
<li><a href="{% url 'multimail:detail' question.id %}">{{ question.domain }}</a></li> <tr>
<th scope="col">Mailbox</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for mailbox in mailbox_list %}
<tr>
<th scope="row"><a href="{% url 'multimail:edit_mailbox' mailbox.id %}">{{ mailbox.username }}@{{ mailbox.domain }}</a></th>
<td><a href="{% url 'multimail:delete_mailbox' mailbox.id %}" class="btn btn-danger btn-sm m-0">Delete</a></td>
</tr>
{% endfor %} {% endfor %}
</ul>
</tbody>
<tfoot>
<tr>
<th scope="row">
</th>
<td><a href="{% url 'multimail:new_mailbox' %}" class="btn btn-primary btn-sm m-0">Add</a>
</td>
</tr>
</tfoot>
</table>
{% else %} {% else %}
<p>No multimail are available.</p> <p>You haven't set up any mailboxes yet.</p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View file

@ -1,9 +0,0 @@
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'multimail:detail' question.id %}">Vote again?</a>

View file

@ -1,17 +1,28 @@
from django.urls import path from django.urls import path
from django.contrib.auth import views as auth_views from django.contrib.auth import views as auth_views
from . import views from . import views, forms
from . import actions from . import actions
app_name = 'multimail' app_name = 'multimail'
urlpatterns = [ urlpatterns = [
path('', views.DomainListView.as_view(), name='index'), path('', views.DomainListView.as_view(), name='index'),
path('domains/', views.DomainListView.as_view(), name='domains'), path('domains/', views.DomainListView.as_view(), name='domains'),
path('domain/new/', forms.new_domain, name='new_domain'),
path('domain/<int:domain_id>/', forms.edit_domain, name='edit_domain'),
path('domain/<int:domain_id>/delete', actions.delete_domain, name='delete_domain'),
path('mailboxes/', views.MailboxListView.as_view(), name='mailboxes'), path('mailboxes/', views.MailboxListView.as_view(), name='mailboxes'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('mailbox/new/', forms.new_mailbox, name='new_mailbox'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('mailbox/<int:mailbox_id>/', forms.edit_mailbox, name='edit_mailbox'),
path('<int:question_id>/vote/', actions.vote, name='vote'), path('mailbox/<int:mailbox_id>/delete', actions.delete_mailbox, name='delete_mailbox'),
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('aliases/', views.AliasListView.as_view(), name='aliases'),
path('alias/new/', forms.new_alias, name='new_alias'),
path('alias/<int:alias_id>/', forms.edit_alias, name='edit_alias'),
path('alias/<int:alias_id>/delete', actions.delete_alias, name='delete_alias'),
path('login/', views.UserLoginView.as_view(), name='login'),
path('logout/', actions.logout, name='logout'),
] ]

View file

@ -1,57 +1,45 @@
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic from django.views import generic
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView
from .models import Choice, Question, Domain, Mailbox from .models import Domain, Mailbox, Alias
from .owner import user_from_request
class UserLoginView(LoginView):
template_name = 'multimail/login.html'
class DomainListView(LoginRequiredMixin, generic.ListView): class DomainListView(LoginRequiredMixin, generic.ListView):
login_url = 'login/' login_url = 'login/'
# redirect_field_name = 'redirect_to'
template_name = 'multimail/domains.html' template_name = 'multimail/domains.html'
context_object_name = 'domain_list' context_object_name = 'domain_list'
def get_queryset(self): def get_queryset(self):
print(self.request.user)
"""Return the last five published questions.""" """Return the last five published questions."""
#return Domain.objects.filter( user = user_from_request(self.request)
# pub_date__lte=timezone.now() return Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])
#).order_by('-pub_date')[:5]
return Domain.objects.all()
class MailboxListView(LoginRequiredMixin, generic.ListView): class MailboxListView(LoginRequiredMixin, generic.ListView):
login_url = 'login/' login_url = 'login/'
# redirect_field_name = 'redirect_to'
template_name = 'multimail/mailboxes.html' template_name = 'multimail/mailboxes.html'
context_object_name = 'mailbox_list' context_object_name = 'mailbox_list'
def get_queryset(self): def get_queryset(self):
print(self.request.user)
"""Return the last five published questions.""" """Return the last five published questions."""
#return Domain.objects.filter( user = user_from_request(self.request)
# pub_date__lte=timezone.now() domains = [ o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
#).order_by('-pub_date')[:5] return Mailbox.objects.filter(domain__in=domains)
return Mailbox.objects.all()
class DetailView(LoginRequiredMixin, generic.DetailView): class AliasListView(LoginRequiredMixin, generic.ListView):
login_url = 'login/' login_url = 'login/'
model = Question template_name = 'multimail/aliases.html'
template_name = 'multimail/detail.html' context_object_name = 'alias_list'
def get_queryset(self): def get_queryset(self):
""" """Return the last five published questions."""
Excludes any questions that aren't published yet. user = user_from_request(self.request)
""" domains = [ o.domain for o in Domain.objects.filter(admin__admin=user['name'], admin__source=user['source'])]
return Question.objects.filter(pub_date__lte=timezone.now()) return Alias.objects.filter(source_domain__in=domains)
class ResultsView(LoginRequiredMixin, generic.DetailView):
login_url = 'login/'
model = Question
template_name = 'multimail/results.html'