authentic8

package module
v0.0.0-...-d6ca7af Latest Latest
Warning

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

Go to latest
Published: May 9, 2020 License: MIT Imports: 21 Imported by: 0

README

Codeship Status for dadamssolutions/authentic8 codecov Maintainability Go Report Card

authentic8

An all-in-one authentication and session handler for golang applications

Documentation

Overview

Package authentic8 provides a self-contained authentication handler using a Postgresql database backend.

The handler will create all the necessary tables it needs or the user can provide a tableName that exists and has the appropriate columns for the application. For example, the table where the user information is stored (by default called 'users') should have at least username (PRIMARY KEY), fname, lname, email, role (int), validated (bool), passhash (char(80)).

authentic8 also "handles" all session information and csrf token generation and validation. That is, this package is designed to be an automatic, all-in-one solution. The user should not have to worry about the logic of authentication and validation, but should know who is logged in, if any.

Index

Constants

View Source
const (
	StandardMode = iota
	AddRedirectQueryMode
	RetainQueriesMode
	RedirectToQueryMode
)

Redirect modes

View Source
const (
	Member = iota
	Manager
	Supervisor
	Admin
)

Represent roles used for users.

Variables

This section is empty.

Functions

func ErrorFromContext

func ErrorFromContext(ctx context.Context) error

ErrorFromContext looks for an error in the context. If there is no error found, then the return value will be nil.

func NewErrorContext

func NewErrorContext(ctx context.Context, err error) context.Context

NewErrorContext adds an error to the context.

func NewSessionContext

func NewSessionContext(ctx context.Context, ses *sessions.Session) context.Context

NewSessionContext adds a *session.Session to the context.

func NewUserContext

func NewUserContext(ctx context.Context, user *User) context.Context

NewUserContext adds a User to the context.

func PostAndOtherOnError

func PostAndOtherOnError(postHandler http.Handler, redirectOnSuccess, redirectOnError http.Handler) adaptd.Adapter

PostAndOtherOnError calls postHandler and then checks the error on the Request's context. If there is an error, the handler passed to the adapter is called.

This is useful for a POST request that tries to log a user in and calls a GET handler on error. The GET handler can then look at the error on the Request's context.

func PutTxOnContext

func PutTxOnContext(db *sql.DB) adaptd.Adapter

PutTxOnContext puts a new database transaction on the context before calling the passed handler. If the transaction that is put on the context should be rolledback, then panic should be called. PutTxOnContext will recover from the panic and report a 500 error. If starting the transaction fails, then panic is called.

func RedirectIfErrorOnContext

func RedirectIfErrorOnContext(redirectHandler http.Handler) adaptd.Adapter

RedirectIfErrorOnContext checks for an error on the Request's context. If the error is not nil, the redirect handler is called.

func RedirectOnError

func RedirectOnError(f func(http.ResponseWriter, *http.Request) error, fh http.Handler, logOnError string) adaptd.Adapter

RedirectOnError redirects based on whether it kind find an error in the Request's context.

func SessionFromContext

func SessionFromContext(ctx context.Context) *sessions.Session

SessionFromContext looks for a session in the context. If there is no session found, then the return value will be nil.

Types

type HTTPAuth

type HTTPAuth struct {
	LoginURL                   string
	RedirectAfterLogin         string
	LogOutURL                  string
	SignUpURL                  string
	RedirectAfterSignUp        string
	SignUpVerificationURL      string
	PasswordResetRequestURL    string
	PasswordResetURL           string
	RedirectAfterResetRequest  string
	PasswordResetEmailTemplate *template.Template
	SignUpEmailTemplate        *template.Template
	GenerateHashFromPassword   func([]byte) ([]byte, error)
	CompareHashAndPassword     func([]byte, []byte) error
	// contains filtered or unexported fields
}

HTTPAuth is a general handler that authenticates a user for http requests. It also handles csrf token generation and validation.

func DefaultHTTPAuth

func DefaultHTTPAuth(db *sql.DB, usersTableName, domainName string, allowXForwardedProto bool, emailSender *email.Sender, sessionTimeout, persistentSessionTimeout, csrfsTimeout, passwordResetTimeout time.Duration, cost int, secret []byte) (*HTTPAuth, error)

DefaultHTTPAuth uses the standard bcyrpt functions for generating and comparing password hashes. cost parameter is the desired cost for bycrypt generated hashes. The parameters listed are the ones necessary for setting up the handler. All other fields are customizable after creating the handler.

In order for this to work properly, you must also set the two email templates and the error template. i.e. `auth.PasswordResetEmailTemplate = template.Must(template.ParseFiles("templates/passwordreset.tmpl.html"))`

func (*HTTPAuth) AddDefaultHandlers

func (a *HTTPAuth) AddDefaultHandlers(db *sql.DB, home, signUp, afterSignUp, verifySignUp, logIn, afterLogIn, logOut, passResetRequest, passResetSent, passReset http.Handler)

AddDefaultHandlers adds the standard handlers needed for the auth handler.

func (*HTTPAuth) AddDefaultHandlersWithMux

func (a *HTTPAuth) AddDefaultHandlersWithMux(mux *http.ServeMux, db *sql.DB, home, signUp, afterSignUp, verifySignUp, logIn, afterLogIn, logOut, passResetRequest, passResetSent, passReset http.Handler)

AddDefaultHandlersWithMux adds the standard handlers needed for the auth handler to the ServeMux.

func (*HTTPAuth) AttachSessionCookie

func (a *HTTPAuth) AttachSessionCookie() adaptd.Adapter

AttachSessionCookie adapter calls the handler and then attaches the session cookie to the response. This should be the last adapter attached to the handler.

func (*HTTPAuth) CSRFGetAdapter

func (a *HTTPAuth) CSRFGetAdapter() adaptd.Adapter

CSRFGetAdapter attaches a new CSRF token to the header of the response.

func (*HTTPAuth) CSRFPostAdapter

func (a *HTTPAuth) CSRFPostAdapter(redirectOnError, logOnError string) adaptd.Adapter

CSRFPostAdapter handles the CSRF token verification for POST requests.

func (*HTTPAuth) CurrentUser

func (a *HTTPAuth) CurrentUser(r *http.Request) *User

CurrentUser returns the username of the current user

func (*HTTPAuth) Flashes

func (a *HTTPAuth) Flashes(tx *sql.Tx, ses *sessions.Session) ([]interface{}, []interface{})

Flashes returns the flashes of the session and updates the database.

func (*HTTPAuth) IsCurrentUser

func (a *HTTPAuth) IsCurrentUser(r *http.Request, username string) bool

IsCurrentUser returns true if the username corresponds to the user logged in with a cookie in the request.

func (*HTTPAuth) LoadOrCreateSession

func (a *HTTPAuth) LoadOrCreateSession() adaptd.Adapter

LoadOrCreateSession adapter loads a session if the request has the correct cookie. If the request does not have the correct cookie, we create one, attach it to the response, and put it on the Request's context.

func (*HTTPAuth) LoginAdapter

func (a *HTTPAuth) LoginAdapter() adaptd.Adapter

LoginAdapter handles the login GET and POST requests If it is determined that the login page should be shown, then the handler passed to the Adapter is called. If the user login POST request fails, the handler passed to the adapter is called again, this time with an error on the Request's context.

The form for the POST request should point back to this handler. The form should have three inputs: username, password, and remember.

func (*HTTPAuth) LogoutAdapter

func (a *HTTPAuth) LogoutAdapter(redirectOnSuccess string) adaptd.Adapter

LogoutAdapter handles the logout requests The handler passed to the Adapter is only called is when the logout fails. In this case, the error and the session are put on the Request's context.

func (*HTTPAuth) MustHaveAdapters

func (a *HTTPAuth) MustHaveAdapters(db *sql.DB, otherAdapters ...adaptd.Adapter) adaptd.Adapter

MustHaveAdapters are the adapters that we must have for essentially every Handler

As of now, they are EnsureHTTPS, PutTxOnContext, LoadOrCreateSession, and AttachSessionCookie (which is at the end)

func (*HTTPAuth) PasswordResetAdapter

func (a *HTTPAuth) PasswordResetAdapter() adaptd.Adapter

PasswordResetAdapter handles the GET and POST requests for reseting the password. If the request is GET with the correct query string, the getHandler passed to the Adapter.

If the request is GET with invalid query string, the user is redirected to redirectOnError unless the user is logged in. An authenticated user is allow to reset their password.

The form shown to the user in a GET request should have inputs with names 'password' and 'repeatedPassword' The POST request should be pointed to the same handler, and the user's password is updated.

After successful password reset, the user is redirected to redirectOnSuccess. If their is an error, the user is redirected to redirectOnError.

func (*HTTPAuth) PasswordResetRequestAdapter

func (a *HTTPAuth) PasswordResetRequestAdapter() adaptd.Adapter

PasswordResetRequestAdapter handles the GET and POST requests for requesting password reset. If the request is GET, the getHandler passed to the Adapter.

The form shown to the user in a GET request should have an input with name 'email' The POST request should be pointed to the same handler, and the user is sent a link to reset their password.

When a POST request is received, the database is checked for the existing user. If the user exists, and email is send to the user. You can include {{.link}} in the template to include the password reset link.

If a user with the supplied email does not exists, then the handler passed to the Adapter is called with the appropriate error on the Request's context.

After successful password reset, the user is redirected to redirectOnSuccess. If their is an error, the user is redirected to redirectOnError.

func (*HTTPAuth) RedirectHandler

func (a *HTTPAuth) RedirectHandler(url string, code int) http.Handler

RedirectHandler returns a standard redirect handler that is compatible with the authentication cookie. This is the same as calling `RedirectHandlerWithMode(url, code, StandardMode)`.

func (*HTTPAuth) RedirectHandlerWithMode

func (a *HTTPAuth) RedirectHandlerWithMode(url string, code, mode int) http.Handler

RedirectHandlerWithMode returns a redirect handler that is compatible with the authentication cookie. The mode determines how it handles redirect URL queries.

StandardMode - ignores queries AddRedirectQueryMode - adds the request URL as a redirect query string to the URL. RedirectToQueryMode - redirects to the redirect query string as a URL All queries are URL Un/Escaped automatically.

func (*HTTPAuth) RedirectIfNoPermission

func (a *HTTPAuth) RedirectIfNoPermission(minRole Role) adaptd.Adapter

RedirectIfNoPermission is like http.HandleFunc except it verifies the user is logged in and has permission to view the page.

func (*HTTPAuth) RedirectIfUserNotAuthenticated

func (a *HTTPAuth) RedirectIfUserNotAuthenticated() adaptd.Adapter

RedirectIfUserNotAuthenticated is like http.HandleFunc except it is verified the user is logged in.

func (*HTTPAuth) SignUpAdapter

func (a *HTTPAuth) SignUpAdapter() adaptd.Adapter

SignUpAdapter handles the sign up GET and POST requests. If it is determine that the sign up page should be shown, then the handler passed to the Adapter is called. If the user sign up POST request fails, the handler passed to the adapter is called again, this time with an error on the Request's context.

The form for the POST request should point back to this handler. The form should have six inputs: firstname, lastname, username, email, password, repeatedPassword

func (*HTTPAuth) SignUpVerificationAdapter

func (a *HTTPAuth) SignUpVerificationAdapter() adaptd.Adapter

SignUpVerificationAdapter handles verification of sign ups. The user is sent an email with a verification link. When the user clicks that link they are sent to this handler that verifies the token they were given and marks them as verified.

func (*HTTPAuth) StandardPostAndGetAdapter

func (a *HTTPAuth) StandardPostAndGetAdapter(postHandler http.Handler, redirectOnSuccess, redirectOnError, logOnError string, extraAdapters ...adaptd.Adapter) adaptd.Adapter

StandardPostAndGetAdapter uses other adapters to do a standard type of POST/GET request.

If the request is POST, then the request is checked for a CSRF token. If the token is verified then the postHandler is called.

If the POST handler does not put an error on the Request's context, then the user is redirected to redirectOnSuccess If, at any point, there is an error on the Request's context (either put there by the postHandler or bad CSRF token detection), then the user is redirected to redirectOnError and logOnError is logged to the console.

type RedirectHandler

type RedirectHandler struct {
	// contains filtered or unexported fields
}

RedirectHandler allows redefining the http.RedirectHandler to use redirect URL queries.

func (RedirectHandler) ServeHTTP

func (rh RedirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves a redirect based on the given mode of the RedirectHandler.

type Role

type Role int

Role is represents the role of a user. Roles elevate and have a linear hierarchy.

func (Role) HasRole

func (r Role) HasRole(permission Role) bool

HasRole returns whether the role has the given permssion level.

type User

type User struct {
	FirstName, LastName, Email, Greet, Username string
	Role                                        Role
	// contains filtered or unexported fields
}

User represents a user to be logged in or signed up represented in the created database. For ease, you would want the representation of the user in your app to embed User.

func UserFromContext

func UserFromContext(ctx context.Context) *User

UserFromContext looks for a User in the context. If there is no User found, then the return value will be nil.

func (User) GetEmail

func (u User) GetEmail() string

GetEmail implements the email.Recipient interface.

func (User) Greeting

func (u User) Greeting() string

Greeting implements the email.Recipient interface.

func (User) HasPermission

func (u User) HasPermission(role Role) bool

HasPermission determines whether the user has the given permission level

func (User) IsValidated

func (u User) IsValidated() bool

IsValidated returns whether the user has validated their login

Directories

Path Synopsis
handlers
csrf
Package csrf provides a functionality for creating, destroying, validating, and attaching Cross-site Forgery Request protection tokens.
Package csrf provides a functionality for creating, destroying, validating, and attaching Cross-site Forgery Request protection tokens.
email
Package email is an email handler used for sending email messages like sign up verifications and password reset requests.
Package email is an email handler used for sending email messages like sign up verifications and password reset requests.
email/smtpauth
Package smtpauth provides implementations of the smtp.Auth interface for sending messages with the LOGIN authentication mechanism, only allowed of SSL/TLS connections.
Package smtpauth provides implementations of the smtp.Auth interface for sending messages with the LOGIN authentication mechanism, only allowed of SSL/TLS connections.
passreset
Package passreset provies a handler for password reset token generation, validation, and deletion.
Package passreset provies a handler for password reset token generation, validation, and deletion.
session
Package session uses a database backend to manage session cookies for a server.
Package session uses a database backend to manage session cookies for a server.
session/sessions
Package sessions contains a Session type used to track session cookies in HTTP responses.
Package sessions contains a Session type used to track session cookies in HTTP responses.

Jump to

Keyboard shortcuts

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