Browse Source

create user with POST

κρμγ 8 years ago
parent
commit
e19597ff13
3 changed files with 47 additions and 0 deletions
  1. 4 0
      README.md
  2. 4 0
      dav_multiuser_cmd/main.go
  3. 39 0
      dav_multiuser_cmd/user.go

+ 4 - 0
README.md

@@ -28,3 +28,7 @@ upload some files `cadaver put /path/to/file`
 
 then look in browser `http://<addr>:6001/hash`
 
+default user/password: root:changeme
+
+add new user: `curl -H "Content-Type: application/json" -d '{"login": "user", "password": "password"}' http://<host>:6001/user`
+

+ 4 - 0
dav_multiuser_cmd/main.go

@@ -38,6 +38,7 @@ func main() {
 	dav := handler()
 	http.Handle("/ipfs/", dav)
 	http.Handle("/ipfs", dav)
+
 	http.HandleFunc("/hash", auth.NewBasicAuthenticator("ipfs", func(user, realm string) (ret string) {
 		un := zbase32.EncodeToString([]byte(user))
 		if hash, err := KV.Read(un); err == nil {
@@ -52,6 +53,9 @@ func main() {
 			resp.Write([]byte(tpl))
 		}
 	}))
+
+	http.Handle("/user", regHandler())
+
 	const addr = "0.0.0.0:6001"
 	log.Println("webdav server started at", addr)
 	log.Println(http.ListenAndServe(addr, nil))

+ 39 - 0
dav_multiuser_cmd/user.go

@@ -0,0 +1,39 @@
+package main
+
+import (
+	"github.com/ant0ine/go-json-rest/rest"
+	"github.com/tv42/zbase32"
+	"golang.org/x/crypto/bcrypt"
+	"net/http"
+)
+
+type User struct {
+	Login    string
+	Password string
+}
+
+func regHandler() http.Handler {
+	api := rest.NewApi()
+	api.Use(rest.DefaultDevStack...)
+
+	router, _ := rest.MakeRouter(rest.Post("/user", func(resp rest.ResponseWriter, req *rest.Request) {
+		user := &User{}
+		if err := req.DecodeJsonPayload(user); err == nil {
+			if user.Login != "" && user.Password != "" {
+				if _, err := KV.Read(user.Login); err != nil {
+					pwd, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
+					KV.Write(zbase32.EncodeToString([]byte(user.Login)), pwd)
+				} else {
+					rest.Error(resp, "wrong user", 400)
+				}
+			} else {
+				rest.Error(resp, "empty data", 400)
+			}
+		} else {
+			rest.Error(resp, "wrong data", 400)
+		}
+	}))
+
+	api.SetApp(router)
+	return api.MakeHandler()
+}