DNS API error message

This commit is contained in:
2024-08-11 12:24:42 -04:00
parent 3e989992df
commit cb87f22d98
6 changed files with 100 additions and 108 deletions
+43 -41
View File
@@ -55,7 +55,10 @@ class DnsProvider extends Table{
} }
static __intraModel(provider){ static __intraModel(provider){
if(!Object.keys(providers).includes(provider)) throw new Error('Invalid DNS provider') if(!Object.keys(providers).includes(provider)){
throw new Error('Invalid DNS provider');
}
let Provider = providers[provider]; let Provider = providers[provider];
let _keyMap = {...this._keyMap, ...Provider._keyMap}; let _keyMap = {...this._keyMap, ...Provider._keyMap};
@@ -67,6 +70,27 @@ class DnsProvider extends Table{
})[this.name]; })[this.name];
} }
static async create(data, ...args){
let __intraModel = this.__intraModel(data.dnsProvider)
let provider = new __intraModel.Provider(data);
let res = await provider.listDomains();
let instance = await super.create.call(__intraModel, data);
if(data.noUpdate !== false) await instance.updateDomains();
return instance;
}
static async get(data, ...args){
let instance = await super.get(data);
let __intraModel = this.__intraModel(instance.dnsProvider)
instance = await super.get.call(__intraModel, data);
instance.provider = new __intraModel.Provider(instance);
return instance;
}
static listProviders(){ static listProviders(){
let out = []; let out = [];
for(let provider in providers){ for(let provider in providers){
@@ -81,67 +105,45 @@ class DnsProvider extends Table{
return out; return out;
} }
static async create(data, ...args){
let __intraModel = this.__intraModel(data.dnsProvider)
let instance = await super.create.call(__intraModel, data);
if(!data.noUpdate) instance.updateDomains();
return instance;
}
static async get(data, ...args){
let instance = await super.get(data);
let __intraModel = this.__intraModel(instance.dnsProvider)
instance = await super.get.call(__intraModel, data);
instance.provider = new __intraModel.Provider(instance);
// instance.domains = Domain.getByProviderId(this.id);
return instance;
}
async updateDomains(){ async updateDomains(){
try{ let domains = await this.provider.listDomains();
let domains = await this.provider.listDomains(); for(let domain of domains){
console.log('got domains', domains) if(!(await Domain.exists(domain.domain))){
for(let domain of domains){ await Domain.create({
if(!(await Domain.exists(domain.domain))){ created_by: this.created_by,
await Domain.create({ domain: domain.domain,
created_by: this.created_by, dnsProvider_id: this.id
domain: domain.domain, });
dnsProvider_id: this.id
});
}
} }
}catch(error){
console.error('updateDomains error', error)
} }
} }
async getDomains(){ async getDomains(){
return Domains.getByProviderId(this.id) return Domain.getByProviderId(this.id);
} }
async remove(){ async remove(){
let id = this.id let id = this.id;
let instance = await super.remove() let instance = await super.remove();
// get all domains for this provider and delete them for(let domain of await this.getDomains()){
await domain.remove();
}
return instance return instance;
} }
toJSON(){ toJSON(){
return { return {
...super.toJSON(), ...super.toJSON(),
domains: this.domains, domains: this.domains,
} };
} }
} }
Domain = ModelPs(Domain); Domain = ModelPs(Domain);
DnsProvider = ModelPs(DnsProvider); DnsProvider = ModelPs(DnsProvider);
module.exports = {Domain, DnsProvider} module.exports = {Domain, DnsProvider};
if(require.main === module){(async function(){try{ if(require.main === module){(async function(){try{
const conf = require('../conf'); const conf = require('../conf');
@@ -150,5 +152,5 @@ if(require.main === module){(async function(){try{
// console.log(aw) // console.log(aw)
}catch(error){ }catch(error){
console.log('IIFE Error:', error) console.log('IIFE Error:', error);
}})()} }})()}
+25
View File
@@ -0,0 +1,25 @@
'use strict';
let dnsErrors = {
unauthorized(instance){
let error = new Error('UnauthorizedDnsApi');
error.name = 'UnauthorizedDnsApi';
error.message = `Unauthorized call to ${instance.constructor ? instance.constructor.name : instance.name}`;
error.status = 424;
return error;
},
other(instance, status, message){
let error = new Error('OtherDnsApiError');
error.name = 'OtherDnsApiError';
error.message = `DNS API Error ${instance.constructor ? instance.constructor.name : instance.name}: `;
error.status = 424;
return error;
},
}
module.exports = {
dnsErrors
};
+18 -22
View File
@@ -1,7 +1,7 @@
'use strict'; 'use strict';
const axios = require('axios'); const axios = require('axios');
const {dnsErrors} = require('./common');
class DigitalOcean{ class DigitalOcean{
static _keyMap = { static _keyMap = {
@@ -28,30 +28,34 @@ class DigitalOcean{
return name; return name;
} }
get axios(){ async axios(method, ...args){
try{ try{
return axios.create({ let a = axios.create({
baseURL: 'https://api.digitalocean.com/v2/', baseURL: 'https://api.digitalocean.com/v2/',
headers: {Authorization: `Bearer ${this.token}`} headers: {Authorization: `Bearer ${this.token}`}
}); });
return await a[method](...args);
}catch(error){ }catch(error){
console.log(error.data); if(!error.response) throw error;
if(error.response.data || error.response.data.id === 'Unauthorized'){
throw dnsErrors.unauthorized(this);
}
throw dnsErrors.other(this, error.response.status, error.response.data.message);
} }
} }
async listDomains(){ async listDomains(){
try{ let res = await this.axios('get', '/domains');
let res = await this.axios.get('/domains'); for(let domain of res.data.domains){
for(let domain of res.data.domains){ domain.domain = domain.name
domain.domain = domain.name }
} return res.data.domains;
return res.data.domains;
}catch{}
} }
async getRecords(domain, options={}){ async getRecords(domain, options={}){
this.__typeCheck(options.type); this.__typeCheck(options.type);
let res = await this.axios.get(`/domains/${domain}/records`, {params: options}) let res = await this.axios('get', `/domains/${domain}/records`, {params: options})
let records = []; let records = [];
for(let record of res.data.domain_records){ for(let record of res.data.domain_records){
@@ -70,12 +74,12 @@ class DigitalOcean{
if(!options.data) throw new Error(`${this.constructor.name} API: 'data' key is required for this action`) if(!options.data) throw new Error(`${this.constructor.name} API: 'data' key is required for this action`)
if(options.name) options.name = this.__parseName(domain, options.name); if(options.name) options.name = this.__parseName(domain, options.name);
let res = await this.axios.post(`/domains/${domain}/records`, options); let res = await this.axios('post', `/domains/${domain}/records`, options);
return res.data; return res.data;
} }
async deleteRecordById(domain, id){ async deleteRecordById(domain, id){
let res = await this.axios.delete(`/domains/${domain}/records/${id}`); let res = await this.axios('delete', `/domains/${domain}/records/${id}`);
} }
async deleteRecords(domain, options){ async deleteRecords(domain, options){
@@ -100,14 +104,6 @@ if(require.main === module){(async function(){try{
// console.log('delete', await digi.deleteRecords('rm-rf.stream', {type: 'TXT'})) // console.log('delete', await digi.deleteRecords('rm-rf.stream', {type: 'TXT'}))
// console.log('get', await digi.getRecords('rm-rf.stream', {type:'TXT', data:'890'})) // console.log('get', await digi.getRecords('rm-rf.stream', {type:'TXT', data:'890'}))
// let porkBun = new PorkBun(conf.porkBun.apiKey, conf.porkBun.secretApiKey);
// console.log(await porkBun.listDomains())
// console.log(await porkBun.deleteRecordById('holycore.quest', '415509355'))
// console.log('IIFE', await porkBun.createRecordForce('holycore.quest', {type:'A', name: 'testapi', content: '127.0.0.5'}))
// console.log('IIFE', await porkBun.getRecords('holycore.quest', {type:'A', name: 'testapi'}))
}catch(error){ }catch(error){
console.log('IIFE Error:', error) console.log('IIFE Error:', error)
}})()} }})()}
+6 -1
View File
@@ -1,6 +1,7 @@
'use strict'; 'use strict';
const axios = require('axios'); const axios = require('axios');
const {dnsErrors} = require('./common');
class PorkBun{ class PorkBun{
@@ -28,7 +29,11 @@ class PorkBun{
return res; return res;
}catch(error){ }catch(error){
throw new Error(`PorkPun API ${error.response.status}: ${error.response.data.message}`) if(!error.response) throw error;
if(error.response.data.message.includes('Invalid API key')){
throw dnsErrors.unauthorized(this);
}
throw dnsErrors.other(this, error.response.status, error.response.data.message)
} }
} }
+1 -30
View File
@@ -51,7 +51,6 @@ router.get('/domain', async function(req, res, next){
router.get('/domain/byProvider/:item', async function(req, res, next){ router.get('/domain/byProvider/:item', async function(req, res, next){
try{ try{
console.log('byProvider', req.params.item, await Domain.getByProviderId(req.params.item))
return res.json({ return res.json({
results: await Domain.getByProviderId(req.params.item) results: await Domain.getByProviderId(req.params.item)
}); });
@@ -63,27 +62,12 @@ router.get('/domain/byProvider/:item', async function(req, res, next){
router.post('/domain/refresh/:item', async function(req, res, next){ router.post('/domain/refresh/:item', async function(req, res, next){
try{ try{
let item = await Model.get(req.params.item); let item = await Model.get(req.params.item);
item.updateDomains(); return res.json({results: await item.updateDomains()});
return res.json({});
}catch(error){ }catch(error){
next(error); next(error);
} }
}) })
router.get('/lookup/:item', async function(req, res, next){
try{
return res.json({
string: req.params.item,
results: await Model.lookUp(req.params.item),
});
}catch(error){
return next(error);
}
});
router.get('/:item', async function(req, res, next){ router.get('/:item', async function(req, res, next){
try{ try{
@@ -129,17 +113,4 @@ router.delete('/:item', async function(req, res, next){
} }
}); });
router.put('/:item/renew', async function(req, res, next){
try{
let item = await Model.get(req.params.item);
item.createWildcardCert();
return res.json({
message: `Requesting wildcard cert for ${req.params.item}`,
})
}catch(error){
next(error);
}
});
module.exports = router; module.exports = router;
+7 -14
View File
@@ -35,14 +35,14 @@
function providerGet(cb){ function providerGet(cb){
app.api.options('dns', function(error, res){ app.api.options('dns', function(error, res){
for(let provider of res.results){ for(let provider of res.results){
$.scope.providerSelect.push(provider) $.scope.providerSelect.push(provider);
for(let field in provider.fields){ for(let field in provider.fields){
$.scope.providerField.push({ $.scope.providerField.push({
...provider.fields[field], ...provider.fields[field],
keyName: field, keyName: field,
provider: provider.name provider: provider.name
}) });
} }
} }
}); });
@@ -127,9 +127,7 @@
<div class="card-header actionMessage" style="display:none"></div> <div class="card-header actionMessage" style="display:none"></div>
<div class="card-body"> <div class="card-body">
<form action="dns/" onsubmit="formAJAX(this)" evalAJAX=" <form action="dns/" onsubmit="formAJAX(this)">
">
<div class="form-group"> <div class="form-group">
<label for="name" class="form-label"> <label for="name" class="form-label">
Name Name
@@ -192,24 +190,19 @@
<button type="button" class="btn btn-warning" method="POST" action="/dns/domain/refresh/{{id}}" onclick="formAJAX()"> <button type="button" class="btn btn-warning" method="POST" action="/dns/domain/refresh/{{id}}" onclick="formAJAX()">
<i class="fa-solid fa-rotate"></i> <i class="fa-solid fa-rotate"></i>
</button> </button>
<button type="button" class="btn btn-info" onclick="$('ol.domain-{{id}}').slideToggle()">
Domains
</button>
<button type="button" class="btn btn-danger" method="DELETE" action="dns/{{id}}" onclick="formAJAX()"> <button type="button" class="btn btn-danger" method="DELETE" action="dns/{{id}}" onclick="formAJAX()">
<i class="fa-solid fa-trash-can"></i> <i class="fa-solid fa-trash-can"></i>
</button> </button>
</span> </span>
</div> </div>
<ol class="domain-{{id}} list-group list-group-numbered list-group-flush" style="display:none;"> <div>
{{#domains}} {{#domains}}
<li class="list-group-item">{{domain}}</li> <b>{{domain}}</b>,
{{/domains}} {{/domains}}
{{^domains}} {{^domains}}
<li class="list-group-item">This has no domains...</li> <span>No domains...</span>
{{/domains}} {{/domains}}
</div>
</ol>
</li> </li>
</ul> </ul>
</div> </div>