Skip to content

Commit

Permalink
Merge pull request OpenNyAI#149 from kanak8278/secret_key
Browse files Browse the repository at this point in the history
Authorization for Bot Installation
  • Loading branch information
shreypandey authored Jul 18, 2024
2 parents 8abe473 + ccff84f commit b841e3e
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 4 deletions.
2 changes: 1 addition & 1 deletion api/app/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,4 @@ async def update_channel_by_bot_id(bot_id: str, data):
stmt = update(JBChannel).where(JBChannel.bot_id == bot_id).values(**data)
await session.execute(stmt)
await session.commit()
return bot_id
return bot_id
20 changes: 19 additions & 1 deletion api/app/routers/v1/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from fastapi import APIRouter, HTTPException, Request
import uuid
from ...crud import get_chat_history, get_bot_list, get_bot_chat_sessions
from ...handlers.v1 import handle_callback, handle_webhook
from ...handlers.v1.bot_handlers import (
Expand All @@ -16,6 +17,7 @@
tags=["v1"],
)

JBMANAGER_KEY = str(uuid.uuid4())

@router.get("/bots")
async def get_bots():
Expand All @@ -30,9 +32,25 @@ async def get_bots():
bot.status = status
return bots

@router.get("/secret")
async def get_secret_key():
return {"secret": JBMANAGER_KEY}


@router.put("/refresh-key")
async def refresh_secret_key():
JBMANAGER_KEY = str(uuid.uuid4())
return {"status": "success"}

@router.post("/bot/install")
async def install_bot(install_content: JBBotCode):
async def install_bot(request:Request, install_content: JBBotCode):
headers = dict(request.headers)
authorization = headers.get("authorization")
if authorization is None:
raise HTTPException(status_code=401, detail="Authorization header not provided")
if authorization != f"Bearer {JBMANAGER_KEY}":
raise HTTPException(status_code=401, detail="Unauthorized")

flow_input = await handle_install_bot(install_content)
try:
produce_message(flow_input)
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/components/settings-model/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import './settings-model.css';
import { sendRequest } from '@/api';
import { fetchSecret } from '@/pages/home/home';

interface InputConfig {
value: string | number | boolean;
Expand Down Expand Up @@ -47,6 +48,7 @@ const SettingsModal: React.FC<Props> = ({ botId, isOpen, onClose, inputs, modelT
const handleSubmit = async () => {
let data:any = {};
let apiEndpoint = '';
let accessToken = null;
if (modelType === 'credentials') {
apiEndpoint = `${APIHOST}/v1/bot/${botId}/configure`;
let credentials:any = {};
Expand All @@ -73,6 +75,13 @@ const SettingsModal: React.FC<Props> = ({ botId, isOpen, onClose, inputs, modelT
data['channels']['whatsapp'] = inputElements['whatsapp'].value;
} else if (modelType === 'install') {
apiEndpoint = `${APIHOST}/v1/bot/install`;
try {
accessToken = await fetchSecret();
} catch (error) {
console.error("Failed to fetch the access token:", error);
alert("Failed to fetch the access token");
return;
}
for (let key in inputElements) {
if (inputElements[key].required === true && !inputElements[key].value.toString().trim()) {
alert(`${key} is required`);
Expand All @@ -89,6 +98,7 @@ const SettingsModal: React.FC<Props> = ({ botId, isOpen, onClose, inputs, modelT
await sendRequest({
url: apiEndpoint,
method: 'POST',
accessToken: accessToken,
body: JSON.stringify(data ),
headers: {
'Content-Type': 'application/json',
Expand Down
27 changes: 25 additions & 2 deletions frontend/src/pages/home/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ interface props {

}

export async function fetchSecret() {
const url = `${APIHOST}/v1/secret`;
try {
const response = await fetch(url);
const data = await response.json();
const secret = data.secret;
return secret; // Return the secret explicitly
} catch (error) {
console.error("Error fetching secret:", error);
throw error; // Throw error to handle it later
}
}

export const Home:React.FunctionComponent = (props:props) => {
const [refreshBots, incrementrefreshBots] = React.useState(0);
const [projects, setProjects] = React.useState([]);
Expand Down Expand Up @@ -103,17 +116,27 @@ export const Home:React.FunctionComponent = (props:props) => {
</div>
</div>
<div className='value'>
<div onClick={() => { navigator.clipboard.writeText("https://bandhujbstorage.z29.web.core.windows.net/"); alert("Installation URL copied") }}>
<div onClick={() => { navigator.clipboard.writeText(import.meta.env.VITE_SERVER_HOST+"/v1/bot/install"); alert("Installation URL copied") }}>
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none">
<path d="M11.75 2C9.95507 2 8.5 3.45508 8.5 5.25V23.25C8.5 25.0449 9.95507 26.5 11.75 26.5H23.75C25.5449 26.5 27 25.0449 27 23.25V5.25C27 3.45507 25.5449 2 23.75 2H11.75ZM10.5 5.25C10.5 4.55964 11.0596 4 11.75 4H23.75C24.4404 4 25 4.55964 25 5.25V23.25C25 23.9404 24.4404 24.5 23.75 24.5H11.75C11.0596 24.5 10.5 23.9404 10.5 23.25V5.25ZM7 5.74902C5.82552 6.2388 5 7.39797 5 8.74994V23.4999C5 27.0898 7.91015 29.9999 11.5 29.9999H20.25C21.6021 29.9999 22.7613 29.1743 23.2511 27.9996H20.2786C20.2691 27.9998 20.2596 27.9999 20.25 27.9999H11.5C9.01472 27.9999 7 25.9852 7 23.4999V5.74902Z" fill="#8B8B8B"/>
</svg>
{import.meta.env.VITE_SERVER_HOST+"/install"}
{import.meta.env.VITE_SERVER_HOST+"/v1/bot/install"}
</div>
<div>
<div onClick={async () => {
try {
const secret = await fetchSecret();
await navigator.clipboard.writeText(secret);
alert("JB Manager secret copied!");
} catch (error) {
alert("Failed to copy secret");
}
}}>
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32" fill="none">
<path d="M11.75 2C9.95507 2 8.5 3.45508 8.5 5.25V23.25C8.5 25.0449 9.95507 26.5 11.75 26.5H23.75C25.5449 26.5 27 25.0449 27 23.25V5.25C27 3.45507 25.5449 2 23.75 2H11.75ZM10.5 5.25C10.5 4.55964 11.0596 4 11.75 4H23.75C24.4404 4 25 4.55964 25 5.25V23.25C25 23.9404 24.4404 24.5 23.75 24.5H11.75C11.0596 24.5 10.5 23.9404 10.5 23.25V5.25ZM7 5.74902C5.82552 6.2388 5 7.39797 5 8.74994V23.4999C5 27.0898 7.91015 29.9999 11.5 29.9999H20.25C21.6021 29.9999 22.7613 29.1743 23.2511 27.9996H20.2786C20.2691 27.9998 20.2596 27.9999 20.25 27.9999H11.5C9.01472 27.9999 7 25.9852 7 23.4999V5.74902Z" fill="#8B8B8B"/>
</svg>
***************************
</div>
</div>
</div>
</div>
Expand Down

0 comments on commit b841e3e

Please sign in to comment.