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
- func ErrorFromContext(ctx context.Context) error
- func NewErrorContext(ctx context.Context, err error) context.Context
- func NewSessionContext(ctx context.Context, ses *sessions.Session) context.Context
- func NewUserContext(ctx context.Context, user *User) context.Context
- func PostAndOtherOnError(postHandler http.Handler, redirectOnSuccess, redirectOnError http.Handler) adaptd.Adapter
- func PutTxOnContext(db *sql.DB) adaptd.Adapter
- func RedirectIfErrorOnContext(redirectHandler http.Handler) adaptd.Adapter
- func RedirectOnError(f func(http.ResponseWriter, *http.Request) error, fh http.Handler, ...) adaptd.Adapter
- func SessionFromContext(ctx context.Context) *sessions.Session
- type HTTPAuth
- func (a *HTTPAuth) AddDefaultHandlers(db *sql.DB, ...)
- func (a *HTTPAuth) AddDefaultHandlersWithMux(mux *http.ServeMux, db *sql.DB, ...)
- func (a *HTTPAuth) AttachSessionCookie() adaptd.Adapter
- func (a *HTTPAuth) CSRFGetAdapter() adaptd.Adapter
- func (a *HTTPAuth) CSRFPostAdapter(redirectOnError, logOnError string) adaptd.Adapter
- func (a *HTTPAuth) CurrentUser(r *http.Request) *User
- func (a *HTTPAuth) Flashes(tx *sql.Tx, ses *sessions.Session) ([]interface{}, []interface{})
- func (a *HTTPAuth) IsCurrentUser(r *http.Request, username string) bool
- func (a *HTTPAuth) LoadOrCreateSession() adaptd.Adapter
- func (a *HTTPAuth) LoginAdapter() adaptd.Adapter
- func (a *HTTPAuth) LogoutAdapter(redirectOnSuccess string) adaptd.Adapter
- func (a *HTTPAuth) MustHaveAdapters(db *sql.DB, otherAdapters ...adaptd.Adapter) adaptd.Adapter
- func (a *HTTPAuth) PasswordResetAdapter() adaptd.Adapter
- func (a *HTTPAuth) PasswordResetRequestAdapter() adaptd.Adapter
- func (a *HTTPAuth) RedirectHandler(url string, code int) http.Handler
- func (a *HTTPAuth) RedirectHandlerWithMode(url string, code, mode int) http.Handler
- func (a *HTTPAuth) RedirectIfNoPermission(minRole Role) adaptd.Adapter
- func (a *HTTPAuth) RedirectIfUserNotAuthenticated() adaptd.Adapter
- func (a *HTTPAuth) SignUpAdapter() adaptd.Adapter
- func (a *HTTPAuth) SignUpVerificationAdapter() adaptd.Adapter
- func (a *HTTPAuth) StandardPostAndGetAdapter(postHandler http.Handler, ...) adaptd.Adapter
- type RedirectHandler
- type Role
- type User
Constants ¶
const ( StandardMode = iota AddRedirectQueryMode RetainQueriesMode RedirectToQueryMode )
Redirect modes
const ( Member = iota Manager Supervisor Admin )
Represent roles used for users.
Variables ¶
This section is empty.
Functions ¶
func ErrorFromContext ¶
ErrorFromContext looks for an error in the context. If there is no error found, then the return value will be nil.
func NewErrorContext ¶
NewErrorContext adds an error to the context.
func NewSessionContext ¶
NewSessionContext adds a *session.Session to the context.
func NewUserContext ¶
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 ¶
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 ¶
RedirectIfErrorOnContext checks for an error on the Request's context. If the error is not nil, the redirect handler is called.
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 ¶
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 ¶
CSRFGetAdapter attaches a new CSRF token to the header of the response.
func (*HTTPAuth) CSRFPostAdapter ¶
CSRFPostAdapter handles the CSRF token verification for POST requests.
func (*HTTPAuth) CurrentUser ¶
CurrentUser returns the username of the current user
func (*HTTPAuth) IsCurrentUser ¶
IsCurrentUser returns true if the username corresponds to the user logged in with a cookie in the request.
func (*HTTPAuth) LoadOrCreateSession ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
RedirectIfNoPermission is like http.HandleFunc except it verifies the user is logged in and has permission to view the page.
func (*HTTPAuth) RedirectIfUserNotAuthenticated ¶
RedirectIfUserNotAuthenticated is like http.HandleFunc except it is verified the user is logged in.
func (*HTTPAuth) SignUpAdapter ¶
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 ¶
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.
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 ¶
UserFromContext looks for a User in the context. If there is no User found, then the return value will be nil.
func (User) HasPermission ¶
HasPermission determines whether the user has the given permission level
func (User) IsValidated ¶
IsValidated returns whether the user has validated their login
Source Files ¶
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. |