auth.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "github.com/fatih/color"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/cli/cmd/config"
  10. loginBrowser "github.com/porter-dev/porter/cli/cmd/login"
  11. "github.com/porter-dev/porter/cli/cmd/utils"
  12. "github.com/spf13/cobra"
  13. )
  14. var authCmd = &cobra.Command{
  15. Use: "auth",
  16. Short: "Commands for authenticating to a Porter server",
  17. }
  18. var loginCmd = &cobra.Command{
  19. Use: "login",
  20. Short: "Authorizes a user for a given Porter server",
  21. Run: func(cmd *cobra.Command, args []string) {
  22. err := login(cmd.Context())
  23. if err != nil {
  24. color.Red("Error logging in: %s\n", err.Error())
  25. os.Exit(1)
  26. }
  27. },
  28. }
  29. var registerCmd = &cobra.Command{
  30. Use: "register",
  31. Short: "Creates a user for a given Porter server",
  32. Run: func(cmd *cobra.Command, args []string) {
  33. err := register(cmd.Context())
  34. if err != nil {
  35. color.Red("Error registering: %s\n", err.Error())
  36. os.Exit(1)
  37. }
  38. },
  39. }
  40. var logoutCmd = &cobra.Command{
  41. Use: "logout",
  42. Short: "Logs a user out of a given Porter server",
  43. Run: func(cmd *cobra.Command, args []string) {
  44. err := checkLoginAndRun(cmd.Context(), args, logout)
  45. if err != nil {
  46. os.Exit(1)
  47. }
  48. },
  49. }
  50. var manual bool = false
  51. func init() {
  52. rootCmd.AddCommand(authCmd)
  53. authCmd.AddCommand(loginCmd)
  54. authCmd.AddCommand(registerCmd)
  55. authCmd.AddCommand(logoutCmd)
  56. loginCmd.PersistentFlags().BoolVar(
  57. &manual,
  58. "manual",
  59. false,
  60. "whether to prompt for manual authentication (username/pw)",
  61. )
  62. }
  63. func login(ctx context.Context) error {
  64. cliConf, err := config.InitAndLoadConfig()
  65. if err != nil {
  66. return fmt.Errorf("error loading porter config: %w", err)
  67. }
  68. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  69. BaseURL: fmt.Sprintf("%s/api", cliConf.Host),
  70. BearerToken: cliConf.Token,
  71. })
  72. if err != nil {
  73. return fmt.Errorf("error creating porter API client: %w", err)
  74. }
  75. user, err := client.AuthCheck(ctx)
  76. if err == nil {
  77. // set the token if the user calls login with the --token flag or the PORTER_TOKEN env
  78. if cliConf.Token != "" {
  79. cliConf.SetToken(cliConf.Token)
  80. color.New(color.FgGreen).Println("Successfully logged in!")
  81. projID, exists, err := api.GetProjectIDFromToken(cliConf.Token)
  82. if err != nil {
  83. return err
  84. }
  85. // if project ID does not exist for the token, this is a user-issued CLI token, so the project
  86. // ID should be queried
  87. if !exists {
  88. err = setProjectForUser(ctx, client, cliConf, user.ID)
  89. if err != nil {
  90. return err
  91. }
  92. } else {
  93. // if the project ID does exist for the token, this is a project-issued token, and
  94. // the project should be set automatically
  95. err = cliConf.SetProject(ctx, client, projID)
  96. if err != nil {
  97. return err
  98. }
  99. err = setProjectCluster(ctx, client, cliConf, projID)
  100. if err != nil {
  101. return err
  102. }
  103. }
  104. } else {
  105. color.Yellow("You are already logged in. If you'd like to log out, run \"porter auth logout\".")
  106. }
  107. return nil
  108. }
  109. // check for the --manual flag
  110. if manual {
  111. return loginManual(ctx, cliConf, client)
  112. }
  113. // log the user in
  114. token, err := loginBrowser.Login(cliConf.Host)
  115. if err != nil {
  116. return err
  117. }
  118. // set the token in config
  119. err = cliConf.SetToken(token)
  120. if err != nil {
  121. return err
  122. }
  123. client, err = api.NewClientWithConfig(ctx, api.NewClientInput{
  124. BaseURL: fmt.Sprintf("%s/api", cliConf.Host),
  125. BearerToken: token,
  126. })
  127. if err != nil {
  128. return fmt.Errorf("error creating porter API client: %w", err)
  129. }
  130. user, err = client.AuthCheck(ctx)
  131. if err != nil {
  132. color.Red("Invalid token.")
  133. return err
  134. }
  135. color.New(color.FgGreen).Println("Successfully logged in!")
  136. return setProjectForUser(ctx, client, cliConf, user.ID)
  137. }
  138. func setProjectForUser(ctx context.Context, client api.Client, config config.CLIConfig, _ uint) error {
  139. // get a list of projects, and set the current project
  140. resp, err := client.ListUserProjects(ctx)
  141. if err != nil {
  142. return err
  143. }
  144. projects := *resp
  145. if len(projects) > 0 {
  146. config.SetProject(ctx, client, projects[0].ID) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  147. err = setProjectCluster(ctx, client, config, projects[0].ID)
  148. if err != nil {
  149. return err
  150. }
  151. }
  152. return nil
  153. }
  154. func loginManual(ctx context.Context, cliConf config.CLIConfig, client api.Client) error {
  155. var username, pw string
  156. fmt.Println("Please log in with an email and password:")
  157. username, err := utils.PromptPlaintext("Email: ")
  158. if err != nil {
  159. return err
  160. }
  161. pw, err = utils.PromptPassword("Password: ")
  162. if err != nil {
  163. return err
  164. }
  165. _, err = client.Login(ctx, &types.LoginUserRequest{
  166. Email: username,
  167. Password: pw,
  168. })
  169. if err != nil {
  170. return err
  171. }
  172. // set the token to empty since this is manual (cookie-based) login
  173. cliConf.SetToken("")
  174. color.New(color.FgGreen).Println("Successfully logged in!")
  175. // get a list of projects, and set the current project
  176. resp, err := client.ListUserProjects(ctx)
  177. if err != nil {
  178. return err
  179. }
  180. projects := *resp
  181. if len(projects) > 0 {
  182. cliConf.SetProject(ctx, client, projects[0].ID) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  183. err = setProjectCluster(ctx, client, cliConf, projects[0].ID)
  184. if err != nil {
  185. return err
  186. }
  187. }
  188. return nil
  189. }
  190. func register(ctx context.Context) error {
  191. config, err := config.InitAndLoadConfig()
  192. if err != nil {
  193. return fmt.Errorf("error loading porter config: %w", err)
  194. }
  195. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  196. BaseURL: fmt.Sprintf("%s/api", config.Host),
  197. BearerToken: config.Token,
  198. })
  199. if err != nil {
  200. return fmt.Errorf("error creating porter API client: %w", err)
  201. }
  202. fmt.Println("Please register your admin account with an email and password:")
  203. username, err := utils.PromptPlaintext("Email: ")
  204. if err != nil {
  205. return err
  206. }
  207. pw, err := utils.PromptPasswordWithConfirmation()
  208. if err != nil {
  209. return err
  210. }
  211. resp, err := client.CreateUser(ctx, &types.CreateUserRequest{
  212. Email: username,
  213. Password: pw,
  214. })
  215. if err != nil {
  216. return err
  217. }
  218. color.New(color.FgGreen).Printf("Created user with email %s and id %d\n", username, resp.ID)
  219. return nil
  220. }
  221. func logout(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, args []string) error {
  222. err := client.Logout(ctx)
  223. if err != nil {
  224. return err
  225. }
  226. cliConf.SetToken("")
  227. color.Green("Successfully logged out")
  228. return nil
  229. }