123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797 |
- // Copyright 2016 The Gogs Authors. All rights reserved.
- // Copyright 2016 The Gitea Authors. All rights reserved.
- // Use of this source code is governed by a MIT-style
- // license that can be found in the LICENSE file.
-
- package cmd
-
- import (
- "context"
- "errors"
- "fmt"
- "os"
- "strings"
- "text/tabwriter"
-
- "code.gitea.io/gitea/models"
- "code.gitea.io/gitea/models/db"
- "code.gitea.io/gitea/models/login"
- user_model "code.gitea.io/gitea/models/user"
- "code.gitea.io/gitea/modules/git"
- "code.gitea.io/gitea/modules/graceful"
- "code.gitea.io/gitea/modules/log"
- pwd "code.gitea.io/gitea/modules/password"
- repo_module "code.gitea.io/gitea/modules/repository"
- "code.gitea.io/gitea/modules/setting"
- "code.gitea.io/gitea/modules/storage"
- auth_service "code.gitea.io/gitea/services/auth"
- "code.gitea.io/gitea/services/auth/source/oauth2"
- repo_service "code.gitea.io/gitea/services/repository"
- user_service "code.gitea.io/gitea/services/user"
-
- "github.com/urfave/cli"
- )
-
- var (
- // CmdAdmin represents the available admin sub-command.
- CmdAdmin = cli.Command{
- Name: "admin",
- Usage: "Command line interface to perform common administrative operations",
- Subcommands: []cli.Command{
- subcmdUser,
- subcmdRepoSyncReleases,
- subcmdRegenerate,
- subcmdAuth,
- subcmdSendMail,
- },
- }
-
- subcmdUser = cli.Command{
- Name: "user",
- Usage: "Modify users",
- Subcommands: []cli.Command{
- microcmdUserCreate,
- microcmdUserList,
- microcmdUserChangePassword,
- microcmdUserDelete,
- },
- }
-
- microcmdUserList = cli.Command{
- Name: "list",
- Usage: "List users",
- Action: runListUsers,
- Flags: []cli.Flag{
- cli.BoolFlag{
- Name: "admin",
- Usage: "List only admin users",
- },
- },
- }
-
- microcmdUserCreate = 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, (Default: 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",
- },
- },
- }
-
- microcmdUserChangePassword = cli.Command{
- Name: "change-password",
- Usage: "Change a user's password",
- Action: runChangePassword,
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "username,u",
- Value: "",
- Usage: "The user to change password for",
- },
- cli.StringFlag{
- Name: "password,p",
- Value: "",
- Usage: "New password to set for user",
- },
- },
- }
-
- microcmdUserDelete = cli.Command{
- Name: "delete",
- Usage: "Delete specific user by id, name or email",
- Flags: []cli.Flag{
- cli.Int64Flag{
- Name: "id",
- Usage: "ID of user of the user to delete",
- },
- cli.StringFlag{
- Name: "username,u",
- Usage: "Username of the user to delete",
- },
- cli.StringFlag{
- Name: "email,e",
- Usage: "Email of the user to delete",
- },
- },
- Action: runDeleteUser,
- }
-
- subcmdRepoSyncReleases = cli.Command{
- Name: "repo-sync-releases",
- Usage: "Synchronize repository releases with tags",
- Action: runRepoSyncReleases,
- }
-
- subcmdRegenerate = cli.Command{
- Name: "regenerate",
- Usage: "Regenerate specific files",
- Subcommands: []cli.Command{
- microcmdRegenHooks,
- microcmdRegenKeys,
- },
- }
-
- microcmdRegenHooks = cli.Command{
- Name: "hooks",
- Usage: "Regenerate git-hooks",
- Action: runRegenerateHooks,
- }
-
- microcmdRegenKeys = cli.Command{
- Name: "keys",
- Usage: "Regenerate authorized_keys file",
- Action: runRegenerateKeys,
- }
-
- subcmdAuth = cli.Command{
- Name: "auth",
- Usage: "Modify external auth providers",
- Subcommands: []cli.Command{
- microcmdAuthAddOauth,
- microcmdAuthUpdateOauth,
- cmdAuthAddLdapBindDn,
- cmdAuthUpdateLdapBindDn,
- cmdAuthAddLdapSimpleAuth,
- cmdAuthUpdateLdapSimpleAuth,
- microcmdAuthList,
- microcmdAuthDelete,
- },
- }
-
- microcmdAuthList = cli.Command{
- Name: "list",
- Usage: "List auth sources",
- Action: runListAuth,
- Flags: []cli.Flag{
- cli.IntFlag{
- Name: "min-width",
- Usage: "Minimal cell width including any padding for the formatted table",
- Value: 0,
- },
- cli.IntFlag{
- Name: "tab-width",
- Usage: "width of tab characters in formatted table (equivalent number of spaces)",
- Value: 8,
- },
- cli.IntFlag{
- Name: "padding",
- Usage: "padding added to a cell before computing its width",
- Value: 1,
- },
- cli.StringFlag{
- Name: "pad-char",
- Usage: `ASCII char used for padding if padchar == '\\t', the Writer will assume that the width of a '\\t' in the formatted output is tabwidth, and cells are left-aligned independent of align_left (for correct-looking results, tabwidth must correspond to the tab width in the viewer displaying the result)`,
- Value: "\t",
- },
- cli.BoolFlag{
- Name: "vertical-bars",
- Usage: "Set to true to print vertical bars between columns",
- },
- },
- }
-
- idFlag = cli.Int64Flag{
- Name: "id",
- Usage: "ID of authentication source",
- }
-
- microcmdAuthDelete = cli.Command{
- Name: "delete",
- Usage: "Delete specific auth source",
- Flags: []cli.Flag{idFlag},
- Action: runDeleteAuth,
- }
-
- oauthCLIFlags = []cli.Flag{
- cli.StringFlag{
- Name: "name",
- Value: "",
- Usage: "Application Name",
- },
- cli.StringFlag{
- Name: "provider",
- Value: "",
- Usage: "OAuth2 Provider",
- },
- cli.StringFlag{
- Name: "key",
- Value: "",
- Usage: "Client ID (Key)",
- },
- cli.StringFlag{
- Name: "secret",
- Value: "",
- Usage: "Client Secret",
- },
- cli.StringFlag{
- Name: "auto-discover-url",
- Value: "",
- Usage: "OpenID Connect Auto Discovery URL (only required when using OpenID Connect as provider)",
- },
- cli.StringFlag{
- Name: "use-custom-urls",
- Value: "false",
- Usage: "Use custom URLs for GitLab/GitHub OAuth endpoints",
- },
- cli.StringFlag{
- Name: "custom-auth-url",
- Value: "",
- Usage: "Use a custom Authorization URL (option for GitLab/GitHub)",
- },
- cli.StringFlag{
- Name: "custom-token-url",
- Value: "",
- Usage: "Use a custom Token URL (option for GitLab/GitHub)",
- },
- cli.StringFlag{
- Name: "custom-profile-url",
- Value: "",
- Usage: "Use a custom Profile URL (option for GitLab/GitHub)",
- },
- cli.StringFlag{
- Name: "custom-email-url",
- Value: "",
- Usage: "Use a custom Email URL (option for GitHub)",
- },
- cli.StringFlag{
- Name: "icon-url",
- Value: "",
- Usage: "Custom icon URL for OAuth2 login source",
- },
- cli.BoolFlag{
- Name: "skip-local-2fa",
- Usage: "Set to true to skip local 2fa for users authenticated by this source",
- },
- }
-
- microcmdAuthUpdateOauth = cli.Command{
- Name: "update-oauth",
- Usage: "Update existing Oauth authentication source",
- Action: runUpdateOauth,
- Flags: append(oauthCLIFlags[:1], append([]cli.Flag{idFlag}, oauthCLIFlags[1:]...)...),
- }
-
- microcmdAuthAddOauth = cli.Command{
- Name: "add-oauth",
- Usage: "Add new Oauth authentication source",
- Action: runAddOauth,
- Flags: oauthCLIFlags,
- }
-
- subcmdSendMail = cli.Command{
- Name: "sendmail",
- Usage: "Send a message to all users",
- Action: runSendMail,
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "title",
- Usage: `a title of a message`,
- Value: "",
- },
- cli.StringFlag{
- Name: "content",
- Usage: "a content of a message",
- Value: "",
- },
- cli.BoolFlag{
- Name: "force,f",
- Usage: "A flag to bypass a confirmation step",
- },
- },
- }
- )
-
- func runChangePassword(c *cli.Context) error {
- if err := argsSet(c, "username", "password"); err != nil {
- return err
- }
-
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
- if !pwd.IsComplexEnough(c.String("password")) {
- return errors.New("Password does not meet complexity requirements")
- }
- pwned, err := pwd.IsPwned(context.Background(), c.String("password"))
- if err != nil {
- return err
- }
- if pwned {
- return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
- }
- uname := c.String("username")
- user, err := user_model.GetUserByName(uname)
- if err != nil {
- return err
- }
- if err = user.SetPassword(c.String("password")); err != nil {
- return err
- }
-
- if err = user_model.UpdateUserCols(db.DefaultContext, user, "passwd", "passwd_hash_algo", "salt"); err != nil {
- return err
- }
-
- fmt.Printf("%s's password has been successfully updated!\n", user.Name)
- return nil
- }
-
- func runCreateUser(c *cli.Context) error {
- 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.Fprintf(os.Stderr, "--name flag is deprecated. Use --username instead.\n")
- }
-
- ctx, cancel := installSignals()
- 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")
- }
-
- // always default to true
- var changePassword = true
-
- // If this is the first user being created.
- // Take it as the admin and don't force a password update.
- if n := user_model.CountUsers(); n == 0 {
- changePassword = false
- }
-
- if c.IsSet("must-change-password") {
- changePassword = c.Bool("must-change-password")
- }
-
- u := &user_model.User{
- Name: username,
- Email: c.String("email"),
- Passwd: password,
- IsActive: true,
- IsAdmin: c.Bool("admin"),
- MustChangePassword: changePassword,
- Theme: setting.UI.DefaultTheme,
- }
-
- if err := user_model.CreateUser(u); err != nil {
- return fmt.Errorf("CreateUser: %v", err)
- }
-
- if c.Bool("access-token") {
- t := &models.AccessToken{
- Name: "gitea-admin",
- UID: u.ID,
- }
-
- if err := models.NewAccessToken(t); err != nil {
- return err
- }
-
- fmt.Printf("Access token was successfully created... %s\n", t.Token)
- }
-
- fmt.Printf("New user '%s' has been successfully created!\n", username)
- return nil
- }
-
- func runListUsers(c *cli.Context) error {
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- users, err := user_model.GetAllUsers()
-
- if err != nil {
- return err
- }
-
- w := tabwriter.NewWriter(os.Stdout, 5, 0, 1, ' ', 0)
-
- if c.IsSet("admin") {
- fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\n")
- for _, u := range users {
- if u.IsAdmin {
- fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", u.ID, u.Name, u.Email, u.IsActive)
- }
- }
- } else {
- fmt.Fprintf(w, "ID\tUsername\tEmail\tIsActive\tIsAdmin\n")
- for _, u := range users {
- fmt.Fprintf(w, "%d\t%s\t%s\t%t\t%t\n", u.ID, u.Name, u.Email, u.IsActive, u.IsAdmin)
- }
-
- }
-
- w.Flush()
- return nil
-
- }
-
- func runDeleteUser(c *cli.Context) error {
- if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {
- return fmt.Errorf("You must provide the id, username or email of a user to delete")
- }
-
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- if err := storage.Init(); err != nil {
- return err
- }
-
- var err error
- var user *user_model.User
- if c.IsSet("email") {
- user, err = user_model.GetUserByEmail(c.String("email"))
- } else if c.IsSet("username") {
- user, err = user_model.GetUserByName(c.String("username"))
- } else {
- user, err = user_model.GetUserByID(c.Int64("id"))
- }
- if err != nil {
- return err
- }
- if c.IsSet("username") && user.LowerName != strings.ToLower(strings.TrimSpace(c.String("username"))) {
- return fmt.Errorf("The user %s who has email %s does not match the provided username %s", user.Name, c.String("email"), c.String("username"))
- }
-
- if c.IsSet("id") && user.ID != c.Int64("id") {
- return fmt.Errorf("The user %s does not match the provided id %d", user.Name, c.Int64("id"))
- }
-
- return user_service.DeleteUser(user)
- }
-
- func runRepoSyncReleases(_ *cli.Context) error {
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- log.Trace("Synchronizing repository releases (this may take a while)")
- for page := 1; ; page++ {
- repos, count, err := models.SearchRepositoryByName(&models.SearchRepoOptions{
- ListOptions: db.ListOptions{
- PageSize: models.RepositoryListDefaultPageSize,
- Page: page,
- },
- Private: true,
- })
- if err != nil {
- return fmt.Errorf("SearchRepositoryByName: %v", err)
- }
- if len(repos) == 0 {
- break
- }
- log.Trace("Processing next %d repos of %d", len(repos), count)
- for _, repo := range repos {
- log.Trace("Synchronizing repo %s with path %s", repo.FullName(), repo.RepoPath())
- gitRepo, err := git.OpenRepository(repo.RepoPath())
- if err != nil {
- log.Warn("OpenRepository: %v", err)
- continue
- }
-
- oldnum, err := getReleaseCount(repo.ID)
- if err != nil {
- log.Warn(" GetReleaseCountByRepoID: %v", err)
- }
- log.Trace(" currentNumReleases is %d, running SyncReleasesWithTags", oldnum)
-
- if err = repo_module.SyncReleasesWithTags(repo, gitRepo); err != nil {
- log.Warn(" SyncReleasesWithTags: %v", err)
- gitRepo.Close()
- continue
- }
-
- count, err = getReleaseCount(repo.ID)
- if err != nil {
- log.Warn(" GetReleaseCountByRepoID: %v", err)
- gitRepo.Close()
- continue
- }
-
- log.Trace(" repo %s releases synchronized to tags: from %d to %d",
- repo.FullName(), oldnum, count)
- gitRepo.Close()
- }
- }
-
- return nil
- }
-
- func getReleaseCount(id int64) (int64, error) {
- return models.GetReleaseCountByRepoID(
- id,
- models.FindReleasesOptions{
- IncludeTags: true,
- },
- )
- }
-
- func runRegenerateHooks(_ *cli.Context) error {
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
- return repo_service.SyncRepositoryHooks(graceful.GetManager().ShutdownContext())
- }
-
- func runRegenerateKeys(_ *cli.Context) error {
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
- return models.RewriteAllPublicKeys()
- }
-
- func parseOAuth2Config(c *cli.Context) *oauth2.Source {
- var customURLMapping *oauth2.CustomURLMapping
- if c.IsSet("use-custom-urls") {
- customURLMapping = &oauth2.CustomURLMapping{
- TokenURL: c.String("custom-token-url"),
- AuthURL: c.String("custom-auth-url"),
- ProfileURL: c.String("custom-profile-url"),
- EmailURL: c.String("custom-email-url"),
- }
- } else {
- customURLMapping = nil
- }
- return &oauth2.Source{
- Provider: c.String("provider"),
- ClientID: c.String("key"),
- ClientSecret: c.String("secret"),
- OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"),
- CustomURLMapping: customURLMapping,
- IconURL: c.String("icon-url"),
- SkipLocalTwoFA: c.Bool("skip-local-2fa"),
- }
- }
-
- func runAddOauth(c *cli.Context) error {
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- return login.CreateSource(&login.Source{
- Type: login.OAuth2,
- Name: c.String("name"),
- IsActive: true,
- Cfg: parseOAuth2Config(c),
- })
- }
-
- func runUpdateOauth(c *cli.Context) error {
- if !c.IsSet("id") {
- return fmt.Errorf("--id flag is missing")
- }
-
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- source, err := login.GetSourceByID(c.Int64("id"))
- if err != nil {
- return err
- }
-
- oAuth2Config := source.Cfg.(*oauth2.Source)
-
- if c.IsSet("name") {
- source.Name = c.String("name")
- }
-
- if c.IsSet("provider") {
- oAuth2Config.Provider = c.String("provider")
- }
-
- if c.IsSet("key") {
- oAuth2Config.ClientID = c.String("key")
- }
-
- if c.IsSet("secret") {
- oAuth2Config.ClientSecret = c.String("secret")
- }
-
- if c.IsSet("auto-discover-url") {
- oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url")
- }
-
- if c.IsSet("icon-url") {
- oAuth2Config.IconURL = c.String("icon-url")
- }
-
- // update custom URL mapping
- var customURLMapping = &oauth2.CustomURLMapping{}
-
- if oAuth2Config.CustomURLMapping != nil {
- customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
- customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL
- customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL
- customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL
- }
- if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") {
- customURLMapping.TokenURL = c.String("custom-token-url")
- }
-
- if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") {
- customURLMapping.AuthURL = c.String("custom-auth-url")
- }
-
- if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") {
- customURLMapping.ProfileURL = c.String("custom-profile-url")
- }
-
- if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") {
- customURLMapping.EmailURL = c.String("custom-email-url")
- }
-
- oAuth2Config.CustomURLMapping = customURLMapping
- source.Cfg = oAuth2Config
-
- return login.UpdateSource(source)
- }
-
- func runListAuth(c *cli.Context) error {
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- loginSources, err := login.Sources()
-
- if err != nil {
- return err
- }
-
- flags := tabwriter.AlignRight
- if c.Bool("vertical-bars") {
- flags |= tabwriter.Debug
- }
-
- padChar := byte('\t')
- if len(c.String("pad-char")) > 0 {
- padChar = c.String("pad-char")[0]
- }
-
- // loop through each source and print
- w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags)
- fmt.Fprintf(w, "ID\tName\tType\tEnabled\n")
- for _, source := range loginSources {
- fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive)
- }
- w.Flush()
-
- return nil
- }
-
- func runDeleteAuth(c *cli.Context) error {
- if !c.IsSet("id") {
- return fmt.Errorf("--id flag is missing")
- }
-
- ctx, cancel := installSignals()
- defer cancel()
-
- if err := initDB(ctx); err != nil {
- return err
- }
-
- source, err := login.GetSourceByID(c.Int64("id"))
- if err != nil {
- return err
- }
-
- return auth_service.DeleteLoginSource(source)
- }
|