-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
auth_status.go
54 lines (45 loc) · 1.08 KB
/
auth_status.go
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
package telegram
import (
"context"
"golang.org/x/xerrors"
"github.com/gotd/td/tg"
"github.com/gotd/td/tgerr"
)
// AuthStatus represents authorization status.
type AuthStatus struct {
// Authorized is true if client is authorized.
Authorized bool
// User is current User object.
User *tg.User
}
func unauthorized(err error) bool {
return tgerr.Is(err, "AUTH_KEY_UNREGISTERED")
}
// AuthStatus gets authorization status of client.
func (c *Client) AuthStatus(ctx context.Context) (*AuthStatus, error) {
u, err := c.Self(ctx)
if err != nil {
if unauthorized(err) {
return &AuthStatus{}, nil
}
return nil, err
}
return &AuthStatus{
Authorized: true,
User: u,
}, nil
}
// AuthIfNecessary runs given auth flow if current session is not authorized.
func (c *Client) AuthIfNecessary(ctx context.Context, flow AuthFlow) error {
auth, err := c.AuthStatus(ctx)
if err != nil {
return xerrors.Errorf("get auth status: %w", err)
}
if auth.Authorized {
return nil
}
if err := flow.Run(ctx, c); err != nil {
return xerrors.Errorf("auth flow: %w", err)
}
return nil
}