auth.go 6.8 KB

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