Skip to content

Instantly share code, notes, and snippets.

@ha6000
Last active August 24, 2020 08:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha6000/072eae5119c4fd3430fbab070c409f3f to your computer and use it in GitHub Desktop.
Save ha6000/072eae5119c4fd3430fbab070c409f3f to your computer and use it in GitHub Desktop.
Wrapper for the cauth universal and premium api
/*
Made by Harry Kruger
License MIT
*/
const Axios = require('axios');
const fs = require('fs');
const path = require('path');
const https = require('https');
const FormData = require('form-data');
/**
* @typedef {Object} APIOpts
* @property {String} [adminBaseUrl=https://cauth.me/api/admin_handler.php] The base url to base admin requests on
* @property {String} [universalBaseUrl=https://cauth.me/api/ins_handler.php] The base url to base universal requests on
* @property {String} programKey Program key for application
* @property {String} apiKey API key for application
* @property {String} [adminKey] Admin key for the user, required for admin methods
*/
/**
* @typedef {Object} User
* @property {String} username
* @property {String} email
* @property {Number} expiry
* @property {String} userVar
* @property {String} hwid
* @property {Number} level
* @property {Boolean} paused
* @property {Boolean} banned
*/
function stringify(str) {
try {
return str.toString();
}
catch(err) {
return ''
}
}
function boolify(bool) {
return bool == 'true' ? true : false
}
function formatUser(user) {
return {
username: stringify(user[0]),
email: stringify(user[1]),
expiry: parseInt(user[2]),
userVar: stringify(user[3]),
hwid: stringify(user[4]),
level: parseInt(user[5]),
paused: boolify(user[6]),
banned: boolify(user[7])
}
}
function formatToken(token) {
return {
token: stringify(token[0]),
days: parseInt(token[1]),
level: parseInt(token[2]),
used: boolify(token[3]),
used_by: stringify(token[4])
}
}
function formatLog(log) {
return {
username: stringify(log[0]),
message: stringify(log[1]),
time: new Date(log[2]),
ip: stringify(log[3])
}
}
function formatForm(obj) {
const form = new FormData();
for (const key in obj) {
form.append(key, obj[key] || '');
}
return form;
}
const optsNotDefined = new TypeError('Options not defined'),
noUsername = new TypeError('Username not specified'),
tokenAmountNotNumber = new TypeError('Token amount not number'),
tokenDaysNotNumber = new TypeError('Token days not number'),
tokenLevelNotNumber = new TypeError('Token level not number'),
tokenTypeNotNumber = new TypeError('Token type not number'),
tokenNotString = new TypeError('Token type not string'),
noPassword = new TypeError('Password not specified'),
noEmail = new TypeError('Email not specified'),
noMessage = new TypeError('Message not specified')
/**
* @class Api interface
*/
class API {
/**
* @param {Object} opts Options passed to constructor
*/
constructor(opts) {
opts = Object.assign({}, {
adminBaseUrl: 'https://cauth.me/api/admin_handler.php',
universalBaseUrl: 'https://cauth.me/api/uni_handler.php'
}, opts);
this.opts = opts;
this.universal = Axios.create({
baseURL: this.opts.universalBaseUrl,
headers: {
'User-Agent': 'Mozilla cAuth'
},
httpsAgent: new https.Agent({
rejectUnauthorized: false,
})
});
this.admin = Axios.create({
baseURL: this.opts.adminBaseUrl,
headers: {
'User-Agent': 'Mozilla cAuth'
},
httpsAgent: new https.Agent({
rejectUnauthorized: false,
})
});
}
/**
* Dispatched a request on a axios object
* @param {Axios} axios axios object to perform request on
* @param {Object} params object for params
* @param {Object} form object for form
* @param {Array} errors responses that will cause reject
* @return {Promise} request that will respond with its data
*/
async dispatch(axios, params, form) {
params = new URLSearchParams(params);
form = formatForm(form);
return axios.post('?' + params, form, {
headers: form.getHeaders()
})
.then(async res => {
if (!res || !res.data) throw new Error('Empty response');
return res.data;
});
}
/**
* Dispatch with universal api
* @param {String} type The type param
* @param {Object} opts Form to post
* @param {Array} errors responses that will cause reject
* @return {Promise} request that will respond with its data
*/
universalDispatch(type, opts) {
opts = Object.assign({}, {
program_key: this.opts.programKey,
api_key: this.opts.apiKey
}, opts);
return this.dispatch(
this.universal,
{ type },
opts)
.then(data => {
if (!data.success) {
const error = new Error(data.message);
error.response = data.response;
throw error;
}
return data;
});
}
/**
* Admin with universal api
* @param {String} type The type param
* @param {Object} opts Form to post
* @param {Array} errors responses that will cause reject
* @return {Promise} request that will respond with its data
*/
adminDispatch(type, opts, errors = []) {
opts = Object.assign({}, {
program_key: this.opts.programKey,
admin_token: this.opts.adminKey
}, opts);
if (errors && !Array.isArray(errors)) throw new Error('Errors not array');
errors = errors.concat([
'program_doesnt_exist',
'not_a_premium_account',
'generate_a_token',
'wrong_admin_token'
]);
return this.dispatch(
this.admin,
{ type },
opts,
errors)
.then(data => {
if (errors.includes(data)) {
throw new Error(data);
}
return data;
});
}
/**
* Fetch a user
* @param {Object} opts object of options
* @param {String} opts.username username to fetch
* @return {Promise<User>}
*/
async fetchUser(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('fetch_single_user', opts,
[
'invalid_username'
])
.then(data => {
return formatUser(data.split('|'));
});
}
/**
* Fetch all users
* @param {Object} opts options params
* @return {Promise<String[]>}
*/
async fetchUsers(opts = {}) {
if (!opts) throw optsNotDefined;
return this.adminDispatch('fetch_all_users', opts)
.then(data => {
return data.split('&').map(user => formatUser(user.split('|')));
})
}
/**
* Resets user hwid
* @param {Object} opts options params
* @param {String} opts.username Username to reset hwid for
* @return {Promise} response for request
*/
async resetHwid(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('reset_user_hwid', opts,
[
'invalid_username'
]);
}
/**
* Dlete a user
* @param {Object} opts options params
* @param {String} opts.username username to delete
* @return {Promise}
*/
async deleteUser(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('delete_user', opts,
[
'invalid_username'
]);
}
/**
* Edit variable for user
* @param {Object} opts
* @param {String} opts.username username to get var of
* @param {String} opts.new_var the new variable
* @return {Promise]} Response from api
*/
async editVar(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
if (typeof opts.new_var != 'string') throw new Error('No new_var specified');
return this.adminDispatch('edit_user_var', opts,
[
'invalid_username'
]);
}
/**
* Puases a user
* @param {Object} opts
* @param {String} opts.username username to pause
* @return {Promise} Response from api
*/
async pauseUser(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('pause_user_sub', opts,
[
'invalid_username',
'user_already_paused',
'no_sub'
]);
}
/**
* Unpuases a user
* @param {Object} opts
* @param {String} opts.username username to pause
* @return {Promise} Response from api
*/
async unpauseUser(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('unpause_user_sub', opts,
[
'invalid_username',
'user_already_paused',
'no_sub'
]);
}
/**
* ban a user
* @param {Object} opts
* @param {String} opts.username username to ban
* @return {Promise} response from api
*/
async banUser(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('ban_user', opts,
[
'invalid_username'
]);
}
/**
* Unban a user
* @param {Object} opts
* @param {String} opts.username username to unban
* @return {Promise} response from api
*/
async unbanUser(opts) {
if (!opts) throw optsNotDefined
if (typeof opts.username != 'string') throw noUsername
return this.adminDispatch('unban_user', opts,
[
'invalid_username'
]);
}
/**
* Generate a token
* @param {Object} opts
* @param {Number} opts.token_amount The amount of tokens to generate
* @param {Number} opts.token_days The amount of days for token
* @param {Number} opts.token_level The level of the token
* @param {Number} opts.token_type The type of token
* @return {Promise} response from api
*/
async genToken(opts) {
opts = Object.assign({}, {
token_amount: 1,
token_days: 1,
token_level: 1,
token_type: 1
}, opts);
if (typeof opts.token_amount != 'number') throw tokenAmountNotNumber;
if (typeof opts.token_days != 'number') throw tokenDaysNotNumber;
if (typeof opts.token_level != 'number') throw tokenLevelNotNumber;
if (typeof opts.token_type != 'number') throw tokenTypeNotNumber;
return this.adminDispatch('gen_token', opts, [
'maximum_tokens_reached',
'only_500_tokens_per_time'
])
.then(res => {
return res.split('|');
});
}
/**
* Fetched a token
* @param {Object} opts
* @param {String} opts.token The token to fetch
* @return {Promise} response from api
*/
async fetchToken(opts) {
if (!opts) throw optsNotDefined;
if (typeof opts.token != 'string') throw tokenNotString;
return this.adminDispatch('fetch_single_token', opts,
[
'invalid_token'
])
.then(data => {
return formatToken(data.split('|'));
});
}
/**
* Fetch all tokens
* @param {Object} [opts={}]
* @return {Promise} response from api
*/
async fetchTokens(opts = {}) {
if (!opts) throw optsNotDefined;
return this.adminDispatch('fetch_all_tokens', opts)
.then(data => {
return data.split('&').map(token => formatToken(token.split('|')));
});
}
/**
* Delete a token
* @param {Object} opts
* @param {String} opts.token token to delete
* @return {Promise} response from api
*/
async deleteToken(opts) {
if (!opts) throw optsNotDefined;
if (typeof opts.token != 'string') throw tokenNotString;
return this.adminDispatch('delete_token', opts, [
'invalid_token'
]);
}
/**
* Delete all logs
* @param {Object} [opts]
* @return {Promise} response from api
*/
async deleteAllLogs(opts = {}) {
if (!opts) throw optsNotDefined;
return this.adminDispatch('delete_all_logs', opts);
}
/**
* Fetch all the logs
* @param {Object} opts
* @return {Promise} response from api
*/
async fetchLogs(opts = {}) {
if (!opts) throw optsNotDefined;
return this.adminDispatch('fetch_all_logs', opts)
.then(data => {
return data.split('&').map(log => formatLog(log.split('|')));
})
.catch(async err => {
if (err && err.message == 'Empty response') return [];
else throw err;
});
}
/**
* Login with user
* @param {Object} opts
* @param {String} opts.username username to login with
* @param {String} opts.password password of user
* @return {Promise} response from api
*/
async login(opts) {
if (!opts) throw optsNotDefined;
if (typeof opts.username != 'string') throw noUsername;
if (typeof opts.password != 'string') throw noPassword;
return this.universalDispatch('login', opts)
.then(async data => {
return data.user_data;
});
}
/**
* Register a user
* @param {Object} opts
* @param {String} opts.username username to register
* @param {String} opts.email email of user
* @param {String} opts.password password of the user
* @param {String} opts.token token of user
* @return {Promise} response from api
*/
async register(opts) {
if (!opts) throw optsNotDefined;
if (typeof opts.username != 'string') throw noUsername;
if (typeof opts.email != 'string') throw noEmail;
if (typeof opts.password != 'string') throw noPassword;
if (typeof opts.token != 'string') throw tokenNotString;
return this.universalDispatch('register', opts, 'response')
.then(data => {
return data.response;
});
}
/**
* Activate a token
* @param {Object} opts
* @param {String} opts.username username to activate token for
* @param {String} opts.password password of user
* @param {String} opts.token token to activate
* @return {Promise} response from api
*/
async activate(opts) {
if (!opts) throw optsNotDefined;
if (typeof opts.username != 'string') throw noUsername;
if (typeof opts.password != 'string') throw noPassword;
if (typeof opts.token != 'string') throw tokenNotString;
return this.universalDispatch('activate', opts)
.then(data => {
return data.response;
});
}
/**
* Log a user
* @param {Object} opts
* @param {String} opts.username username to log
* @param {String} opts.message message to log
* @return {Promise} response from api
*/
async log(opts) {
if (!opts) throw optsNotDefined;
if (!opts.username) throw noUsername;
if (!opts.message) throw noMessage;
return this.universalDispatch('log', opts)
.then(data => {
return data.response;
});
}
}
module.exports = { API }
@ha6000
Copy link
Author

ha6000 commented Aug 24, 2020

it is updated to support universall api changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment