-
Notifications
You must be signed in to change notification settings - Fork 70
Add src users clean to src-cli
#826
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
e6837ef
register users clean
DaedalusG 4104aae
added usage statistics to User Node type
DaedalusG 5bb1f27
mark
DaedalusG 74a3d43
define worker function for user removal
DaedalusG 3b0aa52
before implementing time.Parse(time.RFC3339, payload.UsageStatistics.…
DaedalusG c8b390c
now computes time since last active
DaedalusG 8941c36
added utility function structure
DaedalusG 3a5d5c5
initialize array to store users to be deleted
DaedalusG 25301b8
working query to remove users and flags
DaedalusG c6d6bc8
added a user verification to command
DaedalusG a4cfba4
corrects logic around removeNeverActive flag
DaedalusG 1093e14
better warning messaging
DaedalusG 7f399eb
formating warning
DaedalusG febdc29
add flag to skip verify check
DaedalusG 9fad30c
commented out placeholder code and added TODO comments
DaedalusG 7a6ea3a
addressed many review concerns, added lower bound on -days flag, made…
DaedalusG e11fede
Update cmd/src/users.go
DaedalusG be8a1c5
Update cmd/src/users_clean.go
DaedalusG 01300f6
Update cmd/src/users_clean.go
DaedalusG c642024
correct variable naming bug
DaedalusG 918e36f
remove unused params in get users query
DaedalusG b396f32
Update cmd/src/users.go
DaedalusG d170645
admins must be explcitly removed
DaedalusG 3065b9f
commit dependencies
DaedalusG 010ff3b
camel case
DaedalusG 817d78e
ensure clean doesnt clean the user issuing the command
DaedalusG File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "flag" | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/jedib0t/go-pretty/v6/table" | ||
|
|
||
| "github.com/sourcegraph/src-cli/internal/api" | ||
| ) | ||
|
|
||
| func init() { | ||
| usage := ` | ||
| This command removes users from a Sourcegraph instance who have been inactive for 60 or more days. Admin accounts are omitted by default. | ||
|
|
||
| Examples: | ||
|
|
||
| $ src users clean -days 182 | ||
|
|
||
| $ src users clean -remove-admin -remove-never-active | ||
| ` | ||
|
|
||
| flagSet := flag.NewFlagSet("clean", flag.ExitOnError) | ||
| usageFunc := func() { | ||
| fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src users %s':\n", flagSet.Name()) | ||
| flagSet.PrintDefaults() | ||
| fmt.Println(usage) | ||
| } | ||
| var ( | ||
| daysToDelete = flagSet.Int("days", 60, "Days threshold on which to remove users, must be 60 days or greater and defaults to this value ") | ||
| removeAdmin = flagSet.Bool("remove-admin", false, "clean admin accounts") | ||
| removeNoLastActive = flagSet.Bool("remove-never-active", false, "removes users with null lastActive value") | ||
| skipConfirmation = flagSet.Bool("force", false, "skips user confirmation step allowing programmatic use") | ||
| apiFlags = api.NewFlags(flagSet) | ||
| ) | ||
|
|
||
| handler := func(args []string) error { | ||
| if err := flagSet.Parse(args); err != nil { | ||
| return err | ||
| } | ||
| if *daysToDelete < 60 { | ||
| fmt.Println("-days flag must be set to 60 or greater") | ||
| return nil | ||
| } | ||
|
|
||
| ctx := context.Background() | ||
| client := cfg.apiClient(apiFlags, flagSet.Output()) | ||
|
|
||
| currentUserQuery := ` | ||
| query { | ||
| currentUser { | ||
| username | ||
| } | ||
| } | ||
| ` | ||
| var currentUserResult struct { | ||
| Data struct { | ||
| CurrentUser struct { | ||
| Username string | ||
| } | ||
| } | ||
| } | ||
| if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(currentUserQuery, nil).DoRaw(context.Background(), ¤tUserResult); err != nil || !ok { | ||
| return err | ||
| } | ||
| fmt.Println(currentUserResult) | ||
|
|
||
| usersQuery := ` | ||
| query Users() { | ||
| users() { | ||
| nodes { | ||
| ...UserFields | ||
| } | ||
| } | ||
| } | ||
| ` + userFragment | ||
|
|
||
| // get users to delete | ||
| var usersResult struct { | ||
| Users struct { | ||
| Nodes []User | ||
| } | ||
| } | ||
| if ok, err := client.NewRequest(usersQuery, nil).Do(ctx, &usersResult); err != nil || !ok { | ||
| return err | ||
| } | ||
| fmt.Println(usersResult) | ||
|
|
||
| usersToDelete := make([]UserToDelete, 0) | ||
| for _, user := range usersResult.Users.Nodes { | ||
| daysSinceLastUse, wasLastActive, err := computeDaysSinceLastUse(user) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| // never remove user issuing command | ||
| if user.Username == currentUserResult.Data.CurrentUser.Username { | ||
| continue | ||
| } | ||
| if !wasLastActive && !*removeNoLastActive { | ||
| continue | ||
| } | ||
| if !*removeAdmin && user.SiteAdmin { | ||
| continue | ||
| } | ||
| if daysSinceLastUse <= *daysToDelete && wasLastActive { | ||
| continue | ||
| } | ||
| deleteUser := UserToDelete{user, daysSinceLastUse} | ||
|
|
||
| usersToDelete = append(usersToDelete, deleteUser) | ||
| } | ||
|
|
||
| if *skipConfirmation { | ||
| for _, user := range usersToDelete { | ||
| if err := removeUser(user.User, client, ctx); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // confirm and remove users | ||
| if confirmed, _ := confirmUserRemoval(usersToDelete); !confirmed { | ||
| fmt.Println("Aborting removal") | ||
| return nil | ||
| } else { | ||
| fmt.Println("REMOVING USERS") | ||
| for _, user := range usersToDelete { | ||
| if err := removeUser(user.User, client, ctx); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // Register the command. | ||
| usersCommands = append(usersCommands, &command{ | ||
| flagSet: flagSet, | ||
| handler: handler, | ||
| usageFunc: usageFunc, | ||
| }) | ||
| } | ||
|
|
||
| // computes days since last usage from current day and time and UsageStatistics.LastActiveTime, uses time.Parse | ||
| func computeDaysSinceLastUse(user User) (timeDiff int, wasLastActive bool, _ error) { | ||
| // handle for null lastActiveTime returned from | ||
| if user.UsageStatistics.LastActiveTime == "" { | ||
| wasLastActive = false | ||
| return 0, wasLastActive, nil | ||
| } | ||
| timeLast, err := time.Parse(time.RFC3339, user.UsageStatistics.LastActiveTime) | ||
| if err != nil { | ||
| return 0, false, err | ||
| } | ||
| timeDiff = int(time.Since(timeLast).Hours() / 24) | ||
|
|
||
| return timeDiff, true, err | ||
| } | ||
|
|
||
| // Issue graphQL api request to remove user | ||
| func removeUser(user User, client api.Client, ctx context.Context) error { | ||
| query := `mutation DeleteUser($user: ID!) { | ||
| deleteUser(user: $user) { | ||
| alwaysNil | ||
| } | ||
| }` | ||
| vars := map[string]interface{}{ | ||
| "user": user.ID, | ||
| } | ||
| if ok, err := client.NewRequest(query, vars).Do(ctx, nil); err != nil || !ok { | ||
| return err | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| type UserToDelete struct { | ||
| User User | ||
| DaysSinceLastUse int | ||
| } | ||
|
|
||
| // Verify user wants to remove users with table of users and a command prompt for [y/N] | ||
| func confirmUserRemoval(usersToRemove []UserToDelete) (bool, error) { | ||
| fmt.Printf("Users to remove from instance at %s\n", cfg.Endpoint) | ||
| t := table.NewWriter() | ||
| t.SetOutputMirror(os.Stdout) | ||
| t.AppendHeader(table.Row{"Username", "Email", "Days Since Last Active"}) | ||
| for _, user := range usersToRemove { | ||
| if len(user.User.Emails) > 0 { | ||
| t.AppendRow([]interface{}{user.User.Username, user.User.Emails[0].Email, user.DaysSinceLastUse}) | ||
| t.AppendSeparator() | ||
| } else { | ||
| t.AppendRow([]interface{}{user.User.Username, "", user.DaysSinceLastUse}) | ||
| t.AppendSeparator() | ||
| } | ||
| } | ||
| t.SetStyle(table.StyleRounded) | ||
| t.Render() | ||
| input := "" | ||
| for strings.ToLower(input) != "y" && strings.ToLower(input) != "n" { | ||
| fmt.Printf("Do you wish to proceed with user removal [y/N]: ") | ||
| if _, err := fmt.Scanln(&input); err != nil { | ||
| return false, err | ||
| } | ||
| } | ||
| return strings.ToLower(input) == "y", nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.