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 ¶
- Variables
- func HasVerifiedSession(ctx context.Context) bool
- type Config
- type LoginParams
- type Migration
- type NewRouterParams
- type Repo
- func (r *Repo) GetSession(ctx context.Context, uuid string) (*Session, error)
- func (r *Repo) GetUserByEmail(ctx context.Context, email string) (*User, error)
- func (r *Repo) GetUserByUsername(ctx context.Context, username string) (*User, error)
- func (r *Repo) SaveSession(ctx context.Context, session *Session) error
- func (r *Repo) SaveUser(ctx context.Context, user *User) error
- type Router
- type Session
- type SessionResult
- type SetSessionMiddleware
- type SignupParams
- type Svc
- func (s *Svc) Login(ctx context.Context, p LoginParams) (*SessionResult, error)
- func (s *Svc) Logout(ctx context.Context, sessionUUID string) error
- func (s *Svc) Signup(ctx context.Context, p SignupParams) (*SessionResult, error)
- func (s *Svc) ValidateSession(ctx context.Context, sessionUUID, plainToken string) (bool, *Session, error)
- type User
- type VerifySessionMiddleware
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidCredentials is returned when a credential check fails. This usually happens during the login process.
var ErrNotFound = gorm.ErrRecordNotFound
ErrNotFound is returned when a model does not exist in the repository
var WireModule = wire.NewSet( NewSvc, NewRepo, NewMigration, NewSetSessionMiddleware, NewVerifySessionMiddleware, wire.Struct(new(NewRouterParams), "*"), NewRouter, )
WireModule can be used as part of google/wire setup.
Functions ¶
func HasVerifiedSession ¶
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 ¶
NewMigration instantiates and creates a new migration for cauth models
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 (*Repo) GetSession ¶
GetSession queries the sessions table for a session with the given uuid.
func (*Repo) GetUserByEmail ¶ added in v0.1.3
GetUserByEmail queries the users table for a user with the given email.
func (*Repo) GetUserByUsername ¶
GetUserByUsername queries the users table for a user with the given username.
func (*Repo) SaveSession ¶
SaveSession saves or creates the given session.
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.
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 ¶
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.
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
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 (*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) 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.
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.
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.