Merge pull request #2558 from Computroniks/feature/1685-prometheus-api-key

Added #1685: Add API keys for API authentication
This commit is contained in:
Louis Lam 2023-02-28 16:55:50 +08:00 committed by GitHub
commit 38ab5e0f3e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 921 additions and 17 deletions

View File

@ -0,0 +1,13 @@
-- You should not modify if this have pushed to Github, unless it does serious wrong with the db.
BEGIN TRANSACTION;
CREATE TABLE [api_key] (
[id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[key] VARCHAR(255) NOT NULL,
[name] VARCHAR(255) NOT NULL,
[user_id] INTEGER NOT NULL,
[created_date] DATETIME DEFAULT (DATETIME('now')) NOT NULL,
[active] BOOLEAN DEFAULT 1 NOT NULL,
[expires] DATETIME DEFAULT NULL,
CONSTRAINT FK_user FOREIGN KEY ([user_id]) REFERENCES [user]([id]) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMIT;

5
package-lock.json generated
View File

@ -45,6 +45,7 @@
"mqtt": "~4.3.7", "mqtt": "~4.3.7",
"mssql": "~8.1.4", "mssql": "~8.1.4",
"mysql2": "~2.3.3", "mysql2": "~2.3.3",
"nanoid": "^3.3.4",
"node-cloudflared-tunnel": "~1.0.9", "node-cloudflared-tunnel": "~1.0.9",
"node-radius-client": "~1.0.0", "node-radius-client": "~1.0.0",
"nodemailer": "~6.6.5", "nodemailer": "~6.6.5",
@ -14247,7 +14248,6 @@
"version": "3.3.4", "version": "3.3.4",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz",
"integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==",
"dev": true,
"bin": { "bin": {
"nanoid": "bin/nanoid.cjs" "nanoid": "bin/nanoid.cjs"
}, },
@ -29825,8 +29825,7 @@
"nanoid": { "nanoid": {
"version": "3.3.4", "version": "3.3.4",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz",
"integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw=="
"dev": true
}, },
"native-duplexpair": { "native-duplexpair": {
"version": "1.0.0", "version": "1.0.0",

View File

@ -103,6 +103,7 @@
"mqtt": "~4.3.7", "mqtt": "~4.3.7",
"mssql": "~8.1.4", "mssql": "~8.1.4",
"mysql2": "~2.3.3", "mysql2": "~2.3.3",
"nanoid": "^3.3.4",
"node-cloudflared-tunnel": "~1.0.9", "node-cloudflared-tunnel": "~1.0.9",
"node-radius-client": "~1.0.0", "node-radius-client": "~1.0.0",
"nodemailer": "~6.6.5", "nodemailer": "~6.6.5",

View File

@ -2,7 +2,9 @@ const basicAuth = require("express-basic-auth");
const passwordHash = require("./password-hash"); const passwordHash = require("./password-hash");
const { R } = require("redbean-node"); const { R } = require("redbean-node");
const { setting } = require("./util-server"); const { setting } = require("./util-server");
const { loginRateLimiter } = require("./rate-limiter"); const { loginRateLimiter, apiRateLimiter } = require("./rate-limiter");
const { Settings } = require("./settings");
const dayjs = require("dayjs");
/** /**
* Login to web app * Login to web app
@ -34,8 +36,36 @@ exports.login = async function (username, password) {
}; };
/** /**
* Callback for myAuthorizer * Validate a provided API key
* @callback myAuthorizerCB * @param {string} key API key to verify
*/
async function verifyAPIKey(key) {
if (typeof key !== "string") {
return false;
}
// uk prefix + key ID is before _
let index = key.substring(2, key.indexOf("_"));
let clear = key.substring(key.indexOf("_") + 1, key.length);
let hash = await R.findOne("api_key", " id=? ", [ index ]);
if (hash === null) {
return false;
}
let current = dayjs();
let expiry = dayjs(hash.expires);
if (expiry.diff(current) < 0 || !hash.active) {
return false;
}
return hash && passwordHash.verify(clear, hash.key);
}
/**
* Callback for basic auth authorizers
* @callback authCallback
* @param {any} err Any error encountered * @param {any} err Any error encountered
* @param {boolean} authorized Is the client authorized? * @param {boolean} authorized Is the client authorized?
*/ */
@ -44,9 +74,31 @@ exports.login = async function (username, password) {
* Custom authorizer for express-basic-auth * Custom authorizer for express-basic-auth
* @param {string} username * @param {string} username
* @param {string} password * @param {string} password
* @param {myAuthorizerCB} callback * @param {authCallback} callback
*/ */
function myAuthorizer(username, password, callback) { function apiAuthorizer(username, password, callback) {
// API Rate Limit
apiRateLimiter.pass(null, 0).then((pass) => {
if (pass) {
verifyAPIKey(password).then((valid) => {
callback(null, valid);
// Only allow a set number of api requests per minute
// (currently set to 60)
apiRateLimiter.removeTokens(1);
});
} else {
callback(null, false);
}
});
}
/**
* Custom authorizer for express-basic-auth
* @param {string} username
* @param {string} password
* @param {authCallback} callback
*/
function userAuthorizer(username, password, callback) {
// Login Rate Limit // Login Rate Limit
loginRateLimiter.pass(null, 0).then((pass) => { loginRateLimiter.pass(null, 0).then((pass) => {
if (pass) { if (pass) {
@ -71,7 +123,7 @@ function myAuthorizer(username, password, callback) {
*/ */
exports.basicAuth = async function (req, res, next) { exports.basicAuth = async function (req, res, next) {
const middleware = basicAuth({ const middleware = basicAuth({
authorizer: myAuthorizer, authorizer: userAuthorizer,
authorizeAsync: true, authorizeAsync: true,
challenge: true, challenge: true,
}); });
@ -84,3 +136,32 @@ exports.basicAuth = async function (req, res, next) {
next(); next();
} }
}; };
/**
* Use use API Key if API keys enabled, else use basic auth
* @param {express.Request} req Express request object
* @param {express.Response} res Express response object
* @param {express.NextFunction} next
*/
exports.apiAuth = async function (req, res, next) {
if (!await Settings.get("disableAuth")) {
let usingAPIKeys = await Settings.get("apiKeysEnabled");
let middleware;
if (usingAPIKeys) {
middleware = basicAuth({
authorizer: apiAuthorizer,
authorizeAsync: true,
challenge: true,
});
} else {
middleware = basicAuth({
authorizer: userAuthorizer,
authorizeAsync: true,
challenge: true,
});
}
middleware(req, res, next);
} else {
next();
}
};

View File

@ -113,6 +113,31 @@ async function sendProxyList(socket) {
return list; return list;
} }
/**
* Emit API key list to client
* @param {Socket} socket Socket.io socket instance
* @returns {Promise<void>}
*/
async function sendAPIKeyList(socket) {
const timeLogger = new TimeLogger();
let result = [];
const list = await R.find(
"api_key",
"user_id=?",
[ socket.userID ],
);
for (let bean of list) {
result.push(bean.toPublicJSON());
}
io.to(socket.userID).emit("apiKeyList", result);
timeLogger.print("Sent API Key List");
return list;
}
/** /**
* Emits the version information to the client. * Emits the version information to the client.
* @param {Socket} socket Socket.io socket instance * @param {Socket} socket Socket.io socket instance
@ -157,6 +182,7 @@ module.exports = {
sendImportantHeartbeatList, sendImportantHeartbeatList,
sendHeartbeatList, sendHeartbeatList,
sendProxyList, sendProxyList,
sendAPIKeyList,
sendInfo, sendInfo,
sendDockerHostList sendDockerHostList
}; };

View File

@ -68,6 +68,7 @@ class Database {
"patch-monitor-add-resend-interval.sql": true, "patch-monitor-add-resend-interval.sql": true,
"patch-ping-packet-size.sql": true, "patch-ping-packet-size.sql": true,
"patch-maintenance-table2.sql": true, "patch-maintenance-table2.sql": true,
"patch-api-key-table.sql": true,
"patch-add-gamedig-monitor.sql": true, "patch-add-gamedig-monitor.sql": true,
"patch-add-google-analytics-status-page-tag.sql": true, "patch-add-google-analytics-status-page-tag.sql": true,
"patch-http-body-encoding.sql": true, "patch-http-body-encoding.sql": true,

76
server/model/api_key.js Normal file
View File

@ -0,0 +1,76 @@
const { BeanModel } = require("redbean-node/dist/bean-model");
const { R } = require("redbean-node");
const dayjs = require("dayjs");
class APIKey extends BeanModel {
/**
* Get the current status of this API key
* @returns {string} active, inactive or expired
*/
getStatus() {
let current = dayjs();
let expiry = dayjs(this.expires);
if (expiry.diff(current) < 0) {
return "expired";
}
return this.active ? "active" : "inactive";
}
/**
* Returns an object that ready to parse to JSON
* @returns {Object}
*/
toJSON() {
return {
id: this.id,
key: this.key,
name: this.name,
userID: this.user_id,
createdDate: this.created_date,
active: this.active,
expires: this.expires,
status: this.getStatus(),
};
}
/**
* Returns an object that ready to parse to JSON with sensitive fields
* removed
* @returns {Object}
*/
toPublicJSON() {
return {
id: this.id,
name: this.name,
userID: this.user_id,
createdDate: this.created_date,
active: this.active,
expires: this.expires,
status: this.getStatus(),
};
}
/**
* Create a new API Key and store it in the database
* @param {Object} key Object sent by client
* @param {int} userID ID of socket user
* @returns {Promise<bean>}
*/
static async save(key, userID) {
let bean;
bean = R.dispense("api_key");
bean.key = key.key;
bean.name = key.name;
bean.user_id = userID;
bean.active = key.active;
bean.expires = key.expires;
await R.store(bean);
return bean;
}
}
module.exports = APIKey;

View File

@ -54,6 +54,13 @@ const loginRateLimiter = new KumaRateLimiter({
errorMessage: "Too frequently, try again later." errorMessage: "Too frequently, try again later."
}); });
const apiRateLimiter = new KumaRateLimiter({
tokensPerInterval: 60,
interval: "minute",
fireImmediately: true,
errorMessage: "Too frequently, try again later."
});
const twoFaRateLimiter = new KumaRateLimiter({ const twoFaRateLimiter = new KumaRateLimiter({
tokensPerInterval: 30, tokensPerInterval: 30,
interval: "minute", interval: "minute",
@ -63,5 +70,6 @@ const twoFaRateLimiter = new KumaRateLimiter({
module.exports = { module.exports = {
loginRateLimiter, loginRateLimiter,
apiRateLimiter,
twoFaRateLimiter, twoFaRateLimiter,
}; };

View File

@ -87,7 +87,7 @@ log.debug("server", "Importing Background Jobs");
const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs"); const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs");
const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter"); const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter");
const { basicAuth } = require("./auth"); const { apiAuth } = require("./auth");
const { login } = require("./auth"); const { login } = require("./auth");
const passwordHash = require("./password-hash"); const passwordHash = require("./password-hash");
@ -129,7 +129,7 @@ if (config.demoMode) {
} }
// Must be after io instantiation // Must be after io instantiation
const { sendNotificationList, sendHeartbeatList, sendImportantHeartbeatList, sendInfo, sendProxyList, sendDockerHostList } = require("./client"); const { sendNotificationList, sendHeartbeatList, sendImportantHeartbeatList, sendInfo, sendProxyList, sendDockerHostList, sendAPIKeyList } = require("./client");
const { statusPageSocketHandler } = require("./socket-handlers/status-page-socket-handler"); const { statusPageSocketHandler } = require("./socket-handlers/status-page-socket-handler");
const databaseSocketHandler = require("./socket-handlers/database-socket-handler"); const databaseSocketHandler = require("./socket-handlers/database-socket-handler");
const TwoFA = require("./2fa"); const TwoFA = require("./2fa");
@ -138,6 +138,7 @@ const { cloudflaredSocketHandler, autoStart: cloudflaredAutoStart, stop: cloudfl
const { proxySocketHandler } = require("./socket-handlers/proxy-socket-handler"); const { proxySocketHandler } = require("./socket-handlers/proxy-socket-handler");
const { dockerSocketHandler } = require("./socket-handlers/docker-socket-handler"); const { dockerSocketHandler } = require("./socket-handlers/docker-socket-handler");
const { maintenanceSocketHandler } = require("./socket-handlers/maintenance-socket-handler"); const { maintenanceSocketHandler } = require("./socket-handlers/maintenance-socket-handler");
const { apiKeySocketHandler } = require("./socket-handlers/api-key-socket-handler");
const { generalSocketHandler } = require("./socket-handlers/general-socket-handler"); const { generalSocketHandler } = require("./socket-handlers/general-socket-handler");
const { Settings } = require("./settings"); const { Settings } = require("./settings");
const { CacheableDnsHttpAgent } = require("./cacheable-dns-http-agent"); const { CacheableDnsHttpAgent } = require("./cacheable-dns-http-agent");
@ -229,7 +230,7 @@ let needSetup = false;
// Prometheus API metrics /metrics // Prometheus API metrics /metrics
// With Basic Auth using the first user's username/password // With Basic Auth using the first user's username/password
app.get("/metrics", basicAuth, prometheusAPIMetrics()); app.get("/metrics", apiAuth, prometheusAPIMetrics());
app.use("/", expressStaticGzip("dist", { app.use("/", expressStaticGzip("dist", {
enableBrotli: true, enableBrotli: true,
@ -1503,6 +1504,7 @@ let needSetup = false;
proxySocketHandler(socket); proxySocketHandler(socket);
dockerSocketHandler(socket); dockerSocketHandler(socket);
maintenanceSocketHandler(socket); maintenanceSocketHandler(socket);
apiKeySocketHandler(socket);
generalSocketHandler(socket, server); generalSocketHandler(socket, server);
pluginsHandler(socket, server); pluginsHandler(socket, server);
@ -1611,6 +1613,7 @@ async function afterLogin(socket, user) {
sendNotificationList(socket); sendNotificationList(socket);
sendProxyList(socket); sendProxyList(socket);
sendDockerHostList(socket); sendDockerHostList(socket);
sendAPIKeyList(socket);
await sleep(500); await sleep(500);

View File

@ -0,0 +1,150 @@
const { checkLogin } = require("../util-server");
const { log } = require("../../src/util");
const { R } = require("redbean-node");
const { nanoid } = require("nanoid");
const passwordHash = require("../password-hash");
const apicache = require("../modules/apicache");
const APIKey = require("../model/api_key");
const { Settings } = require("../settings");
const { sendAPIKeyList } = require("../client");
/**
* Handlers for Maintenance
* @param {Socket} socket Socket.io instance
*/
module.exports.apiKeySocketHandler = (socket) => {
// Add a new api key
socket.on("addAPIKey", async (key, callback) => {
try {
checkLogin(socket);
let clearKey = nanoid(40);
let hashedKey = passwordHash.generate(clearKey);
key["key"] = hashedKey;
let bean = await APIKey.save(key, socket.userID);
log.debug("apikeys", "Added API Key");
log.debug("apikeys", key);
// Append key ID and prefix to start of key seperated by _, used to get
// correct hash when validating key.
let formattedKey = "uk" + bean.id + "_" + clearKey;
await sendAPIKeyList(socket);
// Enable API auth if the user creates a key, otherwise only basic
// auth will be used for API.
await Settings.set("apiKeysEnabled", true);
callback({
ok: true,
msg: "Added Successfully.",
key: formattedKey,
keyID: bean.id,
});
} catch (e) {
callback({
ok: false,
msg: e.message,
});
}
});
socket.on("getAPIKeyList", async (callback) => {
try {
checkLogin(socket);
await sendAPIKeyList(socket);
callback({
ok: true,
});
} catch (e) {
console.error(e);
callback({
ok: false,
msg: e.message,
});
}
});
socket.on("deleteAPIKey", async (keyID, callback) => {
try {
checkLogin(socket);
log.debug("apikeys", `Deleted API Key: ${keyID} User ID: ${socket.userID}`);
await R.exec("DELETE FROM api_key WHERE id = ? AND user_id = ? ", [
keyID,
socket.userID,
]);
apicache.clear();
callback({
ok: true,
msg: "Deleted Successfully.",
});
await sendAPIKeyList(socket);
} catch (e) {
callback({
ok: false,
msg: e.message,
});
}
});
socket.on("disableAPIKey", async (keyID, callback) => {
try {
checkLogin(socket);
log.debug("apikeys", `Disabled Key: ${keyID} User ID: ${socket.userID}`);
await R.exec("UPDATE api_key SET active = 0 WHERE id = ? ", [
keyID,
]);
apicache.clear();
callback({
ok: true,
msg: "Disabled Successfully.",
});
await sendAPIKeyList(socket);
} catch (e) {
callback({
ok: false,
msg: e.message,
});
}
});
socket.on("enableAPIKey", async (keyID, callback) => {
try {
checkLogin(socket);
log.debug("apikeys", `Enabled Key: ${keyID} User ID: ${socket.userID}`);
await R.exec("UPDATE api_key SET active = 1 WHERE id = ? ", [
keyID,
]);
apicache.clear();
callback({
ok: true,
msg: "Enabled Successfully",
});
await sendAPIKeyList(socket);
} catch (e) {
callback({
ok: false,
msg: e.message,
});
}
});
};

View File

@ -0,0 +1,219 @@
<template>
<form @submit.prevent="submit">
<div ref="keyaddmodal" class="modal fade" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
{{ $t("Add API Key") }}
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div>
<div class="modal-body">
<!-- Name -->
<div class="mb-3">
<label for="name" class="form-label">{{ $t("Name") }}</label>
<input
id="name" v-model="key.name" type="text" class="form-control"
required
>
</div>
<!-- Expiry -->
<div class="my-3">
<label class="form-label">{{ $t("Expiry date") }}</label>
<div class="d-flex flex-row align-items-center">
<div class="col-6">
<Datepicker
v-model="key.expires"
:dark="$root.isDark"
:monthChangeOnScroll="false"
:minDate="minDate"
format="yyyy-MM-dd HH:mm"
modelType="yyyy-MM-dd HH:mm:ss"
:required="!noExpire"
:disabled="noExpire"
/>
</div>
<div class="col-6 ms-3">
<div class="form-check mb-0">
<input
id="no-expire" v-model="noExpire" class="form-check-input"
type="checkbox"
>
<label class="form-check-label" for="no-expire">{{
$t("Don't expire")
}}</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button
id="monitor-submit-btn" class="btn btn-primary" type="submit"
:disabled="processing"
>
{{ $t("Generate") }}
</button>
</div>
</div>
</div>
</div>
</div>
<div ref="keymodal" class="modal fade" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
{{ $t("Key Added") }}
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div>
<div class="modal-body">
<div class="mb-3">
{{ $t("apiKeyAddedMsg") }}
</div>
<div class="mb-3">
<CopyableInput v-model="clearKey" disabled="disabled" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">
{{ $t('Continue') }}
</button>
</div>
</div>
</div>
</div>
</form>
</template>
<script lang="ts">
import { Modal } from "bootstrap";
import { useToast } from "vue-toastification";
import dayjs from "dayjs";
import Datepicker from "@vuepic/vue-datepicker";
import CopyableInput from "./CopyableInput.vue";
const toast = useToast();
export default {
components: {
CopyableInput,
Datepicker
},
props: {},
// emits: [ "added" ],
data() {
return {
keyaddmodal: null,
keymodal: null,
processing: false,
key: {},
dark: (this.$root.theme === "dark"),
minDate: this.$root.date(dayjs()) + " 00:00",
clearKey: null,
noExpire: false,
};
},
mounted() {
this.keyaddmodal = new Modal(this.$refs.keyaddmodal);
this.keymodal = new Modal(this.$refs.keymodal);
},
methods: {
/**
* Show modal
*/
show() {
this.id = null;
this.key = {
name: "",
expires: this.minDate,
active: 1,
};
this.keyaddmodal.show();
},
/** Submit data to server */
async submit() {
this.processing = true;
if (this.noExpire) {
this.key.expires = null;
}
this.$root.addAPIKey(this.key, async (res) => {
this.keyaddmodal.hide();
this.processing = false;
if (res.ok) {
this.clearKey = res.key;
this.keymodal.show();
this.clearForm();
} else {
toast.error(res.msg);
}
});
},
}
};
</script>
<style lang="scss" scoped>
@import "../assets/vars.scss";
.dark {
.modal-dialog .form-text, .modal-dialog p {
color: $dark-font-color;
}
}
.shadow-box {
padding: 20px;
}
textarea {
min-height: 150px;
}
.dark-calendar::-webkit-calendar-picker-indicator {
filter: invert(1);
}
.weekday-picker {
display: flex;
gap: 10px;
& > div {
display: flex;
flex-direction: column;
align-items: center;
width: 40px;
.form-check-inline {
margin-right: 0;
}
}
}
.day-picker {
display: flex;
gap: 10px;
flex-wrap: wrap;
& > div {
display: flex;
flex-direction: column;
align-items: center;
width: 40px;
.form-check-inline {
margin-right: 0;
}
}
}
</style>

View File

@ -4,7 +4,7 @@
<div class="modal-content"> <div class="modal-content">
<div class="modal-header"> <div class="modal-header">
<h5 id="exampleModalLabel" class="modal-title"> <h5 id="exampleModalLabel" class="modal-title">
{{ $t("Confirm") }} {{ title || $t("Confirm") }}
</h5> </h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" /> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div> </div>
@ -15,7 +15,7 @@
<button type="button" class="btn" :class="btnStyle" data-bs-dismiss="modal" @click="yes"> <button type="button" class="btn" :class="btnStyle" data-bs-dismiss="modal" @click="yes">
{{ yesText }} {{ yesText }}
</button> </button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" @click="no">
{{ noText }} {{ noText }}
</button> </button>
</div> </div>
@ -44,8 +44,13 @@ export default {
type: String, type: String,
default: "No", default: "No",
}, },
/** Title to show on modal. Defaults to translated version of "Config" */
title: {
type: String,
default: null,
}
}, },
emits: [ "yes" ], emits: [ "yes", "no" ],
data: () => ({ data: () => ({
modal: null, modal: null,
}), }),
@ -63,6 +68,12 @@ export default {
yes() { yes() {
this.$emit("yes"); this.$emit("yes");
}, },
/**
* @emits string "no" Notify the parent when No is pressed
*/
no() {
this.$emit("no");
}
}, },
}; };
</script> </script>

View File

@ -0,0 +1,257 @@
<template>
<div>
<div class="add-btn">
<button class="btn btn-primary me-2" type="button" @click="$refs.apiKeyDialog.show()">
<font-awesome-icon icon="plus" /> {{ $t("Add API Key") }}
</button>
</div>
<div>
<span v-if="Object.keys(keyList).length === 0" class="d-flex align-items-center justify-content-center my-3">
{{ $t("No API Keys") }}
</span>
<div
v-for="(item, index) in keyList"
:key="index"
class="item"
:class="item.status"
>
<div class="left-part">
<div
class="circle"
></div>
<div class="info">
<div class="title">{{ item.name }}</div>
<div class="status">
{{ $t("apiKey-" + item.status) }}
</div>
<div class="date">
{{ $t("Created") }}: {{ item.createdDate }}
</div>
<div class="date">
{{ $t("Expires") }}: {{ item.expires || $t("Never") }}
</div>
</div>
</div>
<div class="buttons">
<div class="btn-group" role="group">
<button v-if="item.active" class="btn btn-normal" @click="disableDialog(item.id)">
<font-awesome-icon icon="pause" /> {{ $t("Disable") }}
</button>
<button v-if="!item.active" class="btn btn-primary" @click="enableKey(item.id)">
<font-awesome-icon icon="play" /> {{ $t("Enable") }}
</button>
<button class="btn btn-danger" @click="deleteDialog(item.id)">
<font-awesome-icon icon="trash" /> {{ $t("Delete") }}
</button>
</div>
</div>
</div>
</div>
<div class="text-center mt-3" style="font-size: 13px;">
<a href="https://github.com/louislam/uptime-kuma/wiki/API-Keys" target="_blank">{{ $t("Learn More") }}</a>
</div>
<Confirm ref="confirmPause" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="disableKey">
{{ $t("disableAPIKeyMsg") }}
</Confirm>
<Confirm ref="confirmDelete" btn-style="btn-danger" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="deleteKey">
{{ $t("deleteAPIKeyMsg") }}
</Confirm>
<APIKeyDialog ref="apiKeyDialog" />
</div>
</template>
<script>
import APIKeyDialog from "../../components/APIKeyDialog.vue";
import Confirm from "../Confirm.vue";
import { useToast } from "vue-toastification";
const toast = useToast();
export default {
components: {
APIKeyDialog,
Confirm,
},
data() {
return {
selectedKeyID: null,
};
},
computed: {
keyList() {
let result = Object.values(this.$root.apiKeyList);
return result;
},
},
methods: {
/**
* Show dialog to confirm deletion
* @param {number} keyID ID of monitor that is being deleted
*/
deleteDialog(keyID) {
this.selectedKeyID = keyID;
this.$refs.confirmDelete.show();
},
/**
* Delete a key
*/
deleteKey() {
this.$root.deleteAPIKey(this.selectedKeyID, (res) => {
if (res.ok) {
toast.success(res.msg);
} else {
toast.error(res.msg);
}
});
},
/**
* Show dialog to confirm pause
*/
disableDialog(keyID) {
this.selectedKeyID = keyID;
this.$refs.confirmPause.show();
},
/**
* Pause maintenance
*/
disableKey() {
this.$root.getSocket().emit("disableAPIKey", this.selectedKeyID, (res) => {
this.$root.toastRes(res);
});
},
/**
* Resume maintenance
*/
enableKey(id) {
this.$root.getSocket().emit("enableAPIKey", id, (res) => {
this.$root.toastRes(res);
});
},
},
};
</script>
<style lang="scss" scoped>
@import "../../assets/vars.scss";
.mobile {
.item {
flex-direction: column;
align-items: flex-start;
margin-bottom: 20px;
}
}
.add-btn {
padding-top: 20px;
padding-bottom: 20px;
}
.item {
display: flex;
align-items: center;
gap: 10px;
text-decoration: none;
border-radius: 10px;
transition: all ease-in-out 0.15s;
justify-content: space-between;
padding: 10px;
min-height: 90px;
margin-bottom: 5px;
&:hover {
background-color: $highlight-white;
}
&.active {
.circle {
background-color: $primary;
}
}
&.inactive {
.circle {
background-color: $danger;
}
}
&.expired {
.left-part {
opacity: 0.3;
}
.circle {
background-color: $dark-font-color;
}
}
.left-part {
display: flex;
gap: 12px;
align-items: center;
.circle {
width: 25px;
height: 25px;
border-radius: 50rem;
}
.info {
.title {
font-weight: bold;
font-size: 20px;
}
.status {
font-size: 14px;
}
}
}
.buttons {
display: flex;
gap: 8px;
flex-direction: row-reverse;
.btn-group {
width: 310px;
}
}
}
.date {
margin-top: 5px;
display: block;
font-size: 14px;
background-color: rgba(255, 255, 255, 0.5);
border-radius: 20px;
padding: 0 10px;
width: fit-content;
.dark & {
color: white;
background-color: rgba(255, 255, 255, 0.1);
}
}
.dark {
.item {
&:hover {
background-color: $dark-bg2;
}
}
}
</style>

View File

@ -676,5 +676,22 @@
"Edit Tag": "Edit Tag", "Edit Tag": "Edit Tag",
"Server Address": "Server Address", "Server Address": "Server Address",
"Learn More": "Learn More", "Learn More": "Learn More",
"Body Encoding": "Body Encoding" "Body Encoding": "Body Encoding",
"API Keys": "API Keys",
"Expiry": "Expiry",
"Expiry date": "Expiry date",
"Don't expire": "Don't expire",
"Continue": "Continue",
"Add Another": "Add Another",
"Key Added": "Key Added",
"apiKeyAddedMsg": "Your API key has been added. Please make a note of it as it will not be shown again.",
"Add API Key": "Add API Key",
"No API Keys": "No API Keys",
"apiKey-active": "Active",
"apiKey-expired": "Expired",
"apiKey-inactive": "Inactive",
"Expires": "Expires",
"disableAPIKeyMsg": "Are you sure you want to disable this API key?",
"deleteAPIKeyMsg": "Are you sure you want to delete this API key?",
"Generate": "Generate"
} }

View File

@ -35,7 +35,8 @@ export default {
allowLoginDialog: false, // Allowed to show login dialog, but "loggedIn" have to be true too. This exists because prevent the login dialog show 0.1s in first before the socket server auth-ed. allowLoginDialog: false, // Allowed to show login dialog, but "loggedIn" have to be true too. This exists because prevent the login dialog show 0.1s in first before the socket server auth-ed.
loggedIn: false, loggedIn: false,
monitorList: { }, monitorList: { },
maintenanceList: { }, maintenanceList: {},
apiKeyList: {},
heartbeatList: { }, heartbeatList: { },
importantHeartbeatList: { }, importantHeartbeatList: { },
avgPingList: { }, avgPingList: { },
@ -135,6 +136,10 @@ export default {
this.maintenanceList = data; this.maintenanceList = data;
}); });
socket.on("apiKeyList", (data) => {
this.apiKeyList = data;
});
socket.on("notificationList", (data) => { socket.on("notificationList", (data) => {
this.notificationList = data; this.notificationList = data;
}); });
@ -466,6 +471,17 @@ export default {
socket.emit("getMaintenanceList", callback); socket.emit("getMaintenanceList", callback);
}, },
/**
* Send list of API keys
* @param {socketCB} callback
*/
getAPIKeyList(callback) {
if (!callback) {
callback = () => { };
}
socket.emit("getAPIKeyList", callback);
},
/** /**
* Add a monitor * Add a monitor
* @param {Object} monitor Object representing monitor to add * @param {Object} monitor Object representing monitor to add
@ -540,6 +556,24 @@ export default {
socket.emit("deleteMaintenance", maintenanceID, callback); socket.emit("deleteMaintenance", maintenanceID, callback);
}, },
/**
* Add an API key
* @param {Object} key API key to add
* @param {socketCB} callback
*/
addAPIKey(key, callback) {
socket.emit("addAPIKey", key, callback);
},
/**
* Delete specified API key
* @param {int} keyID ID of key to delete
* @param {socketCB} callback
*/
deleteAPIKey(keyID, callback) {
socket.emit("deleteAPIKey", keyID, callback);
},
/** Clear the hearbeat list */ /** Clear the hearbeat list */
clearData() { clearData() {
console.log("reset heartbeat list"); console.log("reset heartbeat list");

View File

@ -107,6 +107,9 @@ export default {
security: { security: {
title: this.$t("Security"), title: this.$t("Security"),
}, },
"api-keys": {
title: this.$t("API Keys")
},
proxies: { proxies: {
title: this.$t("Proxies"), title: this.$t("Proxies"),
}, },

View File

@ -18,6 +18,7 @@ import NotFound from "./pages/NotFound.vue";
import DockerHosts from "./components/settings/Docker.vue"; import DockerHosts from "./components/settings/Docker.vue";
import MaintenanceDetails from "./pages/MaintenanceDetails.vue"; import MaintenanceDetails from "./pages/MaintenanceDetails.vue";
import ManageMaintenance from "./pages/ManageMaintenance.vue"; import ManageMaintenance from "./pages/ManageMaintenance.vue";
import APIKeys from "./components/settings/APIKeys.vue";
import Plugins from "./components/settings/Plugins.vue"; import Plugins from "./components/settings/Plugins.vue";
// Settings - Sub Pages // Settings - Sub Pages
@ -117,6 +118,10 @@ const routes = [
path: "security", path: "security",
component: Security, component: Security,
}, },
{
path: "api-keys",
component: APIKeys,
},
{ {
path: "proxies", path: "proxies",
component: Proxies, component: Proxies,