auth.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package auth
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path"
  10. "strings"
  11. )
  12. // Where we store the config file
  13. const CONFIGFILE = ".dockercfg"
  14. // the registry server we want to login against
  15. const INDEX_SERVER = "https://index.docker.io"
  16. type AuthConfig struct {
  17. Username string `json:"username"`
  18. Password string `json:"password"`
  19. Email string `json:"email"`
  20. rootPath string `json:-`
  21. }
  22. func NewAuthConfig(username, password, email, rootPath string) *AuthConfig {
  23. return &AuthConfig{
  24. Username: username,
  25. Password: password,
  26. Email: email,
  27. rootPath: rootPath,
  28. }
  29. }
  30. // create a base64 encoded auth string to store in config
  31. func EncodeAuth(authConfig *AuthConfig) string {
  32. authStr := authConfig.Username + ":" + authConfig.Password
  33. msg := []byte(authStr)
  34. encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
  35. base64.StdEncoding.Encode(encoded, msg)
  36. return string(encoded)
  37. }
  38. // decode the auth string
  39. func DecodeAuth(authStr string) (*AuthConfig, error) {
  40. decLen := base64.StdEncoding.DecodedLen(len(authStr))
  41. decoded := make([]byte, decLen)
  42. authByte := []byte(authStr)
  43. n, err := base64.StdEncoding.Decode(decoded, authByte)
  44. if err != nil {
  45. return nil, err
  46. }
  47. if n > decLen {
  48. return nil, fmt.Errorf("Something went wrong decoding auth config")
  49. }
  50. arr := strings.Split(string(decoded), ":")
  51. if len(arr) != 2 {
  52. return nil, fmt.Errorf("Invalid auth configuration file")
  53. }
  54. password := strings.Trim(arr[1], "\x00")
  55. return &AuthConfig{Username: arr[0], Password: password}, nil
  56. }
  57. // load up the auth config information and return values
  58. // FIXME: use the internal golang config parser
  59. func LoadConfig(rootPath string) (*AuthConfig, error) {
  60. confFile := path.Join(rootPath, CONFIGFILE)
  61. if _, err := os.Stat(confFile); err != nil {
  62. return &AuthConfig{}, fmt.Errorf("The Auth config file is missing")
  63. }
  64. b, err := ioutil.ReadFile(confFile)
  65. if err != nil {
  66. return nil, err
  67. }
  68. arr := strings.Split(string(b), "\n")
  69. if len(arr) < 2 {
  70. return nil, fmt.Errorf("The Auth config file is empty")
  71. }
  72. origAuth := strings.Split(arr[0], " = ")
  73. origEmail := strings.Split(arr[1], " = ")
  74. authConfig, err := DecodeAuth(origAuth[1])
  75. if err != nil {
  76. return nil, err
  77. }
  78. authConfig.Email = origEmail[1]
  79. authConfig.rootPath = rootPath
  80. return authConfig, nil
  81. }
  82. // save the auth config
  83. func saveConfig(rootPath, authStr string, email string) error {
  84. confFile := path.Join(rootPath, CONFIGFILE)
  85. if len(email) == 0 {
  86. os.Remove(confFile)
  87. return nil
  88. }
  89. lines := "auth = " + authStr + "\n" + "email = " + email + "\n"
  90. b := []byte(lines)
  91. err := ioutil.WriteFile(confFile, b, 0600)
  92. if err != nil {
  93. return err
  94. }
  95. return nil
  96. }
  97. // try to register/login to the registry server
  98. func Login(authConfig *AuthConfig) (string, error) {
  99. storeConfig := false
  100. client := &http.Client{}
  101. reqStatusCode := 0
  102. var status string
  103. var reqBody []byte
  104. jsonBody, err := json.Marshal(authConfig)
  105. if err != nil {
  106. return "", fmt.Errorf("Config Error: %s", err)
  107. }
  108. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
  109. b := strings.NewReader(string(jsonBody))
  110. req1, err := http.Post(INDEX_SERVER+"/v1/users/", "application/json; charset=utf-8", b)
  111. if err != nil {
  112. return "", fmt.Errorf("Server Error: %s", err)
  113. }
  114. reqStatusCode = req1.StatusCode
  115. defer req1.Body.Close()
  116. reqBody, err = ioutil.ReadAll(req1.Body)
  117. if err != nil {
  118. return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
  119. }
  120. if reqStatusCode == 201 {
  121. status = "Account created. Please use the confirmation link we sent" +
  122. " to your e-mail to activate it.\n"
  123. storeConfig = true
  124. } else if reqStatusCode == 403 {
  125. return "", fmt.Errorf("Login: Your account hasn't been activated. " +
  126. "Please check your e-mail for a confirmation link.")
  127. } else if reqStatusCode == 400 {
  128. if string(reqBody) == "\"Username or email already exists\"" {
  129. req, err := http.NewRequest("GET", INDEX_SERVER+"/v1/users/", nil)
  130. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  131. resp, err := client.Do(req)
  132. if err != nil {
  133. return "", err
  134. }
  135. defer resp.Body.Close()
  136. body, err := ioutil.ReadAll(resp.Body)
  137. if err != nil {
  138. return "", err
  139. }
  140. if resp.StatusCode == 200 {
  141. status = "Login Succeeded\n"
  142. storeConfig = true
  143. } else if resp.StatusCode == 401 {
  144. saveConfig(authConfig.rootPath, "", "")
  145. return "", fmt.Errorf("Wrong login/password, please try again")
  146. } else {
  147. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  148. resp.StatusCode, resp.Header)
  149. }
  150. } else {
  151. return "", fmt.Errorf("Registration: %s", reqBody)
  152. }
  153. } else {
  154. return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
  155. }
  156. if storeConfig {
  157. authStr := EncodeAuth(authConfig)
  158. saveConfig(authConfig.rootPath, authStr, authConfig.Email)
  159. }
  160. return status, nil
  161. }