Skip to content

Commit

Permalink
extract user-agent and client-ip from grpc metadata (techschool#34)
Browse files Browse the repository at this point in the history
Co-authored-by: phamlequang <phamlequang@gmail.com>
  • Loading branch information
techschool and phamlequang authored Apr 10, 2022
1 parent 200cb89 commit 9212f74
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
43 changes: 43 additions & 0 deletions gapi/metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package gapi

import (
"context"

"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
)

const (
grpcGatewayUserAgentHeader = "grpcgateway-user-agent"
userAgentHeader = "user-agent"
xForwardedForHeader = "x-forwarded-for"
)

type Metadata struct {
UserAgent string
ClientIP string
}

func (server *Server) extractMetadata(ctx context.Context) *Metadata {
mtdt := &Metadata{}

if md, ok := metadata.FromIncomingContext(ctx); ok {
if userAgents := md.Get(grpcGatewayUserAgentHeader); len(userAgents) > 0 {
mtdt.UserAgent = userAgents[0]
}

if userAgents := md.Get(userAgentHeader); len(userAgents) > 0 {
mtdt.UserAgent = userAgents[0]
}

if clientIPs := md.Get(xForwardedForHeader); len(clientIPs) > 0 {
mtdt.ClientIP = clientIPs[0]
}
}

if p, ok := peer.FromContext(ctx); ok {
mtdt.ClientIP = p.Addr.String()
}

return mtdt
}
5 changes: 3 additions & 2 deletions gapi/rpc_login_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,13 @@ func (server *Server) LoginUser(ctx context.Context, req *pb.LoginUserRequest) (
return nil, status.Errorf(codes.Internal, "failed to create refresh token")
}

mtdt := server.extractMetadata(ctx)
session, err := server.store.CreateSession(ctx, db.CreateSessionParams{
ID: refreshPayload.ID,
Username: user.Username,
RefreshToken: refreshToken,
UserAgent: "",
ClientIp: "",
UserAgent: mtdt.UserAgent,
ClientIp: mtdt.ClientIP,
IsBlocked: false,
ExpiresAt: refreshPayload.ExpiredAt,
})
Expand Down

0 comments on commit 9212f74

Please sign in to comment.