auth.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. configFile.Configs[k] = authConfig
  94. }
  95. }
  96. return &configFile, nil
  97. }
  98. // save the auth config
  99. func SaveConfig(configFile *ConfigFile) error {
  100. confFile := path.Join(configFile.rootPath, CONFIGFILE)
  101. if len(configFile.Configs) == 0 {
  102. os.Remove(confFile)
  103. return nil
  104. }
  105. for k, authConfig := range configFile.Configs {
  106. authConfig.Auth = encodeAuth(&authConfig)
  107. authConfig.Username = ""
  108. authConfig.Password = ""
  109. configFile.Configs[k] = authConfig
  110. }
  111. b, err := json.Marshal(configFile.Configs)
  112. if err != nil {
  113. return err
  114. }
  115. err = ioutil.WriteFile(confFile, b, 0600)
  116. if err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. // try to register/login to the registry server
  122. func Login(authConfig *AuthConfig) (string, error) {
  123. client := &http.Client{}
  124. reqStatusCode := 0
  125. var status string
  126. var reqBody []byte
  127. jsonBody, err := json.Marshal(authConfig)
  128. if err != nil {
  129. return "", fmt.Errorf("Config Error: %s", err)
  130. }
  131. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
  132. b := strings.NewReader(string(jsonBody))
  133. req1, err := http.Post(IndexServerAddress()+"users/", "application/json; charset=utf-8", b)
  134. if err != nil {
  135. return "", fmt.Errorf("Server Error: %s", err)
  136. }
  137. reqStatusCode = req1.StatusCode
  138. defer req1.Body.Close()
  139. reqBody, err = ioutil.ReadAll(req1.Body)
  140. if err != nil {
  141. return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
  142. }
  143. if reqStatusCode == 201 {
  144. status = "Account created. Please use the confirmation link we sent" +
  145. " to your e-mail to activate it."
  146. } else if reqStatusCode == 403 {
  147. return "", fmt.Errorf("Login: Your account hasn't been activated. " +
  148. "Please check your e-mail for a confirmation link.")
  149. } else if reqStatusCode == 400 {
  150. if string(reqBody) == "\"Username or email already exists\"" {
  151. req, err := http.NewRequest("GET", IndexServerAddress()+"users/", nil)
  152. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  153. resp, err := client.Do(req)
  154. if err != nil {
  155. return "", err
  156. }
  157. defer resp.Body.Close()
  158. body, err := ioutil.ReadAll(resp.Body)
  159. if err != nil {
  160. return "", err
  161. }
  162. if resp.StatusCode == 200 {
  163. status = "Login Succeeded"
  164. } else if resp.StatusCode == 401 {
  165. return "", fmt.Errorf("Wrong login/password, please try again")
  166. } else {
  167. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  168. resp.StatusCode, resp.Header)
  169. }
  170. } else {
  171. return "", fmt.Errorf("Registration: %s", reqBody)
  172. }
  173. } else {
  174. return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
  175. }
  176. return status, nil
  177. }