Skip to content
This repository has been archived by the owner on May 16, 2021. It is now read-only.

Commit

Permalink
Add Command For Unsetting Custom Claims
Browse files Browse the repository at this point in the history
Adds the ability to remove custom claims from the user. It is not
perfect yet, as it replaces key with null.

#20
  • Loading branch information
mainawycliffe committed Aug 18, 2020
1 parent 721de83 commit a294766
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cmd/unsetCustomClaims.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package cmd

import (
"context"
"os"

"github.com/mainawycliffe/kamanda/firebase/auth"
"github.com/mainawycliffe/kamanda/utils"
"github.com/spf13/cobra"
)

// unsetCustomClaimsCmd represents the unsetCustomClaims command
var unsetCustomClaimsCmd = &cobra.Command{
Use: "custom-claims",
Aliases: []string{"customClaims"},
Short: "Unset custom claims from a firebase user account",
Example: "kamanda users unset custom-claims --keys \"role\"",
Run: func(cmd *cobra.Command, args []string) {
keys, _ := cmd.Flags().GetStringArray("keys")
hasError := false
for _, v := range args {
user, err := auth.RemoveCustomClaimFromUser(context.Background(), v, keys)
if err != nil {
hasError = true
utils.StdOutError(os.Stderr, "Error removing custom claims for %s (%s)\n", v, user.Email)
continue
}
utils.StdOutSuccess(os.Stdout, "Successfully remove custom claims for %s (%s)\n", v, user.Email)
}
if hasError {
os.Exit(1)
}
os.Exit(0)
},
}

func init() {
unsetCmd.AddCommand(unsetCustomClaimsCmd)
unsetCustomClaimsCmd.Flags().StringArray("keys", nil, "Custom claims keys to remove")
if err := unsetCustomClaimsCmd.MarkFlagRequired("keys"); err != nil {
utils.StdOutError(os.Stderr, "%s\n", err.Error())
os.Exit(1)
}
}
20 changes: 20 additions & 0 deletions firebase/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,26 @@ func AddCustomClaimToFirebaseUser(ctx context.Context, uid string, customClaims
return nil
}

// RemoveCustomClaimFromUser remove a custom claim or custom claims from a users
// account
func RemoveCustomClaimFromUser(ctx context.Context, UID string, keys []string) (*auth.UserRecord, error) {
customClaimsToUnset := map[string]interface{}{}
for _, v := range keys {
customClaimsToUnset[v] = nil
}
client, err := firebase.Auth(ctx, "", "")
if err != nil {
return nil, fmt.Errorf("Error authenticating firebase account: %w", err)
}
params := &auth.UserToUpdate{}
params.CustomClaims(customClaimsToUnset)
user, err := client.UpdateUser(ctx, UID, params)
if err != nil {
return nil, firebase.NewError(err)
}
return user, nil
}

func DeleteFirebaseUser(ctx context.Context, uid string) error {
if uid == "" {
return fmt.Errorf("The UID of the user can not be empty")
Expand Down

0 comments on commit a294766

Please sign in to comment.