code.gitea.io/gitea@v1.21.7/cmd/admin_user_generate_access_token.go (about) 1 // Copyright 2023 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package cmd 5 6 import ( 7 "fmt" 8 9 auth_model "code.gitea.io/gitea/models/auth" 10 user_model "code.gitea.io/gitea/models/user" 11 12 "github.com/urfave/cli/v2" 13 ) 14 15 var microcmdUserGenerateAccessToken = &cli.Command{ 16 Name: "generate-access-token", 17 Usage: "Generate an access token for a specific user", 18 Flags: []cli.Flag{ 19 &cli.StringFlag{ 20 Name: "username", 21 Aliases: []string{"u"}, 22 Usage: "Username", 23 }, 24 &cli.StringFlag{ 25 Name: "token-name", 26 Aliases: []string{"t"}, 27 Usage: "Token name", 28 Value: "gitea-admin", 29 }, 30 &cli.BoolFlag{ 31 Name: "raw", 32 Usage: "Display only the token value", 33 }, 34 &cli.StringFlag{ 35 Name: "scopes", 36 Value: "", 37 Usage: "Comma separated list of scopes to apply to access token", 38 }, 39 }, 40 Action: runGenerateAccessToken, 41 } 42 43 func runGenerateAccessToken(c *cli.Context) error { 44 if !c.IsSet("username") { 45 return fmt.Errorf("You must provide a username to generate a token for") 46 } 47 48 ctx, cancel := installSignals() 49 defer cancel() 50 51 if err := initDB(ctx); err != nil { 52 return err 53 } 54 55 user, err := user_model.GetUserByName(ctx, c.String("username")) 56 if err != nil { 57 return err 58 } 59 60 // construct token with name and user so we can make sure it is unique 61 t := &auth_model.AccessToken{ 62 Name: c.String("token-name"), 63 UID: user.ID, 64 } 65 66 exist, err := auth_model.AccessTokenByNameExists(ctx, t) 67 if err != nil { 68 return err 69 } 70 if exist { 71 return fmt.Errorf("access token name has been used already") 72 } 73 74 // make sure the scopes are valid 75 accessTokenScope, err := auth_model.AccessTokenScope(c.String("scopes")).Normalize() 76 if err != nil { 77 return fmt.Errorf("invalid access token scope provided: %w", err) 78 } 79 t.Scope = accessTokenScope 80 81 // create the token 82 if err := auth_model.NewAccessToken(ctx, t); err != nil { 83 return err 84 } 85 86 if c.Bool("raw") { 87 fmt.Printf("%s\n", t.Token) 88 } else { 89 fmt.Printf("Access token was successfully created: %s\n", t.Token) 90 } 91 92 return nil 93 }