// Package qrlogin provides QR login flow implementation. // // See https://core.telegram.org/api/qr-login.
package qrlogin import ( ) // QR implements Telegram QR login flow. type QR struct { api *tg.Client appID int appHash string migrate func(ctx context.Context, dcID int) error clock clock.Clock password func(ctx context.Context) (string, error) } // NewQR creates new QR func ( *tg.Client, int, string, Options) QR { .setDefaults() return QR{ api: , appID: , appHash: , clock: .Clock, migrate: .Migrate, password: .Password, } } // ExportResult is a result of exporting login token. // // Exactly one field is set. type ExportResult struct { // Token is set for auth.loginToken: show it and wait for acceptance. Token Token // Authorization is set for auth.loginTokenSuccess: token was already // accepted and login is complete. Authorization *tg.AuthAuthorization // MigrateTo is set for auth.loginTokenMigrateTo: login should be // completed via auth.importLoginToken on given DC. MigrateTo *tg.AuthLoginTokenMigrateTo } // ExportResult exports new login token, returning authorization if token // was already accepted. // // See https://core.telegram.org/api/qr-login#exporting-a-login-token. func ( QR) ( context.Context, ...int64) (ExportResult, error) { , := .export(, ...) if != nil { return ExportResult{}, } switch t := .(type) { case *tg.AuthLoginToken: return ExportResult{Token: NewToken(.Token, .Expires)}, nil case *tg.AuthLoginTokenSuccess: , := .Authorization.(*tg.AuthAuthorization) if ! { return ExportResult{}, errors.Errorf("unexpected type %T", .Authorization) } return ExportResult{Authorization: }, nil case *tg.AuthLoginTokenMigrateTo: return ExportResult{MigrateTo: }, nil default: return ExportResult{}, errors.Errorf("unexpected type %T", ) } } // Export exports new login token. // // If token was already accepted (auth.loginTokenSuccess), Export returns an // empty token and the authorization is discarded; use ExportResult to get it. // If migration is needed, Export returns *MigrationNeededError. // // See https://core.telegram.org/api/qr-login#exporting-a-login-token. func ( QR) ( context.Context, ...int64) (Token, error) { , := .export(, ...) if != nil { return Token{}, } switch t := .(type) { case *tg.AuthLoginToken: return NewToken(.Token, .Expires), nil case *tg.AuthLoginTokenSuccess: // Token was already accepted, authentication successful. return Token{}, nil case *tg.AuthLoginTokenMigrateTo: return Token{}, &MigrationNeededError{ MigrateTo: , } default: return Token{}, errors.Errorf("unexpected type %T", ) } } func ( QR) ( context.Context, ...int64) (tg.AuthLoginTokenClass, error) { , := .api.AuthExportLoginToken(, &tg.AuthExportLoginTokenRequest{ APIID: .appID, APIHash: .appHash, ExceptIDs: , }) if != nil { return nil, errors.Wrap(, "export") } return , nil } // Accept accepts given token. // // See https://core.telegram.org/api/qr-login#accepting-a-login-token. func ( QR) ( context.Context, Token) (*tg.Authorization, error) { return AcceptQR(, .api, ) } // Import imports accepted token. // // If the account has 2FA password and Options.Password is set, the password // is checked, otherwise SESSION_PASSWORD_NEEDED error is returned. // // See https://core.telegram.org/api/qr-login#confirming-importing-the-login-token. func ( QR) ( context.Context) (*tg.AuthAuthorization, error) { , := .importToken() if .needPassword() { return .checkPassword() } return , } // needPassword reports whether err requests 2FA password and it can be // provided. func ( QR) ( error) bool { return != nil && .password != nil && tgerr.Is(, "SESSION_PASSWORD_NEEDED") } func ( QR) ( context.Context) (*tg.AuthAuthorization, error) { , := .password() if != nil { return nil, errors.Wrap(, "get password") } , := auth.NewClient(.api, crypto.DefaultRand(), .appID, .appHash).Password(, ) if != nil { return nil, errors.Wrap(, "check password") } return , nil } func ( QR) ( context.Context) (*tg.AuthAuthorization, error) { , := .api.AuthExportLoginToken(, &tg.AuthExportLoginTokenRequest{ APIID: .appID, APIHash: .appHash, }) if != nil { return nil, errors.Wrap(, "import") } switch t := .(type) { case *tg.AuthLoginTokenMigrateTo: return .importMigrated(, ) case *tg.AuthLoginTokenSuccess: , := .Authorization.(*tg.AuthAuthorization) if ! { return nil, errors.Errorf("unexpected type %T", .Authorization) } return , nil default: return nil, errors.Errorf("unexpected type %T", ) } } // importMigrated completes the login of an account on another DC: migrates // to it and imports the token there. It returns *MigrationNeededError if no // migrate function is set. func ( QR) ( context.Context, *tg.AuthLoginTokenMigrateTo) (*tg.AuthAuthorization, error) { if .migrate == nil { return nil, &MigrationNeededError{ MigrateTo: , } } if := .migrate(, .DCID); != nil { return nil, errors.Wrap(, "migrate") } , := .api.AuthImportLoginToken(, .Token) if != nil { return nil, errors.Wrap(, "import") } , := .(*tg.AuthLoginTokenSuccess) if ! { return nil, errors.Errorf("unexpected type %T", ) } , := .Authorization.(*tg.AuthAuthorization) if ! { return nil, errors.Errorf("unexpected type %T", .Authorization) } return , nil } // finishMigrated is importMigrated with the 2FA check of Import. func ( QR) ( context.Context, *tg.AuthLoginTokenMigrateTo) (*tg.AuthAuthorization, error) { , := .importMigrated(, ) if .needPassword() { return .checkPassword() } return , } // LoggedIn is signal channel to notify about tg.UpdateLoginToken. type LoggedIn <-chan struct{} // OnLoginToken sets handler for given dispatcher and returns signal channel. // // The channel is a latch: an update received while nobody is waiting on the // channel (e.g. during show callback or token export) is kept until read. func ( interface { (tg.LoginTokenHandler) }, ) LoggedIn { := make(chan struct{}, 1) .(func( context.Context, tg.Entities, *tg.UpdateLoginToken) error { select { case <- struct{}{}: default: // Signal is already pending. } return nil }) return } const ( // minTokenWait is the minimum delay before token refresh, protecting // against busy loop if the local clock is ahead of server time. minTokenWait = time.Second // minRetryDelay and maxRetryDelay bound backoff of token refresh retries. minRetryDelay = time.Second maxRetryDelay = time.Minute ) // retryableExportError reports whether token refresh can be retried after err. func ( error) bool { if , := tgerr.AsFloodWait(); { return true } if , := tgerr.As(); { // Internal server errors are transient, other RPC errors are fatal. return .Code >= 500 } // Non-RPC errors (e.g. connection issues) are transient. return true } // nextRetryDelay returns backoff delay after prev delay for given error. func ( time.Duration, error) time.Duration { := min(max(2*, minRetryDelay), maxRetryDelay) if , := tgerr.AsFloodWait(); && > { = } return } // Auth generates new QR login token, shows it and awaits acceptation. // // NB: Show callback may be called more than once if QR expires. // // Transient errors of token refresh are retried with backoff. // // If the token is accepted by an account of another DC, the login is // completed there via Options.Migrate (as in Import), also when the // acceptance is seen on a token refresh instead of updateLoginToken. Without // Options.Migrate, *MigrationNeededError is returned. func ( QR) ( context.Context, LoggedIn, func( context.Context, Token) error, ...int64, ) (*tg.AuthAuthorization, error) { := func( Token) time.Duration { // TODO: use server time when available, as tdlib does. return max(.Expires().Sub(.clock.Now()).Truncate(time.Second), minTokenWait) } , := .ExportResult(, ...) if != nil { if .needPassword() { return .checkPassword() } return nil, } switch { case .Authorization != nil: // Token was already accepted (e.g. before restart on the same // session): the update has already happened, do not wait for it. return .Authorization, nil case .MigrateTo != nil: // Token was already accepted by an account of another DC. return .finishMigrated(, .MigrateTo) } := .Token := .clock.Timer(()) defer clock.StopTimer() var ( time.Duration = true ) for { if { if := (, ); != nil { return nil, errors.Wrap(, "show") } = false } select { case <-.Done(): return nil, errors.Wrap(.Err(), "wait for login") case <-: return .Import() case <-.C(): } , := .ExportResult(, ...) if != nil { // Token may be accepted right before expiration (or the // update is missed), so 2FA can be requested here too. if .needPassword() { return .checkPassword() } if := .Err(); != nil { return nil, errors.Wrap(, "refresh token") } if !retryableExportError() { return nil, } // Keep showing current token, it may still be scanned. = nextRetryDelay(, ) .Reset() continue } = 0 switch { case .Authorization != nil: // QR was scanned and accepted, no need to export again. return .Authorization, nil case .MigrateTo != nil: // QR was accepted by an account of another DC (the update // may come late or not at all): complete the login there. return .finishMigrated(, .MigrateTo) } = .Token = true .Reset(()) } }