⬆️ Upgrade Passport and use Hyper SDK

This commit is contained in:
LittleSheep 2024-06-22 12:29:20 +08:00
parent b951cd2696
commit 72299c810b
13 changed files with 137 additions and 172 deletions

91
.idea/workspace.xml generated
View File

@ -4,35 +4,40 @@
<option name="autoReloadType" value="ALL" />
</component>
<component name="ChangeListManager">
<list default="true" id="18dd0d68-b4b8-40db-9734-9119b5c848bd" name="更改" comment=":bug: Fix uuid duplicate when link exists">
<change afterPath="$PROJECT_DIR$/pkg/internal/gap/net.go" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pkg/internal/grpc/health.go" afterDir="false" />
<list default="true" id="18dd0d68-b4b8-40db-9734-9119b5c848bd" name="更改" comment="&#10;:sparkles: Add health check">
<change afterPath="$PROJECT_DIR$/pkg/internal/gap/client.go" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pkg/internal/server/api/index.go" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pkg/internal/server/exts/auth.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/go.mod" beforeDir="false" afterPath="$PROJECT_DIR$/go.mod" afterDir="false" />
<change beforePath="$PROJECT_DIR$/go.sum" beforeDir="false" afterPath="$PROJECT_DIR$/go.sum" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/database/migrator.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/database/migrator.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/gap/server.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/gap/server.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/attachments.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/attachments.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/client.go" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/grpc/server.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/server.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/attachments_api.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/attachments_api.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/auth.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/attachments.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/attachments.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/attachments_api.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/api/attachments_api.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/auth.go" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/startup.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/server.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/utils.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/exts/utils.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/server/well_known_api.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/server/api/well_known_api.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/auth.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/auth.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/recycler.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/recycler.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/uploader.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/uploader.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/main.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/main.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/settings.toml" beforeDir="false" afterPath="$PROJECT_DIR$/settings.toml" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Go File" />
</list>
</option>
</component>
<component name="GOROOT" url="file:///opt/homebrew/opt/go/libexec" />
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProblemsViewState">
<option name="selectedTabId" value="ProjectErrors" />
</component>
<component name="ProjectColorInfo">{
&quot;customColor&quot;: &quot;&quot;,
&quot;associatedIndex&quot;: 7
@ -42,25 +47,27 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;Go Build.Backend.executor&quot;: &quot;Run&quot;,
&quot;Go 构建.Backend.executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.go.formatter.settings.were.checked&quot;: &quot;true&quot;,
&quot;RunOnceActivity.go.migrated.go.modules.settings&quot;: &quot;true&quot;,
&quot;RunOnceActivity.go.modules.automatic.dependencies.download&quot;: &quot;true&quot;,
&quot;RunOnceActivity.go.modules.go.list.on.any.changes.was.set&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;features/consul&quot;,
&quot;go.import.settings.migrated&quot;: &quot;true&quot;,
&quot;go.sdk.automatically.set&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;/Users/littlesheep/Documents/Projects/Hydrogen/Paperclip/pkg/internal/grpc&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.lookFeel&quot;
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"DefaultGoTemplateProperty": "Go File",
"Go Build.Backend.executor": "Run",
"Go 构建.Backend.executor": "Run",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.go.formatter.settings.were.checked": "true",
"RunOnceActivity.go.migrated.go.modules.settings": "true",
"RunOnceActivity.go.modules.automatic.dependencies.download": "true",
"RunOnceActivity.go.modules.go.list.on.any.changes.was.set": "true",
"git-widget-placeholder": "features/consul",
"go.import.settings.migrated": "true",
"go.sdk.automatically.set": "true",
"last_opened_file_path": "/Users/littlesheep/Documents/Projects/Hydrogen/Paperclip/pkg/internal/grpc",
"node.js.detected.package.eslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"run.code.analysis.last.selected.profile": "pProject Default",
"settings.editor.selected.configurable": "preferences.lookFeel"
}
}</component>
}]]></component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/pkg/internal/grpc" />
@ -68,6 +75,8 @@
<recent name="$PROJECT_DIR$/pkg/internal" />
</key>
<key name="MoveFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/pkg/internal/server/exts" />
<recent name="$PROJECT_DIR$/pkg/internal/server/api" />
<recent name="$PROJECT_DIR$/pkg" />
<recent name="$PROJECT_DIR$/pkg/internal" />
</key>
@ -87,8 +96,8 @@
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-gosdk-33c477a475b1-e0158606a674-org.jetbrains.plugins.go.sharedIndexes.bundled-GO-241.17890.21" />
<option value="bundled-js-predefined-1d06a55b98c1-0b3e54e931b4-JavaScript-GO-241.17890.21" />
<option value="bundled-gosdk-33c477a475b1-e0158606a674-org.jetbrains.plugins.go.sharedIndexes.bundled-GO-241.18034.61" />
<option value="bundled-js-predefined-1d06a55b98c1-0b3e54e931b4-JavaScript-GO-241.18034.61" />
</set>
</attachedChunks>
</component>
@ -96,12 +105,24 @@
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value=":sparkles: Upload attachment requires permission check" />
<MESSAGE value=":sparkles: Provide a faster check attachment exists grpc method" />
<MESSAGE value=":truck: Update url mapping" />
<MESSAGE value=":bug: Fix uuid duplicate when link exists" />
<option name="LAST_COMMIT_MESSAGE" value=":bug: Fix uuid duplicate when link exists" />
<MESSAGE value="&#10;:sparkles: Add health check" />
<option name="LAST_COMMIT_MESSAGE" value="&#10;:sparkles: Add health check" />
</component>
<component name="VgoProject">
<settings-migrated>true</settings-migrated>

14
go.sum
View File

@ -1,5 +1,3 @@
git.solsynth.dev/hydrogen/passport v0.0.0-20240517121420-1e2d5e9f9d87 h1:r+x72tRB9LTJFH3F2rIKydQUXREc7lgxITDnjfFWwGw=
git.solsynth.dev/hydrogen/passport v0.0.0-20240517121420-1e2d5e9f9d87/go.mod h1:mEcDEKashAh3jvoGDbNLefK+HgsJaMj4xEc6vkLZ+Zc=
git.solsynth.dev/hydrogen/passport v0.0.0-20240622041415-c37a55b88b50 h1:DD7aOr4TkwJN0gUGf0zBgj77s9f6ozCuLB2tQjomkK0=
git.solsynth.dev/hydrogen/passport v0.0.0-20240622041415-c37a55b88b50/go.mod h1:XTNEOv75sZI52sNgpum7Z/tgYmlRcHfK7VdhyV7kc0w=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
@ -300,8 +298,7 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY=
golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI=
@ -316,8 +313,7 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -366,8 +362,7 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
@ -376,8 +371,7 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 h1:NnYq6UN9ReLM9/Y01KWNOWyI5xQ9kbIms5GGJVwS/Yc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 h1:1GBuWVLM/KMVUv1t1En5Gs+gFZCNd360GGb4sSxtrhU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0=
google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY=
google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg=

View File

@ -0,0 +1,12 @@
package gap
import (
"git.solsynth.dev/hydrogen/passport/pkg/hyper"
"github.com/spf13/viper"
)
var H *hyper.HyperConn
func NewHyperClient() {
H = hyper.NewHyperConn(viper.GetString("consul.addr"))
}

View File

@ -7,8 +7,6 @@ import (
"github.com/hashicorp/consul/api"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func Register() error {
@ -40,12 +38,3 @@ func Register() error {
return client.Agent().ServiceRegister(registration)
}
func DiscoverPassport() (*grpc.ClientConn, error) {
target := fmt.Sprintf("consul://%s/Hydrogen.Passport", viper.GetString("consul.addr"))
return grpc.NewClient(
target,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
)
}

View File

@ -1,11 +1,10 @@
package server
package api
import (
"context"
"fmt"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/database"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/grpc"
"git.solsynth.dev/hydrogen/passport/pkg/grpc/proto"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/gap"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/server/exts"
"net/url"
"path/filepath"
@ -73,7 +72,7 @@ func getAttachmentMeta(c *fiber.Ctx) error {
}
func createAttachment(c *fiber.Ctx) error {
user := c.Locals("principal").(models.Account)
user := c.Locals("user").(models.Account)
destName := c.Query("destination", viper.GetString("preferred_destination"))
@ -91,18 +90,8 @@ func createAttachment(c *fiber.Ctx) error {
return err
}
requiredPerm, _ := jsoniter.Marshal(file.Size)
if result, err := grpc.Auth.CheckPerm(context.Background(), &proto.CheckPermRequest{
Token: c.Locals("token").(string),
Key: "CreatePaperclipAttachments",
Value: requiredPerm,
}); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("failed to check permission: %v", err))
} else if !result.GetIsValid() {
return fiber.NewError(
fiber.StatusForbidden,
fmt.Sprintf("requires permission CreatePaperclipAttachments equals or greater than %d", file.Size),
)
if err := gap.H.EnsureGrantedPerm(c, "CreatePaperclipAttachments", file.Size); err != nil {
return err
}
usermeta := make(map[string]any)
@ -137,7 +126,11 @@ func createAttachment(c *fiber.Ctx) error {
func updateAttachmentMeta(c *fiber.Ctx) error {
id, _ := c.ParamsInt("id", 0)
user := c.Locals("principal").(models.Account)
user := c.Locals("user").(models.Account)
if err := gap.H.EnsureAuthenticated(c); err != nil {
return err
}
var data struct {
Alternative string `json:"alt"`
@ -146,7 +139,7 @@ func updateAttachmentMeta(c *fiber.Ctx) error {
IsMature bool `json:"is_mature"`
}
if err := BindAndValidate(c, &data); err != nil {
if err := exts.BindAndValidate(c, &data); err != nil {
return err
}
@ -172,7 +165,11 @@ func updateAttachmentMeta(c *fiber.Ctx) error {
func deleteAttachment(c *fiber.Ctx) error {
id, _ := c.ParamsInt("id", 0)
user := c.Locals("principal").(models.Account)
user := c.Locals("user").(models.Account)
if err := gap.H.EnsureAuthenticated(c); err != nil {
return err
}
attachment, err := services.GetAttachmentByID(uint(id))
if err != nil {

View File

@ -0,0 +1,17 @@
package api
import "github.com/gofiber/fiber/v2"
func MapAPIs(app *fiber.App) {
app.Get("/.well-known", getMetadata)
app.Get("/.well-known/destinations", getDestinations)
api := app.Group("/api").Name("API")
{
api.Get("/attachments/:id/meta", getAttachmentMeta)
api.Get("/attachments/:id", openAttachment)
api.Post("/attachments", createAttachment)
api.Put("/attachments/:id", updateAttachmentMeta)
api.Delete("/attachments/:id", deleteAttachment)
}
}

View File

@ -1,4 +1,4 @@
package server
package api
import (
"github.com/gofiber/fiber/v2"

View File

@ -1,50 +0,0 @@
package server
import (
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/services"
"github.com/gofiber/fiber/v2"
"strings"
)
func authMiddleware(c *fiber.Ctx) error {
var token string
if cookie := c.Cookies(services.CookieAccessKey); len(cookie) > 0 {
token = cookie
}
if header := c.Get(fiber.HeaderAuthorization); len(header) > 0 {
tk := strings.Replace(header, "Bearer", "", 1)
token = strings.TrimSpace(tk)
}
c.Locals("token", token)
if err := authFunc(c); err != nil {
return err
}
return c.Next()
}
func authFunc(c *fiber.Ctx, overrides ...string) error {
var token string
if len(overrides) > 0 {
token = overrides[0]
} else {
if tk, ok := c.Locals("token").(string); !ok {
return fiber.NewError(fiber.StatusUnauthorized)
} else {
token = tk
}
}
rtk := c.Cookies(services.CookieRefreshKey)
if user, atk, rtk, err := services.Authenticate(token, rtk); err == nil {
if atk != token {
services.SetJwtCookieSet(c, atk, rtk)
}
c.Locals("principal", user)
return nil
} else {
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
}
}

View File

@ -0,0 +1,19 @@
package exts
import (
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/services"
"git.solsynth.dev/hydrogen/passport/pkg/proto"
"github.com/gofiber/fiber/v2"
)
func LinkAccountMiddleware(c *fiber.Ctx) error {
if val, ok := c.Locals("p_user").(*proto.Userinfo); ok {
if account, err := services.LinkAccount(val); err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} else {
c.Locals("user", account)
}
}
return c.Next()
}

View File

@ -1,4 +1,4 @@
package server
package exts
import (
"github.com/go-playground/validator/v10"

View File

@ -1,6 +1,9 @@
package server
import (
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/gap"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/server/api"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/server/exts"
"strings"
"github.com/gofiber/fiber/v2"
@ -49,17 +52,10 @@ func NewServer() {
Output: log.Logger,
}))
A.Get("/.well-known", getMetadata)
A.Get("/.well-known/destinations", getDestinations)
A.Use(gap.H.AuthMiddleware)
A.Use(exts.LinkAccountMiddleware)
api := A.Group("/api").Name("API")
{
api.Get("/attachments/:id/meta", getAttachmentMeta)
api.Get("/attachments/:id", openAttachment)
api.Post("/attachments", authMiddleware, createAttachment)
api.Put("/attachments/:id", authMiddleware, updateAttachmentMeta)
api.Delete("/attachments/:id", authMiddleware, deleteAttachment)
}
api.MapAPIs(A)
}
func Listen() {

View File

@ -1,18 +1,13 @@
package services
import (
"context"
"errors"
"fmt"
"reflect"
"time"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/database"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/gap"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/models"
"git.solsynth.dev/hydrogen/passport/pkg/grpc/proto"
"git.solsynth.dev/hydrogen/passport/pkg/proto"
"gorm.io/gorm"
"reflect"
)
func LinkAccount(userinfo *proto.Userinfo) (models.Account, error) {
@ -54,30 +49,3 @@ func LinkAccount(userinfo *proto.Userinfo) (models.Account, error) {
return account, err
}
func Authenticate(atk, rtk string) (models.Account, string, string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
var err error
var user models.Account
pc, err := gap.DiscoverPassport()
if err != nil {
return user, atk, rtk, fmt.Errorf("authenticate services was not available")
}
reply, err := proto.NewAuthClient(pc).Authenticate(ctx, &proto.AuthRequest{
AccessToken: atk,
RefreshToken: &rtk,
})
if err != nil {
return user, reply.GetAccessToken(), reply.GetRefreshToken(), err
} else if !reply.IsValid {
return user, reply.GetAccessToken(), reply.GetRefreshToken(), fmt.Errorf("invalid authorization context")
}
user, err = LinkAccount(reply.Userinfo)
return user, reply.GetAccessToken(), reply.GetRefreshToken(), err
}

View File

@ -46,6 +46,8 @@ func main() {
// Connect other services
if err := gap.Register(); err != nil {
log.Error().Err(err).Msg("An error occurred when registering service to gateway...")
} else {
gap.NewHyperClient()
}
// Configure timed tasks