auth: github.com/qor/auth Index | Files | Directories

package auth

import "github.com/qor/auth"

Index

Package Files

auth.go context.go controller.go errors.go handlers.go provider.go redirector.go schema.go session_storer.go user_storer.go utils.go

Constants

const CurrentUser utils.ContextKey = "current_user"

CurrentUser context key to get current user from Request

Variables

var (
    // ErrInvalidPassword invalid password error
    ErrInvalidPassword = errors.New("invalid password")
    // ErrInvalidAccount invalid account error
    ErrInvalidAccount = errors.New("invalid account")
    // ErrUnauthorized unauthorized error
    ErrUnauthorized = errors.New("Unauthorized")
)
var DefaultAssetHandler = func(context *Context) {
    asset := strings.TrimPrefix(context.Request.URL.Path, context.Auth.URLPrefix)

    if context.Request.Header.Get("If-Modified-Since") == cacheSince {
        context.Writer.WriteHeader(http.StatusNotModified)
        return
    }
    context.Writer.Header().Set("Last-Modified", cacheSince)

    if content, err := context.Config.Render.Asset(path.Join("/auth", asset)); err == nil {
        etag := fmt.Sprintf("%x", md5.Sum(content))
        if context.Request.Header.Get("If-None-Match") == etag {
            context.Writer.WriteHeader(http.StatusNotModified)
            return
        }

        if ctype := mime.TypeByExtension(filepath.Ext(asset)); ctype != "" {
            context.Writer.Header().Set("Content-Type", ctype)
        }

        context.Writer.Header().Set("Cache-control", "private, must-revalidate, max-age=300")
        context.Writer.Header().Set("ETag", etag)
        context.Writer.Write(content)
    } else {
        http.NotFound(context.Writer, context.Request)
    }
}

DefaultAssetHandler render auth asset file

var DefaultLoginHandler = func(context *Context, authorize func(*Context) (*claims.Claims, error)) {
    var (
        req         = context.Request
        w           = context.Writer
        claims, err = authorize(context)
    )

    if err == nil && claims != nil {
        context.SessionStorer.Flash(w, req, session.Message{Message: "logged"})
        respondAfterLogged(claims, context)
        return
    }

    context.SessionStorer.Flash(w, req, session.Message{Message: template.HTML(err.Error()), Type: "error"})

    responder.With("html", func() {
        context.Auth.Config.Render.Execute("auth/login", context, req, w)
    }).With([]string{"json"}, func() {

    }).Respond(context.Request)
}

DefaultLoginHandler default login behaviour

var DefaultLogoutHandler = func(context *Context) {

    context.SessionStorer.Delete(context.Writer, context.Request)
    context.Auth.Redirector.Redirect(context.Writer, context.Request, "logout")
}

DefaultLogoutHandler default logout behaviour

var DefaultRegisterHandler = func(context *Context, register func(*Context) (*claims.Claims, error)) {
    var (
        req         = context.Request
        w           = context.Writer
        claims, err = register(context)
    )

    if err == nil && claims != nil {
        respondAfterLogged(claims, context)
        return
    }

    context.SessionStorer.Flash(w, req, session.Message{Message: template.HTML(err.Error()), Type: "error"})

    responder.With("html", func() {
        context.Auth.Config.Render.Execute("auth/register", context, req, w)
    }).With([]string{"json"}, func() {

    }).Respond(context.Request)
}

DefaultRegisterHandler default register behaviour

type Auth Uses

type Auth struct {
    *Config
    // Embed SessionStorer to match Authority's AuthInterface
    SessionStorerInterface
    // contains filtered or unexported fields
}

Auth auth struct

func New Uses

func New(config *Config) *Auth

New initialize Auth

func (*Auth) AuthURL Uses

func (auth *Auth) AuthURL(pth string) string

AuthURL generate URL for auth

func (*Auth) GetCurrentUser Uses

func (auth *Auth) GetCurrentUser(req *http.Request) interface{}

GetCurrentUser get current user from request

func (*Auth) GetDB Uses

func (auth *Auth) GetDB(request *http.Request) *gorm.DB

GetDB get db from request

func (*Auth) GetProvider Uses

func (auth *Auth) GetProvider(name string) Provider

GetProvider get provider with name

func (*Auth) GetProviders Uses

func (auth *Auth) GetProviders() (providers []Provider)

GetProviders return registered providers

func (*Auth) Login Uses

func (auth *Auth) Login(w http.ResponseWriter, req *http.Request, claimer claims.ClaimerInterface) error

Login sign user in

func (*Auth) Logout Uses

func (auth *Auth) Logout(w http.ResponseWriter, req *http.Request)

Logout sign current user out

func (*Auth) NewServeMux Uses

func (auth *Auth) NewServeMux() http.Handler

NewServeMux generate http.Handler for auth

func (*Auth) RegisterProvider Uses

func (auth *Auth) RegisterProvider(provider Provider)

RegisterProvider register auth provider

type Config Uses

type Config struct {
    // Default Database, which will be used in Auth when do CRUD, you can change a request's DB isntance by setting request Context's value, refer https://github.com/qor/auth/blob/master/utils.go#L32
    DB  *gorm.DB
    // AuthIdentityModel a model used to save auth info, like email/password, OAuth token, linked user's ID, https://github.com/qor/auth/blob/master/auth_identity/auth_identity.go is the default implemention
    AuthIdentityModel interface{}
    // UserModel should be point of user struct's instance, it could be nil, then Auth will assume there is no user linked to auth info, and will return current auth info when get current user
    UserModel interface{}
    // Mount Auth into router with URLPrefix's value as prefix, default value is `/auth`.
    URLPrefix string
    // ViewPaths prepend views paths for auth
    ViewPaths []string

    // Auth is using [Render](https://github.com/qor/render) to render pages, you could configure it with your project's Render if you have advanced usage like [BindataFS](https://github.com/qor/bindatafs)
    Render *render.Render
    // Auth is using [Mailer](https://github.com/qor/mailer) to send email, by default, it will print email into console, you need to configure it to send real one
    Mailer *mailer.Mailer
    // UserStorer is an interface that defined how to get/save user, Auth provides a default one based on AuthIdentityModel, UserModel's definition
    UserStorer UserStorerInterface
    // SessionStorer is an interface that defined how to encode/validate/save/destroy session data and flash messages between requests, Auth provides a default method do the job, to use the default value, don't forgot to mount SessionManager's middleware into your router to save session data correctly. refer [session](https://github.com/qor/session) for more details
    SessionStorer SessionStorerInterface
    // Redirector redirect user to a new page after registered, logged, confirmed...
    Redirector RedirectorInterface

    // LoginHandler defined behaviour when request `{Auth Prefix}/login`, default behaviour defined in http://godoc.org/github.com/qor/auth#pkg-variables
    LoginHandler func(*Context, func(*Context) (*claims.Claims, error))
    // RegisterHandler defined behaviour when request `{Auth Prefix}/register`, default behaviour defined in http://godoc.org/github.com/qor/auth#pkg-variables
    RegisterHandler func(*Context, func(*Context) (*claims.Claims, error))
    // LogoutHandler defined behaviour when request `{Auth Prefix}/logout`, default behaviour defined in http://godoc.org/github.com/qor/auth#pkg-variables
    LogoutHandler func(*Context)
}

Config auth config

type Context Uses

type Context struct {
    *Auth
    Claims   *claims.Claims
    Provider Provider
    Request  *http.Request
    Writer   http.ResponseWriter
}

Context context

func (Context) Flashes Uses

func (context Context) Flashes() []session.Message

Flashes get flash messages

func (Context) FormValue Uses

func (context Context) FormValue(name string) string

FormValue get form value with name

type Provider Uses

type Provider interface {
    GetName() string

    ConfigAuth(*Auth)
    Login(*Context)
    Logout(*Context)
    Register(*Context)
    Callback(*Context)
    ServeHTTP(*Context)
}

Provider define Provider interface

type Redirector Uses

type Redirector struct {
    *redirect_back.RedirectBack
}

Redirector default redirector

func (Redirector) Redirect Uses

func (redirector Redirector) Redirect(w http.ResponseWriter, req *http.Request, action string)

Redirect redirect back after action

type RedirectorInterface Uses

type RedirectorInterface interface {
    // Redirect redirect after action
    Redirect(w http.ResponseWriter, req *http.Request, action string)
}

RedirectorInterface redirector interface

type Schema Uses

type Schema struct {
    Provider string
    UID      string

    Name      string
    Email     string
    FirstName string
    LastName  string
    Location  string
    Image     string
    Phone     string
    URL       string

    RawInfo interface{}
}

Schema auth schema

type SessionStorer Uses

type SessionStorer struct {
    SessionName    string
    SigningMethod  jwt.SigningMethod
    SignedString   string
    SessionManager session.ManagerInterface
}

SessionStorer default session storer

func (*SessionStorer) Delete Uses

func (sessionStorer *SessionStorer) Delete(w http.ResponseWriter, req *http.Request) error

Delete delete claims from session manager

func (*SessionStorer) Flash Uses

func (sessionStorer *SessionStorer) Flash(w http.ResponseWriter, req *http.Request, message session.Message) error

Flash add flash message to session data

func (*SessionStorer) Flashes Uses

func (sessionStorer *SessionStorer) Flashes(w http.ResponseWriter, req *http.Request) []session.Message

Flashes returns a slice of flash messages from session data

func (*SessionStorer) Get Uses

func (sessionStorer *SessionStorer) Get(req *http.Request) (*claims.Claims, error)

Get get claims from request

func (*SessionStorer) SignedToken Uses

func (sessionStorer *SessionStorer) SignedToken(claims *claims.Claims) string

SignedToken generate signed token with Claims

func (*SessionStorer) Update Uses

func (sessionStorer *SessionStorer) Update(w http.ResponseWriter, req *http.Request, claims *claims.Claims) error

Update update claims with session manager

func (*SessionStorer) ValidateClaims Uses

func (sessionStorer *SessionStorer) ValidateClaims(tokenString string) (*claims.Claims, error)

ValidateClaims validate auth token

type SessionStorerInterface Uses

type SessionStorerInterface interface {
    // Get get claims from request
    Get(req *http.Request) (*claims.Claims, error)
    // Update update claims with session manager
    Update(w http.ResponseWriter, req *http.Request, claims *claims.Claims) error
    // Delete delete session
    Delete(w http.ResponseWriter, req *http.Request) error

    // Flash add flash message to session data
    Flash(w http.ResponseWriter, req *http.Request, message session.Message) error
    // Flashes returns a slice of flash messages from session data
    Flashes(w http.ResponseWriter, req *http.Request) []session.Message

    // SignedToken generate signed token with Claims
    SignedToken(claims *claims.Claims) string
    // ValidateClaims validate auth token
    ValidateClaims(tokenString string) (*claims.Claims, error)
}

SessionStorerInterface session storer interface for Auth

type UserStorer Uses

type UserStorer struct {
}

UserStorer default user storer

func (UserStorer) Get Uses

func (UserStorer) Get(Claims *claims.Claims, context *Context) (user interface{}, err error)

Get defined how to get user with user id

func (UserStorer) Save Uses

func (UserStorer) Save(schema *Schema, context *Context) (user interface{}, userID string, err error)

Save defined how to save user

type UserStorerInterface Uses

type UserStorerInterface interface {
    Save(schema *Schema, context *Context) (user interface{}, userID string, err error)
    Get(claims *claims.Claims, context *Context) (user interface{}, err error)
}

UserStorerInterface user storer interface

Directories

PathSynopsis
auth_identity
authority
claims
providers/facebook
providers/github
providers/google
providers/password
providers/password/encryptor
providers/password/encryptor/bcrypt_encryptor
providers/phone
providers/twitter

Package auth imports 24 packages (graph) and is imported by 14 packages. Updated 2019-01-03. Refresh now. Tools for package owners.