auth.go 5.1 KB

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