auth.go 7.9 KB

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