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"` }