Skip to content

Commit

Permalink
Add /account/ API
Browse files Browse the repository at this point in the history
  • Loading branch information
taoky committed Oct 15, 2023
1 parent 9c00fe2 commit 3396f7b
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 4 deletions.
29 changes: 28 additions & 1 deletion frontend/templates/admin_user.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,16 @@ <h2 v-else>正在创建</h2>
<div class="form-row">
<a :href="`/admin/auth/user/${opened.pk}/change`">跳转到 Django 用户模型页面(配置权限)……</a>
</div>
<div class="form-row">
<div class="form-row" v-if="account_pks.length > 0">
<a :href="`/admin/frontend/account/${opened.pk}/change`">跳转到 Account 模型页面(查看登录方式信息)……</a>
</div>
<div class="form-row" v-if="account_pks.length > 0">
<a @click.prevent="get_accountlog" href="#">显示 AccountLog 记录</a>
<ul v-if="accountlog && accountlog.length > 0">
<li v-for="log in accountlog">{{ log.content_type }}: {{ log.contents }}</li>
</ul>
<p v-else-if="accountlog">(无结果)</p>
</div>
<div class="form-row">
<label for="form-name">姓名:</label>
<input class="vTextField" type="text" id="form-name" name="name" v-model="opened.name">
Expand Down Expand Up @@ -169,6 +176,8 @@ <h2 v-else>正在创建</h2>
filters: {
group: null,
},
account_pks: [],
accountlog: undefined,
},
created() {
this.refresh();
Expand All @@ -195,6 +204,15 @@ <h2 v-else>正在创建</h2>
},
open(obj) {
this.opened = {...obj};
this.account_pks = [];
this.accountlog = undefined;
axios.post('/account/', {method: 'account_pk', user: obj.pk})
.then(({data: {value}}) => {
this.account_pks = value;
})
.catch(({response: {data: {error}}}) => {
alert(error && error.message);
});
location.hash = `#edit-${obj.pk}`;
},
opened_save() {
Expand All @@ -210,6 +228,15 @@ <h2 v-else>正在创建</h2>
this.opened_disabled = false;
});
},
get_accountlog() {
axios.post('/account/', {method: 'accountlog', user: this.opened.pk})
.then(({data: {value}}) => {
this.accountlog = value;
})
.catch(({response: {data: {error}}}) => {
alert(error && error.message);
});
}
},
});
</script>
Expand Down
35 changes: 33 additions & 2 deletions frontend/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .auth_providers.sustech import LoginView as SUSTECHLoginView
from unittest import mock
from contextlib import contextmanager
import json


USTC_CAS_EXAMPLE_RESPONSE = """<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
Expand Down Expand Up @@ -104,12 +105,42 @@ def setUp(self) -> None:
def test_ustc(self):
self.c.logout()
resp = self.c.get("/accounts/ustc/login/", {"ticket": "ST-1234567890"})
self.assertRedirects(resp, reverse('hub'), target_status_code=302)
self.assertRedirects(resp, reverse("hub"), target_status_code=302)
self.assert_(auth.get_user(self.c).is_authenticated)

@mock.patch("frontend.auth_providers.cas.urlopen", new=mock_urlopen)
def test_sustech(self):
self.c.logout()
resp = self.c.get("/accounts/sustech/login/", {"ticket": "ST-1234567890"})
self.assertRedirects(resp, reverse('hub'), target_status_code=302)
self.assertRedirects(resp, reverse("hub"), target_status_code=302)
self.assert_(auth.get_user(self.c).is_authenticated)


class AccountLogViewPermission(TestCase):
def setUp(self) -> None:
self.c = Client()

def test_anonymous(self):
resp = self.c.post(
reverse("account"),
data=json.dumps({"method": "accountlog", "user": 1}),
content_type="application/json",
)
self.assertEqual(resp.status_code, 400)
code = resp.json()["error"]['code']
self.assertEqual(code, 'permission_required')

@mock.patch("frontend.auth_providers.cas.urlopen", new=mock_urlopen)
def test_low_privilege(self):
# get a ustc account
self.c.logout()
resp = self.c.get("/accounts/sustech/login/", {"ticket": "ST-1234567890"})
self.assert_(auth.get_user(self.c).is_authenticated)
resp = self.c.post(
reverse("account"),
data=json.dumps({"method": "accountlog", "user": 1}),
content_type="application/json",
)
self.assertEqual(resp.status_code, 400)
code = resp.json()["error"]['code']
self.assertEqual(code, 'permission_required')
1 change: 1 addition & 0 deletions frontend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
path('user/', views.UserView.as_view()),
path('qa/', views.QaView.as_view(), name='qa'),
path('credits/', views.CreditsView.as_view(), name='credits'),
path('account/', views.AccountView.as_view(), name='account'),
path('error/', views.ErrorView.as_view()),
path('data/core.json', views.CoreDataView.as_view(), name='coredata'),
path('challenge/<int:challenge_id>/', views.ChallengeURLView.as_view(), name='challenge_url'),
Expand Down
27 changes: 26 additions & 1 deletion frontend/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from server.context import Context
from server.exceptions import Error, NotFound, WrongFormat

from frontend.models import Account, Credits, Qa, SpecialProfileUsedRecord
from frontend.models import Account, AccountLog, Credits, Qa, SpecialProfileUsedRecord


# noinspection PyMethodMayBeStatic
Expand Down Expand Up @@ -267,6 +267,31 @@ def get(self, request):
return TemplateResponse(request, 'credits.html', {'credits': Credits.get()})


class AccountView(View):
def post(self, request):
body = json.loads(request.body)
method = body['method']
user_pk = body['user']
accounts = Account.objects.filter(user__pk=user_pk)
if method == "account_pk":
return JsonResponse({'value': [i.pk for i in accounts]})
elif method == "accountlog":
# Check permission
try:
context = Context.from_request(request)
if request.user.pk is None:
raise PermissionRequired()
user = User.get(context, request.user.pk)
User.test_permission(context, 'user.full', 'user.view', f'user.view_{user.group}')
except PermissionRequired as e:
j = e.json
j['message'] = '您目前没有权限查看此项'
return JsonResponse({'error': j}, status=400)
logs = list(AccountLog.objects.filter(account__in=accounts).values('content_type', 'contents'))
return JsonResponse({'value': logs})



# noinspection PyMethodMayBeStatic
class BaseAdminView(View):
title = None
Expand Down

0 comments on commit 3396f7b

Please sign in to comment.