e4b070db by Leff Tubat

Added authorization function for api endpoint

1 parent 2530d769
...@@ -72,8 +72,6 @@ function App() { ...@@ -72,8 +72,6 @@ function App() {
72 } 72 }
73 73
74 // eslint-disable-next-line 74 // eslint-disable-next-line
75 btutil_getChatUsage();
76 // eslint-disable-next-line
77 let maxTokens = btutilCommon_getCookie("mucnxwlyxt"); 75 let maxTokens = btutilCommon_getCookie("mucnxwlyxt");
78 if (maxTokens==='1'){ 76 if (maxTokens==='1'){
79 return; 77 return;
...@@ -134,6 +132,19 @@ function App() { ...@@ -134,6 +132,19 @@ function App() {
134 }); 132 });
135 const data = await response.json(); 133 const data = await response.json();
136 const parsedData = data.message.trim(); 134 const parsedData = data.message.trim();
135
136 if(data.status === 'invalid'){
137 if(data.limited) {
138 window.btutil_modalRegisterUpgrade();
139 return;
140 }
141 if(data && data.status === 'max-tokens') {
142 window.btutil_maxUsage();
143 return;
144 }
145 window.btutil_modalRegisterUpgrade(true);
146 return;
147 }
137 // "gpt-3.5-turbo" 148 // "gpt-3.5-turbo"
138 let chatLogTurboNew = chatLogTurbo; 149 let chatLogTurboNew = chatLogTurbo;
139 let chatLogOpenSourceNew = chatLogOpenSource; 150 let chatLogOpenSourceNew = chatLogOpenSource;
...@@ -144,9 +155,7 @@ function App() { ...@@ -144,9 +155,7 @@ function App() {
144 }); 155 });
145 userModifiedInput = ""; 156 userModifiedInput = "";
146 } 157 }
147 if(data.usage) { 158
148 window.btutil_setChatUsage('chatbot+', data.usage.prompt_tokens, data.usage.total_tokens);
149 }
150 chatLogTurboNew.push({ role: "user", content: userModifiedInput }); 159 chatLogTurboNew.push({ role: "user", content: userModifiedInput });
151 chatLogTurboNew.push({ role: "assistant", content: parsedData }); 160 chatLogTurboNew.push({ role: "assistant", content: parsedData });
152 161
......
1 const { Configuration, OpenAIApi } = require("openai"); 1 const { Configuration, OpenAIApi } = require("openai");
2 const express = require('express') 2 const express = require('express')
3 const bodyParser = require('body-parser') 3 const bodyParser = require('body-parser')
4 const cookieParser = require("cookie-parser")
4 const cors = require('cors') 5 const cors = require('cors')
5 require('dotenv').config() 6 require('dotenv').config()
6 const rateLimit = require('express-rate-limit') 7 const rateLimit = require('express-rate-limit')
8 const fetch = require('node-fetch');
7 const anchorme = require("anchorme").default; 9 const anchorme = require("anchorme").default;
8 const axios = require('axios'); 10 const axios = require('axios');
9 const { encodingForModel } = require('js-tiktoken'); 11 const { encodingForModel } = require('js-tiktoken');
...@@ -68,19 +70,26 @@ app.use(bodyParser.json()) ...@@ -68,19 +70,26 @@ app.use(bodyParser.json())
68 app.use(cors()) 70 app.use(cors())
69 app.use(require('morgan')('dev')) 71 app.use(require('morgan')('dev'))
70 app.use(rateLimiter) 72 app.use(rateLimiter)
73 app.use(cookieParser());
71 74
72 const max_tokens = process.env.MAX_TOKENS_chatbot_plus ? parseInt(process.env.MAX_TOKENS_chatbot_plus) : 512; 75 const max_tokens = process.env.MAX_TOKENS_chatbot_plus ? parseInt(process.env.MAX_TOKENS_chatbot_plus) : 512;
73 // Routing 76 // Routing
74 77 const hostapi = process.env.REACT_APP_HOST_API || "https://api.ai-pro.org";
78 const user_secret_id = process.env.USER_SECRET_ID || "aiwp_logged_in";
79 const aiwp_app_id = "chatbot+";
75 // Primary Open AI Route 80 // Primary Open AI Route
76 app.post('/api', async (req, res) => { 81 app.post('/api', async (req, res) => {
77 if(!req.get('origin') || (!req.get('origin').includes(req.get('host')))) { 82 // if(!req.get('origin') || (!req.get('origin').includes(req.get('host')))) {
78 res.status(401); 83 // res.status(401);
79 res.send('Method Not Allowed'); 84 // res.send('Method Not Allowed');
80 return; 85 // return;
81 } 86 // }
82 const { message, currentModel, temperature } = req.body; 87 const { message, currentModel, temperature } = req.body;
83 88
89 const validate = await validation(aiwp_app_id, req, res);
90 if(!validate) return;
91 const { IS_FREE_USER, aiwp_logged_in, TRIED_USAGE} = validate;
92
84 if (currentModel == "gpt-3.5-turbo" || currentModel == "gpt-3.5-turbo-0301") { 93 if (currentModel == "gpt-3.5-turbo" || currentModel == "gpt-3.5-turbo-0301") {
85 runGPTTurbo(req, res); 94 runGPTTurbo(req, res);
86 return; 95 return;
...@@ -136,10 +145,15 @@ app.post('/api', async (req, res) => { ...@@ -136,10 +145,15 @@ app.post('/api', async (req, res) => {
136 usage.prompt_tokens = (enc.encode(query_prompt)).length; 145 usage.prompt_tokens = (enc.encode(query_prompt)).length;
137 usage.completion_tokens = (enc.encode(input)).length; 146 usage.completion_tokens = (enc.encode(input)).length;
138 usage.total_tokens = usage.prompt_tokens + usage.completion_tokens; 147 usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
148
139 } catch (e) { 149 } catch (e) {
140 console.log('Error encoding prompt text', e); 150 console.log('Error encoding prompt text', e);
141 } 151 }
142 152 if(IS_FREE_USER) {
153 await setUsage({
154 aiwp_logged_in, app: 'chatbot+', prompt_token: usage.prompt_tokens, total_token: usage.total_tokens, aiwp_app_id, usage_tries: TRIED_USAGE
155 });
156 }
143 res.json({ 157 res.json({
144 usage: usage, 158 usage: usage,
145 message: anchorme({ 159 message: anchorme({
...@@ -303,6 +317,114 @@ async function runOpensource(req, res) { ...@@ -303,6 +317,114 @@ async function runOpensource(req, res) {
303 } 317 }
304 } 318 }
305 319
320 async function authenticate(params) {
321 let data = await fetch(`${hostapi}/e/authenticate/v2`, {
322 method: "POST",
323 headers: {
324 "Content-Type": "application/json"
325 },
326 body: JSON.stringify(params),
327 referrer: "https://api.ai-pro.org"
328 });
329 return await data.json();
330 }
331
332 async function getLimitedUsage(params) {
333 let data = await fetch(`${hostapi}/e/get-usage`, {
334 method: "POST",
335 headers: {
336 "Content-Type": "application/json"
337 },
338 body: JSON.stringify(params),
339 referrer: "https://api.ai-pro.org"
340 });
341 return await data.json();
342 }
343 async function getUsage(params) {
344 let data = await fetch(`${hostapi}/e/get-chat-usage`, {
345 method: "POST",
346 headers: {
347 "Content-Type": "application/json"
348 },
349 body: JSON.stringify(params),
350 referrer: "https://api.ai-pro.org"
351 });
352 return await data.json();
353 }
354 async function setUsage(params) {
355 fetch(`${hostapi}/e/set-usage`, {
356 method: "POST",
357 headers: {
358 "Content-Type": "application/json"
359 },
360 body: JSON.stringify(params),
361 referrer: "https://api.ai-pro.org"
362 });
363 fetch(`${hostapi}/e/set-chat-usage`, {
364 method: "POST",
365 headers: {
366 "Content-Type": "application/json"
367 },
368 body: JSON.stringify(params),
369 referrer: "https://api.ai-pro.org"
370 });
371 }
372
373 async function validation (aiwp_app_id, req, res) {
374 const aiwp_logged_in = req.cookies[user_secret_id] ? decodeURIComponent(req.cookies[user_secret_id]) : "";
375 const limit = req.cookies["WcvYPABR"] ? parseInt(req.cookies["WcvYPABR"].replace(/\D/g, '')) : 3;
376 let IS_FREE_USER = false;
377 let TRIED_USAGE = 0;
378
379 if (aiwp_logged_in) {
380 let auth = await authenticate({ aiwp_logged_in, user_event_data: {}, user_event: 'endpoint' });
381 if (!auth.success) {
382 IS_FREE_USER = true;
383 if (auth.is_restrict) {
384 res.json({ status: "invalid", restrict: true, redirect: auth.redirect });
385 res.end();
386 return false;
387 } else if (typeof auth.has_pro_access === "undefined" && !auth.has_pro_access) {
388 res.json({ status: "invalid", restrict: true });
389 res.end();
390 return false;
391 }
392 }
393 if (!auth.subscription_type || (auth.auth_version === 'v2' && auth.subscription_type.toLowerCase() === 'basic')) {
394 res.json({ status: "invalid" });
395 res.status(200);
396 return false;
397 }
398 let data = await getUsage({
399 aiwp_logged_in, app: 'chatbot+'
400 });
401
402 if (!(data.success === 1 && data.status === 'valid')) {
403 res.json({ status: "invalid", data });
404 res.status(200);
405 return false;
406 }
407 } else {
408 IS_FREE_USER = true;
409 let data = await getLimitedUsage({
410 aiwp_app_id
411 });
412
413 if (data.usage !== null) {
414 TRIED_USAGE = parseInt(data.usage);
415 }
416 return { IS_FREE_USER, aiwp_logged_in, TRIED_USAGE };
417 }
418 if (IS_FREE_USER && TRIED_USAGE >= limit) {
419 res.json({ status: "invalid", limited: true });
420 res.end();
421 return false;
422 }
423 if (IS_FREE_USER) TRIED_USAGE++;
424
425 return { IS_FREE_USER, aiwp_logged_in, TRIED_USAGE };
426 };
427
306 428
307 429
308 // Get Models Route 430 // Get Models Route
......
...@@ -5,22 +5,26 @@ ...@@ -5,22 +5,26 @@
5 "main": "index.js", 5 "main": "index.js",
6 "scripts": { 6 "scripts": {
7 "test": "echo \"Error: no test specified\" && exit 1", 7 "test": "echo \"Error: no test specified\" && exit 1",
8 "start": "node index.js" 8 "start": "node index.js",
9 "dev": "nodemon index.js"
9 }, 10 },
10 "author": "", 11 "author": "",
11 "license": "ISC", 12 "license": "ISC",
12 "dependencies": { 13 "dependencies": {
13 "js-tiktoken": "1.0.7",
14 "anchorme": "^2.1.2", 14 "anchorme": "^2.1.2",
15 "axios": "^1.5.1", 15 "axios": "^1.5.1",
16 "body-parser": "^1.20.1", 16 "body-parser": "^1.20.1",
17 "cookie": "0.5.0", 17 "cookie": "0.5.0",
18 "cookie-parser": "1.4.6", 18 "cookie-parser": "^1.4.6",
19 "cors": "^2.8.5", 19 "cors": "^2.8.5",
20 "dotenv": "^16.0.3", 20 "dotenv": "^16.0.3",
21 "express": "^4.18.2", 21 "express": "^4.18.2",
22 "express-rate-limit": "^6.7.0", 22 "express-rate-limit": "^6.7.0",
23 "js-cookie": "^3.0.5",
24 "js-tiktoken": "1.0.7",
23 "morgan": "^1.10.0", 25 "morgan": "^1.10.0",
26 "node-fetch": "^2.7.0",
27 "nodemon": "^3.1.0",
24 "openai": "^3.2.0" 28 "openai": "^3.2.0"
25 } 29 }
26 } 30 }
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!