about summary refs log tree commit diff
path: root/login.go
blob: aa24db5f0db01d086846dcff96b3e5bd654c037f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package matrix

import (
	"encoding/json"

	"gopkg.in/h2non/gentleman.v2"
	"gopkg.in/h2non/gentleman.v2/plugins/body"
)

// 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
	}

	authinfo.HomeServer = homeserver

	return authinfo, nil
}