auth.go 5.4 KB

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