From b01b26b12d951a7beaf4137809c5f16af7a16423 Mon Sep 17 00:00:00 2001 From: DeveloperDurp Date: Fri, 23 Jun 2023 12:21:35 -0400 Subject: [PATCH] update --- controller/controller.go | 98 +++++++++++++++++++++++++++++----------- controller/dadjoke.go | 33 ++++++++++++++ controller/health.go | 4 +- controller/openai.go | 31 +++++++------ controller/unraid.go | 21 +++++---- docs/docs.go | 29 ++++++++++++ docs/swagger.json | 29 ++++++++++++ docs/swagger.yaml | 19 ++++++++ go.mod | 13 ++++-- go.sum | 36 ++++++++------- main.go | 68 ++++------------------------ model/admin.go | 40 ++++++++++------ model/dadjoke.go | 13 ++++++ 13 files changed, 290 insertions(+), 144 deletions(-) create mode 100644 controller/dadjoke.go create mode 100644 model/dadjoke.go diff --git a/controller/controller.go b/controller/controller.go index 8b86fae..6cf0d20 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -1,41 +1,85 @@ package controller import ( - "os" + "log" + "net/http" + "strings" - openai "github.com/sashabaranov/go-openai" + "github.com/caarlos0/env/v6" + "github.com/gin-gonic/gin" + "github.com/joho/godotenv" + "github.com/sashabaranov/go-openai" + + "gitlab.com/DeveloperDurp/DurpAPI/model" ) type Controller struct { - openaiClient *openai.Client - unraidAPIKey string - unraidURI string - ClientID string - ClientSecret string - RedirectURL string - AuthURL string - TokenURL string + Cfg model.Config + dbcfg model.DBConfig } func NewController() *Controller { + err := godotenv.Load(".env") + if err != nil { + log.Fatalf("unable to load file: %e", err) + } + controller := &Controller{} + controller.Cfg = model.Config{} + controller.dbcfg = model.DBConfig{} - openaiApiKey := os.Getenv("OPENAI_API_KEY") - unraidAPIKey := os.Getenv("UNRAID_API_KEY") - unraidURI := os.Getenv("UNRAID_URI") - ClientID := os.Getenv("ClientID") - ClientSecret := os.Getenv("ClientSecret") - RedirectURL := os.Getenv("RedirectURL") - AuthURL := os.Getenv("AuthURL") - TokenURL := os.Getenv("TokenURL") + err = env.Parse(&controller.Cfg) + if err != nil { + log.Fatalf("unable to parse environment variables: %e", err) + } + err = env.Parse(&controller.dbcfg) + if err != nil { + log.Fatalf("unable to parse database variables: %e", err) + } + controller.Cfg.OpenaiClient = *openai.NewClient(controller.Cfg.OpenaiApiKey) + return controller +} - return &Controller{ - openaiClient: openai.NewClient(openaiApiKey), - unraidAPIKey: unraidAPIKey, - unraidURI: unraidURI, - ClientID: ClientID, - ClientSecret: ClientSecret, - RedirectURL: RedirectURL, - AuthURL: AuthURL, - TokenURL: TokenURL, +func (c *Controller) AuthMiddleware( + allowedGroups []string, + currentGroups string, +) gin.HandlerFunc { + return func(c *gin.Context) { + var groups []string + + if currentGroups != "" { + groups = strings.Split(currentGroups, ",") + } else { + // Get the user groups from the request headers + groupsHeader := c.GetHeader("X-authentik-groups") + + // Split the groups header value into individual groups + groups = strings.Split(groupsHeader, "|") + } + + // Check if the user belongs to any of the allowed groups + isAllowed := false + for _, allowedGroup := range allowedGroups { + for _, group := range groups { + if group == allowedGroup { + isAllowed = true + break + } + } + if isAllowed { + break + } + } + + // If the user is not in any of the allowed groups, respond with unauthorized access + if !isAllowed { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ + "message": "Unauthorized access", + "groups": groups, + }) + return + } + + // Call the next handler + c.Next() } } diff --git a/controller/dadjoke.go b/controller/dadjoke.go new file mode 100644 index 0000000..bd4af3f --- /dev/null +++ b/controller/dadjoke.go @@ -0,0 +1,33 @@ +package controller + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "gitlab.com/DeveloperDurp/DurpAPI/model" +) + +// GetDadJoke godoc +// +// @Summary Generate dadjoke +// @Description get a dad joke +// @Tags DadJoke +// @Accept json +// @Produce application/json +// @Success 200 {object} model.Message "response" +// @failure 400 {object} model.Message "error" +// @Router /jokes/dadjoke [get] +func (c *Controller) GetDadJoke(ctx *gin.Context) { + var req model.DadJoke + + if err := ctx.ShouldBindJSON(&req); err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"message": err}) + } + message := "test" + // message, err := service.GetDadJoke(req) + // if err != nil { + // ctx.JSON(http.StatusInternalServerError, gin.H{"message": err}) + // } + ctx.JSON(http.StatusOK, gin.H{"message": message}) +} diff --git a/controller/health.go b/controller/health.go index 44b78cb..93fe7da 100644 --- a/controller/health.go +++ b/controller/health.go @@ -17,7 +17,5 @@ import ( // @failure 400 {object} model.Message "error" // @Router /health/getHealth [get] func (c *Controller) GetHealth(ctx *gin.Context) { - // Return the health in the response body - ctx.JSON(http.StatusOK, gin.H{"message": "OK"}) + ctx.JSON(http.StatusOK, gin.H{"message": "OK"}) } - diff --git a/controller/openai.go b/controller/openai.go index db320fd..f15541e 100644 --- a/controller/openai.go +++ b/controller/openai.go @@ -10,7 +10,7 @@ import ( ) type ChatRequest struct { - Message string `json:"message"` + Message string `json:"message"` } // GeneralOpenAI godoc @@ -22,17 +22,18 @@ type ChatRequest struct { // @Produce application/json // @Param message query string true "Ask ChatGPT a general question" // @Success 200 {object} model.Message "response" -//@failure 400 {object} model.Message "error" +// +// @failure 400 {object} model.Message "error" +// // @Router /openai/general [get] func (c *Controller) GeneralOpenAI(ctx *gin.Context) { + var req ChatRequest - var req ChatRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + req.Message = ctx.Query("message") + } - if err := ctx.ShouldBindJSON(&req); err != nil { - req.Message = ctx.Query("message") - } - - result, err := createChatCompletion(c, req.Message) + result, err := c.createChatCompletion(req.Message) if err != nil { err := ctx.AbortWithError(http.StatusInternalServerError, err) if err != nil { @@ -55,9 +56,14 @@ func (c *Controller) GeneralOpenAI(ctx *gin.Context) { // @failure 400 {object} model.Message "error" // @Router /openai/travelagent [get] func (c *Controller) TravelAgentOpenAI(ctx *gin.Context) { - message := "I want you to act as a travel guide. I will give you my location and you will give me suggestions. " + ctx.Query("message") + var req ChatRequest + if err := ctx.ShouldBindJSON(&req); err != nil { + req.Message = ctx.Query("message") + } - result, err := createChatCompletion(c, message) + req.Message = "I want you to act as a travel guide. I will give you my location and you will give me suggestions. " + req.Message + + result, err := c.createChatCompletion(req.Message) if err != nil { err := ctx.AbortWithError(http.StatusInternalServerError, err) if err != nil { @@ -68,9 +74,8 @@ func (c *Controller) TravelAgentOpenAI(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"message": result}) } -func createChatCompletion(c *Controller, message string) (string, error) { - - var client = c.openaiClient +func (c *Controller) createChatCompletion(message string) (string, error) { + client := c.Cfg.OpenaiClient resp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ diff --git a/controller/unraid.go b/controller/unraid.go index b00da49..2036b03 100644 --- a/controller/unraid.go +++ b/controller/unraid.go @@ -9,12 +9,6 @@ import ( "strings" "github.com/gin-gonic/gin" - "gitlab.com/DeveloperDurp/DurpAPI/model" -) - -var ( - unraidAPIKey = model.UnraidAPIKey - UnraidURI = model.UnraidURI ) // UnraidPowerUsage godoc @@ -28,7 +22,6 @@ var ( // @failure 412 {object} model.Message "error" // @Router /unraid/powerusage [get] func (c *Controller) UnraidPowerUsage(ctx *gin.Context) { - jar, err := cookiejar.New(nil) if err != nil { fmt.Println(err) @@ -41,10 +34,14 @@ func (c *Controller) UnraidPowerUsage(ctx *gin.Context) { form := url.Values{ "username": {"root"}, - "password": {unraidAPIKey}, + "password": {c.Cfg.UnraidAPIKey}, } - req, err := http.NewRequest("POST", "https://"+UnraidURI+"/login", strings.NewReader(form.Encode())) + req, err := http.NewRequest( + "POST", + "https://"+c.Cfg.UnraidURI+"/login", + strings.NewReader(form.Encode()), + ) if err != nil { fmt.Println(err) return @@ -62,7 +59,11 @@ func (c *Controller) UnraidPowerUsage(ctx *gin.Context) { return } - req, err = http.NewRequest("GET", "https://"+UnraidURI+"/plugins/corsairpsu/status.php", nil) + req, err = http.NewRequest( + "GET", + "https://"+c.Cfg.UnraidURI+"/plugins/corsairpsu/status.php", + nil, + ) if err != nil { fmt.Println(err) return diff --git a/docs/docs.go b/docs/docs.go index 8f06587..81e15d5 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -54,6 +54,35 @@ const docTemplate = `{ } } }, + "/jokes/dadjoke": { + "get": { + "description": "get a dad joke", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DadJoke" + ], + "summary": "Generate dadjoke", + "responses": { + "200": { + "description": "response", + "schema": { + "$ref": "#/definitions/model.Message" + } + }, + "400": { + "description": "error", + "schema": { + "$ref": "#/definitions/model.Message" + } + } + } + } + }, "/openai/general": { "get": { "description": "Ask ChatGPT a general question", diff --git a/docs/swagger.json b/docs/swagger.json index 8d280d6..67e4e2b 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -45,6 +45,35 @@ } } }, + "/jokes/dadjoke": { + "get": { + "description": "get a dad joke", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "DadJoke" + ], + "summary": "Generate dadjoke", + "responses": { + "200": { + "description": "response", + "schema": { + "$ref": "#/definitions/model.Message" + } + }, + "400": { + "description": "error", + "schema": { + "$ref": "#/definitions/model.Message" + } + } + } + } + }, "/openai/general": { "get": { "description": "Ask ChatGPT a general question", diff --git a/docs/swagger.yaml b/docs/swagger.yaml index e08284c..397a13c 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -78,6 +78,25 @@ paths: summary: Generate Health status tags: - health + /jokes/dadjoke: + get: + consumes: + - application/json + description: get a dad joke + produces: + - application/json + responses: + "200": + description: response + schema: + $ref: '#/definitions/model.Message' + "400": + description: error + schema: + $ref: '#/definitions/model.Message' + summary: Generate dadjoke + tags: + - DadJoke /openai/general: get: consumes: diff --git a/go.mod b/go.mod index 7d3f26b..44211c3 100644 --- a/go.mod +++ b/go.mod @@ -4,10 +4,13 @@ go 1.19 require ( github.com/gin-gonic/gin v1.9.0 + github.com/joho/godotenv v1.5.1 github.com/sashabaranov/go-openai v1.6.1 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.0 github.com/swaggo/swag v1.8.12 + gorm.io/driver/postgres v1.5.2 + gorm.io/gorm v1.25.1 ) require github.com/google/go-cmp v0.5.8 // indirect @@ -17,6 +20,7 @@ require ( github.com/PuerkitoBio/purell v1.1.1 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/bytedance/sonic v1.8.0 // indirect + github.com/caarlos0/env/v6 v6.10.1 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect @@ -27,7 +31,11 @@ require ( github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.11.2 // indirect github.com/goccy/go-json v0.10.0 // indirect - github.com/incu6us/goimports-reviser v0.1.6 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/pgx/v5 v5.3.1 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.0.9 // indirect @@ -37,11 +45,10 @@ require ( github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.9 // indirect golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect - golang.org/x/crypto v0.5.0 // indirect + golang.org/x/crypto v0.8.0 // indirect golang.org/x/net v0.10.0 // indirect golang.org/x/sys v0.8.0 // indirect golang.org/x/text v0.9.0 // indirect diff --git a/go.sum b/go.sum index 64f0a8c..144a217 100644 --- a/go.sum +++ b/go.sum @@ -7,6 +7,8 @@ github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdko github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.8.0 h1:ea0Xadu+sHlu7x5O3gKhRpQ1IKiMrSiHttPF0ybECuA= github.com/bytedance/sonic v1.8.0/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/caarlos0/env/v6 v6.10.1 h1:t1mPSxNpei6M5yAeu1qtRdPAK29Nbcf/n3G7x+b3/II= +github.com/caarlos0/env/v6 v6.10.1/go.mod h1:hvp/ryKXKipEkcuYjs9mI4bBCg+UI0Yhgm5Zu0ddvwc= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= @@ -43,8 +45,18 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/incu6us/goimports-reviser v0.1.6 h1:KgSvPzI5VRnsVHBJEyIy0so+1thtYhLpLTfhloAQoiA= -github.com/incu6us/goimports-reviser v0.1.6/go.mod h1:Y85VqadcOjTzAbVLbjasX2qSxmHGaZYYOWdlIq7U28I= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.3.1 h1:Fcr8QJ1ZeLi5zsPZqQeUZhNhxfkkKBOgJuYkJHoBOtU= +github.com/jackc/pgx/v5 v5.3.1/go.mod h1:t3JDKnCBlYIc0ewLF0Q7B8MXmoIaBOZj/ic7iHozM/8= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -72,8 +84,6 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= @@ -83,7 +93,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -100,21 +109,16 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.9 h1:rmenucSohSTiyL09Y+l2OCk+FrMxGMzho2+tjr5ticU= github.com/ugorji/go/codec v1.2.9/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= -golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -122,10 +126,8 @@ golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -147,12 +149,10 @@ golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200407143752-a3568bac92ae/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4= golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= @@ -168,4 +168,8 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.5.2 h1:ytTDxxEv+MplXOfFe3Lzm7SjG09fcdb3Z/c056DTBx0= +gorm.io/driver/postgres v1.5.2/go.mod h1:fmpX0m2I1PKuR7mKZiEluwrP3hbs+ps7JIGMUBpCgl8= +gorm.io/gorm v1.25.1 h1:nsSALe5Pr+cM3V1qwwQ7rOkw+6UeLrX5O4v3llhHa64= +gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/main.go b/main.go index 6990c8b..5f0c3a4 100644 --- a/main.go +++ b/main.go @@ -2,21 +2,13 @@ package main import ( "fmt" - "net/http" - "strings" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" + "gitlab.com/DeveloperDurp/DurpAPI/controller" "gitlab.com/DeveloperDurp/DurpAPI/docs" - "gitlab.com/DeveloperDurp/DurpAPI/model" -) - -var ( - host = model.Host - version = model.Version - groupsenv = model.Groupsenv ) // @title DurpAPI @@ -33,11 +25,11 @@ var ( // @BasePath /api/v1 func main() { - r := gin.Default() c := controller.NewController() - docs.SwaggerInfo.Host = host - docs.SwaggerInfo.Version = version + + docs.SwaggerInfo.Host = c.Cfg.Host + docs.SwaggerInfo.Version = c.Cfg.Version v1 := r.Group("/api/v1") { @@ -45,15 +37,19 @@ func main() { { health.GET("getHealth", c.GetHealth) } + jokes := v1.Group("/jokes") + { + jokes.GET("dadjoke", c.GetDadJoke) + } openai := v1.Group("/openai") { - openai.Use(authMiddleware([]string{"openai"})) + openai.Use(c.AuthMiddleware([]string{"openai"}, c.Cfg.Groupsenv)) openai.GET("general", c.GeneralOpenAI) openai.GET("travelagent", c.TravelAgentOpenAI) } unraid := v1.Group("/unraid") { - unraid.Use(authMiddleware([]string{"unraid"})) + openai.Use(c.AuthMiddleware([]string{"unraid"}, c.Cfg.Groupsenv)) unraid.GET("powerusage", c.UnraidPowerUsage) } } @@ -64,47 +60,3 @@ func main() { fmt.Println("Failed to start server") } } - -func authMiddleware(allowedGroups []string) gin.HandlerFunc { - - return func(c *gin.Context) { - - var groups []string - - if groupsenv != "" { - groups = strings.Split(groupsenv, ",") - } else { - // Get the user groups from the request headers - groupsHeader := c.GetHeader("X-authentik-groups") - - // Split the groups header value into individual groups - groups = strings.Split(groupsHeader, "|") - } - - // Check if the user belongs to any of the allowed groups - isAllowed := false - for _, allowedGroup := range allowedGroups { - for _, group := range groups { - if group == allowedGroup { - isAllowed = true - break - } - } - if isAllowed { - break - } - } - - // If the user is not in any of the allowed groups, respond with unauthorized access - if !isAllowed { - c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ - "message": "Unauthorized access", - "groups": groups, - }) - return - } - - // Call the next handler - c.Next() - } -} diff --git a/model/admin.go b/model/admin.go index 437025f..40318b8 100644 --- a/model/admin.go +++ b/model/admin.go @@ -1,17 +1,29 @@ package model -import "os" - -var ( - OpenaiApiKey = os.Getenv("OPENAI_API_KEY") - UnraidAPIKey = os.Getenv("UNRAID_API_KEY") - UnraidURI = os.Getenv("UNRAID_URI") - ClientID = os.Getenv("ClientID") - ClientSecret = os.Getenv("ClientSecret") - RedirectURL = os.Getenv("RedirectURL") - AuthURL = os.Getenv("AuthURL") - TokenURL = os.Getenv("TokenURL") - Host = os.Getenv("host") - Version = os.Getenv("version") - Groupsenv = os.Getenv("groups") +import ( + "github.com/sashabaranov/go-openai" + "gorm.io/gorm" ) + +type Config struct { + OpenaiClient openai.Client + OpenaiApiKey string `env:"openai_api_key"` + UnraidAPIKey string `env:"unraid_api_key"` + UnraidURI string `env:"unraid_uri"` + Host string `env:"host"` + Version string `env:"version"` + Groupsenv string `env:"groupsenv"` +} + +type DBConfig struct { + Host string `env:"db_host"` + Port string `env:"db_port"` + Password string `env:"db_pass"` + User string `env:"db_user"` + DBName string `env:"db_name"` + SSLMode string `env:"db_sslmode"` +} + +type Repository struct { + DB *gorm.DB +} diff --git a/model/dadjoke.go b/model/dadjoke.go new file mode 100644 index 0000000..1cbc52c --- /dev/null +++ b/model/dadjoke.go @@ -0,0 +1,13 @@ +package model + +type DadJokes struct { + ID uint `gorm: "primary key;autoIncrement" json:"id"` + Author *string `json:"author"` + Title *string `json:"title"` + Publisher *string `json:"publisher"` +} +type DadJoke struct { + Author string `json:"author"` + Title string `json:"title"` + Publisher string `json:"publisher"` +}