auth.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "github.com/fatih/color"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/cli/cmd/config"
  10. loginBrowser "github.com/porter-dev/porter/cli/cmd/login"
  11. "github.com/porter-dev/porter/cli/cmd/utils"
  12. "github.com/spf13/cobra"
  13. )
  14. var authCmd = &cobra.Command{
  15. Use: "auth",
  16. Short: "Commands for authenticating to a Porter server",
  17. }
  18. var loginCmd = &cobra.Command{
  19. Use: "login",
  20. Short: "Authorizes a user for a given Porter server",
  21. Run: func(cmd *cobra.Command, args []string) {
  22. err := login()
  23. if err != nil {
  24. color.Red("Error logging in: %s\n", err.Error())
  25. os.Exit(1)
  26. }
  27. },
  28. }
  29. var registerCmd = &cobra.Command{
  30. Use: "register",
  31. Short: "Creates a user for a given Porter server",
  32. Run: func(cmd *cobra.Command, args []string) {
  33. err := register()
  34. if err != nil {
  35. color.Red("Error registering: %s\n", err.Error())
  36. os.Exit(1)
  37. }
  38. },
  39. }
  40. var logoutCmd = &cobra.Command{
  41. Use: "logout",
  42. Short: "Logs a user out of a given Porter server",
  43. Run: func(cmd *cobra.Command, args []string) {
  44. err := checkLoginAndRun(args, logout)
  45. if err != nil {
  46. os.Exit(1)
  47. }
  48. },
  49. }
  50. var manual bool = false
  51. func init() {
  52. rootCmd.AddCommand(authCmd)
  53. authCmd.AddCommand(loginCmd)
  54. authCmd.AddCommand(registerCmd)
  55. authCmd.AddCommand(logoutCmd)
  56. loginCmd.PersistentFlags().BoolVar(
  57. &manual,
  58. "manual",
  59. false,
  60. "whether to prompt for manual authentication (username/pw)",
  61. )
  62. }
  63. func login() error {
  64. client := api.NewClientWithToken(cliConf.Host+"/api", cliConf.Token)
  65. user, err := client.AuthCheck(context.Background())
  66. if err == nil {
  67. // set the token if the user calls login with the --token flag or the PORTER_TOKEN env
  68. if cliConf.Token != "" {
  69. cliConf.SetToken(cliConf.Token)
  70. color.New(color.FgGreen).Println("Successfully logged in!")
  71. projID, exists, err := api.GetProjectIDFromToken(cliConf.Token)
  72. if err != nil {
  73. return err
  74. }
  75. // if project ID does not exist for the token, this is a user-issued CLI token, so the project
  76. // ID should be queried
  77. if !exists {
  78. err = setProjectForUser(client, user.ID)
  79. if err != nil {
  80. return err
  81. }
  82. } else {
  83. // if the project ID does exist for the token, this is a project-issued token, and
  84. // the project should be set automatically
  85. err = cliConf.SetProject(projID)
  86. if err != nil {
  87. return err
  88. }
  89. err = setProjectCluster(client, projID)
  90. if err != nil {
  91. return err
  92. }
  93. }
  94. } else {
  95. color.Yellow("You are already logged in. If you'd like to log out, run \"porter auth logout\".")
  96. }
  97. return nil
  98. }
  99. // check for the --manual flag
  100. if manual {
  101. return loginManual()
  102. }
  103. // log the user in
  104. token, err := loginBrowser.Login(cliConf.Host)
  105. if err != nil {
  106. return err
  107. }
  108. // set the token in config
  109. err = cliConf.SetToken(token)
  110. if err != nil {
  111. return err
  112. }
  113. client = api.NewClientWithToken(cliConf.Host+"/api", token)
  114. user, err = client.AuthCheck(context.Background())
  115. if err != nil {
  116. color.Red("Invalid token.")
  117. return err
  118. }
  119. color.New(color.FgGreen).Println("Successfully logged in!")
  120. return setProjectForUser(client, user.ID)
  121. }
  122. func setProjectForUser(client *api.Client, userID uint) error {
  123. // get a list of projects, and set the current project
  124. resp, err := client.ListUserProjects(context.Background())
  125. if err != nil {
  126. return err
  127. }
  128. projects := *resp
  129. if len(projects) > 0 {
  130. cliConf.SetProject(projects[0].ID)
  131. err = setProjectCluster(client, projects[0].ID)
  132. if err != nil {
  133. return err
  134. }
  135. }
  136. return nil
  137. }
  138. func loginManual() error {
  139. client := api.NewClient(cliConf.Host+"/api", "cookie.json")
  140. var username, pw string
  141. fmt.Println("Please log in with an email and password:")
  142. username, err := utils.PromptPlaintext("Email: ")
  143. if err != nil {
  144. return err
  145. }
  146. pw, err = utils.PromptPassword("Password: ")
  147. if err != nil {
  148. return err
  149. }
  150. _, err = client.Login(context.Background(), &types.LoginUserRequest{
  151. Email: username,
  152. Password: pw,
  153. })
  154. if err != nil {
  155. return err
  156. }
  157. // set the token to empty since this is manual (cookie-based) login
  158. cliConf.SetToken("")
  159. color.New(color.FgGreen).Println("Successfully logged in!")
  160. // get a list of projects, and set the current project
  161. resp, err := client.ListUserProjects(context.Background())
  162. if err != nil {
  163. return err
  164. }
  165. projects := *resp
  166. if len(projects) > 0 {
  167. cliConf.SetProject(projects[0].ID)
  168. err = setProjectCluster(client, projects[0].ID)
  169. if err != nil {
  170. return err
  171. }
  172. }
  173. return nil
  174. }
  175. func register() error {
  176. fmt.Println("Please register your admin account with an email and password:")
  177. username, err := utils.PromptPlaintext("Email: ")
  178. if err != nil {
  179. return err
  180. }
  181. pw, err := utils.PromptPasswordWithConfirmation()
  182. if err != nil {
  183. return err
  184. }
  185. client := config.GetAPIClient()
  186. resp, err := client.CreateUser(context.Background(), &types.CreateUserRequest{
  187. Email: username,
  188. Password: pw,
  189. })
  190. if err != nil {
  191. return err
  192. }
  193. color.New(color.FgGreen).Printf("Created user with email %s and id %d\n", username, resp.ID)
  194. return nil
  195. }
  196. func logout(user *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  197. err := client.Logout(context.Background())
  198. if err != nil {
  199. return err
  200. }
  201. cliConf.SetToken("")
  202. color.Green("Successfully logged out")
  203. return nil
  204. }