cauth

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2021 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package cauth provides the primitives and the service layer for authentication. It supports multiple forms of authentication including username/password, email/password, phone otp, email magic links, etc. It includes a VerifySessionMiddleware that can be used in chttp.Route to protect it with a valid user session.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidCredentials = errors.New("invalid credentials")

ErrInvalidCredentials is returned when a credential check fails. This usually happens during the login process.

View Source
var ErrNotFound = gorm.ErrRecordNotFound

ErrNotFound is returned when a model does not exist in the repository

WireModule can be used as part of google/wire setup.

Functions

func HasVerifiedSession

func HasVerifiedSession(ctx context.Context) bool

HasVerifiedSession checks if the context has a valid session

Types

type Config added in v0.1.3

type Config struct {
	VerificationCodeLen      uint   `toml:"verification_code_len" default:"6"`
	VerificationEmailSubject string `toml:"verification_email_subject" default:"Verification Code"`
	VerificationEmailFrom    string `toml:"verification_email_from" default:"webmaster@example.com"`
}

Config configures the cauth module

type LoginParams

type LoginParams struct {
	Email    *string `json:"email"`
	Username *string `json:"username"`
	Password *string `json:"password"`
}

LoginParams hold the params needed to login a user.

type Migration

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

Migration can create db tables for cauth models

func NewMigration

func NewMigration(db *gorm.DB) *Migration

NewMigration instantiates and creates a new migration for cauth models

func (*Migration) Run

func (m *Migration) Run() error

Run creates the tables corresponding to cauth models using the given db connection.

type NewRouterParams

type NewRouterParams struct {
	Auth      *Svc
	SessionMW *VerifySessionMiddleware
	RW        *chttp.ReaderWriter
	Logger    clogger.Logger
}

NewRouterParams holds the dependencies to create a new Router.

type Repo

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

Repo represents the repository layer for all models in the cauth package.

func NewRepo

func NewRepo(db *gorm.DB) *Repo

NewRepo instantiates and returns a new Repo.

func (*Repo) GetSession

func (r *Repo) GetSession(ctx context.Context, uuid string) (*Session, error)

GetSession queries the sessions table for a session with the given uuid.

func (*Repo) GetUserByEmail added in v0.1.3

func (r *Repo) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail queries the users table for a user with the given email.

func (*Repo) GetUserByUsername

func (r *Repo) GetUserByUsername(ctx context.Context, username string) (*User, error)

GetUserByUsername queries the users table for a user with the given username.

func (*Repo) SaveSession

func (r *Repo) SaveSession(ctx context.Context, session *Session) error

SaveSession saves or creates the given session.

func (*Repo) SaveUser

func (r *Repo) SaveUser(ctx context.Context, user *User) error

SaveUser saves or creates the given user.

type Router

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

Router handles incoming HTTP requests related the cauth package.

func NewRouter

func NewRouter(p NewRouterParams) *Router

NewRouter instantiates and returns a new Router.

func (*Router) HandleLogin

func (ro *Router) HandleLogin(w http.ResponseWriter, r *http.Request)

HandleLogin handles a user login request.

func (*Router) HandleLogout

func (ro *Router) HandleLogout(w http.ResponseWriter, r *http.Request)

HandleLogout handles a user logout request.

func (*Router) HandleSignup

func (ro *Router) HandleSignup(w http.ResponseWriter, r *http.Request)

HandleSignup handles a user signup request.

func (*Router) Routes

func (ro *Router) Routes() []chttp.Route

Routes returns the routes managed by this router.

type Session

type Session struct {
	UUID      string    `gorm:"primaryKey" json:"uuid"`
	CreatedAt time.Time `gorm:"not null" json:"-"`

	UserUUID  string    `gorm:"not null" json:"user_uuid"`
	Token     []byte    `gorm:"not null" json:"-"`
	ExpiresAt time.Time `gorm:"not null" json:"expires_at"`
}

Session represents a single logged-in session that a user is able create after providing valid login credentials.

func GetCurrentSession

func GetCurrentSession(ctx context.Context) *Session

GetCurrentSession returns the session in the HTTP request context. It should only be used in HTTP request handlers that have the SetSessionMiddleware on them. If a session is not found, this method will panic. To avoid panics, verify that a session exists either with the VerifySessionMiddleware or the HasVerifiedSession function.

func (Session) TableName

func (u Session) TableName() string

TableName returns the table name where the sessions are stored.

type SessionResult

type SessionResult struct {
	User              *User    `json:"user"`
	Session           *Session `json:"session"`
	PlainSessionToken string   `json:"plain_session_token"`
}

SessionResult is usually used when a new session is created. It holds the plain session token that can be used to authenticate the session as well as other related entities such as the user and session.

type SetSessionMiddleware

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

SetSessionMiddleware is a middleware that checks for a valid session uuid and token in the Authorization header using basic auth. If the session is present, it is validated, saved in the request ctx, and the next handler is called. If the session is invalid, an unauthorized response is sent back. The next handler is also called if the authorizaiton header is missing. To ensure verified session, use in conjunction with VerifySessionMiddleware.

func NewSetSessionMiddleware

func NewSetSessionMiddleware(auth *Svc, rw *chttp.ReaderWriter, logger clogger.Logger) *SetSessionMiddleware

NewSetSessionMiddleware instantiates and creates a new SetSessionMiddleware

func (*SetSessionMiddleware) Handle

func (mw *SetSessionMiddleware) Handle(next http.Handler) http.Handler

Handle implements the middleware for SetSessionMiddleware.

type SignupParams

type SignupParams struct {
	Email    *string `json:"email"`
	Username *string `json:"username"`
	Password *string `json:"password"`
}

SignupParams hold the params needed to signup a new user.

type Svc

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

Svc provides methods to manage users and sessions.

func NewSvc

func NewSvc(repo *Repo, mailer cmailer.Mailer, appConfig cconfig.Config) (*Svc, error)

NewSvc instantiates and returns a new Svc.

func (*Svc) Login

func (s *Svc) Login(ctx context.Context, p LoginParams) (*SessionResult, error)

Login logs in an existing user with the given credentials. If the login succeeds, it creates a new session and returns it.

func (*Svc) Logout

func (s *Svc) Logout(ctx context.Context, sessionUUID string) error

Logout invalidates the session identified by the given sessionUUID.

func (*Svc) Signup

func (s *Svc) Signup(ctx context.Context, p SignupParams) (*SessionResult, error)

Signup creates a new user. If contact methods such as email or phone are provided, it will send verification codes so them. It creates a new session for this newly created user and returns that.

func (*Svc) ValidateSession

func (s *Svc) ValidateSession(ctx context.Context, sessionUUID, plainToken string) (bool, *Session, error)

ValidateSession validates whether the provided plainToken is valid for the session identified by the given sessionUUID.

type User

type User struct {
	UUID      string    `gorm:"primaryKey" json:"uuid"`
	CreatedAt time.Time `gorm:"not null" json:"-"`
	UpdatedAt time.Time `gorm:"not null" json:"-"`

	Email    *string `json:"email,omitempty"`
	Username *string `json:"username,omitempty"`

	Password           []byte `json:"-"`
	PasswordResetToken []byte `json:"-"`
}

User represents a user who has created an account. This model stores their login credentials as well as their metadata.

func (User) TableName

func (u User) TableName() string

TableName returns the table name where the users are stored.

type VerifySessionMiddleware

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

VerifySessionMiddleware is a middleware that checks for a valid session object in the request context. The session can be set in the request context with the SetSessionMiddleware.

func NewVerifySessionMiddleware

func NewVerifySessionMiddleware(auth *Svc, rw *chttp.ReaderWriter, logger clogger.Logger) *VerifySessionMiddleware

NewVerifySessionMiddleware instantiates and creates a new VerifySessionMiddleware.

func (*VerifySessionMiddleware) Handle

func (mw *VerifySessionMiddleware) Handle(next http.Handler) http.Handler

Handle implements the middleware for VerifySessionMiddleware.

Directories

Path Synopsis
Package cauthtest provides utilities to test cauth
Package cauthtest provides utilities to test cauth

Jump to

Keyboard shortcuts

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