chore: initial work on displaying clients in dash

This commit is contained in:
0x1a8510f2 2023-01-21 13:09:20 +00:00
parent 3a9f515b7c
commit 55e1f59456
Signed by: 0x1a8510f2
GPG Key ID: 1C692E355D76775D
5 changed files with 185 additions and 122 deletions

View File

@ -3,6 +3,7 @@ package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/user"
@ -22,6 +23,11 @@ type authSuccessResponse struct {
Access authStatus `json:"access"`
}
type clientsRequest struct {
Offset int `json:"offset"`
Limit int `json:"limit"`
}
type sendRequest struct {
Target string `json:"target"`
Payload struct {
@ -32,6 +38,39 @@ type sendRequest struct {
Conditions struct{} `json:"conditions"`
}
func handleClients(r *http.Request, w http.ResponseWriter, s *state) {
// Pull necessary information out of the request.
// Get the data from the request body.
reqbody, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
// Parse the request body.
reqdata := clientsRequest{}
err = json.Unmarshal(reqbody, &reqdata)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Collect necessary information.
clients, totalClients := s.GetClients(reqdata.Offset, reqdata.Limit)
// Build response data.
data, err := json.Marshal(map[string]any{
"clients": clients,
"total": totalClients,
})
if err != nil {
panic(fmt.Sprintf("error while generating `clients` API response: %v", err))
}
// Send!
w.Write(data)
}
func handleAbout(w http.ResponseWriter) {
// Collect necessary information.
buildinfo, _ := debug.ReadBuildInfo()

View File

@ -97,6 +97,20 @@ func main() {
path := strings.TrimPrefix(r.URL.EscapedPath(), "/X/")
switch path {
case "checkauth":
if !StatusInGroup(AuthStatus(r), AUTH_STATUS_A, AUTH_STATUS_V) {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusNoContent)
case "clients":
// Require auth.
if !StatusInGroup(AuthStatus(r), AUTH_STATUS_A, AUTH_STATUS_V) {
w.WriteHeader(http.StatusUnauthorized)
return
}
handleClients(r, w, s)
case "about":
// Require auth.
if !StatusInGroup(AuthStatus(r), AUTH_STATUS_A, AUTH_STATUS_V) {
@ -154,12 +168,6 @@ func main() {
Data: packetData,
})
w.WriteHeader(http.StatusNoContent)
case "checkauth":
if !StatusInGroup(AuthStatus(r), AUTH_STATUS_A, AUTH_STATUS_V) {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.WriteHeader(http.StatusNoContent)
case "auth":
// Make sure we haven't exceeded the limit for failed logins.

View File

@ -1,6 +1,7 @@
package main
import (
"sort"
"sync"
"time"
@ -114,3 +115,35 @@ func (s *state) Prune() {
wg.Wait()
}
func (s *state) GetClients(offset int, limit int) (map[string]client, int) {
s.clientsMutex.Lock()
defer s.clientsMutex.Unlock()
clientsLength := len(s.clients)
if offset > clientsLength {
return map[string]client{}, clientsLength
}
length := limit
if limit > clientsLength {
length = clientsLength
}
sortedKeys := make([]string, offset+length)
i := 0
for k := range s.clients {
sortedKeys[i] = k
i++
}
sort.Strings(sortedKeys)
wantedKeys := sortedKeys[offset:]
clientsCopy := make(map[string]client, len(wantedKeys))
for _, k := range wantedKeys {
clientsCopy[k] = s.clients[k]
}
return clientsCopy, clientsLength
}

View File

@ -3,6 +3,7 @@ import { sha512 } from './helpers'
const API_PATH_BASE = 'X/'
const API_PATH_AUTH = API_PATH_BASE+'auth'
const API_PATH_CHECKAUTH = API_PATH_BASE+'checkauth'
const API_PATH_CLIENTS = API_PATH_BASE+'clients'
const API_PATH_ABOUT = API_PATH_BASE+'about'
export default class API {
@ -137,9 +138,20 @@ export default class API {
return true
}
async fetchClients(offset: number, limit: number) {
const res = await this.apifetch(API_PATH_CLIENTS, {
method: 'POST',
body: JSON.stringify({
offset,
limit
})
})
return res.json()
}
async fetchAbout() {
const res = await this.apifetch(API_PATH_ABOUT)
return await res.json()
return res.json()
}
}

View File

@ -6,23 +6,23 @@
<Toolbar class="mb-4">
<template v-slot:start>
<div class="my-2">
<Button label="New" icon="pi pi-plus" class="p-button-success mr-2" @click="openNew" />
<Button label="Delete" icon="pi pi-trash" class="p-button-danger" @click="confirmDeleteSelected" :disabled="!selectedProducts || !selectedProducts.length" />
<Button label="New" icon="pi pi-plus" class="p-button-success mr-2" @click="" />
<Button label="Delete" icon="pi pi-trash" class="p-button-danger" @click="" :disabled="!clientsSelected || !clientsSelected.length" />
</div>
</template>
<template v-slot:end>
<FileUpload mode="basic" accept="image/*" :maxFileSize="1000000" label="Import" chooseLabel="Import" class="mr-2 inline-block" />
<Button label="Export" icon="pi pi-upload" class="p-button-help" @click="exportCSV($event)" />
<Button label="Export" icon="pi pi-upload" class="p-button-help" @click="" />
</template>
</Toolbar>
<DataTable ref="dt" :value="products" v-model:selection="selectedProducts" dataKey="id" :paginator="true" :rows="10" :filters="filters"
<DataTable ref="dt" :value="clients" v-model:selection="clientsSelected" dataKey="id" :paginator="true" :rows="10" :filters="filters"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown" :rowsPerPageOptions="[5,10,25]"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} products" responsiveLayout="scroll">
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} clients" responsiveLayout="scroll">
<template #header>
<div class="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 class="m-0">Manage Products</h5>
<h5 class="m-0">Manage Clients</h5>
<span class="block mt-2 md:mt-0 p-input-icon-left">
<i class="pi pi-search" />
<InputText v-model="filters['global'].value" placeholder="Search..." />
@ -31,151 +31,122 @@
</template>
<Column selectionMode="multiple" headerStyle="width: 3rem"></Column>
<Column field="code" header="Code" :sortable="true" headerStyle="width:14%; min-width:10rem;">
<Column field="code" header="Strain ID" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Code</span>
<span class="p-column-title">Strain ID</span>
{{slotProps.data.code}}
</template>
</Column>
<Column field="name" header="Name" :sortable="true" headerStyle="width:14%; min-width:10rem;">
<Column field="name" header="Init Time" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Name</span>
<span class="p-column-title">Init Time</span>
{{slotProps.data.name}}
</template>
</Column>
<Column header="Image" headerStyle="width:14%; min-width:10rem;">
<Column header="Modules" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Image</span>
<span class="p-column-title">Modules</span>
<img :src="'images/product/' + slotProps.data.image" :alt="slotProps.data.image" class="shadow-2" width="100" />
</template>
</Column>
<Column field="price" header="Price" :sortable="true" headerStyle="width:14%; min-width:8rem;">
<Column field="price" header="Host OS" headerStyle="width:14%; min-width:8rem;">
<template #body="slotProps">
<span class="p-column-title">Price</span>
{{formatCurrency(slotProps.data.price)}}
<span class="p-column-title">Host OS</span>
{{1}}
</template>
</Column>
<Column field="category" header="Category" :sortable="true" headerStyle="width:14%; min-width:10rem;">
<Column field="category" header="Host Arch" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Category</span>
{{formatCurrency(slotProps.data.category)}}
<span class="p-column-title">Host Arch</span>
{{1}}
</template>
</Column>
<Column field="rating" header="Reviews" :sortable="true" headerStyle="width:14%; min-width:10rem;">
<Column field="rating" header="Hostname" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Rating</span>
<span class="p-column-title">Hostname</span>
<Rating :modelValue="slotProps.data.rating" :readonly="true" :cancel="false" />
</template>
</Column>
<Column field="inventoryStatus" header="Status" :sortable="true" headerStyle="width:14%; min-width:10rem;">
<Column field="inventoryStatus" header="Host User" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Status</span>
<span class="p-column-title">Host User</span>
<span :class="'product-badge status-' + (slotProps.data.inventoryStatus ? slotProps.data.inventoryStatus.toLowerCase() : '')">{{slotProps.data.inventoryStatus}}</span>
</template>
</Column>
<Column field="inventoryStatus" header="Host User ID" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Host User ID</span>
<span :class="'product-badge status-' + (slotProps.data.inventoryStatus ? slotProps.data.inventoryStatus.toLowerCase() : '')">{{slotProps.data.inventoryStatus}}</span>
</template>
</Column>
<Column field="inventoryStatus" header="Errors" headerStyle="width:14%; min-width:10rem;">
<template #body="slotProps">
<span class="p-column-title">Errors</span>
<span :class="'product-badge status-' + (slotProps.data.inventoryStatus ? slotProps.data.inventoryStatus.toLowerCase() : '')">{{slotProps.data.inventoryStatus}}</span>
</template>
</Column>
<Column headerStyle="min-width:10rem;">
<template #body="slotProps">
<Button icon="pi pi-pencil" class="p-button-rounded p-button-success mr-2" @click="editProduct(slotProps.data)" />
<Button icon="pi pi-trash" class="p-button-rounded p-button-warning mt-2" @click="confirmDeleteProduct(slotProps.data)" />
<Button icon="pi pi-pencil" class="p-button-rounded p-button-success mr-2" @click="" />
<Button icon="pi pi-trash" class="p-button-rounded p-button-warning mt-2" @click="" />
</template>
</Column>
</DataTable>
<Dialog v-model:visible="productDialog" :style="{width: '450px'}" header="Product Details" :modal="true" class="p-fluid">
<img :src="'images/product/' + product.image" :alt="product.image" v-if="product.image" width="150" class="mt-0 mx-auto mb-5 block shadow-2" />
<div class="field">
<label for="name">Name</label>
<InputText id="name" v-model.trim="product.name" required="true" autofocus :class="{'p-invalid': submitted && !product.name}" />
<small class="p-invalid" v-if="submitted && !product.name">Name is required.</small>
</div>
<div class="field">
<label for="description">Description</label>
<Textarea id="description" v-model="product.description" required="true" rows="3" cols="20" />
</div>
<div class="field">
<label for="inventoryStatus" class="mb-3">Inventory Status</label>
<Dropdown id="inventoryStatus" v-model="product.inventoryStatus" :options="statuses" optionLabel="label" placeholder="Select a Status">
<template #value="slotProps">
<div v-if="slotProps.value && slotProps.value.value">
<span :class="'product-badge status-' +slotProps.value.value">{{slotProps.value.label}}</span>
</div>
<div v-else-if="slotProps.value && !slotProps.value.value">
<span :class="'product-badge status-' +slotProps.value.toLowerCase()">{{slotProps.value}}</span>
</div>
<span v-else>
{{slotProps.placeholder}}
</span>
</template>
</Dropdown>
</div>
<div class="field">
<label class="mb-3">Category</label>
<div class="formgrid grid">
<div class="field-radiobutton col-6">
<RadioButton id="category1" name="category" value="Accessories" v-model="product.category" />
<label for="category1">Accessories</label>
</div>
<div class="field-radiobutton col-6">
<RadioButton id="category2" name="category" value="Clothing" v-model="product.category" />
<label for="category2">Clothing</label>
</div>
<div class="field-radiobutton col-6">
<RadioButton id="category3" name="category" value="Electronics" v-model="product.category" />
<label for="category3">Electronics</label>
</div>
<div class="field-radiobutton col-6">
<RadioButton id="category4" name="category" value="Fitness" v-model="product.category" />
<label for="category4">Fitness</label>
</div>
</div>
</div>
<div class="formgrid grid">
<div class="field col">
<label for="price">Price</label>
<InputNumber id="price" v-model="product.price" mode="currency" currency="USD" locale="en-US" />
</div>
<div class="field col">
<label for="quantity">Quantity</label>
<InputNumber id="quantity" v-model="product.quantity" integeronly />
</div>
</div>
<template #footer>
<Button label="Cancel" icon="pi pi-times" class="p-button-text" @click="hideDialog"/>
<Button label="Save" icon="pi pi-check" class="p-button-text" @click="saveProduct" />
</template>
</Dialog>
<Dialog v-model:visible="deleteProductDialog" :style="{width: '450px'}" header="Confirm" :modal="true">
<div class="flex align-items-center justify-content-center">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
<span v-if="product">Are you sure you want to delete <b>{{product.name}}</b>?</span>
</div>
<template #footer>
<Button label="No" icon="pi pi-times" class="p-button-text" @click="deleteProductDialog = false"/>
<Button label="Yes" icon="pi pi-check" class="p-button-text" @click="deleteProduct" />
</template>
</Dialog>
<Dialog v-model:visible="deleteProductsDialog" :style="{width: '450px'}" header="Confirm" :modal="true">
<div class="flex align-items-center justify-content-center">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
<span v-if="product">Are you sure you want to delete the selected products?</span>
</div>
<template #footer>
<Button label="No" icon="pi pi-times" class="p-button-text" @click="deleteProductsDialog = false"/>
<Button label="Yes" icon="pi pi-check" class="p-button-text" @click="deleteSelectedProducts" />
</template>
</Dialog>
</div>
</div>
</div>
</template>
<script>
<script lang="ts">
import { defineComponent } from 'vue'
import { FilterMatchMode } from 'primevue/api'
import API from '../../api/api'
export default defineComponent({
data() {
return {
api: new API(),
clients: [],
clientsSelected: [],
clientsCount: 0,
clientsOffset: 0,
clientsLimit: 50,
clientDialog: false,
filters: {
global: {
value: '',
matchMode: FilterMatchMode.CONTAINS,
}
},
timer: 0
}
},
mounted() {
this.startAutoUpdate()
},
beforeUnmount () {
this.cancelAutoUpdate()
},
methods: {
updatePageData () {
this.api.fetchClients(this.clientsOffset, this.clientsLimit).then((data) => {
this.clients = data['clients']
this.clientsCount = data['total']
});
},
startAutoUpdate() {
this.updatePageData()
this.timer = setInterval(this.updatePageData, 5000)
},
cancelAutoUpdate() {
clearInterval(this.timer)
},
},
})
</script>
<!-- <script lang="ts">
import {FilterMatchMode} from 'primevue/api';
import ProductService from '../../api/api';
@ -291,7 +262,7 @@ export default {
}
}
}
</script>
</script> -->
<style scoped lang="scss">
@import '../../assets/styles/badges.scss';