Skip to content

Commit

Permalink
impl RBAC
Browse files Browse the repository at this point in the history
  • Loading branch information
aradwann committed Feb 3, 2024
1 parent bd65200 commit 976c031
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
16 changes: 15 additions & 1 deletion gapi/authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const (
authorizationBearer = "bearer"
)

func (server *Server) authorizeUser(ctx context.Context) (*token.Payload, error) {
func (server *Server) authorizeUser(ctx context.Context, accessibleRoles []string) (*token.Payload, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errors.New("missing metadata")
Expand All @@ -40,5 +40,19 @@ func (server *Server) authorizeUser(ctx context.Context) (*token.Payload, error)
if err != nil {
return nil, fmt.Errorf("invalid access token %s", err)
}

if !hasPermission(payload.Role, accessibleRoles) {
return nil, errors.New("permission denied")
}

return payload, nil
}

func hasPermission(userRole string, accessibleRoles []string) bool {
for _, role := range accessibleRoles {
if userRole == role {
return true
}
}
return false
}
1 change: 1 addition & 0 deletions gapi/rpc_create_user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func randomUser(t *testing.T) (user db.User, password string) {
HashedPassword: hashedPassword,
FullName: util.RandomOwner(),
Email: util.RandomEmail(),
Role: util.GeneratorRole,
}
return
}
Expand Down
2 changes: 1 addition & 1 deletion gapi/rpc_update_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
)

func (server *Server) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {
authPayload, err := server.authorizeUser(ctx)
authPayload, err := server.authorizeUser(ctx, []string{util.AdminRole, util.GeneratorRole})
if err != nil {
return nil, unauthenticatedError(err)
}
Expand Down

0 comments on commit 976c031

Please sign in to comment.