auth.go 5.3 KB

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