summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/matterbridge/Rocket.Chat.Go.SDK/realtime/users.go
blob: 09a4f1f46acfba3f7bca521ff031d6007c34ed50 (plain) (blame)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package realtime

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"

	"github.com/Jeffail/gabs"
	"github.com/matterbridge/Rocket.Chat.Go.SDK/models"
)

type ddpLoginRequest struct {
	User     ddpUser     `json:"user"`
	Password ddpPassword `json:"password"`
}

type ddpTokenLoginRequest struct {
	Token string `json:"resume"`
}

type ddpUser struct {
	Email string `json:"email"`
}

type ddpPassword struct {
	Digest    string `json:"digest"`
	Algorithm string `json:"algorithm"`
}

// RegisterUser a new user on the server. This function does not need a logged in user. The registered user gets logged in
// to set its username.
func (c *Client) RegisterUser(credentials *models.UserCredentials) (*models.User, error) {

	if _, err := c.ddp.Call("registerUser", credentials); err != nil {
		return nil, err
	}

	user, err := c.Login(credentials)
	if err != nil {
		return nil, err
	}

	if _, err := c.ddp.Call("setUsername", credentials.Name); err != nil {
		return nil, err
	}

	return user, nil
}

// Login a user.
// token shouldn't be nil, otherwise the password and the email are not allowed to be nil.
//
// https://rocket.chat/docs/developer-guides/realtime-api/method-calls/login/
func (c *Client) Login(credentials *models.UserCredentials) (*models.User, error) {
	var request interface{}
	if credentials.Token != "" {
		request = ddpTokenLoginRequest{
			Token: credentials.Token,
		}
	} else {
		digest := sha256.Sum256([]byte(credentials.Password))
		request = ddpLoginRequest{
			User: ddpUser{Email: credentials.Email},
			Password: ddpPassword{
				Digest:    hex.EncodeToString(digest[:]),
				Algorithm: "sha-256",
			},
		}
	}

	rawResponse, err := c.ddp.Call("login", request)
	if err != nil {
		return nil, err
	}

	user := getUserFromData(rawResponse.(map[string]interface{}))
	if credentials.Token == "" {
		credentials.ID, credentials.Token = user.ID, user.Token
	}

	return user, nil
}

func getUserFromData(data interface{}) *models.User {
	document, _ := gabs.Consume(data)

	expires, _ := strconv.ParseFloat(stringOrZero(document.Path("tokenExpires.$date").Data()), 64)
	return &models.User{
		ID:           stringOrZero(document.Path("id").Data()),
		Token:        stringOrZero(document.Path("token").Data()),
		TokenExpires: int64(expires),
	}
}

// SetPresence set user presence
func (c *Client) SetPresence(status string) error {
	_, err := c.ddp.Call("UserPresence:setDefaultStatus", status)
	if err != nil {
		return err
	}

	return nil
}