Started work on API tokens

reminder
Etzelia 2018-11-21 17:04:47 -06:00 committed by John Olheiser
parent d35b77014f
commit 7ae8fa576d
3 changed files with 73 additions and 16 deletions

41
api/admin.py 100644
View File

@ -0,0 +1,41 @@
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from minecraft_manager.api.models import Token
class TokenActiveFilter(admin.SimpleListFilter):
title = _('Active')
parameter_name = 'active'
def lookups(self, request, model_admin):
return (
('0', _('Active')),
('1', _('Inactive')),
)
def queryset(self, request, queryset):
if self.value() == '0':
return queryset.filter(active=True)
if self.value() == '1':
return queryset.filter(active=False)
class TokenAdmin(admin.ModelAdmin):
list_filter = (TokenActiveFilter,)
fieldsets = (
(None, {
'fields': ('key', 'active')
}),
('Permissions', {
'fields': ('web_get_permission', 'web_post_permission', 'plugin_get_permission', 'plugin_post_permission',
'form_get_permission', 'form_post_permission', 'model_get_permission', 'model_post_permission',
'stats_get_permission', 'stats_post_permission')
})
)
try:
admin.site.register(Token, TokenAdmin)
except admin.sites.AlreadyRegistered:
pass

16
api/models.py 100644
View File

@ -0,0 +1,16 @@
from django.db import models
class Token(models.Model):
key = models.CharField("Key", max_length=50, unique=True)
active = models.BooleanField("Active", default=True)
web_get_permission = models.BooleanField("Web API GET", default=False)
web_post_permission = models.BooleanField("Web API POST", default=False)
plugin_get_permission = models.BooleanField("Plugin API GET", default=False)
plugin_post_permission = models.BooleanField("Plugin API POST", default=False)
form_get_permission = models.BooleanField("Form API GET", default=False)
form_post_permission = models.BooleanField("Form API POST", default=False)
model_get_permission = models.BooleanField("Model API GET", default=False)
model_post_permission = models.BooleanField("Model API POST", default=False)
stats_get_permission = models.BooleanField("Stats API GET", default=False)
stats_post_permission = models.BooleanField("Stats API POST", default=False)

View File

@ -7,7 +7,6 @@ from django.apps import apps
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.http import JsonResponse, HttpResponse from django.http import JsonResponse, HttpResponse
from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from django.views.generic import View from django.views.generic import View
from django.forms import modelform_factory from django.forms import modelform_factory
@ -15,29 +14,30 @@ from django.forms import modelform_factory
import minecraft_manager.forms as MCMForms import minecraft_manager.forms as MCMForms
from minecraft_manager.models import Player, UserSettings, Application, IP, Ticket, Warning from minecraft_manager.models import Player, UserSettings, Application, IP, Ticket, Warning
import minecraft_manager.api.api as mcm_api import minecraft_manager.api.api as mcm_api
from minecraft_manager.api.models import Token
import minecraft_manager.utils as mcm_utils import minecraft_manager.utils as mcm_utils
import minecraft_manager.external.stats as mcm_stats import minecraft_manager.external.stats as mcm_stats
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def request_allowed(request): def request_allowed(request, permission):
is_authenticated = False is_authenticated = False
if hasattr(request, 'user'): if hasattr(request, 'user'):
if hasattr(request.user, 'is_authenticated'): if hasattr(request.user, 'is_authenticated'):
is_authenticated = request.user.is_authenticated is_authenticated = request.user.is_authenticated
password = getattr(settings, 'API_PASSWORD', None)
get = request.GET get = request.GET
post= request.POST post = request.POST
request_password = None request_password = None
if 'api' in get: if 'api' in get:
request_password = get['api'] request_password = get['api']
elif 'api' in post: elif 'api' in post:
request_password = post['api'] request_password = post['api']
correct_password = False token_permission = False
if password and request_password: if Token.objects.filter(active=True, key=request_password).exists():
correct_password = request_password == password token = Token.objects.get(active=True, key=request_password)
return is_authenticated or correct_password token_permission = getattr(token, permission, False)
return is_authenticated or token_permission
def clean(model, data): def clean(model, data):
@ -60,7 +60,7 @@ class WebAPI(View):
def get(self, request, keyword): def get(self, request, keyword):
get = request.GET get = request.GET
data = {'success': False, 'message': 'API failed'} data = {'success': False, 'message': 'API failed'}
if request_allowed(request): if request_allowed(request, 'web_get_permission'):
keyword = keyword.lower() keyword = keyword.lower()
if keyword == 'log': if keyword == 'log':
html_global = "" html_global = ""
@ -102,7 +102,7 @@ class WebAPI(View):
def post(self, request, keyword): def post(self, request, keyword):
post = request.POST post = request.POST
data = {} data = {}
if request_allowed(request): if request_allowed(request, 'web_post_permission'):
keyword = keyword.lower() keyword = keyword.lower()
if keyword == 'settings' and request.user.usersettings: if keyword == 'settings' and request.user.usersettings:
for s in [a for a in dir(UserSettings) if not a.startswith('__') and not callable(getattr(UserSettings,a))]: for s in [a for a in dir(UserSettings) if not a.startswith('__') and not callable(getattr(UserSettings,a))]:
@ -155,7 +155,7 @@ class PluginAPI(View):
def get(self, request, keyword): def get(self, request, keyword):
json = {'status': True, 'message': '', 'extra': ''} json = {'status': True, 'message': '', 'extra': ''}
if request_allowed(request): if request_allowed(request, 'plugin_get_permission'):
get = request.GET get = request.GET
keyword = keyword.lower() keyword = keyword.lower()
@ -163,7 +163,7 @@ class PluginAPI(View):
def post(self, request, keyword): def post(self, request, keyword):
json = {'status': True, 'message': '', 'extra': ''} json = {'status': True, 'message': '', 'extra': ''}
if request_allowed(request): if request_allowed(request, 'plugin_post_permission'):
post = request.POST post = request.POST
keyword = keyword.lower() keyword = keyword.lower()
if "application" == keyword: if "application" == keyword:
@ -323,7 +323,7 @@ class FormAPI(View):
def get(self, request, request_model): def get(self, request, request_model):
html = "" html = ""
if request_allowed(request): if request_allowed(request, 'form_get_permission'):
get = request.GET get = request.GET
model = None model = None
for m in apps.get_app_config('minecraft_manager').get_models(): for m in apps.get_app_config('minecraft_manager').get_models():
@ -346,7 +346,7 @@ class FormAPI(View):
def post(self, request, request_model): def post(self, request, request_model):
html = "" html = ""
if request_allowed(request): if request_allowed(request, 'form_post_permission'):
post = request.POST post = request.POST
model = None model = None
for m in apps.get_app_config('minecraft_manager').get_models(): for m in apps.get_app_config('minecraft_manager').get_models():
@ -376,7 +376,7 @@ class ModelAPI(View):
def get(self, request, request_model): def get(self, request, request_model):
json = [] json = []
if request_allowed(request): if request_allowed(request, 'model_get_permission'):
get = request.GET get = request.GET
model = None model = None
for m in apps.get_app_config('minecraft_manager').get_models(): for m in apps.get_app_config('minecraft_manager').get_models():
@ -404,7 +404,7 @@ class StatsAPI(View):
def get(self, request): def get(self, request):
json = [] json = []
if request_allowed(request): if request_allowed(request, 'stats_get_permission'):
get = request.GET get = request.GET
if 'stat' in get: if 'stat' in get:
if 'uuid' in get: if 'uuid' in get: