tgauth

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: GPL-3.0 Imports: 13 Imported by: 0

README

tgAuth

Go package for work telegram login widget

Package provide structure, methods and functions for telegram login widget and imitate his work for non browser clients.

Content

Installation

go get github.com/Richtermnd/tgAuth

Usage

Login

How it works?

  1. Telegram widget send data to server
  2. Server check data and return token
  3. Client send requests with token in Authorization header
  4. MiddlewareTelegramAuth check token.

Package provides a handler for login. You can just use this handler or wrap it in your own handler.

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/Richtermnd/tgauth"
)

const token = "your token"

var ttl = time.Hour * 12

func main() {
	loginHandler := tgauth.LoginHandler(tgauth.FromURL, token, ttl)
	// Simple use
	http.HandleFunc("/login", loginHandler)
	// Wrapped
	http.HandleFunc("/login2", func(w http.ResponseWriter, r *http.Request) {
		log.Println("Wrapped")
		loginHandler(w, r)
	})
	http.ListenAndServe(":8080", nil)
}
Middleware

Package also provides a middleware for telegram auth. Middleware check token in header of request and add user to context if token is valid.

package main

import (
	"encoding/json"
	"net/http"
	"time"

	"github.com/Richtermnd/tgauth"
)

const token = "your token"

var ttl = time.Hour * 12

func main() {
	middleware := tgauth.LoginRequiredMiddleware(token, ttl)
	http.Handle("/me", middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := tgauth.FromContext(r)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		json.NewEncoder(w).Encode(user)
        w.WriteHeader(http.StatusOK)
	})))

	http.ListenAndServe(":8080", nil)
}

Documentation

Index

Constants

View Source
const (
	ContextUserKey ContextKey = "user-data" // key for storing user in context
	TokenSeparator string     = "$"         // Fields separator for token string
)

Variables

View Source
var (
	ErrNoData   = errors.New("no telegram data")
	ErrBadToken = errors.New("bad token")
)

Functions

func LoginHandler

func LoginHandler(loginWay func(r *http.Request) (TelegramUserData, error), token string, ttl time.Duration) func(w http.ResponseWriter, r *http.Request)

func LoginRequiredMiddleware

func LoginRequiredMiddleware(token string, ttl time.Duration) func(next http.Handler) http.Handler

Types

type ContextKey

type ContextKey string

ContextKey used for avoid collision in context

type TelegramUserData

type TelegramUserData struct {
	TGID      int64  `json:"id"`         // telegram id
	FirstName string `json:"first_name"` // first name
	LastName  string `json:"last_name"`  // last name
	Username  string `json:"username"`   // username
	PhotoURL  string `json:"photo_url"`  // photo url
	AuthDate  int64  `json:"auth_date"`  // auth date UNIX timestamp
	Hash      string `json:"hash"`       // hash
}

TelegramUserData - https://core.telegram.org/widgets/login#receiving-authorization-data

func FromContext

func FromContext(r *http.Request) (TelegramUserData, error)

FromContext Get TelegramUserData that middleware put in context.

func FromJSON

func FromJSON(r *http.Request) (TelegramUserData, error)

FromJSON TelegramUserData from body of request.

It doesn't check is data valid, all invalid/empty fields will be ignored. If data is invalid, user will not pass authorisation check.

func FromTokenString

func FromTokenString(token string) (TelegramUserData, error)

FromTokenString parse a TelegramUserData struct from a token string.

The token string is expected to be in the format:

{tg_id}{sep}{first_name}{sep}{last_name}{sep}{username}{sep}{photo_url}{sep}{auth_date}{sep}{hash}

Where {sep} is the TokenSeparator constant.

func FromURL

func FromURL(r *http.Request) (TelegramUserData, error)

FromURL TelegramUserData from query of request

It doesn't check is data valid, all invalid/empty fields will be ignored. If data is invalid, user will not pass authorisation check.

func (*TelegramUserData) GenerateHash

func (u *TelegramUserData) GenerateHash(token string) string

Generate hash from TelegramUserData.

Use this for send TelegramUserData not from telegram widget. Telegram bots for example.

func (*TelegramUserData) IsExpiredData

func (u *TelegramUserData) IsExpiredData(ttl time.Duration) bool

IsExpiredDate Check ttl of telegram data. Return true if data is expired.

func (*TelegramUserData) IsTelegramAuthorization

func (u *TelegramUserData) IsTelegramAuthorization(token string) bool

IsTelegramAuthorization

https://core.telegram.org/widgets/login#checking-authorization

func (*TelegramUserData) TokenString

func (u *TelegramUserData) TokenString() string

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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