scst-proxy 0.2__tar.gz → 0.6.10__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. scst_proxy-0.6.10/MANIFEST.in +1 -0
  2. {scst_proxy-0.2 → scst_proxy-0.6.10}/PKG-INFO +2 -9
  3. scst_proxy-0.6.10/scst_proxy/__init__.py +3 -0
  4. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/admin.py +1 -1
  5. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/apps.py +5 -4
  6. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/forms.py +0 -0
  7. scst_proxy-0.6.10/scst_proxy/helpers.py +42 -0
  8. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/hooks.py +10 -4
  9. scst_proxy-0.6.10/scst_proxy/menu.py +10 -0
  10. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/migrations/0001_initial.py +0 -0
  11. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/migrations/0002_alter_pluginsettings_options.py +0 -0
  12. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/migrations/0003_alter_pluginsettings_options.py +0 -0
  13. scst_proxy-0.6.10/scst_proxy/migrations/0004_pluginsettings_proxy_address.py +18 -0
  14. scst_proxy-0.6.10/scst_proxy/migrations/0005_alter_pluginsettings_options.py +17 -0
  15. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/migrations/__init__.py +0 -0
  16. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/models.py +10 -2
  17. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/signals.py +16 -21
  18. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/tasks.py +2 -9
  19. scst_proxy-0.6.10/scst_proxy/templates/scst_proxy/main.html +156 -0
  20. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/urls.py +0 -0
  21. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy/views.py +14 -34
  22. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy.egg-info/PKG-INFO +2 -9
  23. scst_proxy-0.6.10/scst_proxy.egg-info/SOURCES.txt +26 -0
  24. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy.egg-info/dependency_links.txt +0 -0
  25. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy.egg-info/requires.txt +1 -1
  26. {scst_proxy-0.2 → scst_proxy-0.6.10}/scst_proxy.egg-info/top_level.txt +0 -0
  27. scst_proxy-0.6.10/setup.py +17 -0
  28. scst_proxy-0.2/MANIFEST.in +0 -2
  29. scst_proxy-0.2/scst_proxy/__init__.py +0 -1
  30. scst_proxy-0.2/scst_proxy/helpers.py +0 -45
  31. scst_proxy-0.2/scst_proxy/templates/scst_proxy/main.html +0 -248
  32. scst_proxy-0.2/scst_proxy/templates/scst_proxy/settings.html +0 -54
  33. scst_proxy-0.2/scst_proxy.egg-info/SOURCES.txt +0 -36
  34. scst_proxy-0.2/setup.py +0 -33
  35. {scst_proxy-0.2 → scst_proxy-0.6.10}/setup.cfg +0 -0
@@ -0,0 +1 @@
1
+ recursive-include templates/scst_proxy *.html
@@ -1,21 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scst_proxy
3
- Version: 0.2
3
+ Version: 0.6.10
4
4
  Summary: Register user on SCST proxy server
5
5
  Author: Aleksey Misyagin
6
6
  Author-email: me@misyagin.ru
7
- Classifier: Development Status :: 3 - Alpha
8
- Classifier: Environment :: Web Environment
9
- Classifier: Framework :: Django
10
- Classifier: Intended Audience :: Developers
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Programming Language :: Python :: 3
13
- Requires-Dist: allianceauth>=2.0.0
7
+ Requires-Dist: allianceauth>=2.11
14
8
  Requires-Dist: requests
15
9
  Requires-Dist: django-ipware
16
10
  Dynamic: author
17
11
  Dynamic: author-email
18
- Dynamic: classifier
19
12
  Dynamic: description
20
13
  Dynamic: requires-dist
21
14
  Dynamic: summary
@@ -0,0 +1,3 @@
1
+ PLUGIN_TITLE = 'Прокси-сервер альянса'
2
+ PLUGIN_NAME = 'scst_proxy'
3
+ default_app_config = f'{PLUGIN_NAME}.apps.ScStProxySettings'
@@ -3,7 +3,7 @@ from .models import PluginSettings
3
3
 
4
4
  @admin.register(PluginSettings)
5
5
  class PluginSettingsAdmin(admin.ModelAdmin):
6
- list_display = ('api_endpoint','api_key')
6
+ list_display = ('api_endpoint','api_key','proxy_address')
7
7
  readonly_fields = ('id',)
8
8
 
9
9
  def has_add_permission(self, request):
@@ -1,13 +1,14 @@
1
1
  from django.apps import AppConfig
2
+ from . import PLUGIN_NAME
2
3
 
3
4
 
4
5
  class ScStProxySettings(AppConfig):
5
- name = 'scst_proxy'
6
- label = 'scst_proxy'
7
- default_pesmissions = ('scst_proxy.can_use_proxy')
6
+ name = PLUGIN_NAME
7
+ label = PLUGIN_NAME
8
+ default_pesmissions = (f'{PLUGIN_NAME}.can_use_proxy')
8
9
 
9
10
 
10
11
  def ready(self):
11
12
  # Импортируем хуки при загрузке приложения
12
13
  from . import hooks # noqa
13
- import scst_proxy.signals
14
+ from . import signals
@@ -0,0 +1,42 @@
1
+
2
+ from django.http import JsonResponse
3
+ from scst_proxy.models import PluginSettings
4
+ from allianceauth.services.hooks import get_extension_logger
5
+ import requests
6
+
7
+ logger = get_extension_logger(__name__)
8
+
9
+ def remove_user_api_call(user):
10
+ settings = PluginSettings.get_settings()
11
+ try:
12
+ character_name = user.profile.main_character.character_name
13
+
14
+ # Get API key from user settings (you'll need to implement this)
15
+ try:
16
+ api_key = settings.api_key
17
+ except AttributeError:
18
+ logger.error('API key not configured')
19
+ return JsonResponse(
20
+ {'status': 'error', 'message': 'API key not configured'},
21
+ status=400
22
+ )
23
+
24
+ # Prepare API request
25
+ api_url = settings.api_endpoint + 'delete' # Replace with your API URL
26
+ params = {
27
+ 'login': character_name,
28
+ 'apikey': api_key
29
+ }
30
+
31
+ try:
32
+ response = requests.delete(api_url, json=params, headers={'Content-Type': 'application/json'})
33
+ response.raise_for_status()
34
+ return JsonResponse({'response':response.json()})
35
+ except requests.exceptions.RequestException as e:
36
+ logger.error(e)
37
+ return JsonResponse(
38
+ {'status': 'error', 'message': str(e), 'params': str(params), 'endpoint': api_url},
39
+ status=500
40
+ )
41
+ except Exception as e:
42
+ logger.error(e)
@@ -3,7 +3,7 @@ from allianceauth.services.hooks import MenuItemHook, UrlHook, ServicesHook, get
3
3
  from django.utils.translation import gettext_lazy as _
4
4
  from . import urls
5
5
  from scst_proxy.tasks import send_permission_removed_notification_task
6
- #from django.contrib.auth import get_user_model
6
+ from . import PLUGIN_TITLE, PLUGIN_NAME
7
7
 
8
8
  logger = get_extension_logger(__name__)
9
9
 
@@ -11,20 +11,26 @@ class ProxyRegMenuItem(MenuItemHook):
11
11
  def __init__(self):
12
12
  MenuItemHook.__init__(
13
13
  self,
14
- 'Прокси-сервер альянса', # Текст в меню
14
+ PLUGIN_TITLE, # Текст в меню
15
15
  'fas fa-server', # Иконка Font Awesome (например, fa-rocket)
16
16
  'scst_proxy:main', # Имя URL из urls.py
17
17
  navactive=['scst_proxy:'], # Подсветка меню при активности
18
18
  )
19
+ def render(self, request):
20
+ permissions = list(request.user.get_all_permissions())
21
+ if (f'{PLUGIN_NAME}.can_view_page') in permissions:
22
+ return MenuItemHook.render(self, request)
23
+ return ""
19
24
 
20
25
  class UpdateUserService(ServicesHook):
21
26
  def __init__(self):
22
27
  ServicesHook.__init__(self)
23
28
  self.urlpatterns = self.urlpatterns
29
+
24
30
  #Изменение State
25
31
  def update_groups(self, user):
26
32
  permissions = list(user.get_all_permissions())
27
- if 'scst_proxy.can_use_proxy' not in permissions:
33
+ if f'{PLUGIN_NAME}.can_use_proxy' not in permissions:
28
34
  logger.debug('Пользователь %s больше не имеет доступа к прокси серверу' % user)
29
35
  send_permission_removed_notification_task(user)
30
36
  else :
@@ -38,7 +44,7 @@ def register_menu():
38
44
 
39
45
  @hooks.register("url_hook")
40
46
  def register_urls():
41
- return UrlHook(urls, "scst_proxy", r"^scst_proxy/")
47
+ return UrlHook(urls, PLUGIN_NAME, r"^scst_proxy/")
42
48
 
43
49
  @hooks.register('services_hook')
44
50
  def register_service():
@@ -0,0 +1,10 @@
1
+ from allianceauth.menu import menu_factory
2
+
3
+ @menu_factory.register
4
+ def register_menu_item():
5
+ """Глобальное меню, отображаемое в левом меню."""
6
+ return {
7
+ 'label': 'Your Menu Item',
8
+ 'url': 'your-url-name', # URL-шаблон для вашего пункта меню
9
+ 'order': 100, # Порядок отображения пункта меню в меню
10
+ }
@@ -0,0 +1,18 @@
1
+ # Generated by Django 4.2.23 on 2025-06-30 22:38
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('scst_proxy', '0003_alter_pluginsettings_options'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AddField(
14
+ model_name='pluginsettings',
15
+ name='proxy_address',
16
+ field=models.CharField(default='scst.proxy.ekzoman.ru', max_length=255, verbose_name='Адрес проси сервера'),
17
+ ),
18
+ ]
@@ -0,0 +1,17 @@
1
+ # Generated by Django 4.2.23 on 2025-07-01 11:50
2
+
3
+ from django.db import migrations
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('scst_proxy', '0004_pluginsettings_proxy_address'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AlterModelOptions(
14
+ name='pluginsettings',
15
+ options={'permissions': [('can_use_proxy', 'Может использовать прокси сервер'), ('can_view_page', 'Может смотреть страницу плагина')], 'verbose_name': 'Настройки плагина', 'verbose_name_plural': 'Настройки плагина'},
16
+ ),
17
+ ]
@@ -1,4 +1,5 @@
1
1
  from django.db import models
2
+ from . import PLUGIN_NAME
2
3
 
3
4
  class PluginSettings(models.Model):
4
5
  """Модель для хранения настроек плагина"""
@@ -13,15 +14,22 @@ class PluginSettings(models.Model):
13
14
  verbose_name="API ключ"
14
15
  )
15
16
 
17
+ proxy_address = models.CharField(
18
+ max_length=255,
19
+ default='scst.proxy.ekzoman.ru',
20
+ verbose_name='Адрес проси сервера'
21
+ )
22
+
16
23
  class Meta:
17
24
  verbose_name = "Настройки плагина"
18
25
  verbose_name_plural = "Настройки плагина"
19
26
  permissions = [
20
- ("can_use_proxy","Может использовать прокси сервер")
27
+ ("can_use_proxy","Может использовать прокси сервер"),
28
+ ("can_view_page", "Может смотреть страницу плагина")
21
29
  ]
22
30
 
23
31
  def __str__(self):
24
- return "ProxyReg"
32
+ return PLUGIN_NAME
25
33
 
26
34
  @classmethod
27
35
  def get_settings(cls):
@@ -2,44 +2,39 @@
2
2
 
3
3
  from django.db.models.signals import m2m_changed
4
4
  from django.dispatch import receiver
5
+ from django.contrib.auth import get_user
5
6
  from django.contrib.auth.models import User, Permission
6
- from scst_proxy.models import PluginSettings
7
- from scst_proxy.tasks import send_permission_removed_notification_task,send_permission_added_notification_task
7
+ from scst_proxy.tasks import send_permission_removed_notification_task
8
8
  import logging
9
- import requests
10
- import os
11
9
 
12
- logger = logging.getLogger(__name__)
13
10
 
11
+ logger = logging.getLogger(__name__)
14
12
 
15
13
  @receiver(m2m_changed, sender=User.user_permissions.through)
16
14
  def user_permissions_changed(sender, instance, action, pk_set, **kwargs):
17
15
  """
18
16
  Обработчик сигнала m2m_changed для отслеживания добавления и удаления разрешений пользователя.
19
17
  """
20
- if action == "post_add":
21
- # Разрешения добавлены пользователю
18
+ if action == "post_remove":
19
+ # Разрешения удалены у пользователя
22
20
  for perm_id in pk_set:
23
21
  try:
24
22
  permission = Permission.objects.get(pk=perm_id)
25
- send_permission_change_notification(instance, permission, 'added')
26
- logger.info(f"Permission '{permission.codename}' added to user '{instance.username}'.")
23
+ send_permission_removed_notification_task(instance)
24
+ logger.info(f"Permission '{permission.codename}' removed from user '{instance.username}'.")
27
25
  except Permission.DoesNotExist:
28
26
  logger.error(f"Permission with id {perm_id} does not exist.")
29
- elif action == "post_remove":
27
+
28
+ @receiver(m2m_changed, sender=User.groups.through)
29
+ def user_group_changed(sender, instance, action, pk_set, **kwargs):
30
+ """
31
+ Обработчик сигнала m2m_changed для отслеживания добавления и удаления группы пользователя.
32
+ """
33
+ if action == "post_remove":
30
34
  # Разрешения удалены у пользователя
31
35
  for perm_id in pk_set:
32
36
  try:
33
37
  permission = Permission.objects.get(pk=perm_id)
34
- send_permission_change_notification(instance, permission, 'removed')
35
- logger.info(f"Permission '{permission.codename}' removed from user '{instance.username}'.")
38
+ logger.info(f"Permission '{permission.codename}' removed from user.")
36
39
  except Permission.DoesNotExist:
37
- logger.error(f"Permission with id {perm_id} does not exist.")
38
-
39
- def send_permission_change_notification(user, permission, action):
40
- data = {
41
- 'user': user,
42
- 'permission': permission
43
- }
44
- if action == "removed":
45
- send_permission_removed_notification_task.delay(data)
40
+ logger.error(f"Permission with id {perm_id} does not exist.")
@@ -12,12 +12,5 @@ def send_permission_removed_notification_task(user):
12
12
  logger.info(f"Уведомление об изменении состояния пользователя {user.username} отправлено успешно.")
13
13
  remove_user_api_call(user)
14
14
  except requests.RequestException as e:
15
- logger.error(f"Ошибка при отправке уведомления об изменении состояния пользователя {user.username}: {e}")
16
- # Опционально: реализуйте повторные попытки или уведомления администраторов
17
-
18
- @shared_task
19
- def send_permission_added_notification_task(user):
20
- try:
21
- logger.info(f"Уведомление об изменении состояния пользователя {user.username} отправлено успешно.")
22
- except requests.RequestException as e:
23
- logger.error(f"Ошибка при отправке уведомления об изменении состояния пользователя {user.username}: {e}")
15
+ logger.error(f"Ошибка при отправке уведомления об изменении состояния пользователя: {e}")
16
+ # Опционально: реализуйте повторные попытки или уведомления администраторов
@@ -0,0 +1,156 @@
1
+ {% extends "allianceauth/base-bs5.html" %}
2
+ {% load i18n %}
3
+ {% load static %}
4
+
5
+ {% block page_title %}{% trans PAGE_TITLE %}{% endblock %}
6
+ {% block header_nav_brand %}
7
+ <a class="nav-link text-white link-light link-underline link-underline-opacity-0" href="{% url 'scst_proxy:main' %}">Прокси-сервер альянса</a>
8
+ {% endblock header_nav_brand %}
9
+
10
+
11
+ {% block content %}
12
+ <div class="aa-plugin-container proxyreg">
13
+ <div class="panel panel-default pb-4 pt-4 mb-4 container border border-4 border-dark">
14
+ <div class="panel-body container">
15
+ <div class="row">
16
+ <div class="col">
17
+ <a href="https://docs.google.com/document/d/1UIOhdmiSoY2HsmS5bJ_H8H4MbUVT6aC521kmO0pKEiI/edit?usp=sharing" target="_blank">Инструкция по настройке</a>
18
+ </div>
19
+ </div>
20
+ <div class="row">
21
+ <div class="col">
22
+ Сначала выполните все шаги в инструкции, после чего можете запросить ваш пароль.
23
+ </div>
24
+ </div>
25
+ </div>
26
+ </div>
27
+ <div class="panel panel-default pb-4 pt-4 mb-4 container border border-4 border-dark">
28
+ <div class="panel-heading">
29
+ <h4 class="panel-title">{% trans "Вход на прокси-сервер" %}</h3>
30
+ </div>
31
+ <div class="panel-body container">
32
+ <div class="pt-4 pb-2 row">
33
+ <div class="col col-2">Адрес сервера:</div>
34
+ <div class="col">
35
+ <b>{{ PROXY_URL }}</b> <input type="hidden" id="serverInput" value="{{ PROXY_URL }}" /> <button class="btn bnt-sm btn-secondary" id="urlClipboard"><i class="fa-regular fa-clipboard"></i></button>
36
+ </div>
37
+ </div>
38
+ <div class="pt-2 pb-2 row">
39
+ <div class="col col-2">Ваш логин:</div>
40
+ <div class="col">
41
+ <b>{{ CHARACTER_NAME }}</b> <input type="hidden" id="loginInput" disabled value="{{ CHARACTER_NAME }}" /> <button class="btn bnt-sm btn-secondary" id="loginClipboard"><i class="fa-regular fa-clipboard"></i></button>
42
+ </div>
43
+ </div>
44
+ <div class="pb-4">
45
+ <button id="apiButton" class="btn btn-primary p-2">{% trans "Получить пароль" %}</button>
46
+ <br />
47
+ <small class="text-warning pt-4">
48
+ Пароль не хранится на сервере. Для получения нового пароля нажмите "Получить пароль"
49
+ </small>
50
+ </div>
51
+ <div class="pb-3">
52
+ <div id="resultMessage" class="alert" style="display: none; margin-top: 15px;"></div>
53
+ </div>
54
+ </div>
55
+ </div>
56
+
57
+ </div>
58
+
59
+ <div
60
+ class="modal fade"
61
+ id="confirm-dialog"
62
+ tabindex="-1"
63
+ role="dialog"
64
+ aria-labelledby="confirmDialog"
65
+ aria-hidden="true"
66
+ >
67
+ <div class="modal-dialog">
68
+ <div class="modal-content">
69
+ <div class="modal-header">
70
+ <h5 class="modal-title" id="confirmDialog">Пароль обновлен</h5>
71
+ </div>
72
+ <div class="modal-body">
73
+ ...
74
+ </div>
75
+ <div class="modal-footer">
76
+ <button
77
+ type="button"
78
+ class="btn btn-secondary"
79
+ data-dismiss="modal"
80
+ data-bs-dismiss="modal"
81
+ >
82
+ Закрыть
83
+ </button>
84
+ <button id="clipboardBtn" type="button" class="btn btn-primary" onclick=""><i class="fa-regular fa-clipboard mr-2"></i> В Буфер</button>
85
+ </div>
86
+ </div>
87
+ </div>
88
+
89
+
90
+ </div>
91
+
92
+
93
+ <script src="https://code.jquery.com/jquery-3.7.1.min.js" type="text/javascript"></script>
94
+ <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
95
+ <script>
96
+ $(document).ready(function() {
97
+ $('#apiButton').click(function() {
98
+ $.ajax({
99
+ url: "{% url 'scst_proxy:call_api' %}",
100
+ method: "POST",
101
+ dataType: "json",
102
+ beforeSend: function(xhr) {
103
+ xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
104
+ $('#apiButton').prop('disabled', true);
105
+ $('#resultMessage').hide();
106
+ },
107
+ success: function(data) {
108
+ var message = "Ваш новый пароль: <b class='text-danger'>" + data.password + "</b><br/><br/>Запомните или запишите свой пароль. Мы не храним ваши пароли.";
109
+
110
+ $('.modal-body').html(message);
111
+ var successModal = new bootstrap.Modal(document.getElementById('confirm-dialog'),{});
112
+
113
+ successModal.show();
114
+
115
+ var btn = document.getElementById('clipboardBtn');
116
+ btn.removeEventListener('click',(e)=>{
117
+ e.preventDefault();
118
+ copyToClipboard(data.password);
119
+ });
120
+ btn.addEventListener('click', (e)=>{
121
+ e.preventDefault();
122
+ copyToClipboard(data.password);
123
+ });
124
+ },
125
+ error: function(xhr) {
126
+ var message = "Произошла ошибка. Попробуйте еще раз. Если ошибка сохранится, обратитесь к администратору.\r\n" + xhr.message;
127
+ $('#resultMessage').removeClass('alert-success').addClass('alert-danger').text(message).show();
128
+ },
129
+ complete: function() {
130
+ $('#apiButton').prop('disabled', false);
131
+ }
132
+ });
133
+ });
134
+ $('#loginClipboard').click(function(){
135
+ copyToClipboard($('#loginInput').val());
136
+ });
137
+ $('#urlClipboard').click(function(){
138
+ copyToClipboard($('#serverInput').val());
139
+ });
140
+ });
141
+ async function copyToClipboard(textToCopy) {
142
+ try {
143
+ await navigator.clipboard.writeText(textToCopy);
144
+ console.log('Text copied to clipboard successfully!');
145
+ } catch (err) {
146
+ console.error('Failed to copy text: ', err);
147
+ }
148
+ }
149
+
150
+ </script>
151
+ <style>
152
+ .proxyreg img {
153
+ max-height: 400px;
154
+ }
155
+ </style>
156
+ {% endblock %}
File without changes
@@ -3,50 +3,30 @@ from django.shortcuts import render
3
3
  from django.http import JsonResponse
4
4
  from django.views.decorators.http import require_http_methods
5
5
  import requests
6
- from ipware import get_client_ip
7
6
  from django.template.exceptions import TemplateDoesNotExist
8
7
  from django.core.exceptions import PermissionDenied
9
- from django.contrib import messages
10
8
  from django.contrib.auth.models import User
11
-
12
- from .forms import PluginSettingsForm
13
9
  from .models import PluginSettings
14
-
15
-
16
-
17
- # @login_required
18
- # @permission_required('scst_proxy.change_pluginsettings')
19
- # def settings_view(request):
20
- # try:
21
- # instance = PluginSettings.objects.get(pk=1)
22
- # except PluginSettings.DoesNotExist:
23
- # instance = None
24
-
25
- # if request.method == 'POST':
26
- # form = PluginSettingsForm(request.POST, instance=instance)
27
- # if form.is_valid():
28
- # form.save()
29
- # messages.success(request, 'Настройки успешно сохранены!')
30
- # return redirect('scst_proxy:settings')
31
- # else:
32
- # form = PluginSettingsForm(instance=instance)
33
-
34
- # context = {
35
- # 'form': form,
36
- # 'page_title': 'Настройки плагина ProxyReg'
37
- # }
38
- # return render(request, 'scst_proxy/settings.html', context)
10
+ from . import PLUGIN_NAME, PLUGIN_TITLE
39
11
 
40
12
 
41
13
  @login_required
42
- @permission_required('scst_proxy.can_use_proxy')
14
+ @permission_required(f'{PLUGIN_NAME}.can_view_page')
43
15
  def main_view(request):
44
16
  try:
45
17
  permissions = list(request.user.get_all_permissions())
46
- if 'scst_proxy.can_use_proxy' not in permissions:
18
+ accessPermission = f'{PLUGIN_NAME}.can_view_page'
19
+ if accessPermission not in permissions:
47
20
  raise PermissionDenied("У вас нет доступа к этому плагину")
48
21
 
49
- return render(request, 'scst_proxy/main.html')
22
+ context = {
23
+ 'PAGE_TITLE': PLUGIN_TITLE,
24
+ 'PROXY_URL': PluginSettings.get_settings().proxy_address,
25
+ 'CHARACTER_NAME': request.user.profile.main_character.character_name.replace(' ','_')
26
+ }
27
+
28
+ return render(request, f'{ PLUGIN_NAME }/main.html', context)
29
+
50
30
  except TemplateDoesNotExist as e:
51
31
  return JsonResponse(
52
32
  {'status': 'error', 'message': 'Template not found'},
@@ -56,7 +36,7 @@ def main_view(request):
56
36
 
57
37
 
58
38
  @login_required
59
- @permission_required('scst_proxy.can_use_proxy')
39
+ @permission_required(f'{PLUGIN_NAME}.can_view_page')
60
40
  @require_http_methods(["POST"])
61
41
  def call_api_endpoint(request):
62
42
  # Get user IP address
@@ -79,7 +59,7 @@ def call_api_endpoint(request):
79
59
  newPassword = User.objects.make_random_password()
80
60
  params = {
81
61
  'password': newPassword,
82
- 'login': character_name,
62
+ 'login': character_name.replace(' ','_'),
83
63
  'apikey': api_key
84
64
  }
85
65
 
@@ -1,21 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scst_proxy
3
- Version: 0.2
3
+ Version: 0.6.10
4
4
  Summary: Register user on SCST proxy server
5
5
  Author: Aleksey Misyagin
6
6
  Author-email: me@misyagin.ru
7
- Classifier: Development Status :: 3 - Alpha
8
- Classifier: Environment :: Web Environment
9
- Classifier: Framework :: Django
10
- Classifier: Intended Audience :: Developers
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Programming Language :: Python :: 3
13
- Requires-Dist: allianceauth>=2.0.0
7
+ Requires-Dist: allianceauth>=2.11
14
8
  Requires-Dist: requests
15
9
  Requires-Dist: django-ipware
16
10
  Dynamic: author
17
11
  Dynamic: author-email
18
- Dynamic: classifier
19
12
  Dynamic: description
20
13
  Dynamic: requires-dist
21
14
  Dynamic: summary
@@ -0,0 +1,26 @@
1
+ MANIFEST.in
2
+ setup.py
3
+ scst_proxy/__init__.py
4
+ scst_proxy/admin.py
5
+ scst_proxy/apps.py
6
+ scst_proxy/forms.py
7
+ scst_proxy/helpers.py
8
+ scst_proxy/hooks.py
9
+ scst_proxy/menu.py
10
+ scst_proxy/models.py
11
+ scst_proxy/signals.py
12
+ scst_proxy/tasks.py
13
+ scst_proxy/urls.py
14
+ scst_proxy/views.py
15
+ scst_proxy.egg-info/PKG-INFO
16
+ scst_proxy.egg-info/SOURCES.txt
17
+ scst_proxy.egg-info/dependency_links.txt
18
+ scst_proxy.egg-info/requires.txt
19
+ scst_proxy.egg-info/top_level.txt
20
+ scst_proxy/migrations/0001_initial.py
21
+ scst_proxy/migrations/0002_alter_pluginsettings_options.py
22
+ scst_proxy/migrations/0003_alter_pluginsettings_options.py
23
+ scst_proxy/migrations/0004_pluginsettings_proxy_address.py
24
+ scst_proxy/migrations/0005_alter_pluginsettings_options.py
25
+ scst_proxy/migrations/__init__.py
26
+ scst_proxy/templates/scst_proxy/main.html
@@ -1,3 +1,3 @@
1
- allianceauth>=2.0.0
1
+ allianceauth>=2.11
2
2
  requests
3
3
  django-ipware
@@ -0,0 +1,17 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name='scst_proxy',
5
+ version='0.6.10',
6
+ packages=find_packages(),
7
+ include_package_data=True,
8
+ install_requires=[
9
+ 'allianceauth>=2.11',
10
+ 'requests',
11
+ 'django-ipware',
12
+ ],
13
+ description='Register user on SCST proxy server',
14
+ long_description='Provides registration for Alliance Auth users to register their credentials on proxy server.',
15
+ author='Aleksey Misyagin',
16
+ author_email='me@misyagin.ru'
17
+ )
@@ -1,2 +0,0 @@
1
- recursive-include scst_proxy/templates *.*
2
- recursive-include scst_proxy/static/scst_proxy/images *.*
@@ -1 +0,0 @@
1
- default_app_config = 'scst_proxy.apps.ScStProxySettings'
@@ -1,45 +0,0 @@
1
-
2
- from django.http import JsonResponse
3
- from scst_proxy.models import PluginSettings
4
- import requests
5
-
6
-
7
- def add_menu_items():
8
- return [
9
- {
10
- 'label': 'Регистрация прокси',
11
- 'url': 'scst_proxy:main',
12
- 'icon': 'fa-home-icon',
13
- }
14
- ]
15
-
16
- def remove_user_api_call(user):
17
- settings = PluginSettings.get_settings()
18
-
19
- character_name = user.profile.main_character.character_name
20
-
21
- # Get API key from user settings (you'll need to implement this)
22
- try:
23
- api_key = settings.api_key
24
- except AttributeError:
25
- return JsonResponse(
26
- {'status': 'error', 'message': 'API key not configured'},
27
- status=400
28
- )
29
-
30
- # Prepare API request
31
- api_url = settings.api_endpoint + 'delete' # Replace with your API URL
32
- params = {
33
- 'login': character_name,
34
- 'apikey': api_key
35
- }
36
-
37
- try:
38
- response = requests.delete(api_url, json=params, headers={'Content-Type': 'application/json'})
39
- response.raise_for_status()
40
- return JsonResponse({'response':response.json()})
41
- except requests.exceptions.RequestException as e:
42
- return JsonResponse(
43
- {'status': 'error', 'message': str(e), 'params': str(params), 'endpoint': api_url},
44
- status=500
45
- )
@@ -1,248 +0,0 @@
1
- {% extends "allianceauth/base-bs5.html" %}
2
- {% load i18n %}
3
- {% load static %}
4
- {% block page_title %}{% trans "Подключение чатов" %}{% endblock %}
5
- {% block header_nav_brand %}
6
- <a class="nav-link text-white link-light link-underline link-underline-opacity-0" href="{% url 'scst_proxy:main' %}">Прокси-сервер альянса</a>
7
- {% endblock header_nav_brand %}
8
-
9
-
10
- {% block content %}
11
- <div class="aa-plugin-container proxyreg">
12
- <div class="panel panel-default pb-4 pt-4 mb-4 container border border-4 border-dark">
13
- <div class="panel-heading">
14
- <h4 class="panel-title">{% trans "Вход на прокси-сервер" %}</h3>
15
- </div>
16
- <div class="panel-body container">
17
- <p class="pt-4 pb-2">
18
- Ваш логин: <input type="text" id="loginInput" disabled value="{{ request.user.profile.main_character.character_name }}" /> <button class="btn bnt-sm btn-secondary" id="loginClipboard"><i class="fa-regular fa-clipboard"></i></button>
19
- </p>
20
- <p class="pb-4">
21
- <button id="apiButton" class="btn btn-primary p-2">{% trans "Получить пароль" %}</button>
22
- <br />
23
- <small class="text-warning">
24
- Пароль не хранится на сервере. Для получения нового пароля нажмите "Получить пароль"
25
- </small>
26
- </p>
27
- <div class="pb-3">
28
-
29
- <div id="resultMessage" class="alert" style="display: none; margin-top: 15px;"></div>
30
- </div>
31
- </div>
32
- </div>
33
- <div class="panel panel-default pb-4 pt-4 mb-4 container border border-4 border-dark">
34
- <div class="panel-body container">
35
- <div class="row">
36
- <div class="col">
37
- <a href="https://docs.google.com/document/d/1UIOhdmiSoY2HsmS5bJ_H8H4MbUVT6aC521kmO0pKEiI/edit?usp=sharing" target="_blank">Инструкция по настройке</a>
38
- </div>
39
- </div>
40
- </div>
41
- </div>
42
- <!-- <div class="panel panel-default pt-4 container">
43
- <div class="panel-heading">
44
- <h4 class="pb-3">Настройки</h2>
45
- </div>
46
- <div class="panel-body">
47
-
48
- <div class="row">
49
- <div class="col">
50
- <p>
51
- Чтобы починить чаты в Eve Online необходимо прописать прокси сервер в настройках системы.
52
- </p>
53
- <p class="pb-4">
54
- 1. Для этого вам необходимо открыть приложение "Блокнот" от имени администратора. Нажмите на меню пуск в левом нижнем углу (в Windows 11 может располагаться посередине).<br/><br/>
55
- <img src="{% static 'scst_proxy/images/start_icon.png' %}" alt="start_icon" />
56
- </p>
57
- </div>
58
- </div>
59
- <div class="row">
60
- <div class="col">
61
- <p class="pb-4">
62
- 2. В поисковой строке введите слово "Блокнот" (notepad на некоторых версиях Windows) . Когда приложение будет найдено, нажмите на него правой кнопкой мыши для вызова контекстного окна. В котором нужно выбрать "Запустить от имени Администратора" <br/>
63
- <div class="container-fluid">
64
- <div class="row">
65
- <div class="col">
66
- <img src="{% static 'scst_proxy/images/notepad_1.png' %}" alt="start_icon" />
67
- </div>
68
- <div class="col">
69
- <img src="{% static 'scst_proxy/images/notepad_7.jpg' %}" alt="start_icon" />
70
- </div>
71
- </div>
72
- </div>
73
- </p>
74
- </div>
75
- </div>
76
- <div class="row">
77
- <div class="col">
78
- <p class="pb-4">
79
- 3. В открывшемся окне блокнота нажмите на меню "Файл" и кликните по пункту "Открыть". <br/><br/>
80
- <img src="{% static 'scst_proxy/images/notepad_2.png' %}" />
81
- </p>
82
- </div>
83
- </div>
84
- <div class="row">
85
- <div class="col">
86
- <p class="pb-4">
87
- 4. В диалоговом окне выбора файла введите <b>C:\Windows\System32\drivers\etc\hosts</b> в поле "Имя файла" и нажмите кнопку "Открыть".<br/><br/>
88
- <img src="{% static 'scst_proxy/images/notepad_3.png' %}" />
89
- </p>
90
- </div>
91
- </div>
92
- <div class="row">
93
- <div class="col">
94
- <p class="pb-4">
95
- 5. В открывшемся файле необходимо добавить новую строчку. Установите курсор в самый конец и два раза нажмите на Enter. На новой строке вставьте текст:
96
- <blockquote class="blockquote border border-2 border-dark p-4">
97
- <b>89.223.122.157 live.chat.eveonline.com</b>
98
- </blockquote>
99
- <br/>
100
- <br/>
101
- <img src="{% static 'scst_proxy/images/notepad_4.png' %}" />
102
- </p>
103
- </div>
104
- </div>
105
- <div class="row">
106
- <div class="col">
107
- <p class="pb-4">
108
- 6. Для сохраниния изменений нажмите на "Файл" в строке меню блокнота и нажмите на "Сохранить". Если вас попросять подтвердить сохранение, подтвердите. <br /><br/>
109
- <img src="{% static 'scst_proxy/images/notepad_5.png' %}" />
110
- </p>
111
- </div>
112
- </div>
113
- <div class="row">
114
- <div class="col">
115
- <p class="pb-4">
116
- 7. Закройте блокнот (в Windows 11 перед закрытием блокнота нужно закрыть вкладку с редактируемым файлом) и снова откройте блокнот. Откройте файл как описано в пункте 4 и убедитесь, что введенная строка сохранена.
117
- </p>
118
- </div>
119
- </div>
120
- <div class="row">
121
- <div class="col">
122
- <p class="pb-4">
123
- 8. Нажмите на кнопку "Регистрация" внизу страницы, чтобы получить доступ к прокси серверу.
124
- </p>
125
- </div>
126
- </div>
127
- <div class="row">
128
- <div class="col">
129
- <p class="pb-4">
130
- 9. Закройте блокнот и <b class="text-warning">перезапустите EveOnline!</b> (без перезапуска eve online изменения не будут работать). <b class="text-warning">Перезагружать компьютер не обязательно.</b>
131
- </p>
132
- </div>
133
- </div>
134
- <div class="row">
135
- <div class="col">
136
- <p class="pb-4">
137
- 10. Наслаждайтесь игрой с работающими чатами.
138
- </P>
139
- </div>
140
- </div>
141
- <div class="row">
142
- <div class="col">
143
- <p class="pb-4">
144
- В любой момент вы можете вернуть настройки удалив строчку из файла hosts.
145
- </p>
146
- <p class="pt-4 pb-4 text-warning">
147
- Так как у большинства игроков домашний интернет имеет динамический IP-адрес, после его обновления доступ к прокси сервера может пропасть. Если у вас пропал доступ к чатам, снова нажмите кнопку "Регистрация" и перезапустите клиент Eve online. Ваш новый IP адрес будет добавлен, а чаты будут работать.
148
- </p>
149
- </div>
150
- </div>
151
- </div>
152
- </div> -->
153
- </div>
154
-
155
- <div
156
- class="modal fade"
157
- id="confirm-dialog"
158
- tabindex="-1"
159
- role="dialog"
160
- aria-labelledby="confirmDialog"
161
- aria-hidden="true"
162
- >
163
- <div class="modal-dialog">
164
- <div class="modal-content">
165
- <div class="modal-header">
166
- <h5 class="modal-title" id="confirmDialog">Пароль обновлен</h5>
167
- </div>
168
- <div class="modal-body">
169
- ...
170
- </div>
171
- <div class="modal-footer">
172
- <button
173
- type="button"
174
- class="btn btn-secondary"
175
- data-dismiss="modal"
176
- data-bs-dismiss="modal"
177
- >
178
- Закрыть
179
- </button>
180
- <button id="clipboardBtn" type="button" class="btn btn-primary" onclick=""><i class="fa-regular fa-clipboard mr-2"></i> В Буфер</button>
181
- </div>
182
- </div>
183
- </div>
184
- </div>
185
-
186
-
187
- <script src="https://code.jquery.com/jquery-3.7.1.slim.min.js"
188
- type="text/javascript"></script>
189
- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
190
- <script>
191
- $(document).ready(function() {
192
- $('#apiButton').click(function() {
193
- $.ajax({
194
- url: "{% url 'scst_proxy:call_api' %}",
195
- method: "POST",
196
- dataType: "json",
197
- beforeSend: function(xhr) {
198
- xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
199
- $('#apiButton').prop('disabled', true);
200
- $('#resultMessage').hide();
201
- },
202
- success: function(data) {
203
- var message = "Ваш новый пароль: <b class='text-danger'>" + data.password + "</b><br/><br/>Запомните или запишите свой пароль. Мы не храним ваши пароли.";
204
-
205
- $('.modal-body').html(message);
206
- var successModal = new bootstrap.Modal(document.getElementById('confirm-dialog'),{});
207
-
208
- successModal.show();
209
-
210
- var btn = document.getElementById('clipboardBtn');
211
- btn.removeEventListener('click',(e)=>{
212
- e.preventDefault();
213
- copyToClipboard(data.password);
214
- });
215
- btn.addEventListener('click', (e)=>{
216
- e.preventDefault();
217
- copyToClipboard(data.password);
218
- });
219
- },
220
- error: function(xhr) {
221
- var message = "Произошла ошибка. Попробуйте еще раз. Если ошибка сохранится, обратитесь к администратору.\r\n" + xhr.message;
222
- $('#resultMessage').removeClass('alert-success').addClass('alert-danger').text(message).show();
223
- },
224
- complete: function() {
225
- $('#apiButton').prop('disabled', false);
226
- }
227
- });
228
- });
229
- $('#loginClipboard').click(function(){
230
- copyToClipboard($('#loginInput').val());
231
- });
232
- });
233
- async function copyToClipboard(textToCopy) {
234
- try {
235
- await navigator.clipboard.writeText(textToCopy);
236
- console.log('Text copied to clipboard successfully!');
237
- } catch (err) {
238
- console.error('Failed to copy text: ', err);
239
- }
240
- }
241
-
242
- </script>
243
- <style>
244
- .proxyreg img {
245
- max-height: 400px;
246
- }
247
- </style>
248
- {% endblock %}
@@ -1,54 +0,0 @@
1
- {% extends "allianceauth/base-bs5.html" %}
2
- {% load i18n %}
3
-
4
- {% block page_title %}{% trans "Конфигурация плагина ProxyReg" %}{% endblock %}
5
-
6
- {% block content %}
7
- <div class="col-lg-12">
8
- <div class="panel panel-default">
9
- <div class="panel-heading">
10
- <h3 class="panel-title">{% trans "Конфигурация плагина ProxyReg" %}</h3>
11
- </div>
12
- <div class="panel-body">
13
- {% if messages %}
14
- <div class="alert alert-success">
15
- {% for message in messages %}
16
- {{ message }}
17
- {% endfor %}
18
- </div>
19
- {% endif %}
20
-
21
- <form method="post">
22
- {% csrf_token %}
23
-
24
- <div class="form-group">
25
- {{ form.api_endpoint.label_tag }}
26
- {{ form.api_endpoint }}
27
- </div>
28
-
29
- <div class="row">
30
- <div class="col-md-6">
31
- <div class="form-group">
32
- {{ form.api_key.label_tag }}
33
- {{ form.api_key }}
34
- </div>
35
- </div>
36
- </div>
37
-
38
- <button type="submit" class="btn btn-primary">
39
- {% trans "Сохранить настройки" %}
40
- </button>
41
- </form>
42
- </div>
43
- </div>
44
- </div>
45
- {% endblock %}
46
-
47
- {% block extra_script %}
48
- <script>
49
- $(document).ready(function() {
50
- // Добавьте кастомные скрипты при необходимости
51
- $('input[type="checkbox"]').addClass('form-check-input');
52
- });
53
- </script>
54
- {% endblock %}
@@ -1,36 +0,0 @@
1
- MANIFEST.in
2
- setup.py
3
- ./scst_proxy/__init__.py
4
- ./scst_proxy/admin.py
5
- ./scst_proxy/apps.py
6
- ./scst_proxy/forms.py
7
- ./scst_proxy/helpers.py
8
- ./scst_proxy/hooks.py
9
- ./scst_proxy/models.py
10
- ./scst_proxy/signals.py
11
- ./scst_proxy/tasks.py
12
- ./scst_proxy/urls.py
13
- ./scst_proxy/views.py
14
- ./scst_proxy/migrations/0001_initial.py
15
- ./scst_proxy/migrations/0002_alter_pluginsettings_options.py
16
- ./scst_proxy/migrations/0003_alter_pluginsettings_options.py
17
- ./scst_proxy/migrations/__init__.py
18
- scst_proxy/__init__.py
19
- scst_proxy/admin.py
20
- scst_proxy/apps.py
21
- scst_proxy/forms.py
22
- scst_proxy/helpers.py
23
- scst_proxy/hooks.py
24
- scst_proxy/models.py
25
- scst_proxy/tasks.py
26
- scst_proxy/urls.py
27
- scst_proxy/views.py
28
- scst_proxy.egg-info/PKG-INFO
29
- scst_proxy.egg-info/SOURCES.txt
30
- scst_proxy.egg-info/dependency_links.txt
31
- scst_proxy.egg-info/requires.txt
32
- scst_proxy.egg-info/top_level.txt
33
- scst_proxy/migrations/0001_initial.py
34
- scst_proxy/migrations/__init__.py
35
- scst_proxy/templates/scst_proxy/main.html
36
- scst_proxy/templates/scst_proxy/settings.html
scst_proxy-0.2/setup.py DELETED
@@ -1,33 +0,0 @@
1
- from setuptools import setup, find_packages
2
-
3
- setup(
4
- name='scst_proxy',
5
- version='0.2',
6
- package_dir={'': '.'},
7
- packages=find_packages(),
8
- include_package_data=True,
9
- install_requires=[
10
- 'allianceauth>=2.0.0',
11
- 'requests',
12
- 'django-ipware',
13
- ],
14
- description='Register user on SCST proxy server',
15
- long_description='Provides registration for Alliance Auth users to register their credentials on proxy server.',
16
- author='Aleksey Misyagin',
17
- author_email='me@misyagin.ru',
18
- classifiers=[
19
- 'Development Status :: 3 - Alpha',
20
- 'Environment :: Web Environment',
21
- 'Framework :: Django',
22
- 'Intended Audience :: Developers',
23
- 'License :: OSI Approved :: MIT License',
24
- 'Programming Language :: Python :: 3',
25
- ],
26
- package_data={
27
- 'html_templates': [
28
- 'templates/*.*',
29
- 'templates/**/*',
30
- ],
31
- 'scst_proxy':[ 'static/*' ]
32
- }
33
- )
File without changes