auth.go 5.2 KB

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