auth.go 7.7 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. 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. _, _ = color.New(color.FgGreen).Println("Successfully logged in!")
  130. return setProjectForUser(ctx, client, currentProfile)
  131. }
  132. err = config.SetToken(cliConf.Token, currentProfile)
  133. if err != nil {
  134. return err
  135. }
  136. err = config.SetHost(cliConf.Host, currentProfile)
  137. if err != nil {
  138. return err
  139. }
  140. projID, exists, err := api.GetProjectIDFromToken(cliConf.Token)
  141. if err != nil {
  142. return err
  143. }
  144. // if project ID does not exist for the token, this is a user-issued CLI token, so the project
  145. // ID should be queried
  146. if !exists {
  147. err = setProjectForUser(ctx, client, currentProfile)
  148. if err != nil {
  149. return err
  150. }
  151. } else {
  152. // if the project ID does exist for the token, this is a project-issued token, and
  153. // the project should be set automatically
  154. err = config.SetProject(projID, currentProfile)
  155. if err != nil {
  156. return err
  157. }
  158. err = setProjectCluster(ctx, client, currentProfile, projID)
  159. if err != nil {
  160. return err
  161. }
  162. }
  163. _, _ = color.New(color.FgGreen).Println("Successfully logged in!")
  164. return nil
  165. }
  166. func setProjectForUser(ctx context.Context, client api.Client, currentProfile string) error {
  167. // get a list of projects, and set the current project
  168. resp, err := client.ListUserProjects(ctx)
  169. if err != nil {
  170. return err
  171. }
  172. projects := *resp
  173. if len(projects) > 0 {
  174. config.SetProject(projects[0].ID, currentProfile) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  175. err = setProjectCluster(ctx, client, currentProfile, projects[0].ID)
  176. if err != nil {
  177. return err
  178. }
  179. }
  180. return nil
  181. }
  182. func loginManual(ctx context.Context, cliConf config.CLIConfig, client api.Client, currentProfile string) error {
  183. client.CookieFilePath = "cookie.json" // required as this uses cookies for auth instead of a token
  184. var username, pw string
  185. fmt.Println("Please log in with an email and password:")
  186. username, err := utils.PromptPlaintext("Email: ")
  187. if err != nil {
  188. return err
  189. }
  190. pw, err = utils.PromptPassword("Password: ")
  191. if err != nil {
  192. return err
  193. }
  194. _, err = client.Login(ctx, &types.LoginUserRequest{
  195. Email: username,
  196. Password: pw,
  197. })
  198. if err != nil {
  199. return err
  200. }
  201. // set the token to empty since this is manual (cookie-based) login
  202. config.SetToken("", currentProfile)
  203. color.New(color.FgGreen).Println("Successfully logged in!")
  204. // get a list of projects, and set the current project
  205. resp, err := client.ListUserProjects(ctx)
  206. if err != nil {
  207. return err
  208. }
  209. projects := *resp
  210. if len(projects) > 0 {
  211. config.SetProject(projects[0].ID, currentProfile) //nolint:errcheck,gosec // do not want to change logic of CLI. New linter error
  212. err = setProjectCluster(ctx, client, currentProfile, projects[0].ID)
  213. if err != nil {
  214. return err
  215. }
  216. }
  217. return nil
  218. }
  219. func register(ctx context.Context, cliConf config.CLIConfig) error {
  220. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  221. BaseURL: fmt.Sprintf("%s/api", cliConf.Host),
  222. BearerToken: cliConf.Token,
  223. })
  224. if err != nil {
  225. if !errors.Is(err, api.ErrNoAuthCredential) {
  226. return fmt.Errorf("error creating porter API client: %w", err)
  227. }
  228. }
  229. fmt.Println("Please register your admin account with an email and password:")
  230. username, err := utils.PromptPlaintext("Email: ")
  231. if err != nil {
  232. return err
  233. }
  234. pw, err := utils.PromptPasswordWithConfirmation()
  235. if err != nil {
  236. return err
  237. }
  238. resp, err := client.CreateUser(ctx, &types.CreateUserRequest{
  239. Email: username,
  240. Password: pw,
  241. })
  242. if err != nil {
  243. return err
  244. }
  245. color.New(color.FgGreen).Printf("Created user with email %s and id %d\n", username, resp.ID)
  246. return nil
  247. }
  248. 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 {
  249. err := client.Logout(ctx)
  250. if err != nil {
  251. if !strings.Contains(err.Error(), "You are not logged in.") &&
  252. !strings.Contains(err.Error(), "does not have a role in project") {
  253. return err
  254. }
  255. }
  256. config.SetToken("", currentProfile)
  257. config.SetCluster(0, currentProfile)
  258. config.SetProject(0, currentProfile)
  259. color.Green("Successfully logged out")
  260. return nil
  261. }