Skip to content

Commit

Permalink
use session to protect public bots
Browse files Browse the repository at this point in the history
  • Loading branch information
n4ze3m committed Oct 12, 2023
1 parent d9f2d94 commit 6c3d448
Show file tree
Hide file tree
Showing 10 changed files with 287 additions and 140 deletions.
75 changes: 38 additions & 37 deletions app/ui/src/services/api.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,53 @@
import axios from 'axios';
import { getToken } from './cookie';
import axios from "axios";
import { getToken } from "./cookie";

export const baseURL = import.meta.env.VITE_API_URL || '/api/v1';
export const baseURL = import.meta.env.VITE_API_URL || "/api/v1";

const instance = axios.create({
baseURL,
headers: {
"Content-Type": "application/json",
},
baseURL,
headers: {
"Content-Type": "application/json",
},
});

instance.interceptors.request.use(
(config) => {
const token = getToken()
if (token) {
config.headers!.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
(config) => {
const token = getToken();
if (token) {
config.headers!.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
},
);

instance.interceptors.response.use(
(res) => {
return res;
},
async (err) => {
const originalConfig = err.config;
if (err.response) {
if (err.response.status === 401 && !originalConfig._retry) {
originalConfig._retry = true;
try {
return instance(originalConfig);
} catch (_error) {

return Promise.reject(_error);
}
}

if (err.response.status === 403 && err.response.data) {
return Promise.reject(err.response.data);
}
(res) => {
return res;
},
async (err) => {
const originalConfig = err.config;
if (err.response) {
if (err.response.status === 401 && !originalConfig._retry) {
originalConfig._retry = true;
try {
return instance(originalConfig);
} catch (_error) {
return Promise.reject(_error);
}
} else if (err.response.status === 401 && originalConfig._retry) {
window.location.href = "/#/login";
}

return Promise.reject(err);
if (err.response.status === 403 && err.response.data) {
return Promise.reject(err.response.data);
}
}

return Promise.reject(err);
},
);

export default instance;
export default instance;
6 changes: 5 additions & 1 deletion docker/.env
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ GOOGLE_API_KEY=""
# Eleven labs API Key -> https://elevenlabs.io/
ELEVENLABS_API_KEY=""
# Dialoqbase Q Concurency
DB_QUEUE_CONCURRENCY=1
DB_QUEUE_CONCURRENCY=1
# Dialoqbase Session Secret
DB_SESSION_SECRET="super-secret-key"
# Dialoqbase Session Secure
DB_SESSION_SECURE="false"
1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"license": "MIT",
"dependencies": {
"@fastify/autoload": "^5.0.0",
"@fastify/cookie": "^9.1.0",
"@fastify/cors": "^8.3.0",
"@fastify/jwt": "^7.0.0",
"@fastify/multipart": "^7.6.0",
Expand Down
8 changes: 8 additions & 0 deletions server/prisma/migrations/q_14/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- AlterTable
ALTER TABLE "Bot" ADD COLUMN "options" JSON DEFAULT '{}',
ADD COLUMN "use_rag" BOOLEAN NOT NULL DEFAULT false;

ALTER TABLE "Bot" ADD COLUMN "bot_protect" BOOLEAN NOT NULL DEFAULT false;


ALTER TABLE "Bot" ADD COLUMN "bot_api_key" TEXT NULL DEFAULT NULL;
14 changes: 9 additions & 5 deletions server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ model Bot {
text_to_voice_type_metadata Json @default("{}") @db.Json
use_hybrid_search Boolean @default(false)
haveDataSourcesBeenAdded Boolean @default(false)
use_rag Boolean @default(false)
bot_protect Boolean @default(false)
bot_api_key String?
options Json? @default("{}") @db.Json
BotAppearance BotAppearance[]
document BotDocument[]
BotIntegration BotIntegration[]
Expand Down Expand Up @@ -103,12 +107,12 @@ model BotIntegration {
}

model BotTelegramHistory {
id Int @id @default(autoincrement())
chat_id Int?
id Int @id @default(autoincrement())
chat_id Int?
new_chat_id String?
identifier String?
human String?
bot String?
identifier String?
human String?
bot String?
}

model BotDiscordHistory {
Expand Down
27 changes: 22 additions & 5 deletions server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import cors from "@fastify/cors";
import fastifyStatic from "@fastify/static";
import fastifyMultipart from "@fastify/multipart";
import { FastifySSEPlugin } from "@waylaidwanderer/fastify-sse-v2";
import fastifyCookie from "@fastify/cookie";
import fastifySession from "@fastify/session";
import { getSessionSecret, isCookieSecure } from "./utils/session";

declare module "fastify" {
interface Session {
is_bot_allowed: boolean;
}
}

export type AppOptions = {} & Partial<AutoloadPluginOptions>;

Expand Down Expand Up @@ -40,13 +49,21 @@ const app: FastifyPluginAsync<AppOptions> = async (
preCompressed: true,
});

await fastify.register(import('fastify-raw-body'), {
field: 'rawBody', // change the default request.rawBody property name
fastify.register(fastifyCookie);
fastify.register(fastifySession, {
secret: getSessionSecret(),
cookie: {
secure: isCookieSecure(),
},
});

await fastify.register(import("fastify-raw-body"), {
field: "rawBody", // change the default request.rawBody property name
global: false, // add the rawBody to every request. **Default true**
encoding: 'utf8', // set it to false to set rawBody as a Buffer **Default utf8**
encoding: "utf8", // set it to false to set rawBody as a Buffer **Default utf8**
runFirst: true, // get the body before any preParsing hook change/uncompress it. **Default false**
routes: [] // array of routes, **`global`** will be ignored, wildcard routes not supported
})
routes: [], // array of routes, **`global`** will be ignored, wildcard routes not supported
});
};

export default app;
Expand Down
5 changes: 2 additions & 3 deletions server/src/routes/bot/handlers/get.handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { ChatStyleRequest } from "./types";

import { ChatStyleRequest } from "./types";

export const getChatStyleByIdHandler = async (
request: FastifyRequest<ChatStyleRequest>,
Expand Down Expand Up @@ -51,7 +50,7 @@ export const getChatStyleByIdHandler = async (
},
};
}

request.session.is_bot_allowed = true;
return {
data: {
background_color: "#ffffff",
Expand Down
Loading

0 comments on commit 6c3d448

Please sign in to comment.