client

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: May 23, 2024 License: MIT Imports: 15 Imported by: 2

README

Staffio client and general OAuth2 client

settings with environment

OAUTH_CLIENT_ID=
OAUTH_CLIENT_SECRET=
OAUTH_PREFIX=https://staffio.work
OAUTH_URI_AUTHORIZE=/authorize
OAUTH_URI_TOKEN=/token
OAUTH_URI_INFO=/info/me
OAUTH_REDIRECT_URL=/auth/callback
OAUTH_SCOPES='openid'

Example for staffio SP

package main

import (
	"fmt"
	"net/http"

	staffio "github.com/liut/staffio-client"
)

func main() {

	loginPath := "/auth/login"
	staffio.SetLoginPath(loginPath)
	staffio.SetAdminPath("/admin")

	http.HandleFunc(loginPath, staffio.LoginHandler)
	http.Handle("/auth/callback", staffio.AuthCodeCallback("admin"))

	authF1 := staffio.Middleware()
	authF1 := staffio.Middleware(staffio.WithRefresh()) // auto refresh token time
	authF1 := staffio.Middleware(staffio.WithRefresh(), staffio.WithURI(loginPath)) // auto refresh and redirect
	http.Handle("/admin", authF1(http.HandlerFunc(handlerAdminWelcome)))
	// more handlers
}

func handlerAdminWelcome(w http.ResponseWriter, r *http.Request) {
	user := staffio.UserFromContext(r.Context())
	fmt.Fprintf(w, "welcome %s", user.Name)
}


// Middleware for gin
func Middleware(opts ...staffio.OptFunc) gin.HandlerFunc {
	option := staffio.NewOption(opts...)
	return func(c *gin.Context) {
		user, err := staffio.UserFromRequest(c.Request)
		if err != nil {
			if option.URI != "" {
				c.Redirect(http.StatusFound, option.URI)
			} else {
				c.AbortWithStatus(http.StatusUnauthorized)
			}
			return
		}
		if option.Refresh && user.NeedRefresh() {
			user.Refresh()
			user.Signin(c.Writer)
		}
		req := c.Request
		c.Request = req.WithContext(staffio.ContextWithUser(req.Context(), user))
		c.Next()
	}
}

// UserFromContext for gin
func UserFromContext(c *gin.Context) (user *User, ok bool) {
	return staffio.UserFromContext(c.Request.Context())
}

// AuthCodeCallback for gin handler which for Check auth with role[s] when auth-code callback
func AuthCodeCallback(roleName ...string) gin.HandlerFunc {
	return gin.WrapH(staffio.AuthCodeCallback(roleName...))
}


// HandlerShowMe for gin
func HandlerShowMe(c *gin.Context) {
	user, ok := staffio.UserFromContext(c.Request.Context())
	if !ok {
		c.AbortWithStatus(http.StatusUnauthorized)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"me":    user,
	})
}

Documentation

Index

Constants

View Source
const (
	TokenKey ctxKey = iota
)

Variables

View Source
var (
	UserFromRequest = auth.UserFromRequest
	UserFromContext = auth.UserFromContext
	ContextWithUser = auth.ContextWithUser

	NewAuth = auth.New
)

vars

View Source
var (
	ErrNoToken = errors.New("oauth2 token not found")
	ErrNoRole  = errors.New("the user not in special roles")

	AdminPath = "/admin/"
	LoginPath = "/auth/login"
)

Functions

func AuthCodeCallback

func AuthCodeCallback(roles ...string) http.Handler

AuthCodeCallback Handler for Check auth with role[s] when auth-code callback

func AuthCodeCallbackWrap

func AuthCodeCallbackWrap(next http.Handler) http.Handler

AuthCodeCallbackWrap is a middleware that injects a InfoToken with roles into the context of callback request

func AuthMiddleware

func AuthMiddleware(redirect bool) func(next http.Handler) http.Handler

AuthMiddleware ...

func GetOAuth2Config

func GetOAuth2Config() *oauth2.Config

GetOAuth2Config deprecated:

func LoginHandler

func LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler ...

func LoginStart added in v0.1.13

func LoginStart(w http.ResponseWriter, r *http.Request) string

LoginStart generate state into cookie and return redirectURI

func LogoutHandler added in v0.1.3

func LogoutHandler(w http.ResponseWriter, r *http.Request)

LogoutHandler ...

func Middleware added in v0.1.1

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

Middleware ...

func MiddlewareWordy added in v0.1.8

func MiddlewareWordy(redir bool) func(next http.Handler) http.Handler

MiddlewareWordy ...

func RegisterStateStore added in v0.1.16

func RegisterStateStore(ss StateStore)

func RequestInfo added in v0.1.12

func RequestInfo(ctx context.Context, tok *oauth2.Token, obj any, parts ...string) error

func SetAdminPath

func SetAdminPath(path string)

func SetLoginPath

func SetLoginPath(path string)

func SetupClient added in v0.1.15

func SetupClient(conf *oauth2.Config, clientID, clientSecret string)

Setup oauth2 config

func SetupRedirectURL added in v0.1.15

func SetupRedirectURL(conf *oauth2.Config, s string)

func SetupScopes added in v0.1.15

func SetupScopes(conf *oauth2.Config, scopes []string)

func Signin added in v0.1.8

func Signin(user UserEncoder, w http.ResponseWriter)

Signin ...

func Signout added in v0.1.3

func Signout(w http.ResponseWriter)

Signout ...

func StateGet added in v0.1.12

func StateGet(r *http.Request) string

func StateSet added in v0.1.12

func StateSet(w http.ResponseWriter, state string)

func StateUnset added in v0.1.12

func StateUnset(w http.ResponseWriter)

func TokenFromContext

func TokenFromContext(ctx context.Context) *oauth2.Token

TokenFromContext returns a oauth2.Token from the given context if one is present. Returns nil if a oauth2.Token cannot be found.

func UidFromToken

func UidFromToken(tok *oauth2.Token) string

UidFromToken extract uid from oauth2.Token

func WithCookie added in v0.1.6

func WithCookie(name string, strs ...string) auth.OptFunc

WithCookie ...

func WithRefresh added in v0.1.1

func WithRefresh() auth.OptFunc

WithRefresh ...

func WithURI added in v0.1.1

func WithURI(uri string) auth.OptFunc

WithURI ...

Types

type Authorizer added in v0.1.6

type Authorizer = auth.Authorizer

Authorizer ...

type CodeCallback added in v0.1.6

type CodeCallback struct {
	InRoles  []string
	TokenGot TokenFunc
}

CodeCallback ..

func (*CodeCallback) Handler added in v0.1.6

func (cc *CodeCallback) Handler() http.Handler

Handler ...

type IClient added in v0.2.3

type IClient interface {
	auth.Authorizer

	LoginStart(w http.ResponseWriter, r *http.Request) string
}

type IStaff added in v0.1.6

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

IStaff ...

type InfoError added in v0.1.11

type InfoError struct {
	ErrCode    string `json:"error,omitempty"`
	ErrMessage string `json:"error_description,omitempty"`
}

func (InfoError) GetError added in v0.1.16

func (e InfoError) GetError() error

type InfoToken

type InfoToken struct {
	InfoError

	AccessToken  string     `json:"access_token"`
	TokenType    string     `json:"token_type,omitempty"`
	RefreshToken string     `json:"refresh_token,omitempty"`
	ExpiresIn    int64      `json:"expires_in,omitempty"`
	Expiry       time.Time  `json:"expiry,omitempty"`
	User         *User      `json:"user,omitempty"`
	Me           *Staff     `json:"me,omitempty"`
	Roles        auth.Names `json:"group,omitempty"`
}

InfoToken ...

func AuthRequestWithRole

func AuthRequestWithRole(r *http.Request, role ...string) (it *InfoToken, err error)

AuthRequestWithRole called in AuthCallback

func RequestInfoToken

func RequestInfoToken(tok *oauth2.Token, roles ...string) (*InfoToken, error)

RequestInfoToken ...

func (*InfoToken) GetExpiry

func (tok *InfoToken) GetExpiry() time.Time

GetExpiry ...

type OptFunc added in v0.1.1

type OptFunc = auth.OptFunc

OptFunc ...

type RoleMe

type RoleMe map[string]interface{}

func (RoleMe) Has

func (r RoleMe) Has(name string) bool

type Staff

type Staff struct {
	UID            string `json:"uid" form:"uid"`                     // 登录名
	CommonName     string `json:"cn,omitempty" form:"cn"`             // 全名
	GivenName      string `json:"gn,omitempty" form:"gn"`             // 名
	Surname        string `json:"sn,omitempty" form:"sn"`             // 姓
	Nickname       string `json:"nickname,omitempty" form:"nickname"` // 昵称
	Birthday       string `json:"birthday,omitempty" form:"birthday"` // 生日
	Gender         string `json:"gender,omitempty"`                   // 1=male, 2=female, 0=unknown
	Mobile         string `json:"mobile,omitempty"`                   // cell phone number
	Email          string `json:"email,omitempty"`
	EmployeeNumber string `json:"eid,omitempty" form:"eid"`
	EmployeeType   string `json:"etype,omitempty" form:"etitle"`
	AvatarPath     string `json:"avatarPath,omitempty" form:"avatar"`
	Provider       string `json:"provider,omitempty"`
}

Staff is a retrieved employee struct.

type StateStore added in v0.1.16

type StateStore interface {
	Save(w http.ResponseWriter, state string) error
	Verify(r *http.Request, state string) bool
	Wipe(w http.ResponseWriter, state string)
}

type TokenFunc added in v0.1.6

type TokenFunc func(it *InfoToken) UserEncoder

TokenFunc ...

type User

type User = auth.User

User ...

type UserEncoder added in v0.1.6

type UserEncoder interface {
	auth.Encoder
	GetUID() string
	GetName() string
}

UserEncoder ...

Jump to

Keyboard shortcuts

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