Provide external apis for ability of auth

This commit is contained in:
2024-10-22 23:23:58 +08:00
parent 0f4112e08b
commit a1412acc90
7 changed files with 58 additions and 13 deletions

View File

@ -1,6 +1,7 @@
package api
import (
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/internal/directory"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/proxy"
@ -29,6 +30,12 @@ func forwardService(c *fiber.Ctx) error {
url = strings.Replace(url, "/cgi/"+ogKeyword, "", 1)
url = *service.HttpAddr + url
if tk, ok := c.Locals("nex_token").(string); ok {
c.Set(fiber.HeaderAuthorization, fmt.Sprintf("Bearer %s", tk))
} else {
c.Set(fiber.HeaderAuthorization, "")
}
log.Debug().
Str("from", ogUrl).
Str("to", url).

View File

@ -1,12 +1,15 @@
package api
import (
"git.solsynth.dev/hypernet/nexus/pkg/internal/auth"
"git.solsynth.dev/hypernet/nexus/pkg/internal/http/ws"
"github.com/gofiber/contrib/websocket"
"github.com/gofiber/fiber/v2"
)
func MapAPIs(app *fiber.App) {
app.Use(auth.ContextMiddleware)
// Some built-in public-accessible APIs
wellKnown := app.Group("/.well-known").Name("Well Known")
{
@ -18,12 +21,7 @@ func MapAPIs(app *fiber.App) {
}
// Common websocket gateway
app.Use(func(c *fiber.Ctx) error {
/*if err := exts.EnsureAuthenticated(c); err != nil {
return err
}*/
return c.Next()
}).Get("/ws", websocket.New(ws.Listen))
app.Use(auth.ValidatorMiddleware).Get("/ws", websocket.New(ws.Listen))
app.All("/inv/:command", invokeCommand)
app.All("/cgi/:service/*", forwardService)

View File

@ -2,10 +2,10 @@ package ws
import (
"git.solsynth.dev/hypernet/nexus/pkg/internal/directory"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"math/rand"
"sync"
"git.solsynth.dev/hypernet/nexus/pkg/internal/models"
"github.com/gofiber/contrib/websocket"
)
@ -14,7 +14,7 @@ var (
wsConn = make(map[uint]map[uint64]*websocket.Conn)
)
func ClientRegister(user models.Account, conn *websocket.Conn) uint64 {
func ClientRegister(user sec.UserInfo, conn *websocket.Conn) uint64 {
wsMutex.Lock()
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[uint64]*websocket.Conn)
@ -31,7 +31,7 @@ func ClientRegister(user models.Account, conn *websocket.Conn) uint64 {
return clientId
}
func ClientUnregister(user models.Account, id uint64) {
func ClientUnregister(user sec.UserInfo, id uint64) {
wsMutex.Lock()
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[uint64]*websocket.Conn)

View File

@ -1,8 +1,8 @@
package ws
import (
"git.solsynth.dev/hypernet/nexus/pkg/internal/models"
"git.solsynth.dev/hypernet/nexus/pkg/nex"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
"github.com/gofiber/contrib/websocket"
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog/log"
@ -10,7 +10,7 @@ import (
)
func Listen(c *websocket.Conn) {
user := c.Locals("user").(models.Account)
user := c.Locals("nex_user").(sec.UserInfo)
// Push connection
clientId := ClientRegister(user, c)