Skip to content

Commit

Permalink
refactoring api-key view => ajax
Browse files Browse the repository at this point in the history
  • Loading branch information
ansibleguy committed Feb 10, 2024
1 parent 53d2b7d commit cdbb36a
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 28 deletions.
12 changes: 9 additions & 3 deletions src/ansible-webui/aw/api_endpoints/key.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from hashlib import md5

from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import APIView
from rest_framework import serializers
Expand All @@ -10,9 +12,9 @@
from aw.api_endpoints.base import API_PERMISSION, get_api_user, BaseResponse, GenericResponse


# todo: allow user to add comment to easier identify token
class KeyReadResponse(BaseResponse):
tokens = serializers.ListSerializer(child=serializers.CharField())
token = serializers.CharField()
id = serializers.CharField()


class KeyWriteResponse(BaseResponse):
Expand All @@ -32,7 +34,11 @@ class APIKey(APIView):
summary='Return a list of all existing API keys of the current user.',
)
def get(request):
return Response({'tokens': [key.name for key in AwAPIKey.objects.filter(user=get_api_user(request))]})
tokens = []
for key in AwAPIKey.objects.filter(user=get_api_user(request)):
tokens.append({'token': key.name, 'id': md5(key.name.encode('utf-8')).hexdigest()})

return Response(tokens)

@extend_schema(
request=None,
Expand Down
6 changes: 3 additions & 3 deletions src/ansible-webui/aw/api_endpoints/permission.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth.models import User, Group
from django.core.exceptions import ObjectDoesNotExist
from django.db.utils import IntegrityError
from rest_framework.generics import GenericAPIView
Expand Down Expand Up @@ -37,7 +37,7 @@ class Meta:
allow_blank=True,
)
users = serializers.MultipleChoiceField(
choices=[user.id for user in settings.AUTH_USER_MODEL.objects.all()],
choices=[user.id for user in User.objects.all()],
allow_blank=True,
)
groups = serializers.MultipleChoiceField(
Expand Down Expand Up @@ -74,7 +74,7 @@ def create_or_update(validated_data: dict, perm: JobPermission = None):
users = []
for user_id in validated_data['users']:
try:
users.append(settings.AUTH_USER_MODEL.objects.get(id=user_id))
users.append(User.objects.get(id=user_id))

except ObjectDoesNotExist:
continue
Expand Down
5 changes: 4 additions & 1 deletion src/ansible-webui/aw/static/js/aw.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,10 @@ function apiBrowseDir(inputElement, choicesElement, selector, base, searchType)
});
}

function fetchApiTableData(dataTable, apiEndpoint, updateFunction) {
function fetchApiTableData(apiEndpoint, updateFunction) {
// NOTE: data needs to be list of dict and include an 'id' attribute
dataTable = document.getElementById("aw-api-data-table");

$.get(apiEndpoint, function(data) {
existingEntryIds = [];
// for each existing entry
Expand Down
14 changes: 11 additions & 3 deletions src/ansible-webui/aw/static/js/settings/api_key.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
function updateApiTableDataKey(row, entry) {
entryRow.insertCell(0).innerText = entry.token;
actionsTemplate = document.getElementById("aw-api-data-tmpl-actions").innerHTML;
entryRow.insertCell(1).innerHTML = actionsTemplate.replaceAll('${TOKEN}', entry.token);
}

$( document ).ready(function() {
apiEndpoint = "/api/key";
$(".aw-api-key-add").click(function(){
$.post("/api/key", function(data, status){
$.post(apiEndpoint, function(data, status){
prompt("Your new API key:\n\nToken: " + data.token + "\nKey:", data.key);
reloadAwData();
});
});
});
fetchApiTableData(apiEndpoint, updateApiTableDataKey);
setInterval('fetchApiTableData(apiEndpoint, updateApiTableDataKey)', (DATA_REFRESH_SEC * 1000));
});
5 changes: 2 additions & 3 deletions src/ansible-webui/aw/static/js/settings/permission.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ function updateApiTableDataPermission(row, entry) {
}

$( document ).ready(function() {
dataTable = document.getElementById("aw-api-data-table");
apiEndpoint = "/api/permission";
fetchApiTableData(dataTable, apiEndpoint, updateApiTableDataPermission);
setInterval('fetchApiTableData(dataTable, apiEndpoint, updateApiTableDataPermission)', (DATA_REFRESH_SEC * 1000));
fetchApiTableData(apiEndpoint, updateApiTableDataPermission);
setInterval('fetchApiTableData(apiEndpoint, updateApiTableDataPermission)', (DATA_REFRESH_SEC * 1000));
});
18 changes: 6 additions & 12 deletions src/ansible-webui/aw/templates/settings/api_key.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,11 @@
{% block content %}
<script src="{% static 'js/settings/api_key.js' %}"></script>
<div class="table-responsive aw-data">
<table class="table table-striped aw-text-responsive">
<table class="table table-striped aw-text-responsive" id="aw-api-data-table">
<tr>
<th>API Token</th>
<th>Actions</th>
</tr>
{# todo: build table using ajax to allow for clean refresh #}
{% for token in api_key_tokens %}
<tr>
<td>{{ token }}</td>
<td>
<button class="btn btn-danger aw-btn-action aw-api-click" title="Delete" aw-api-endpoint="key" aw-api-item="{{ token }}" aw-api-method="delete">
{% include "../button/icon/delete.html" %}
</button>
</td>
</tr>
{% endfor %}
<tr>
<td colspan="100%">
{% include "../button/refresh.html" %}
Expand All @@ -28,5 +17,10 @@
</td>
</tr>
</table>
<div id="aw-api-data-tmpl-actions" hidden="hidden">
<button class="btn btn-danger aw-btn-action aw-api-click" title="Delete" aw-api-endpoint="key" aw-api-item="${TOKEN}" aw-api-method="delete">
{% include "../button/icon/delete.html" %}
</button>
</div>
</div>
{% endblock %}
5 changes: 2 additions & 3 deletions src/ansible-webui/aw/views/settings.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.urls import path
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth.models import User, Group
from django.db.utils import OperationalError
from django.shortcuts import HttpResponse
from django.shortcuts import render, redirect
Expand Down Expand Up @@ -47,7 +46,7 @@ class Meta:
users = MultipleChoiceField(
required=False,
widget=SelectMultiple,
choices=((user.id, user.username) for user in settings.AUTH_USER_MODEL.objects.all())
choices=((user.id, user.username) for user in User.objects.all())
)
groups = MultipleChoiceField(
required=False,
Expand Down

0 comments on commit cdbb36a

Please sign in to comment.