logingLocalServer.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package login
  2. import (
  3. "fmt"
  4. "net"
  5. "net/http"
  6. "net/url"
  7. )
  8. const loginFailedHTML = `
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <meta charset="utf-8" />
  13. <title>Login failed</title>
  14. </head>
  15. <body>
  16. <h4>Some failures occurred during the authentication</h4>
  17. <p>You can log an issue at <a href="https://github.com/azure/azure-cli/issues">Azure CLI GitHub Repository</a> and we will assist you in resolving it.</p>
  18. </body>
  19. </html>
  20. `
  21. const successfullLoginHTML = `
  22. <!DOCTYPE html>
  23. <html>
  24. <head>
  25. <meta charset="utf-8" />
  26. <meta http-equiv="refresh" content="10;url=https://docs.microsoft.com/cli/azure/">
  27. <title>Login successfully</title>
  28. </head>
  29. <body>
  30. <h4>You have logged into Microsoft Azure!</h4>
  31. <p>You can close this window, or we will redirect you to the <a href="https://docs.microsoft.com/cli/azure/">Azure CLI documents</a> in 10 seconds.</p>
  32. </body>
  33. </html>
  34. `
  35. func startLoginServer(queryCh chan url.Values) (int, error) {
  36. mux := http.NewServeMux()
  37. mux.HandleFunc("/", queryHandler(queryCh))
  38. listener, err := net.Listen("tcp", ":0")
  39. if err != nil {
  40. return 0, err
  41. }
  42. availablePort := listener.Addr().(*net.TCPAddr).Port
  43. server := &http.Server{Handler: mux}
  44. go func() {
  45. if err := server.Serve(listener); err != nil {
  46. queryCh <- url.Values{
  47. "error": []string{fmt.Sprintf("error starting http server with: %v", err)},
  48. }
  49. }
  50. }()
  51. return availablePort, nil
  52. }
  53. func queryHandler(queryCh chan url.Values) func(w http.ResponseWriter, r *http.Request) {
  54. queryHandler := func(w http.ResponseWriter, r *http.Request) {
  55. _, hasCode := r.URL.Query()["code"]
  56. if hasCode {
  57. _, err := w.Write([]byte(successfullLoginHTML))
  58. if err != nil {
  59. queryCh <- url.Values{
  60. "error": []string{err.Error()},
  61. }
  62. } else {
  63. queryCh <- r.URL.Query()
  64. }
  65. } else {
  66. _, err := w.Write([]byte(loginFailedHTML))
  67. if err != nil {
  68. queryCh <- url.Values{
  69. "error": []string{err.Error()},
  70. }
  71. } else {
  72. queryCh <- r.URL.Query()
  73. }
  74. }
  75. }
  76. return queryHandler
  77. }