about summary refs log tree commit diff
path: root/login.go
diff options
context:
space:
mode:
Diffstat (limited to 'login.go')
-rw-r--r--login.go75
1 files changed, 75 insertions, 0 deletions
diff --git a/login.go b/login.go
new file mode 100644
index 0000000..3e35858
--- /dev/null
+++ b/login.go
@@ -0,0 +1,75 @@
+package matrix
+
+import (
+	"encoding/json"
+
+	"github.com/h2non/gentleman/plugins/body"
+	"gopkg.in/h2non/gentleman.v2"
+	"gopkg.in/h2non/gentleman.v2/plugins/query"
+)
+
+// Login logs in to the homeserver and returns an Authinfo struct containing
+// information such as the UserID, the HomeServer of the entity that was logged
+// and most important: the AccessToken for further verification
+func Login(username, password, homeserver string) (Authinfo, error) {
+	cli := gentleman.New()
+	cli.URL(homeserver)
+
+	req := cli.Request()
+	req.Path("/_matrix/client/r0/login")
+	req.Method("POST")
+
+	data := map[string]string{
+		"type":     "m.login.password",
+		"user":     username,
+		"password": password,
+	}
+	req.Use(body.JSON(data))
+
+	res, err := req.Send()
+	if err != nil {
+		return Authinfo{}, err
+	}
+	if !res.Ok {
+		return Authinfo{}, err
+	}
+
+	var authinfo Authinfo
+	if err := json.Unmarshal(res.Bytes(), &authinfo); err != nil {
+		return Authinfo{}, err
+	}
+	return authinfo, nil
+}
+
+func Sync(authinfo Authinfo) {
+	cli := gentleman.New()
+	cli.URL(authinfo.HomeServer)
+
+	req := cli.Request()
+	req.Path("/_matrix/client/r0/sync")
+	req.Method("GET")
+
+    req.Use(query.Set("access_token", authinfo.AccessToken))
+
+	res, err := req.Send()
+	if err != nil {
+		return err
+	}
+	if !res.Ok {
+		return err
+	}
+
+	var authinfo Authinfo
+	if err := json.Unmarshal(res.Bytes(), &authinfo); err != nil {
+		return Authinfo{}, err
+	}
+	return authinfo, nil
+}
+
+// Authinfo defines the fields returned after logging in
+type Authinfo struct {
+	UserID      string `json:"user_id"`
+	HomeServer  string `json:"home_server"`
+	DeviceID    string `json:"device_id"`
+	AccessToken string `json:"access_token"`
+}