Skip to content

Commit

Permalink
impl auth on update user rpc
Browse files Browse the repository at this point in the history
  • Loading branch information
aradwann committed Jan 5, 2024
1 parent 892b458 commit 1c94ad5
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
44 changes: 44 additions & 0 deletions gapi/authorization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package gapi

import (
"context"
"errors"
"fmt"
"strings"

"github.com/aradwann/eenergy/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, errors.New("missing metadata")
}
values := md.Get(authorizationHeader)
if len(values) == 0 {
return nil, errors.New("missing authorization header")
}

authHeader := values[0]
fields := strings.Fields(authHeader)
if len(fields) < 2 {
return nil, errors.New("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
}
4 changes: 4 additions & 0 deletions gapi/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ func invalidArgumentError(violations []*errdetails.BadRequest_FieldViolation) er
}
return statusDetails.Err()
}
func unauthenticatedError(err error) error {

return status.Errorf(codes.Unauthenticated, "unauthorized: %s", err)
}
9 changes: 9 additions & 0 deletions gapi/rpc_update_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ import (
)

func (server *Server) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {
authPayload, err := server.authorizeUser(ctx)
if err != nil {
return nil, unauthenticatedError(err)
}

if authPayload.Username != req.GetUsername() {
return nil, status.Error(codes.PermissionDenied, "cannot update other user's info")
}

violations := validateUpdateUserRequest(req)
if violations != nil {
return nil, invalidArgumentError(violations)
Expand Down

0 comments on commit 1c94ad5

Please sign in to comment.