auth

package
v0.99.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2024 License: MIT Imports: 12 Imported by: 91

Documentation

Overview

Package auth provides authentication on top of tg.Client.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrPasswordAuthNeeded = errors.New("2FA required")

ErrPasswordAuthNeeded means that 2FA auth is required.

Call Client.Password to provide 2FA password.

View Source
var ErrPasswordInvalid = errors.New("invalid password")

ErrPasswordInvalid means that password provided to Password is invalid.

Note that telegram does not trim whitespace characters by default, check that provided password is expected and clean whitespaces if needed. You can use strings.TrimSpace(password) for this.

View Source
var ErrPasswordNotProvided = errors.New("password requested but not provided")

ErrPasswordNotProvided means that password requested by Telegram, but not provided by user.

Functions

func IsKeyUnregistered deprecated

func IsKeyUnregistered(err error) bool

IsKeyUnregistered reports whether err is AUTH_KEY_UNREGISTERED error.

Deprecated: use IsUnauthorized.

func IsUnauthorized added in v0.54.0

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is 401 UNAUTHORIZED.

https://core.telegram.org/api/errors#401-unauthorized

func NewPasswordHash added in v0.56.0

func NewPasswordHash(
	password []byte,
	algo *tg.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow,
) (hash []byte, _ error)

NewPasswordHash computes new password hash to update password.

Notice that NewPasswordHash mutates given alg.

See https://core.telegram.org/api/srp#setting-a-new-2fa-password.

func PasswordHash added in v0.56.0

func PasswordHash(
	password []byte,
	srpID int64,
	srpB, secureRandom []byte,
	alg tg.PasswordKdfAlgoClass,
) (*tg.InputCheckPasswordSRP, error)

PasswordHash computes password hash to log in.

See https://core.telegram.org/api/srp#checking-the-password-with-srp.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client implements Telegram authentication.

func NewClient

func NewClient(
	api *tg.Client,
	rand io.Reader,
	appID int,
	appHash string,
) *Client

NewClient initializes and returns Telegram authentication client.

func (*Client) AcceptTOS

func (c *Client) AcceptTOS(ctx context.Context, id tg.DataJSON) error

AcceptTOS accepts version of Terms Of Service.

func (*Client) Bot

func (c *Client) Bot(ctx context.Context, token string) (*tg.AuthAuthorization, error)

Bot performs bot authentication request.

func (*Client) CancelPasswordReset added in v0.56.0

func (c *Client) CancelPasswordReset(ctx context.Context) error

CancelPasswordReset cancels password reset.

See https://core.telegram.org/api/srp#password-reset.

func (*Client) IfNecessary

func (c *Client) IfNecessary(ctx context.Context, flow Flow) error

IfNecessary runs given auth flow if current session is not authorized.

func (*Client) Password

func (c *Client) Password(ctx context.Context, password string) (*tg.AuthAuthorization, error)

Password performs login via secure remote password (aka 2FA).

Method can be called after SignIn to provide password if requested.

func (*Client) ResetPassword added in v0.56.0

func (c *Client) ResetPassword(ctx context.Context) (time.Time, error)

ResetPassword resets cloud password and returns time to wait until reset be performed. If time is zero, password was successfully reset.

May return ResetFailedWaitError.

See https://core.telegram.org/api/srp#password-reset.

Example
package main

import (
	"context"
	"fmt"

	"github.com/go-faster/errors"

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/auth"
)

func main() {
	ctx := context.Background()
	client := telegram.NewClient(telegram.TestAppID, telegram.TestAppHash, telegram.Options{})
	if err := client.Run(ctx, func(ctx context.Context) error {
		wait, err := client.Auth().ResetPassword(ctx)
		var waitErr *auth.ResetFailedWaitError
		switch {
		case errors.As(err, &waitErr):
			// Telegram requested wait until making new reset request.
			fmt.Printf("Wait until %s to reset password.\n", wait.String())
		case err != nil:
			return err
		}

		// If returned time is zero, password was successfully reset.
		if wait.IsZero() {
			fmt.Println("Password was reset.")
			return nil
		}

		fmt.Printf("Password will be reset on %s.\n", wait.String())
		return nil
	}); err != nil {
		panic(err)
	}
}
Output:

func (*Client) SendCode

func (c *Client) SendCode(ctx context.Context, phone string, options SendCodeOptions) (tg.AuthSentCodeClass, error)

SendCode requests code for provided phone number, returning code hash and error if any. Use AuthFlow to reduce boilerplate.

This method should be called first in user authentication flow.

func (*Client) SignIn

func (c *Client) SignIn(ctx context.Context, phone, code, codeHash string) (*tg.AuthAuthorization, error)

SignIn performs sign in with provided user phone, code and code hash.

If ErrPasswordAuthNeeded is returned, call Password to provide 2FA password.

To obtain codeHash, use SendCode.

func (*Client) SignUp

func (c *Client) SignUp(ctx context.Context, s SignUp) (*tg.AuthAuthorization, error)

SignUp registers a validated phone number in the system.

To obtain codeHash, use SendCode. Use AuthFlow helper to handle authentication flow.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (*Status, error)

Status gets authorization status of client.

func (*Client) Test added in v0.45.0

func (c *Client) Test(ctx context.Context, dc int) error

Test creates and runs auth flow using Test authenticator if current session is not authorized.

func (*Client) TestUser added in v0.45.0

func (c *Client) TestUser(ctx context.Context, phone string, dc int) error

TestUser creates and runs auth flow using TestUser authenticator if current session is not authorized.

func (*Client) UpdatePassword added in v0.56.0

func (c *Client) UpdatePassword(
	ctx context.Context,
	newPassword string,
	opts UpdatePasswordOptions,
) error

UpdatePassword sets new cloud password for this account.

See https://core.telegram.org/api/srp#setting-a-new-2fa-password.

Example
package main

import (
	"context"

	"github.com/gotd/td/telegram"
	"github.com/gotd/td/telegram/auth"
)

func main() {
	ctx := context.Background()
	client := telegram.NewClient(telegram.TestAppID, telegram.TestAppHash, telegram.Options{})
	if err := client.Run(ctx, func(ctx context.Context) error {
		// Updating password.
		if err := client.Auth().UpdatePassword(ctx, "new_password", auth.UpdatePasswordOptions{
			// Hint sets new password hint.
			Hint: "new password hint",
			// Password will be called if old password is requested by Telegram.
			//
			// If password was requested and Password is nil, auth.ErrPasswordNotProvided error will be returned.
			Password: func(ctx context.Context) (string, error) {
				return "old_password", nil
			},
		}); err != nil {
			return err
		}

		return nil
	}); err != nil {
		panic(err)
	}
}
Output:

type CodeAuthenticator

type CodeAuthenticator interface {
	Code(ctx context.Context, sentCode *tg.AuthSentCode) (string, error)
}

CodeAuthenticator asks user for received authentication code.

type CodeAuthenticatorFunc

type CodeAuthenticatorFunc func(ctx context.Context, sentCode *tg.AuthSentCode) (string, error)

CodeAuthenticatorFunc is functional wrapper for CodeAuthenticator.

func (CodeAuthenticatorFunc) Code

func (c CodeAuthenticatorFunc) Code(ctx context.Context, sentCode *tg.AuthSentCode) (string, error)

Code implements CodeAuthenticator interface.

type Flow

type Flow struct {
	Auth    UserAuthenticator
	Options SendCodeOptions
}

Flow simplifies boilerplate for authentication flow.

func NewFlow

func NewFlow(auth UserAuthenticator, opt SendCodeOptions) Flow

NewFlow initializes new authentication flow.

func (Flow) Run

func (f Flow) Run(ctx context.Context, client FlowClient) error

Run starts authentication flow on client.

type FlowClient

type FlowClient interface {
	SignIn(ctx context.Context, phone, code, codeHash string) (*tg.AuthAuthorization, error)
	SendCode(ctx context.Context, phone string, options SendCodeOptions) (tg.AuthSentCodeClass, error)
	Password(ctx context.Context, password string) (*tg.AuthAuthorization, error)
	SignUp(ctx context.Context, s SignUp) (*tg.AuthAuthorization, error)
}

FlowClient abstracts telegram client for Flow.

type ResetFailedWaitError added in v0.56.0

type ResetFailedWaitError struct {
	Result tg.AccountResetPasswordFailedWait
}

ResetFailedWaitError reports that you recently requested a password reset that was cancel and need to wait until the specified date before requesting another reset.

func (*ResetFailedWaitError) Error added in v0.56.0

func (r *ResetFailedWaitError) Error() string

Error implements error.

func (ResetFailedWaitError) Until added in v0.56.0

Until returns time required to wait.

type SendCodeOptions

type SendCodeOptions struct {
	// AllowFlashCall allows phone verification via phone calls.
	AllowFlashCall bool
	// Pass true if the phone number is used on the current device.
	// Ignored if AllowFlashCall is not set.
	CurrentNumber bool
	// If a token that will be included in eventually sent SMSs is required:
	// required in newer versions of android, to use the android SMS receiver APIs.
	AllowAppHash bool
}

SendCodeOptions defines how to send auth code to user.

type SignUp

type SignUp struct {
	PhoneNumber   string
	PhoneCodeHash string
	FirstName     string
	LastName      string
}

SignUp wraps parameters for SignUp.

type SignUpRequired

type SignUpRequired struct {
	TermsOfService tg.HelpTermsOfService
}

SignUpRequired means that log in failed because corresponding account does not exist, so sign up is required.

func (*SignUpRequired) Error

func (s *SignUpRequired) Error() string

func (*SignUpRequired) Is

func (s *SignUpRequired) Is(err error) bool

Is returns true if err is SignUpRequired.

type Status

type Status struct {
	// Authorized is true if client is authorized.
	Authorized bool
	// User is current User object.
	User *tg.User
}

Status represents authorization status.

type UpdatePasswordOptions added in v0.56.0

type UpdatePasswordOptions struct {
	// Hint is new password hint.
	Hint string
	// Password is password callback.
	//
	// If password was requested and Password is nil, ErrPasswordNotProvided error will be returned.
	Password func(ctx context.Context) (string, error)
}

UpdatePasswordOptions is options structure for UpdatePassword.

type UserAuthenticator

type UserAuthenticator interface {
	Phone(ctx context.Context) (string, error)
	Password(ctx context.Context) (string, error)
	AcceptTermsOfService(ctx context.Context, tos tg.HelpTermsOfService) error
	SignUp(ctx context.Context) (UserInfo, error)
	CodeAuthenticator
}

UserAuthenticator asks user for phone, password and received authentication code.

func CodeOnly

func CodeOnly(phone string, code CodeAuthenticator) UserAuthenticator

CodeOnly creates UserAuthenticator with constant phone and no password.

func Constant

func Constant(phone, password string, code CodeAuthenticator) UserAuthenticator

Constant creates UserAuthenticator with constant phone and password.

func Env

func Env(prefix string, code CodeAuthenticator) UserAuthenticator

Env creates UserAuthenticator which gets phone and password from environment variables.

func Test

func Test(randReader io.Reader, dc int) UserAuthenticator

Test returns UserAuthenticator that authenticates via testing credentials.

Can be used only with testing server. Will perform sign up if test user is not registered.

func TestUser added in v0.45.0

func TestUser(phone string, dc int) UserAuthenticator

TestUser returns UserAuthenticator that authenticates via testing credentials. Uses given phone to sign in/sign up.

Can be used only with testing server. Will perform sign up if test user is not registered.

type UserInfo

type UserInfo struct {
	FirstName string
	LastName  string
}

UserInfo represents user info required for sign up.

Directories

Path Synopsis
Package qrlogin provides QR login flow implementation.
Package qrlogin provides QR login flow implementation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL