Flowise

Форк
0
71 строка · 2.9 Кб
1
import { Request, Response, NextFunction } from 'express'
2
import { getRateLimiter } from '../../utils/rateLimit'
3
import chatflowsService from '../../services/chatflows'
4
import logger from '../../utils/logger'
5
import predictionsServices from '../../services/predictions'
6
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
7
import { StatusCodes } from 'http-status-codes'
8

9
// Send input message and get prediction result (External)
10
const createPrediction = async (req: Request, res: Response, next: NextFunction) => {
11
    try {
12
        if (typeof req.params === 'undefined' || !req.params.id) {
13
            throw new InternalFlowiseError(
14
                StatusCodes.PRECONDITION_FAILED,
15
                `Error: predictionsController.createPrediction - id not provided!`
16
            )
17
        }
18
        if (!req.body) {
19
            throw new InternalFlowiseError(
20
                StatusCodes.PRECONDITION_FAILED,
21
                `Error: predictionsController.createPrediction - body not provided!`
22
            )
23
        }
24
        const chatflow = await chatflowsService.getChatflowById(req.params.id)
25
        if (!chatflow) {
26
            throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chatflow ${req.params.id} not found`)
27
        }
28
        let isDomainAllowed = true
29
        logger.info(`[server]: Request originated from ${req.headers.origin}`)
30
        if (chatflow.chatbotConfig) {
31
            const parsedConfig = JSON.parse(chatflow.chatbotConfig)
32
            // check whether the first one is not empty. if it is empty that means the user set a value and then removed it.
33
            const isValidAllowedOrigins = parsedConfig.allowedOrigins?.length && parsedConfig.allowedOrigins[0] !== ''
34
            if (isValidAllowedOrigins) {
35
                const originHeader = req.headers.origin as string
36
                const origin = new URL(originHeader).host
37
                isDomainAllowed =
38
                    parsedConfig.allowedOrigins.filter((domain: string) => {
39
                        try {
40
                            const allowedOrigin = new URL(domain).host
41
                            return origin === allowedOrigin
42
                        } catch (e) {
43
                            return false
44
                        }
45
                    }).length > 0
46
            }
47
        }
48
        if (isDomainAllowed) {
49
            //@ts-ignore
50
            const apiResponse = await predictionsServices.buildChatflow(req, req?.io)
51
            return res.json(apiResponse)
52
        } else {
53
            throw new InternalFlowiseError(StatusCodes.UNAUTHORIZED, `This site is not allowed to access this chatbot`)
54
        }
55
    } catch (error) {
56
        next(error)
57
    }
58
}
59

60
const getRateLimiterMiddleware = async (req: Request, res: Response, next: NextFunction) => {
61
    try {
62
        return getRateLimiter(req, res, next)
63
    } catch (error) {
64
        next(error)
65
    }
66
}
67

68
export default {
69
    createPrediction,
70
    getRateLimiterMiddleware
71
}
72

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.