Skip to content

Commit

Permalink
Add session info to access log
Browse files Browse the repository at this point in the history
  • Loading branch information
zensh committed Jul 27, 2023
1 parent a3262d5 commit 37d2814
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/teambition/gear"
"github.com/yiwen-ai/yiwen-api/src/conf"
"github.com/yiwen-ai/yiwen-api/src/logging"
"github.com/yiwen-ai/yiwen-api/src/util"
)

Expand Down Expand Up @@ -51,9 +52,12 @@ func (m AuthLevel) Auth(ctx *gear.Context) error {
return gear.ErrUnauthorized.From(err)
}

log := logging.FromCtx(ctx)
log["uid"] = sess.UserID
if l > 1 && !sess.HasToken() {
return gear.ErrUnauthorized.WithMsg("invalid token")
}
log["aud"] = sess.AppID

ctxHeader := make(http.Header)
// inject auth headers into context for base service
Expand Down
5 changes: 2 additions & 3 deletions src/util/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,11 @@ func RequestCBOR(ctx context.Context, cli *http.Client, method, api string, inpu

data, err := io.ReadAll(resp.Body)
if resp.StatusCode > 206 || err != nil {
str, _ := cbor.Diagnose(data)
return fmt.Errorf("RequestCBOR %q failed, code: %d, error: %v, body: %s",
api, resp.StatusCode, err, string(data))
api, resp.StatusCode, err, str)
}

// fmt.Printf("%x\n", data)

return cbor.Unmarshal(data, output)
}

Expand Down
20 changes: 20 additions & 0 deletions src/util/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ var ZeroID ID
var JARVIS ID = mustParseID("0000000000000jarvis0") // system user
var ANON ID = mustParseID("000000000000000anon0") // anonymous user

func NewID() ID {
return ID(xid.New())
}

func ParseID(s string) (ID, error) {
id, err := xid.FromString(s)
if err != nil {
Expand All @@ -33,6 +37,10 @@ func mustParseID(s string) ID {

type ID xid.ID

func (id ID) Unwrap() xid.ID {
return xid.ID(id)
}

func (id *ID) String() string {
if id == nil {
return ""
Expand Down Expand Up @@ -88,6 +96,14 @@ func (id *ID) UnmarshalText(data []byte) error {

type UUID uuid.UUID

func NewUUID() UUID {
id, err := uuid.NewUUID()
if err != nil {
panic(err)
}
return UUID(id)
}

func (id *UUID) String() string {
if id == nil {
return ""
Expand All @@ -96,6 +112,10 @@ func (id *UUID) String() string {
return uuid.UUID(*id).String()
}

func (id UUID) Unwrap() uuid.UUID {
return uuid.UUID(id)
}

func (id UUID) Base64() string {
return base64.RawURLEncoding.EncodeToString(id[:])
}
Expand Down

0 comments on commit 37d2814

Please sign in to comment.