auth.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. // _, _ = color.New(color.FgGreen).Println("Successfully logged in!")
  131. // return setProjectForUser(ctx, client, 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, 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, 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, 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, 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, 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. }