mirror of
https://github.com/hanzoai/ai.git
synced 2026-11-21 11:09:56 +00:00
These carry Hanzo-only copyright but derive from casibase/OpenAgent upstream counterparts. record_chain.go is near-verbatim (12 diff lines over 97); storage/iam.go is upstream's storage/casdoor.go with an import swap and a CasdoorProvider -> IamProvider rename. Adds the "Portions Copyright <year> The OpenAgent Authors" line this repo already uses correctly on 322 other files, with upstream's own years. cmd/aid/main.go is left alone: it has no upstream counterpart. Co-authored-by: Hanzo Dev <[email protected]>
196 lines
5.7 KiB
Go
196 lines
5.7 KiB
Go
// Copyright 2023-2025 Hanzo AI Inc.. All Rights Reserved.
|
|
// Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package routers
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/hanzoai/ai/conf"
|
|
"github.com/hanzoai/ai/i18n"
|
|
iam "github.com/hanzoai/ai/internal/iam"
|
|
"github.com/hanzoai/ai/util"
|
|
"github.com/hanzoai/ai/web"
|
|
)
|
|
|
|
type Response struct {
|
|
Status string `json:"status"`
|
|
Msg string `json:"msg"`
|
|
Data interface{} `json:"data"`
|
|
Data2 interface{} `json:"data2"`
|
|
}
|
|
|
|
func GetSessionUser(ctx *web.Context) *iam.User {
|
|
// Twin of controllers.GetSessionClaims: a nil session store resolves to "no
|
|
// session user", never a panic. ctx.Input.Session dereferences CruSession
|
|
// directly, and CruSession is only populated by beego's SessionStart — which
|
|
// does NOT run when the embedded cloud binary serves these routes without the
|
|
// session hook. This function runs in the BeforeRouter filters (RateLimit,
|
|
// BalanceGate, Authz) via resolveBillingKey — BEFORE the controller — so a nil
|
|
// store here was a pre-model 500 on every /v1 request. Fail-secure: no session
|
|
// ⇒ no user ⇒ the filters bill/limit by the raw key and the controller enforces
|
|
// Bearer-credential auth (typed 401 for an invalid/absent credential).
|
|
if ctx == nil || ctx.Input == nil || ctx.Input.CruSession == nil {
|
|
return nil
|
|
}
|
|
s := ctx.Input.Session("user")
|
|
if s == nil {
|
|
return nil
|
|
}
|
|
|
|
claims, ok := s.(iam.Claims)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
return &claims.User
|
|
}
|
|
|
|
func getUsername(ctx *web.Context) (username string) {
|
|
user := GetSessionUser(ctx)
|
|
if user != nil {
|
|
username = util.GetIdFromOwnerAndName(user.Owner, user.Name)
|
|
} else {
|
|
username, _ = getUsernameByClientIdSecret(ctx)
|
|
}
|
|
return
|
|
}
|
|
|
|
func responseError(ctx *web.Context, error string, data ...interface{}) {
|
|
// ctx.ResponseWriter.WriteHeader(http.StatusForbidden)
|
|
|
|
// Get language from Accept-Language header
|
|
language := ctx.Request.Header.Get("Accept-Language")
|
|
if len(language) > 2 {
|
|
language = language[0:2]
|
|
}
|
|
language = conf.GetLanguage(language)
|
|
|
|
// Translate error message if it contains namespace prefix
|
|
translatedError := error
|
|
if strings.Contains(error, ":") {
|
|
translatedError = i18n.Translate(language, error)
|
|
}
|
|
|
|
resp := Response{Status: "error", Msg: translatedError}
|
|
switch len(data) {
|
|
case 2:
|
|
resp.Data2 = data[1]
|
|
fallthrough
|
|
case 1:
|
|
resp.Data = data[0]
|
|
}
|
|
|
|
err := ctx.Output.JSON(resp, true, false)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
// responseErrorStatus writes the standard error envelope with an explicit HTTP
|
|
// status. Filters use it so an auth/authz denial is a real 401/403, not Beego's
|
|
// default 200 — a denial must never look like success to a client. The body
|
|
// shape is unchanged; only the status differs.
|
|
func responseErrorStatus(ctx *web.Context, status int, error string, data ...interface{}) {
|
|
ctx.Output.SetStatus(status)
|
|
responseError(ctx, error, data...)
|
|
}
|
|
|
|
// denyUnauthorized renders a 401 (no/invalid credential).
|
|
func denyUnauthorized(ctx *web.Context, error string, data ...interface{}) {
|
|
responseErrorStatus(ctx, http.StatusUnauthorized, error, data...)
|
|
}
|
|
|
|
// denyForbidden renders a 403 (authenticated but not permitted).
|
|
func denyForbidden(ctx *web.Context, error string, data ...interface{}) {
|
|
responseErrorStatus(ctx, http.StatusForbidden, error, data...)
|
|
}
|
|
|
|
func setSessionUser(ctx *web.Context, userId string) {
|
|
owner, name, err := util.GetOwnerAndNameFromIdWithError(userId)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
claims := iam.Claims{
|
|
User: iam.User{
|
|
Owner: owner,
|
|
Name: name,
|
|
IsAdmin: true,
|
|
},
|
|
}
|
|
err = ctx.Input.CruSession.Set("user", claims)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// https://github.com/beego/beego/issues/3445#issuecomment-455411915
|
|
ctx.Input.CruSession.SessionRelease(ctx.ResponseWriter)
|
|
}
|
|
|
|
func getUsernameByClientIdSecret(ctx *web.Context) (string, error) {
|
|
clientId, clientSecret, ok := ctx.Request.BasicAuth()
|
|
if !ok {
|
|
clientId = ctx.Input.Query("clientId")
|
|
clientSecret = ctx.Input.Query("clientSecret")
|
|
}
|
|
|
|
if clientId == "" || clientSecret == "" {
|
|
return "", nil
|
|
}
|
|
|
|
applicationName := conf.GetConfigString("IAM_APP_NAME")
|
|
if clientSecret != conf.GetConfigString("IAM_CLIENT_SECRET") {
|
|
return "", fmt.Errorf("Incorrect client secret for application: %s", applicationName)
|
|
}
|
|
|
|
return util.GetIdFromOwnerAndName("app", applicationName), nil
|
|
}
|
|
|
|
func getUsernameByAccessToken(accessTokenInput string) (string, error) {
|
|
applicationName := conf.GetConfigString("IAM_APP_NAME")
|
|
clientSecret := conf.GetConfigString("IAM_CLIENT_SECRET")
|
|
clientId := conf.GetConfigString("IAM_CLIENT_ID")
|
|
accessToken := getMd5HexDigest(clientId + ":" + clientSecret)
|
|
if accessTokenInput != accessToken {
|
|
return "", fmt.Errorf("Incorrect access token for application: %s", applicationName)
|
|
}
|
|
|
|
return util.GetIdFromOwnerAndName("app", applicationName), nil
|
|
}
|
|
|
|
func parseBearerToken(ctx *web.Context) string {
|
|
header := ctx.Request.Header.Get("Authorization")
|
|
tokens := strings.Split(header, " ")
|
|
if len(tokens) != 2 {
|
|
return ""
|
|
}
|
|
|
|
prefix := tokens[0]
|
|
if prefix != "Bearer" {
|
|
return ""
|
|
}
|
|
|
|
return tokens[1]
|
|
}
|
|
|
|
func getMd5HexDigest(s string) string {
|
|
hash := md5.Sum([]byte(s))
|
|
res := hex.EncodeToString(hash[:])
|
|
return res
|
|
}
|