diff --git a/src/lib/Server.js b/src/lib/Server.js index 4cfe0b41..2c27315e 100644 --- a/src/lib/Server.js +++ b/src/lib/Server.js @@ -108,6 +108,35 @@ module.exports = class Server { res.header('Content-Type', 'text/plain'); res.send(config); })) + //get client by storeId + .get('/api/wireguard/client/storeId/:storeId', Util.promisify(async (req, res) => { + const { storeId } = req.params; + debug(storeId); + const clientId = await WireGuard.getClientIdByStoreId({ storeId }); + const config = await WireGuard.getClientConfiguration({ clientId: clientId }); + const configName = storeId + .replace(/[^a-zA-Z0-9_=+.-]/g, '-') + .replace(/(-{2,}|-$)/g, '-') + .replace(/-$/, '') + .substring(0, 32); + res.header('Content-Disposition', `attachment; filename="${configName || clientId}.conf"`); + res.header('Content-Type', 'text/plain'); + res.send(config); + })) + //get client by name //!!! only for old windows API + .get('/api/wireguard/client/:name', Util.promisify(async (req, res) => { + const { name } = req.params; + const clientId = await WireGuard.getClientIdByName({ name }); + const config = await WireGuard.getClientConfiguration({ clientId: clientId }); + const configName = name + .replace(/[^a-zA-Z0-9_=+.-]/g, '-') + .replace(/(-{2,}|-$)/g, '-') + .replace(/-$/, '') + .substring(0, 32); + res.header('Content-Disposition', `attachment; filename="${configName || clientId}.conf"`); + res.header('Content-Type', 'text/plain'); + res.send(config); + })) .post('/api/wireguard/client', Util.promisify(async req => { const { name , storeId } = req.body; if (name === undefined) { diff --git a/src/lib/WireGuard.js b/src/lib/WireGuard.js index 2e2e3e52..6bb476d6 100644 --- a/src/lib/WireGuard.js +++ b/src/lib/WireGuard.js @@ -186,12 +186,36 @@ AllowedIPs = ${client.address}/32`; const config = await this.getConfig(); const client = config.clients[clientId]; if (!client) { - throw new ServerError(`Client Not Found: ${clientId}`, 404); + throw new ServerError(`Client Not Found2: ${clientId}`, 404); } return client; } + //get client by storeId + async getClientIdByStoreId({ storeId }) { + //get all clients + const clients = await this.getClients(); + //find client by storeId + const client = clients.find(client => client.storeId === storeId); + if (!client) { + throw new ServerError(`Client Not Found3: ${storeId}`, 404); + } + return client.id; + } + + //get client by name + async getClientIdByName({ name }) { + //get all clients + const clients = await this.getClients(); + //find client by name + const client = clients.find(client => client.name === name); + if (!client) { + throw new ServerError(`Client Not Found: ${name}`, 404); + } + return client.id; + } + //get local ip static async getLocalIP() { var ip = await Util.exec('hostname -I');