mirror of
				https://codeberg.org/forgejo/forgejo.git
				synced 2025-11-03 16:01:11 +00:00 
			
		
		
		
	urfave/cli v2 will eventually become unmaintained, switch over to v3 which is the latest supported version. Note: the `docs` command would be a lot of work to restore with v3 ([the package is still in alpha](https://github.com/urfave/cli-docs)) An alternative to avoid a breaking change would be to not upgrade from v2 to v3 for that reason alone. Note: these commits were cherry-picked from https://code.forgejo.org/forgefriends/forgefriends Note: it is best reviewed side by side with no display of whitespace changes (there are a lot of those when converting vars to func). - a few functional changes were necessary and are noted in context in the file changes tab - https://cli.urfave.org/migrate-v2-to-v3/ upgrade instructions were followed in the most minimal way possible - upgrade gof3 to v3.10.8 which includes and upgrade from urfave/cli v2 to urfave/cli v3 - upgrade gitlab.com/gitlab-org/api/client-go v0.129.0 because it is an indirect dependency of gof3 and requires a change because of a deprecated field that otherwise triggers a lint error but nothing else otherwise - verified that the [script](https://codeberg.org/forgejo/docs/src/branch/next/scripts/cli-docs.sh) that generates the [CLI documentation](https://codeberg.org/forgejo/docs/src/branch/next/scripts/cli-docs.sh) still works. There are cosmetic differences and the **help** subcommand is no longer advertised (although it is still supported) but the `--help` option is advertised as expected so it is fine. - end-to-end tests [passed](https://code.forgejo.org/forgejo/end-to-end/pulls/667) (they use the Forgejo CLI to some extent) ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - I added test coverage for Go changes... - [ ] in their respective `*_test.go` for unit tests. - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I added test coverage for JavaScript changes... - [ ] in `web_src/js/*.test.js` if it can be unit tested. - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. ### Release notes - [ ] I do not want this change to show in the release notes. - [ ] I want the title to show in the release notes with a link to this pull request. - [x] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. <!--start release-notes-assistant--> ## Release notes <!--URL:https://codeberg.org/forgejo/forgejo--> - Breaking features - [PR](https://codeberg.org/forgejo/forgejo/pulls/8035): <!--number 8035 --><!--line 0 --><!--description VGhlIGBmb3JnZWpvIGRvY3NgIGNvbW1hbmQgaXMgZGVwcmVjYXRlZCBhbmQgQ0xJIGVycm9ycyBhcmUgbm93IGRpc3BsYXllZCBvbiBzdGRlcnIgaW5zdGVhZCBvZiBzdGRvdXQuIFRoZXNlIGJyZWFraW5nIGNoYW5nZXMgaGFwcGVuZWQgYmVjYXVzZSB0aGUgcGFja2FnZSB1c2VkIHRvIHBhcnNlIHRoZSBjb21tYW5kIGxpbmUgYXJndW1lbnRzIHdhcyBbdXBncmFkZWQgZnJvbSB2MiB0byB2M10oaHR0cHM6Ly9jbGkudXJmYXZlLm9yZy9taWdyYXRlLXYyLXRvLXYzLykuIEEgW3NlcGFyYXRlIHByb2plY3Qgd2FzIGluaXRpYXRlZF0oaHR0cHM6Ly9naXRodWIuY29tL3VyZmF2ZS9jbGktZG9jcykgdG8gcmUtaW1wbGVtZW50IHRoZSBgZG9jc2AgY29tbWFuZCwgYnV0IGl0IGlzIG5vdCB5ZXQgcHJvZHVjdGlvbiByZWFkeS4=-->The `forgejo docs` command is deprecated and CLI errors are now displayed on stderr instead of stdout. These breaking changes happened because the package used to parse the command line arguments was [upgraded from v2 to v3](https://cli.urfave.org/migrate-v2-to-v3/). A [separate project was initiated](https://github.com/urfave/cli-docs) to re-implement the `docs` command, but it is not yet production ready.<!--description--> <!--end release-notes-assistant--> Co-authored-by: limiting-factor <limiting-factor@posteo.com> Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/8035 Reviewed-by: Gusted <gusted@noreply.codeberg.org>
		
			
				
	
	
		
			214 lines
		
	
	
	
		
			6 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			214 lines
		
	
	
	
		
			6 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
// Copyright 2023 The Gitea Authors. All rights reserved.
 | 
						|
// SPDX-License-Identifier: MIT
 | 
						|
 | 
						|
package cmd
 | 
						|
 | 
						|
import (
 | 
						|
	"context"
 | 
						|
	"errors"
 | 
						|
	"fmt"
 | 
						|
	"strings"
 | 
						|
 | 
						|
	auth_model "forgejo.org/models/auth"
 | 
						|
	"forgejo.org/models/db"
 | 
						|
	user_model "forgejo.org/models/user"
 | 
						|
	pwd "forgejo.org/modules/auth/password"
 | 
						|
	"forgejo.org/modules/optional"
 | 
						|
	"forgejo.org/modules/setting"
 | 
						|
 | 
						|
	"github.com/urfave/cli/v3"
 | 
						|
)
 | 
						|
 | 
						|
func microcmdUserCreate() *cli.Command {
 | 
						|
	return &cli.Command{
 | 
						|
		Name:   "create",
 | 
						|
		Usage:  "Create a new user in database",
 | 
						|
		Action: runCreateUser,
 | 
						|
		Flags: []cli.Flag{
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "name",
 | 
						|
				Usage: "Username. DEPRECATED: use username instead",
 | 
						|
			},
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "username",
 | 
						|
				Usage: "Username",
 | 
						|
			},
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "password",
 | 
						|
				Usage: "User password",
 | 
						|
			},
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "email",
 | 
						|
				Usage: "User email address",
 | 
						|
			},
 | 
						|
			&cli.BoolFlag{
 | 
						|
				Name:  "admin",
 | 
						|
				Usage: "User is an admin",
 | 
						|
			},
 | 
						|
			&cli.BoolFlag{
 | 
						|
				Name:  "random-password",
 | 
						|
				Usage: "Generate a random password for the user",
 | 
						|
			},
 | 
						|
			&cli.BoolFlag{
 | 
						|
				Name:  "must-change-password",
 | 
						|
				Usage: "Set this option to false to prevent forcing the user to change their password after initial login",
 | 
						|
				Value: true,
 | 
						|
			},
 | 
						|
			&cli.IntFlag{
 | 
						|
				Name:  "random-password-length",
 | 
						|
				Usage: "Length of the random password to be generated",
 | 
						|
				Value: 12,
 | 
						|
			},
 | 
						|
			&cli.BoolFlag{
 | 
						|
				Name:  "access-token",
 | 
						|
				Usage: "Generate access token for the user",
 | 
						|
			},
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "access-token-name",
 | 
						|
				Usage: `Name of the generated access token`,
 | 
						|
				Value: "gitea-admin",
 | 
						|
			},
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "access-token-scopes",
 | 
						|
				Usage: `Scopes of the generated access token, comma separated. Examples: "all", "public-only,read:issue", "write:repository,write:user"`,
 | 
						|
				Value: "all",
 | 
						|
			},
 | 
						|
			&cli.BoolFlag{
 | 
						|
				Name:  "restricted",
 | 
						|
				Usage: "Make a restricted user account",
 | 
						|
			},
 | 
						|
			&cli.StringFlag{
 | 
						|
				Name:  "fullname",
 | 
						|
				Usage: `The full, human-readable name of the user`,
 | 
						|
			},
 | 
						|
		},
 | 
						|
	}
 | 
						|
}
 | 
						|
 | 
						|
func runCreateUser(ctx context.Context, c *cli.Command) error {
 | 
						|
	// this command highly depends on the many setting options (create org, visibility, etc.), so it must have a full setting load first
 | 
						|
	// duplicate setting loading should be safe at the moment, but it should be refactored & improved in the future.
 | 
						|
	setting.LoadSettings()
 | 
						|
 | 
						|
	if err := argsSet(c, "email"); err != nil {
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	if c.IsSet("name") && c.IsSet("username") {
 | 
						|
		return errors.New("cannot set both --name and --username flags")
 | 
						|
	}
 | 
						|
	if !c.IsSet("name") && !c.IsSet("username") {
 | 
						|
		return errors.New("one of --name or --username flags must be set")
 | 
						|
	}
 | 
						|
 | 
						|
	if c.IsSet("password") && c.IsSet("random-password") {
 | 
						|
		return errors.New("cannot set both -random-password and -password flags")
 | 
						|
	}
 | 
						|
 | 
						|
	var username string
 | 
						|
	if c.IsSet("username") {
 | 
						|
		username = c.String("username")
 | 
						|
	} else {
 | 
						|
		username = c.String("name")
 | 
						|
		_, _ = fmt.Fprint(c.Root().ErrWriter, "--name flag is deprecated. Use --username instead.\n")
 | 
						|
	}
 | 
						|
 | 
						|
	ctx, cancel := installSignals(ctx)
 | 
						|
	defer cancel()
 | 
						|
 | 
						|
	if err := initDB(ctx); err != nil {
 | 
						|
		return err
 | 
						|
	}
 | 
						|
 | 
						|
	var password string
 | 
						|
	if c.IsSet("password") {
 | 
						|
		password = c.String("password")
 | 
						|
	} else if c.IsSet("random-password") {
 | 
						|
		var err error
 | 
						|
		password, err = pwd.Generate(c.Int("random-password-length"))
 | 
						|
		if err != nil {
 | 
						|
			return err
 | 
						|
		}
 | 
						|
		fmt.Printf("generated random password is '%s'\n", password)
 | 
						|
	} else {
 | 
						|
		return errors.New("must set either password or random-password flag")
 | 
						|
	}
 | 
						|
 | 
						|
	isAdmin := c.Bool("admin")
 | 
						|
	mustChangePassword := true // always default to true
 | 
						|
	if c.IsSet("must-change-password") {
 | 
						|
		// if the flag is set, use the value provided by the user
 | 
						|
		mustChangePassword = c.Bool("must-change-password")
 | 
						|
	} else {
 | 
						|
		// check whether there are users in the database
 | 
						|
		hasUserRecord, err := db.IsTableNotEmpty(&user_model.User{})
 | 
						|
		if err != nil {
 | 
						|
			return fmt.Errorf("IsTableNotEmpty: %w", err)
 | 
						|
		}
 | 
						|
		if !hasUserRecord {
 | 
						|
			// if this is the first admin being created, don't force to change password (keep the old behavior)
 | 
						|
			mustChangePassword = false
 | 
						|
		}
 | 
						|
	}
 | 
						|
 | 
						|
	restricted := optional.None[bool]()
 | 
						|
 | 
						|
	if c.IsSet("restricted") {
 | 
						|
		restricted = optional.Some(c.Bool("restricted"))
 | 
						|
	}
 | 
						|
 | 
						|
	// default user visibility in app.ini
 | 
						|
	visibility := setting.Service.DefaultUserVisibilityMode
 | 
						|
 | 
						|
	u := &user_model.User{
 | 
						|
		Name:               username,
 | 
						|
		Email:              c.String("email"),
 | 
						|
		Passwd:             password,
 | 
						|
		IsAdmin:            isAdmin,
 | 
						|
		MustChangePassword: mustChangePassword,
 | 
						|
		Visibility:         visibility,
 | 
						|
		FullName:           c.String("fullname"),
 | 
						|
	}
 | 
						|
 | 
						|
	overwriteDefault := &user_model.CreateUserOverwriteOptions{
 | 
						|
		IsActive:     optional.Some(true),
 | 
						|
		IsRestricted: restricted,
 | 
						|
	}
 | 
						|
 | 
						|
	var accessTokenName string
 | 
						|
	var accessTokenScope auth_model.AccessTokenScope
 | 
						|
	if c.IsSet("access-token") {
 | 
						|
		accessTokenName = strings.TrimSpace(c.String("access-token-name"))
 | 
						|
		if accessTokenName == "" {
 | 
						|
			return errors.New("access-token-name cannot be empty")
 | 
						|
		}
 | 
						|
		var err error
 | 
						|
		accessTokenScope, err = auth_model.AccessTokenScope(c.String("access-token-scopes")).Normalize()
 | 
						|
		if err != nil {
 | 
						|
			return fmt.Errorf("invalid access token scope provided: %w", err)
 | 
						|
		}
 | 
						|
		if !accessTokenScope.HasPermissionScope() {
 | 
						|
			return errors.New("access token does not have any permission")
 | 
						|
		}
 | 
						|
	} else if c.IsSet("access-token-name") || c.IsSet("access-token-scopes") {
 | 
						|
		return errors.New("access-token-name and access-token-scopes flags are only valid when access-token flag is set")
 | 
						|
	}
 | 
						|
 | 
						|
	// arguments should be prepared before creating the user & access token, in case there is anything wrong
 | 
						|
 | 
						|
	// create the user
 | 
						|
	if err := user_model.CreateUser(ctx, u, overwriteDefault); err != nil {
 | 
						|
		return fmt.Errorf("CreateUser: %w", err)
 | 
						|
	}
 | 
						|
	fmt.Printf("New user '%s' has been successfully created!\n", username)
 | 
						|
 | 
						|
	// create the access token
 | 
						|
	if accessTokenScope != "" {
 | 
						|
		t := &auth_model.AccessToken{Name: accessTokenName, UID: u.ID, Scope: accessTokenScope}
 | 
						|
		if err := auth_model.NewAccessToken(ctx, t); err != nil {
 | 
						|
			return err
 | 
						|
		}
 | 
						|
		fmt.Printf("Access token was successfully created... %s\n", t.Token)
 | 
						|
	}
 | 
						|
	return nil
 | 
						|
}
 |