Skip to content

Commit

Permalink
feat: Add authorization middleware for user update endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
arya2004 committed Aug 13, 2024
1 parent 6c12f15 commit f6ff958
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
57 changes: 57 additions & 0 deletions gapi/authorization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package gapi

import (
"context"
"fmt"
"strings"

"github.com/arya2004/xyfin/token"
"google.golang.org/grpc/metadata"
)


const (
authorizationHeader = "authorization"
authorizationBearer = "bearer"
)

func (server *Server) authorizeUser(ctx context.Context) (*token.Payload, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, fmt.Errorf("missing metadata")
}

values := md.Get(authorizationHeader)
if len(values) == 0 {
return nil, fmt.Errorf("missing authorization header")
}

authHeader := values[0]
fields := strings.Fields(authHeader)
if len(fields) < 2 {
return nil, fmt.Errorf("invalid authorization header format")
}

authType := strings.ToLower(fields[0])
if authType != authorizationBearer {
return nil, fmt.Errorf("unsupported authorization type: %s", authType)
}

accessToken := fields[1]
payload, err := server.tokenMaker.VerifyToken(accessToken)
if err != nil {
return nil, fmt.Errorf("invalid access token: %s", err)
}


return payload, nil
}

func hasPermission(userRole string, accessibleRoles []string) bool {
for _, role := range accessibleRoles {
if userRole == role {
return true
}
}
return false
}
9 changes: 9 additions & 0 deletions gapi/rpc_update_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@ import (

func (server *Server) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {

authPayload, err := server.authorizeUser(ctx)
if err != nil {
return nil, validators.UnauthenticatedError(err)
}

violations := validateUpdateUserRequest(req)
if violations != nil {
return nil, validators.InvalidArgumentError(violations)
}

if authPayload.Username != req.GetUsername() {
return nil, status.Errorf(codes.PermissionDenied, "cannot update other users")
}



arg := db.UpdateUserParams{
Expand Down

0 comments on commit f6ff958

Please sign in to comment.