auth.go 5.2 KB

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