Show community account last login and count info on admin page

The collection facility was added in
[200~9e70a4e0c32f8db0178f05dac4c1fca7b317e7c5, but no way was added to
view it. To make it a  bit more useful, add a static set of info on the
user edit page in /admin/ that shows the last login and number of logins
per site.
This commit is contained in:
Magnus Hagander
2020-07-07 12:24:08 +02:00
parent e9c84c668f
commit e850a9bf3e
3 changed files with 47 additions and 1 deletions

View File

@ -6,6 +6,9 @@ from django import forms
import base64
from pgweb.util.widgets import TemplateRenderWidget
from pgweb.util.db import exec_to_dict
from .models import CommunityAuthSite, CommunityAuthOrg
@ -31,7 +34,8 @@ class CommunityAuthSiteAdmin(admin.ModelAdmin):
class PGUserChangeForm(UserChangeForm):
"""just like UserChangeForm, butremoves "username" requirement"""
logininfo = forms.CharField(label="Community login history")
def __init__(self, *args, **kwargs):
super(PGUserChangeForm, self).__init__(*args, **kwargs)
# because the auth.User model is set to "blank=False" and the Django
@ -41,6 +45,14 @@ class PGUserChangeForm(UserChangeForm):
if self.fields.get('username'):
del self.fields['username']
self.fields['logininfo'].widget = TemplateRenderWidget(
template='forms/widgets/community_auth_usage_widget.html',
context={
'logins': exec_to_dict("SELECT s.name AS service, lastlogin, logincount FROM account_communityauthsite s INNER JOIN account_communityauthlastlogin l ON s.id=l.site_id WHERE user_id=%(userid)s ORDER BY lastlogin DESC", {
'userid': self.instance.pk,
}),
})
class PGUserAdmin(UserAdmin):
"""overrides default Django user admin"""
@ -52,6 +64,14 @@ class PGUserAdmin(UserAdmin):
return self.readonly_fields + ('username',)
return self.readonly_fields
@property
def fieldsets(self):
fs = list(super().fieldsets)
fs.append(
('Community authentication', {'fields': ('logininfo', )}),
)
return fs
admin.site.register(CommunityAuthSite, CommunityAuthSiteAdmin)
admin.site.register(CommunityAuthOrg)

View File

@ -0,0 +1,14 @@
<table>
<tr>
<th>Service</th>
<th>Last login</th>
<th>Login count</th>
</tr>
{%for l in logins%}
<tr>
<td>{{l.service}}</td>
<td>{{l.lastlogin}}</td>
<td>{{l.logincount}}</td>
</tr>
{%endfor%}
</table>

12
pgweb/util/widgets.py Normal file
View File

@ -0,0 +1,12 @@
from django.forms.widgets import Widget
class TemplateRenderWidget(Widget):
def __init__(self, *args, **kwargs):
self.template_name = kwargs.pop('template')
self.templatecontext = kwargs.pop('context')
super().__init__(*args, **kwargs)
def get_context(self, name, value, attrs):
return self.templatecontext