Avatar Ilya Mateyko

go.astrophena.name/base Module

GitHub repository | Commit (49382e9)

Base Go packages for my projects.

package tgauth

import "go.astrophena.name/base/tgauth"

Package tgauth provides middleware for handling Telegram authentication.

See https://core.telegram.org/widgets/login for details.

Index

Types

type Identity

type Identity struct {
	ID        int64
	Username  string
	FirstName string
	LastName  string
	PhotoURL  string
	AuthDate  time.Time
}

Identity contains information about the logged in user.

func Identify

func Identify(r *http.Request) *Identity

Identify returns the Identity value stored in ctx, returning nil in case it doesn't exist.

type Middleware

type Middleware struct {
	// CheckFunc is a function that checks if the authenticated user is allowed to
	// access the resource. If CheckFunc is nil, all authenticated users are
	// allowed.
	CheckFunc func(*http.Request, *Identity) bool
	// Token is a Telegram bot token.
	Token string
	// TTL is the time-to-live for a user session. If set, the session expires
	// after this time; otherwise, it doesn't.
	TTL time.Duration
}

Middleware is a middleware for handling Telegram authentication.

func (*Middleware) LoggedIn

func (mw *Middleware) LoggedIn(r *http.Request) bool

LoggedIn reports if the user is logged in.

func (*Middleware) LoginHandler

func (mw *Middleware) LoginHandler(redirectTarget string) http.Handler

LoginHandler returns a handler that handles Telegram authentication.

It expects to receive authentication data as query parameters from Telegram, validates it, and sets cookies.

If authentication is successful, the user is redirected to redirectTarget.

func (*Middleware) LogoutHandler

func (mw *Middleware) LogoutHandler(redirectTarget string) http.Handler

LogoutHandler returns a handler that logs the user out. After that, the user is redirected to redirectTarget.

func (*Middleware) Middleware

func (mw *Middleware) Middleware(enforceAuth bool) func(next http.Handler) http.Handler

Middleware returns a middleware that identifies the user and optionally checks if the user is logged in.

If the user is not logged in, it responds with an error web.ErrUnauthorized.

Otherwise, it calls the next handler.