mirror of
https://gitlab.crans.org/mediatek/med.git
synced 2024-11-30 10:13:03 +00:00
77 lines
2.4 KiB
Python
77 lines
2.4 KiB
Python
# -*- mode: python; coding: utf-8 -*-
|
|
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
from django.contrib import admin
|
|
from django.contrib.auth import get_user_model
|
|
from django.db.models import Q
|
|
|
|
from med.admin import admin_site
|
|
from .models import GameSave, Player
|
|
|
|
|
|
class PlayerInline(admin.TabularInline):
|
|
model = Player
|
|
|
|
# Do not always show extra players
|
|
extra = 0
|
|
min_num = 5
|
|
|
|
|
|
class GameSaveAdmin(admin.ModelAdmin):
|
|
inlines = [PlayerInline, ]
|
|
list_display = ('__str__', 'game_master', 'game_has_ended')
|
|
date_hierarchy = 'created_at'
|
|
autocomplete_fields = ('game_master',)
|
|
|
|
def has_change_permission(self, request, obj=None):
|
|
"""
|
|
If user is game master then authorize edit
|
|
"""
|
|
if obj and obj.game_master == request.user:
|
|
return True
|
|
return super().has_change_permission(request, obj)
|
|
|
|
def has_delete_permission(self, request, obj=None):
|
|
"""
|
|
If user is game master then authorize deletion
|
|
"""
|
|
if obj and obj.game_master == request.user:
|
|
return True
|
|
return super().has_delete_permission(request, obj)
|
|
|
|
def add_view(self, request, form_url='', extra_context=None):
|
|
"""
|
|
Autoselect game master when creating a new game
|
|
"""
|
|
# Make GET data mutable
|
|
data = request.GET.copy()
|
|
data['game_master'] = request.user
|
|
request.GET = data
|
|
return super().add_view(request, form_url, extra_context)
|
|
|
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
|
"""
|
|
Authorize game master change only if user can see all users
|
|
"""
|
|
if db_field.name == 'game_master':
|
|
if not request.user.has_perm('users.view_user'):
|
|
kwargs['queryset'] = get_user_model().objects.filter(
|
|
username=request.user.username)
|
|
return super().formfield_for_foreignkey(db_field, request, **kwargs)
|
|
|
|
def get_queryset(self, request):
|
|
"""
|
|
List all game save only if user has view permission
|
|
else, list only own games and ended games
|
|
"""
|
|
queryset = super().get_queryset(request)
|
|
if request.user.has_perm('sporz.view_gamesave'):
|
|
return queryset
|
|
return queryset.filter(
|
|
Q(game_master=request.user) | Q(game_has_ended=True)
|
|
)
|
|
|
|
|
|
admin_site.register(GameSave, GameSaveAdmin)
|