login

package
v0.0.0-...-d76ec73 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2020 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package login contains methods for obtaining structure of the user data and its validation.

Example (FastStart)
package main

import (
	"fmt"
	"log"

	"github.com/fasthttp/router"
	http "github.com/valyala/fasthttp"
	"gitlab.com/toby3d/telegram/login"
)

const htmlTemplate string = `<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Telegram login</title>
  </head>
  <body>
    <script async src="https://telegram.org/js/telegram-widget.js?11" data-telegram-login="toby3dBot"
      data-size="large" data-auth-url="https://example.site/callback" data-request-access="write"></script>
  </body>
</html>`

func main() {
	// Use bot AccessToken from @BotFather as ClientSecret.
	c := login.Config{
		ClientSecret:       "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
		RedirectURL:        "https://example.site/callback",
		RequestWriteAccess: true,
	}

	// Create example server with authorization and token (callback) handlers.
	r := router.New()
	r.GET("/", func(ctx *http.RequestCtx) {
		// Render page with embeded Telegram Login button (until Telegram enable the possibility of login by
		// link.)
		ctx.SuccessString("text/html", htmlTemplate)

		// NOTE(toby3d): Telegram does not yet allow you to login without script via a link, as is common
		// in traditional OAuth2 applications, stopping at the last step with redirect to callback. The
		// 'embed=[0|1]' parameter has no effect now, which is very similar to a bug.
		//ctx.SuccessString("text/html", fmt.Sprintf(htmlTemplate, c.AuthCodeURL(language.English)))
	})
	r.GET("/callback", func(ctx *http.RequestCtx) {
		q := ctx.QueryArgs()
		u := login.User{
			AuthDate:  int64(q.GetUintOrZero(login.KeyAuthDate)),
			FirstName: string(q.Peek(login.KeyFirstName)),
			Hash:      string(q.Peek(login.KeyHash)),
			ID:        q.GetUintOrZero(login.KeyID),
			LastName:  string(q.Peek(login.KeyLastName)),
			PhotoURL:  string(q.Peek(login.KeyPhotoURL)),
			Username:  string(q.Peek(login.KeyUsername)),
		}

		if !c.Verify(&u) {
			ctx.Error("Unable to verify data", http.StatusUnauthorized)
			return
		}

		ctx.SuccessString("text/plain", fmt.Sprintf("Hello, %s!", u.FullName()))
	})

	if err := http.ListenAndServe(":80", r.Handler); err != nil {
		log.Fatalln(err.Error())
	}
}
Output:

Index

Examples

Constants

View Source
const (
	KeyAuthDate  string = "auth_date"
	KeyFirstName string = "first_name"
	KeyHash      string = "hash"
	KeyID        string = "id"
	KeyLastName  string = "last_name"
	KeyPhotoURL  string = "photo_url"
	KeyUsername  string = "username"
)

Key represents available and supported query arguments keys.

View Source
const Endpoint string = "https://oauth.telegram.org/auth"

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// ClientSecret is the bot token.
	ClientSecret string

	// RedirectURL is the URL to redirect users going through the login flow.
	RedirectURL string

	// RequestWriteAccess request the permission for bot to send messages to the user.
	RequestWriteAccess bool
}

func (*Config) AuthCodeURL

func (c *Config) AuthCodeURL(lang language.Tag) string

AuthCodeURL returns a URL to Telegram login page that asks for permissions for the required scopes explicitly.

func (Config) ClientID

func (c Config) ClientID() string

ClientID returns bot ID from it's ClientSecret token.

func (*Config) Verify

func (c *Config) Verify(u *User) bool

Verify verify the authentication and the integrity of the data received by comparing the received hash parameter with the hexadecimal representation of the HMAC-SHA-256 signature of the data-check-string with the SHA256 hash of the bot's token used as a secret key.

type User

type User struct {
	AuthDate  int64  `json:"auth_date"`
	FirstName string `json:"first_name"`
	Hash      string `json:"hash"`
	ID        int    `json:"id"`
	LastName  string `json:"last_name,omitempty"`
	PhotoURL  string `json:"photo_url,omitempty"`
	Username  string `json:"username,omitempty"`
}

User contains data about authenticated user.

func (User) AuthTime

func (u User) AuthTime() time.Time

AuthTime convert AuthDate field into time.Time.

func (User) FullName

func (u User) FullName() string

FullName return user first name only or full name if last name is present.

func (User) HasLastName

func (u User) HasLastName() bool

HasLastName checks what the current user has a LastName.

func (User) HasPhoto

func (u User) HasPhoto() bool

HasPhoto checks what the current user has a photo.

func (User) HasUsername

func (u User) HasUsername() bool

HasUsername checks what the current user has a username.

Jump to

Keyboard shortcuts

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