auth.go 6.4 KB

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