auth.go 7.6 KB

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