Skip to content

Commit

Permalink
#43 リファクタリング.
Browse files Browse the repository at this point in the history
  • Loading branch information
yoneyan committed Sep 15, 2024
1 parent 8f8ba91 commit fd4c913
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 125 deletions.
57 changes: 22 additions & 35 deletions custom_auth/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,51 +139,38 @@ def create_group(self, user_id):
raise ValueError("ユーザとグループの紐づけに失敗しました")


class GroupForm(forms.Form):
name = forms.CharField(label="グループ名", max_length=150, required=True)
postcode = forms.CharField(label="郵便番号", max_length=10, required=True)
address = forms.CharField(label="住所", max_length=250, required=True)
address_en = forms.CharField(label="住所(English)", max_length=250, required=True)
phone = forms.CharField(label="phone", max_length=30, required=True)
country = forms.CharField(label="居住国", max_length=30, initial="Japan", required=True)

def __init__(self, edit=False, disable=False, *args, **kwargs):
class GroupForm(forms.ModelForm):
class Meta:
model = Group
fields = ("postcode", "address_jp", "address", "phone", "country")
labels = {
"postcode": "郵便番号",
"address_jp": "住所",
"address": "住所(English)",
"phone": "phone",
"country": "居住国",
}

def __init__(self, *args, **kwargs):
editable = kwargs.pop("editable", False) # group_id を引数として受け取る
super().__init__(*args, **kwargs)
if edit:
self.fields["name"].widget.attrs["readonly"] = True
if disable:
self.fields["postcode"].widget.attrs["disabled"] = True
self.fields["address"].widget.attrs["disabled"] = True
self.fields["address_en"].widget.attrs["disabled"] = True
self.fields["phone"].widget.attrs["disabled"] = True
self.fields["country"].widget.attrs["disabled"] = True
self.fields["name"].widget.attrs["class"] = "form-control"
if editable:
self.fields["postcode"].widget.attrs["disabled"] = True
self.fields["address_jp"].widget.attrs["disabled"] = True
self.fields["address"].widget.attrs["disabled"] = True
self.fields["phone"].widget.attrs["disabled"] = True
self.fields["country"].widget.attrs["disabled"] = True
self.fields["postcode"].widget.attrs["class"] = "form-control p-postal-code"
self.fields["address"].widget.attrs["class"] = (
self.fields["address_jp"].widget.attrs["class"] = (
"form-control p-region p-locality p-street-address p-extended-address"
)
self.fields["address_en"].widget.attrs["class"] = "form-control"
self.fields["address"].widget.attrs["class"] = "form-control"
self.fields["phone"].widget.attrs["class"] = "form-control"
self.fields["country"].widget.attrs["class"] = "form-control p-country-name"

for field in self.fields.values():
field.widget.attrs["placeholder"] = field.label

def update_group(self, group_id):
try:
Group.objects.update_group(
group_id=group_id,
postcode=self.cleaned_data["postcode"],
name=self.cleaned_data["name"],
address=self.cleaned_data["address"],
address_en=self.cleaned_data["address_en"],
email=self.cleaned_data["email"],
phone=self.cleaned_data["phone"],
country=self.cleaned_data["country"],
)
except Exception:
raise ValueError("グループの更新に失敗しました")


class TwoAuthForm(forms.Form):
title = forms.CharField(label="名前", max_length=100, required=True)
Expand Down
4 changes: 2 additions & 2 deletions custom_auth/group_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
urlpatterns = [
path("", views.list_groups, name="index"),
path("add/", views.add_group, name="add"),
path("edit/<int:group_id>", views.edit_group, name="edit"),
path("permission/<int:group_id>", views.group_permission, name="permission"),
path("<int:group_id>/edit", views.edit_group, name="edit"),
path("<int:group_id>/permission", views.group_permission, name="permission"),
path("<int:group_id>/payment", views.group_payment, name="payment"),
]
3 changes: 1 addition & 2 deletions custom_auth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,11 @@ def create_group(
**extra_fields,
)

def update_group(self, group_id, postcode, address, address_en, email, phone, country):
def update_group(self, group_id, postcode, address, address_en, phone, country):
group = Group.objects.get(id=group_id)
group.postcode = postcode
group.address = address
group.address_en = address_en
group.email = email
group.phone = phone
group.country = country
group.save()
Expand Down
12 changes: 7 additions & 5 deletions custom_auth/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@ def post_group(sender, instance, created, **kwargs):
return

notify_update_db(model_name=sender.__name__, instance=instance)
# 審査NG => 審査OKの場合にサービス追加とJPNIC追加を出来るようにする
if not instance._pre_save_instance.is_pass and instance.is_pass:
instance.allow_service_add = True
instance.allow_jpnic_add = True
instance.save(update_fields=["allow_service_add", "allow_jpnic_add"])
# インスタンスに以前の状態があれば審査状態の変化を確認する
if hasattr(instance, "_pre_save_instance") and instance._pre_save_instance:
# 審査NG => 審査OKの場合にサービス追加とJPNIC追加を出来るようにする
if not instance._pre_save_instance.is_pass and instance.is_pass:
instance.allow_service_add = True
instance.allow_jpnic_add = True
instance.save(update_fields=["allow_service_add", "allow_jpnic_add"])
# Statusが1以外の場合はサービス追加とJPNIC追加を禁止する
if instance.status != 1:
instance.allow_service_add = False
Expand Down
94 changes: 37 additions & 57 deletions custom_auth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.urls import reverse

from custom_auth.form import (
EmailChangeForm,
Expand Down Expand Up @@ -180,71 +181,50 @@ def add_group(request):

@login_required
def edit_group(request, group_id):
error = None
administrator = False
try:
group = request.user.groups.get(id=group_id)
group_data = {
"name": group.name,
"postcode": group.postcode,
"address": group.address_jp,
"address_en": group.address,
"phone": group.phone,
"country": group.country,
}
administrator = group.usergroup_set.filter(user=request.user, is_admin=True).exists()
if request.method == "POST" and administrator and group.is_pass:
form = GroupForm(data=request.POST)
if form.is_valid():
try:
form.update_group(group_id=group.id)
return render(request, "done.html", {"text": "登録・変更が完了しました"})
except ValueError as err:
error = err
else:
form = GroupForm(initial=group_data, edit=True, disable=not group.is_pass)
except Exception:
group = None
form = None
user_group = request.user.usergroup_set.filter(group_id=group_id, user=request.user).first()
if not user_group:
return render(request, "error.html", {"text": "このグループにアクセスする権限がありません"})
form = GroupForm(request.POST or None, instance=user_group.group, editable=not user_group.is_admin)
if request.method == "POST" and user_group.is_admin and user_group.group.is_pass:
if form.is_valid():
form.save()
return render(request, "done.html", {"text": "登録・変更が完了しました"})

context = {"form": form, "group": group, "administrator": administrator, "error": error}
context = {"form": form, "group": user_group.group, "is_administrator": user_group.is_admin}
return render(request, "group/edit.html", context)


@login_required
def group_permission(request, group_id):
error = None
administrator = False
permission_all = False
try:
group = request.user.groups.get(id=group_id)
permission_all = group.usergroup_set.all()
administrator = group.usergroup_set.filter(user=request.user, is_admin=True).exists()
if request.method == "POST" and administrator and group.is_active:
id = request.POST.get("id", 0)
is_exists = False
for permission_user in permission_all:
if permission_user.id == int(id):
is_exists = True
break
if not is_exists:
error = "変更権限がありません"
else:
try:
user_group = UserGroup.objects.get(id=int(id))
if "no_admin" in request.POST:
user_group.is_admin = False
user_group.save()
elif "admin" in request.POST:
user_group.is_admin = True
user_group.save()
return redirect("/group/permission/%d" % group_id)
except Exception:
error = "アップデート処理でエラーが発生しました"
except Exception:
group = None
user_group = request.user.usergroup_set.filter(group_id=group_id, user=request.user).first()
if not user_group:
return render(request, "error.html", {"text": "このグループにアクセスする権限がありません"})
permissions = user_group.group.usergroup_set.all()
if request.method == "POST" and user_group.is_admin and user_group.group.is_pass:
permission_id = int(request.POST.get("id", 0))
is_exists = user_group.group.usergroup_set.filter(id=permission_id).exists()
if not is_exists:
error = "変更権限がありません"
else:
try:
user_group = UserGroup.objects.get(id=permission_id)
if "no_admin" in request.POST:
user_group.is_admin = False
user_group.save()
elif "admin" in request.POST:
user_group.is_admin = True
user_group.save()
return redirect(reverse("custom_auth_group:permission", args=[group_id]))
except Exception:
error = "アップデート処理でエラーが発生しました"

context = {"group": group, "permission": permission_all, "administrator": administrator, "error": error}
context = {
"group": user_group.group,
"permissions": permissions,
"is_administrator": user_group.is_admin,
"error": error,
}
return render(request, "group/edit_permission.html", context)


Expand Down
2 changes: 1 addition & 1 deletion dsbd/templates/group/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ <h2 class="card-title">Group情報閲覧・修正</h2>
{% csrf_token %}
{{ form }}
<br/>
{% if group.is_active and administrator %}
{% if group.status == 1 and is_administrator %}
<button type="submit" class="btn btn-primary">変更
</button>{% endif %}
</form>
Expand Down
38 changes: 16 additions & 22 deletions dsbd/templates/group/edit_permission.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,21 @@ <h2 class="card-title">Group権限設定</h2>
<div class="card-body">
<h5 class="card-title">{{ group.name }}</h5>
<br/>
<div class="container">
<div>
<a class="btn btn-primary btn-sm"
href="{% url 'custom_auth_group:permission' group.id %}">権限設定</a>
</div>
</div>
</div>
<div class="card-footer">
{% if group.is_active %}
{% if group.status == 1 %}
<span class="badge bg-primary">有効</span>
{% else %}
<span class="badge bg-danger">無効</span>{% endif %}
{% if administrator %}
{% if is_administrator %}
<span class="badge bg-success">管理者権限</span>{% endif %}
<span
class="badge bg-secondary">Service: {{ group.service_set.count }}</span>
</div>
</div>
<br/>
<br/>
{% if permission %}
{% if permissions %}
<table class="table table-striped">
<thead>
<tr>
Expand All @@ -53,37 +47,37 @@ <h5 class="card-title">{{ group.name }}</h5>
</tr>
</thead>
<tbody>
{% for e in permission %}
{% for permission in permissions %}
<tr>
<th scope="row">{{ e.id }}</th>
<td>{{ e.created_at }}</td>
<td>{{ e.user.id }}: {{ e.user.username }}</td>
<td>{{ e.group.id }}: {{ e.group.name }}</td>
<th scope="row">{{ permission.id }}</th>
<td>{{ permission.created_at }}</td>
<td>{{ permission.user.id }}: {{ permission.user.username }}</td>
<td>{{ permission.group.id }}: {{ permission.group.name }}</td>
<td>
{% if e.is_admin %}
{% if permission.is_admin %}
<span class="badge bg-success">管理者権限</span>
{% else %}
<span class="badge bg-primary">ユーザ権限</span>
{% endif %}
{% if e.enable_ldap %}
{% if permission.enable_ldap %}
<span class="badge bg-success">LDAP有効</span>
{% elif e.ldap_register %}
{% elif permission.ldap_register %}
<span class="badge bg-danger">LDAP無効</span>
{% endif %}
</td>
<td>
{% if administrator %}
{% if is_administrator %}
<form method="post">
{% csrf_token %}
<input type="text"
value={{ e.id }} name="id"
value={{ permission.id }} name="id"
hidden>
{% if e.is_admin and e.user.id != request.user.id %}
{% if permission.is_admin and permission.user.id != request.user.id %}
<button type="submit"
class="btn btn-primary btn-sm"
name="no_admin">ユーザ権限に変更
</button>
{% elif e.is_admin %}
{% elif permission.is_admin %}
ユーザ権限に変更出来ません
{% else %}
<button type="submit"
Expand All @@ -101,7 +95,7 @@ <h5 class="card-title">{{ group.name }}</h5>
</tbody>
</table>
{% endif %}
{% if not administrator %}
{% if not is_administrator %}
<p>管理者権限がないため、権限設定を変更出来ません。</p>
{% endif %}
{% else %}
Expand Down
15 changes: 14 additions & 1 deletion dsbd/templates/ticket/chat.html
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,19 @@ <h6 class="m-b-0">{{ user.username }}</h6>
}
}

function escapeHTML(str) {
return str.replace(/[&<>"']/g, function (match) {
const escape = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
return escape[match];
});
}

function connect() {
const wsScheme = (window.location.protocol === 'https:' ? 'wss' : 'ws');
const hostname = window.location.host;
Expand All @@ -350,7 +363,7 @@ <h6 class="m-b-0">{{ user.username }}</h6>
console.log(data);
let element = document.getElementById('chat_websocket');

let message = data.message.replace(/\n/, '<br>');
let message = escapeHTML(data.message).replace(/\n/g, '<br>');

let html = '<li class="clearfix">';
if (data.username === '{{ request.user.username }}' && !data.is_admin) {
Expand Down

0 comments on commit fd4c913

Please sign in to comment.