auth.go 5.5 KB

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