e4b070db by Leff Tubat

Added authorization function for api endpoint

1 parent 2530d769
......@@ -72,8 +72,6 @@ function App() {
}
// eslint-disable-next-line
btutil_getChatUsage();
// eslint-disable-next-line
let maxTokens = btutilCommon_getCookie("mucnxwlyxt");
if (maxTokens==='1'){
return;
......@@ -134,6 +132,19 @@ function App() {
});
const data = await response.json();
const parsedData = data.message.trim();
if(data.status === 'invalid'){
if(data.limited) {
window.btutil_modalRegisterUpgrade();
return;
}
if(data && data.status === 'max-tokens') {
window.btutil_maxUsage();
return;
}
window.btutil_modalRegisterUpgrade(true);
return;
}
// "gpt-3.5-turbo"
let chatLogTurboNew = chatLogTurbo;
let chatLogOpenSourceNew = chatLogOpenSource;
......@@ -144,9 +155,7 @@ function App() {
});
userModifiedInput = "";
}
if(data.usage) {
window.btutil_setChatUsage('chatbot+', data.usage.prompt_tokens, data.usage.total_tokens);
}
chatLogTurboNew.push({ role: "user", content: userModifiedInput });
chatLogTurboNew.push({ role: "assistant", content: parsedData });
......
const { Configuration, OpenAIApi } = require("openai");
const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require("cookie-parser")
const cors = require('cors')
require('dotenv').config()
const rateLimit = require('express-rate-limit')
const fetch = require('node-fetch');
const anchorme = require("anchorme").default;
const axios = require('axios');
const { encodingForModel } = require('js-tiktoken');
......@@ -68,19 +70,26 @@ app.use(bodyParser.json())
app.use(cors())
app.use(require('morgan')('dev'))
app.use(rateLimiter)
app.use(cookieParser());
const max_tokens = process.env.MAX_TOKENS_chatbot_plus ? parseInt(process.env.MAX_TOKENS_chatbot_plus) : 512;
// Routing
const hostapi = process.env.REACT_APP_HOST_API || "https://api.ai-pro.org";
const user_secret_id = process.env.USER_SECRET_ID || "aiwp_logged_in";
const aiwp_app_id = "chatbot+";
// Primary Open AI Route
app.post('/api', async (req, res) => {
if(!req.get('origin') || (!req.get('origin').includes(req.get('host')))) {
res.status(401);
res.send('Method Not Allowed');
return;
}
// if(!req.get('origin') || (!req.get('origin').includes(req.get('host')))) {
// res.status(401);
// res.send('Method Not Allowed');
// return;
// }
const { message, currentModel, temperature } = req.body;
const validate = await validation(aiwp_app_id, req, res);
if(!validate) return;
const { IS_FREE_USER, aiwp_logged_in, TRIED_USAGE} = validate;
if (currentModel == "gpt-3.5-turbo" || currentModel == "gpt-3.5-turbo-0301") {
runGPTTurbo(req, res);
return;
......@@ -136,10 +145,15 @@ app.post('/api', async (req, res) => {
usage.prompt_tokens = (enc.encode(query_prompt)).length;
usage.completion_tokens = (enc.encode(input)).length;
usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
} catch (e) {
console.log('Error encoding prompt text', e);
}
if(IS_FREE_USER) {
await setUsage({
aiwp_logged_in, app: 'chatbot+', prompt_token: usage.prompt_tokens, total_token: usage.total_tokens, aiwp_app_id, usage_tries: TRIED_USAGE
});
}
res.json({
usage: usage,
message: anchorme({
......@@ -303,6 +317,114 @@ async function runOpensource(req, res) {
}
}
async function authenticate(params) {
let data = await fetch(`${hostapi}/e/authenticate/v2`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(params),
referrer: "https://api.ai-pro.org"
});
return await data.json();
}
async function getLimitedUsage(params) {
let data = await fetch(`${hostapi}/e/get-usage`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(params),
referrer: "https://api.ai-pro.org"
});
return await data.json();
}
async function getUsage(params) {
let data = await fetch(`${hostapi}/e/get-chat-usage`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(params),
referrer: "https://api.ai-pro.org"
});
return await data.json();
}
async function setUsage(params) {
fetch(`${hostapi}/e/set-usage`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(params),
referrer: "https://api.ai-pro.org"
});
fetch(`${hostapi}/e/set-chat-usage`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(params),
referrer: "https://api.ai-pro.org"
});
}
async function validation (aiwp_app_id, req, res) {
const aiwp_logged_in = req.cookies[user_secret_id] ? decodeURIComponent(req.cookies[user_secret_id]) : "";
const limit = req.cookies["WcvYPABR"] ? parseInt(req.cookies["WcvYPABR"].replace(/\D/g, '')) : 3;
let IS_FREE_USER = false;
let TRIED_USAGE = 0;
if (aiwp_logged_in) {
let auth = await authenticate({ aiwp_logged_in, user_event_data: {}, user_event: 'endpoint' });
if (!auth.success) {
IS_FREE_USER = true;
if (auth.is_restrict) {
res.json({ status: "invalid", restrict: true, redirect: auth.redirect });
res.end();
return false;
} else if (typeof auth.has_pro_access === "undefined" && !auth.has_pro_access) {
res.json({ status: "invalid", restrict: true });
res.end();
return false;
}
}
if (!auth.subscription_type || (auth.auth_version === 'v2' && auth.subscription_type.toLowerCase() === 'basic')) {
res.json({ status: "invalid" });
res.status(200);
return false;
}
let data = await getUsage({
aiwp_logged_in, app: 'chatbot+'
});
if (!(data.success === 1 && data.status === 'valid')) {
res.json({ status: "invalid", data });
res.status(200);
return false;
}
} else {
IS_FREE_USER = true;
let data = await getLimitedUsage({
aiwp_app_id
});
if (data.usage !== null) {
TRIED_USAGE = parseInt(data.usage);
}
return { IS_FREE_USER, aiwp_logged_in, TRIED_USAGE };
}
if (IS_FREE_USER && TRIED_USAGE >= limit) {
res.json({ status: "invalid", limited: true });
res.end();
return false;
}
if (IS_FREE_USER) TRIED_USAGE++;
return { IS_FREE_USER, aiwp_logged_in, TRIED_USAGE };
};
// Get Models Route
......
......@@ -5,22 +5,26 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
"start": "node index.js",
"dev": "nodemon index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"js-tiktoken": "1.0.7",
"anchorme": "^2.1.2",
"axios": "^1.5.1",
"body-parser": "^1.20.1",
"cookie": "0.5.0",
"cookie-parser": "1.4.6",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-rate-limit": "^6.7.0",
"js-cookie": "^3.0.5",
"js-tiktoken": "1.0.7",
"morgan": "^1.10.0",
"node-fetch": "^2.7.0",
"nodemon": "^3.1.0",
"openai": "^3.2.0"
}
}
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!