0bbc31c1 by 周伟奇

Merge branch 'feature/admin2'

2 parents 797a0668 4cfb40a9
1 from django.contrib import admin 1 from django.conf import settings
2 from django.contrib import admin, messages
3 from django.contrib.admin.options import IS_POPUP_VAR
4 from django.contrib.admin.utils import unquote
5 from django.contrib.auth import update_session_auth_hash
6 from django.contrib.auth.forms import (
7 AdminPasswordChangeForm, UserChangeForm, UserCreationForm,
8 )
9 from django.contrib.auth.models import Group, User
10 from django.core.exceptions import PermissionDenied
11 from django.db import router, transaction
12 from django.http import Http404, HttpResponseRedirect
13 from django.template.response import TemplateResponse
14 from django.urls import path, reverse
15 from django.utils.decorators import method_decorator
16 from django.utils.html import escape
17 from django.utils.translation import gettext, gettext_lazy as _
18 from django.views.decorators.csrf import csrf_protect
19 from django.views.decorators.debug import sensitive_post_parameters
20 from apps.myadmin.admin import admin_site
2 21
3 # Register your models here. 22 csrf_protect_m = method_decorator(csrf_protect)
23 sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())
24
25
26 class GroupAdmin(admin.ModelAdmin):
27 search_fields = ('name',)
28 ordering = ('name',)
29 filter_horizontal = ('permissions',)
30
31 def formfield_for_manytomany(self, db_field, request=None, **kwargs):
32 if db_field.name == 'permissions':
33 qs = kwargs.get('queryset', db_field.remote_field.model.objects)
34 # Avoid a major performance hit resolving permission names which
35 # triggers a content_type load:
36 kwargs['queryset'] = qs.select_related('content_type')
37 return super().formfield_for_manytomany(db_field, request=request, **kwargs)
38
39
40 class UserAdmin(admin.ModelAdmin):
41 add_form_template = 'admin/auth/user/add_form.html'
42 change_user_password_template = None
43 fieldsets = (
44 (None, {'fields': ('username', 'password')}),
45 (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
46 (_('Permissions'), {
47 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
48 }),
49 (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
50 )
51 add_fieldsets = (
52 (None, {
53 'classes': ('wide',),
54 'fields': ('username', 'password1', 'password2'),
55 }),
56 )
57 form = UserChangeForm
58 add_form = UserCreationForm
59 change_password_form = AdminPasswordChangeForm
60 list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
61 list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
62 search_fields = ('username', 'first_name', 'last_name', 'email')
63 ordering = ('username',)
64 filter_horizontal = ('groups', 'user_permissions',)
65
66 def get_fieldsets(self, request, obj=None):
67 if not obj:
68 return self.add_fieldsets
69 return super().get_fieldsets(request, obj)
70
71 def get_form(self, request, obj=None, **kwargs):
72 """
73 Use special form during user creation
74 """
75 defaults = {}
76 if obj is None:
77 defaults['form'] = self.add_form
78 defaults.update(kwargs)
79 return super().get_form(request, obj, **defaults)
80
81 def get_urls(self):
82 return [
83 path(
84 '<id>/password/',
85 self.admin_site.admin_view(self.user_change_password),
86 name='auth_user_password_change',
87 ),
88 ] + super().get_urls()
89
90 def lookup_allowed(self, lookup, value):
91 # Don't allow lookups involving passwords.
92 return not lookup.startswith('password') and super().lookup_allowed(lookup, value)
93
94 @sensitive_post_parameters_m
95 @csrf_protect_m
96 def add_view(self, request, form_url='', extra_context=None):
97 with transaction.atomic(using=router.db_for_write(self.model)):
98 return self._add_view(request, form_url, extra_context)
99
100 def _add_view(self, request, form_url='', extra_context=None):
101 # It's an error for a user to have add permission but NOT change
102 # permission for users. If we allowed such users to add users, they
103 # could create superusers, which would mean they would essentially have
104 # the permission to change users. To avoid the problem entirely, we
105 # disallow users from adding users if they don't have change
106 # permission.
107 if not self.has_change_permission(request):
108 if self.has_add_permission(request) and settings.DEBUG:
109 # Raise Http404 in debug mode so that the user gets a helpful
110 # error message.
111 raise Http404(
112 'Your user does not have the "Change user" permission. In '
113 'order to add users, Django requires that your user '
114 'account have both the "Add user" and "Change user" '
115 'permissions set.')
116 raise PermissionDenied
117 if extra_context is None:
118 extra_context = {}
119 username_field = self.model._meta.get_field(self.model.USERNAME_FIELD)
120 defaults = {
121 'auto_populated_fields': (),
122 'username_help_text': username_field.help_text,
123 }
124 extra_context.update(defaults)
125 return super().add_view(request, form_url, extra_context)
126
127 @sensitive_post_parameters_m
128 def user_change_password(self, request, id, form_url=''):
129 user = self.get_object(request, unquote(id))
130 if not self.has_change_permission(request, user):
131 raise PermissionDenied
132 if user is None:
133 raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
134 'name': self.model._meta.verbose_name,
135 'key': escape(id),
136 })
137 if request.method == 'POST':
138 form = self.change_password_form(user, request.POST)
139 if form.is_valid():
140 form.save()
141 change_message = self.construct_change_message(request, form, None)
142 self.log_change(request, user, change_message)
143 msg = gettext('Password changed successfully.')
144 messages.success(request, msg)
145 update_session_auth_hash(request, form.user)
146 return HttpResponseRedirect(
147 reverse(
148 '%s:%s_%s_change' % (
149 self.admin_site.name,
150 user._meta.app_label,
151 user._meta.model_name,
152 ),
153 args=(user.pk,),
154 )
155 )
156 else:
157 form = self.change_password_form(user)
158
159 fieldsets = [(None, {'fields': list(form.base_fields)})]
160 adminForm = admin.helpers.AdminForm(form, fieldsets, {})
161
162 context = {
163 'title': _('Change password: %s') % escape(user.get_username()),
164 'adminForm': adminForm,
165 'form_url': form_url,
166 'form': form,
167 'is_popup': (IS_POPUP_VAR in request.POST or
168 IS_POPUP_VAR in request.GET),
169 'add': True,
170 'change': False,
171 'has_delete_permission': False,
172 'has_change_permission': True,
173 'has_absolute_url': False,
174 'opts': self.model._meta,
175 'original': user,
176 'save_as': False,
177 'show_save': True,
178 **self.admin_site.each_context(request),
179 }
180
181 request.current_app = self.admin_site.name
182
183 return TemplateResponse(
184 request,
185 self.change_user_password_template or
186 'admin/auth/user/change_password.html',
187 context,
188 )
189
190 def response_add(self, request, obj, post_url_continue=None):
191 """
192 Determine the HttpResponse for the add_view stage. It mostly defers to
193 its superclass implementation but is customized because the User model
194 has a slightly different workflow.
195 """
196 # We should allow further modification of the user just added i.e. the
197 # 'Save' button should behave like the 'Save and continue editing'
198 # button except in two scenarios:
199 # * The user has pressed the 'Save and add another' button
200 # * We are adding a user in a popup
201 if '_addanother' not in request.POST and IS_POPUP_VAR not in request.POST:
202 request.POST = request.POST.copy()
203 request.POST['_continue'] = 1
204 return super().response_add(request, obj, post_url_continue)
205
206
207 admin_site.register(Group, GroupAdmin)
208 admin_site.register(User, UserAdmin)
......
...@@ -9,7 +9,7 @@ from settings import conf ...@@ -9,7 +9,7 @@ from settings import conf
9 9
10 # Create your views here. 10 # Create your views here.
11 11
12 # https://auth-i.bmwgroup.net/auth/oauth2/intranetb2x/ 12 # https://auth-i.bmwgroup.net/auth/oauth2/
13 iwa_url_params = { 13 iwa_url_params = {
14 'scope': 'openid', 14 'scope': 'openid',
15 'response_type': 'code', 15 'response_type': 'code',
...@@ -17,7 +17,7 @@ iwa_url_params = { ...@@ -17,7 +17,7 @@ iwa_url_params = {
17 'client_id': conf.IWA_CLIENT_ID 17 'client_id': conf.IWA_CLIENT_ID
18 } 18 }
19 iwa_url_params_str = '&'.join(['{0}={1}'.format(k, v) for k, v in iwa_url_params.items()]) 19 iwa_url_params_str = '&'.join(['{0}={1}'.format(k, v) for k, v in iwa_url_params.items()])
20 iwa_url = '{0}authorize?{1}'.format(conf.IWA_URL, iwa_url_params_str) 20 iwa_url = '{0}intranetb2x/authorize?{1}'.format(conf.IWA_URL, iwa_url_params_str)
21 client_id_base64 = base64.b64encode('{0}:{1}'.format( 21 client_id_base64 = base64.b64encode('{0}:{1}'.format(
22 conf.IWA_CLIENT_ID, conf.IWA_CLIENT_SECRET).encode('utf-8')).decode('utf-8') 22 conf.IWA_CLIENT_ID, conf.IWA_CLIENT_SECRET).encode('utf-8')).decode('utf-8')
23 23
...@@ -54,7 +54,9 @@ class IWALoginView(IWABaseView, GenericView): ...@@ -54,7 +54,9 @@ class IWALoginView(IWABaseView, GenericView):
54 def post(self, request, *args, **kwargs): 54 def post(self, request, *args, **kwargs):
55 code = request.data.get('code', '') 55 code = request.data.get('code', '')
56 # redirect_uri = request.data.get('redirect_uri', '') 56 # redirect_uri = request.data.get('redirect_uri', '')
57 q_number = self.get_q_number(conf.IWA_URL, code, conf.IWA_REDIRECT_URI, client_id_base64) 57 iwa_res = self.get_q_number(conf.IWA_URL, code, conf.IWA_REDIRECT_URI, client_id_base64)
58 q_number = iwa_res.get('sub', '')
59 self.running_log.info('iwa_res: {0}'.format(iwa_res))
58 60
59 is_valid, data = self.validate(q_number) 61 is_valid, data = self.validate(q_number)
60 62
......
1 from django.contrib import admin 1 from django.contrib import admin
2 from .models import Keywords, Configs 2 from .models import Keywords, Configs
3 from .named_enum import KeywordsType 3 from .named_enum import KeywordsType
4 from apps.myadmin.admin import admin_site
4 5
5 6
6 # Register your models here. 7 # Register your models here.
...@@ -19,7 +20,7 @@ class ConfigsAdmin(admin.ModelAdmin): ...@@ -19,7 +20,7 @@ class ConfigsAdmin(admin.ModelAdmin):
19 list_display = ('id', 'value', 'comment') 20 list_display = ('id', 'value', 'comment')
20 21
21 22
22 admin.site.register(Keywords, KeywordsAdmin) 23 admin_site.register(Keywords, KeywordsAdmin)
23 admin.site.register(Configs, ConfigsAdmin) 24 admin_site.register(Configs, ConfigsAdmin)
24 admin.site.site_header = '宝马OCR' 25 # admin.site.site_header = '宝马OCR'
25 admin.site.site_title = '宝马OCR' 26 # admin.site.site_title = '宝马OCR'
......
1 from django.contrib import admin
2 from django.views.decorators.cache import never_cache
3 from django.http import HttpResponseRedirect
4 from settings import conf
5
6
7 iwa_admin_url_params = {
8 'scope': 'openid',
9 'response_type': 'code',
10 'redirect_uri': conf.IWA_REDIRECT_URI,
11 'client_id': conf.IWA_CLIENT_ID,
12 'acr_values': 'strongAuth4000Service'
13 }
14 iwa_admin_url_params_str = '&'.join(['{0}={1}'.format(k, v) for k, v in iwa_admin_url_params.items()])
15 iwa_admin_url = '{0}realms/root/realms/intranetb2x/authorize?{1}'.format(conf.IWA_URL, iwa_admin_url_params_str)
16
17
18 class MyAdminSite(admin.AdminSite):
19 site_header = 'BMW OCR'
20 site_title = 'BMW OCR'
21
22 @never_cache
23 def login(self, request, extra_context=None):
24 return HttpResponseRedirect(iwa_admin_url)
25
26
27 admin_site = MyAdminSite()
1 from django.contrib.admin.apps import AdminConfig
2
3
4 class MyAdminConfig(AdminConfig):
5 default_site = 'apps.myadmin.admin.MyAdminSite'
1 from django.db import models
2
3 # Create your models here.
1 from django.shortcuts import render
2
3 # Create your views here.
...@@ -13,11 +13,13 @@ Including another URLconf ...@@ -13,11 +13,13 @@ Including another URLconf
13 1. Import the include() function: from django.urls import include, path 13 1. Import the include() function: from django.urls import include, path
14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 """ 15 """
16 from django.contrib import admin 16 # from django.contrib import admin
17 from django.urls import path, include 17 from django.urls import path, include
18 from apps.myadmin.admin import admin_site
18 19
19 urlpatterns = [ 20 urlpatterns = [
20 path('admin/', admin.site.urls), 21 # path('admin/', admin.site.urls),
22 path('admin/', admin_site.urls),
21 path(r'api/user/', include('apps.account.urls')), 23 path(r'api/user/', include('apps.account.urls')),
22 path(r'api/create/', include('apps.doc.create_urls')), 24 path(r'api/create/', include('apps.doc.create_urls')),
23 path(r'api/priority/', include('apps.doc.priority_urls')), 25 path(r'api/priority/', include('apps.doc.priority_urls')),
......
...@@ -135,7 +135,7 @@ class IWABaseView: ...@@ -135,7 +135,7 @@ class IWABaseView:
135 iwa_user_url = '{0}userinfo'.format(iwa_url_base) 135 iwa_user_url = '{0}userinfo'.format(iwa_url_base)
136 res = requests.get(iwa_user_url, headers=headers) 136 res = requests.get(iwa_user_url, headers=headers)
137 137
138 return res.json().get('sub', '') 138 return res.json()
139 139
140 @staticmethod 140 @staticmethod
141 def validate(q_number): 141 def validate(q_number):
......
...@@ -35,7 +35,8 @@ ALLOWED_HOSTS = conf.ALLOWED_HOSTS ...@@ -35,7 +35,8 @@ ALLOWED_HOSTS = conf.ALLOWED_HOSTS
35 # Application definition 35 # Application definition
36 36
37 INSTALLED_APPS = [ 37 INSTALLED_APPS = [
38 'django.contrib.admin', 38 # 'django.contrib.admin',
39 'apps.myadmin.apps.MyAdminConfig',
39 'django.contrib.auth', 40 'django.contrib.auth',
40 'django.contrib.contenttypes', 41 'django.contrib.contenttypes',
41 'django.contrib.sessions', 42 'django.contrib.sessions',
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!