auth

package module
v0.1.20 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 10 Imported by: 4

README

simpauth

Go HTTP user authentication library with cookie-based session storage.

Features

  • Simple API with minimal configuration
  • Cookie-based session with HttpOnly (serialized with msgp for compact size)
  • Multiple token sources: Header, Cookie, URL param
  • Auto refresh when nearing expiration
  • Context integration for user propagation
  • Works with standard net/http and Fiber

Install

go get github.com/liut/simpauth

Usage

import auth "github.com/liut/simpauth"

// Create authorizer
authorizer := auth.New(
    auth.WithCookie("_user", "/", "example.net"), // cookie name, path, domain
    auth.WithMaxAge(3600),                        // max age in seconds
    auth.WithRefresh(),                           // auto refresh
)

// Login
func login(w http.ResponseWriter, r *http.Request) {
    user := &auth.User{
        UID:  "user123",
        Name: "John",
    }
    user.Refresh()
    authorizer.Signin(user, w)
}

// Protected handler
func welcome(w http.ResponseWriter, r *http.Request) {
    user, ok := auth.UserFromContext(r.Context())
    if !ok {
        http.Error(w, "Unauthorized", 401)
        return
    }
    fmt.Fprintf(w, "Welcome, %s", user.Name)
}

// Apply middleware
handler := authorizer.Middleware()(http.HandlerFunc(welcome))

Token Sources

Checked in order:

  1. Authorization: Bearer <token> header
  2. Cookie
  3. URL parameter ?token=<token>

Options

  • WithCookie(name, path, domain) - Configure cookie
  • WithMaxAge(seconds) - Session lifetime, default 3600s
  • WithRefresh() - Auto refresh when nearing expiration
  • WithURI(redirectURL) - Redirect URL when unauthorized

Sign Out

authorizer.Signout(w)

Convert Custom User Types

Implement IUser interface and use ToUser():

type IUser interface {
    GetOID() string
    GetUID() string
    GetName() string
    GetAvatar() string
}

authUser := auth.ToUser(myUser)

Documentation

Index

Constants

View Source
const (
	UserKey ctxKey = iota
)

consts

Variables

View Source
var (
	DefaultLifetime int64 = 3600
	Guest                 = &User{}
)

vars

View Source
var (
	ErrNoTokenInRequest = errors.New("no token present in request")
)

vars

Functions

func ContextWithUser added in v0.1.1

func ContextWithUser(ctx context.Context, user IUser) context.Context

ContextWithUser ...

func Middleware added in v0.1.0

func Middleware(opts ...OptFunc) func(next http.Handler) http.Handler

Middleware ...

func Signin

func Signin(user Encoder, w http.ResponseWriter) error

Signin write user encoded string into cookie, Deprecated

func Signout

func Signout(w http.ResponseWriter)

Signout setcookie with empty, Deprecated

func TokenFrom added in v0.1.3

func TokenFrom(args ...any) string

TokenFrom return token string valid interfaces: *http.Request, Request.Header, *fiber.Ctx

func WithRedirect

func WithRedirect(uri string) func(next http.Handler) http.Handler

WithRedirect ... Deprecated by Middleware(WithURI(uri))

Types

type Authorizer added in v0.1.4

type Authorizer interface {
	Middleware() func(next http.Handler) http.Handler
	MiddlewareWordy(redir bool) func(next http.Handler) http.Handler
	UserFromRequest(r *http.Request) (user *User, err error)
	TokenFromRequest(r *http.Request) (s string, err error)
	TokenFrom(args ...any) string
	Cooking(value string) *http.Cookie
	Signin(user Encoder, w http.ResponseWriter) error
	Signout(w http.ResponseWriter)
	With(opts ...OptFunc)
}

Authorizer ...

func Default added in v0.1.7

func Default() Authorizer

Default return default instance

func New added in v0.1.4

func New(opts ...OptFunc) Authorizer

New build option with args

func NewOption added in v0.1.1

func NewOption(opts ...OptFunc) Authorizer

NewOption ..., Deprecated: use New()

type Cookier added in v0.1.3

type Cookier interface {
	Cookie(k string) (*http.Cookie, error)
}

Cookier ex: http.Request

type Encoder added in v0.1.4

type Encoder interface {
	Encode() (string, error)
}

Encoder ...

type FormValuer added in v0.1.3

type FormValuer interface {
	FormValue(k string) string
}

FormValuer ex: http.Request

type Getter added in v0.1.3

type Getter interface {
	Get(k string) string
}

Getter ex: Request.Header

type IUser added in v0.1.16

type IUser interface {
	GetOID() string
	GetUID() string  // uid
	GetName() string // nickname
	GetAvatar() string
}

IUser ...

func UserFromContext

func UserFromContext(ctx context.Context) (IUser, bool)

UserFromContext ...

type Names

type Names []string

Names ...

func (Names) Has

func (z Names) Has(name string) bool

Has ...

func (Names) MarshalMsg

func (z Names) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (Names) Msgsize

func (z Names) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*Names) UnmarshalMsg

func (z *Names) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type OptFunc added in v0.1.0

type OptFunc func(opt *option)

OptFunc ...

func WithCookie added in v0.1.4

func WithCookie(name string, args ...string) OptFunc

WithCookie set cookie 1-3 options: name, path, domain, see also http.Cookie

func WithHeader added in v0.1.17

func WithHeader(key string) OptFunc

func WithMaxAge added in v0.1.4

func WithMaxAge(age int) OptFunc

WithMaxAge set cookie max age: >= 0, default 3600, see also http.Cookie

func WithRefresh added in v0.1.0

func WithRefresh() OptFunc

WithRefresh The option with auto refresh

func WithURI added in v0.1.0

func WithURI(uri string) OptFunc

WithURI The option with redirect uri

type User

type User struct {
	OID       string `json:"oid,omitzero" msg:"i"` // pk id, objectID, see define in andvari
	UID       string `json:"uid" msg:"u"`          // username, login name
	Name      string `json:"name" msg:"n"`         // nickname, realname, display name
	Avatar    string `json:"avatar,omitzero" msg:"a"`
	LastHit   int64  `json:"hit,omitzero" msg:"h"`
	TeamID    int64  `json:"tid,omitzero" msg:"t"`
	Roles     Names  `json:"roles,omitzero" msg:"r"`
	Watchings Names  `json:"watching,omitzero" msg:"w"`
}

User 在线用户

func ToUser added in v0.1.16

func ToUser(u IUser) User

func UserFromRequest

func UserFromRequest(r *http.Request) (user *User, err error)

UserFromRequest get user from cookie, Deprecated

func (*User) Decode

func (u *User) Decode(s string) (err error)

Decode ...

func (User) Encode

func (u User) Encode() (s string, err error)

Encode ...

func (User) GetAvatar added in v0.1.19

func (u User) GetAvatar() string

func (User) GetName added in v0.1.10

func (u User) GetName() string

func (User) GetOID added in v0.1.20

func (u User) GetOID() string

func (User) GetUID added in v0.1.10

func (u User) GetUID() string

func (*User) IsExpired

func (u *User) IsExpired() bool

IsExpired ...

func (*User) IsExpiredWith added in v0.1.16

func (u *User) IsExpiredWith(lifetime int64) bool

IsExpiredWith checks if the user is expired with given lifetime in seconds.

func (*User) MarshalMsg

func (z *User) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (*User) Msgsize

func (z *User) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*User) NeedRefresh

func (u *User) NeedRefresh() bool

NeedRefresh checks if the user needs refresh.

func (*User) NeedRefreshWith added in v0.1.16

func (u *User) NeedRefreshWith(lifetime int64) bool

NeedRefreshWith checks if the user needs refresh with given lifetime in seconds.

func (*User) Refresh

func (u *User) Refresh()

Refresh lastHit to time Unix

func (*User) Signin

func (user *User) Signin(w http.ResponseWriter) error

Signin call Signin for login

func (*User) UnmarshalMsg

func (z *User) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

Jump to

Keyboard shortcuts

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