improve documentation
This commit is contained in:
parent
232463e1db
commit
0826963742
16 changed files with 80 additions and 28 deletions
|
|
@ -18,7 +18,7 @@ import (
|
||||||
"github.com/go-chi/render"
|
"github.com/go-chi/render"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewAPI configures application resources and routes
|
// NewAPI configures application resources and routes.
|
||||||
func NewAPI() (*chi.Mux, error) {
|
func NewAPI() (*chi.Mux, error) {
|
||||||
logger := logging.NewLogger()
|
logger := logging.NewLogger()
|
||||||
|
|
||||||
|
|
@ -94,7 +94,7 @@ func corsConfig() *cors.Cors {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// SPAHandler serves the public Single Page Application
|
// SPAHandler serves the public Single Page Application.
|
||||||
func SPAHandler(publicDir string) http.HandlerFunc {
|
func SPAHandler(publicDir string) http.HandlerFunc {
|
||||||
handler := http.FileServer(http.Dir(publicDir))
|
handler := http.FileServer(http.Dir(publicDir))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import (
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Server provides an http.Server
|
// Server provides an http.Server.
|
||||||
type Server struct {
|
type Server struct {
|
||||||
*http.Server
|
*http.Server
|
||||||
}
|
}
|
||||||
|
|
@ -42,7 +42,7 @@ func NewServer() (*Server, error) {
|
||||||
return &Server{&srv}, nil
|
return &Server{&srv}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start runs ListenAndServe on the http.Server with graceful shutdown
|
// Start runs ListenAndServe on the http.Server with graceful shutdown.
|
||||||
func (srv *Server) Start() {
|
func (srv *Server) Start() {
|
||||||
log.Println("starting server...")
|
log.Println("starting server...")
|
||||||
go func() {
|
go func() {
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,8 @@ var (
|
||||||
errTokenNotFound = errors.New("login token not found")
|
errTokenNotFound = errors.New("login token not found")
|
||||||
)
|
)
|
||||||
|
|
||||||
// loginToken is an in-memory saved token referencing an account ID and an expiry date.
|
// LoginToken is an in-memory saved token referencing an account ID and an expiry date.
|
||||||
type loginToken struct {
|
type LoginToken struct {
|
||||||
Token string
|
Token string
|
||||||
AccountID int
|
AccountID int
|
||||||
Expiry time.Time
|
Expiry time.Time
|
||||||
|
|
@ -21,7 +21,7 @@ type loginToken struct {
|
||||||
|
|
||||||
// LoginTokenAuth implements passwordless login authentication flow using temporary in-memory stored tokens.
|
// LoginTokenAuth implements passwordless login authentication flow using temporary in-memory stored tokens.
|
||||||
type LoginTokenAuth struct {
|
type LoginTokenAuth struct {
|
||||||
token map[string]loginToken
|
token map[string]LoginToken
|
||||||
mux sync.RWMutex
|
mux sync.RWMutex
|
||||||
loginURL string
|
loginURL string
|
||||||
loginTokenLength int
|
loginTokenLength int
|
||||||
|
|
@ -31,7 +31,7 @@ type LoginTokenAuth struct {
|
||||||
// NewLoginTokenAuth configures and returns a LoginToken authentication instance.
|
// NewLoginTokenAuth configures and returns a LoginToken authentication instance.
|
||||||
func NewLoginTokenAuth() (*LoginTokenAuth, error) {
|
func NewLoginTokenAuth() (*LoginTokenAuth, error) {
|
||||||
a := &LoginTokenAuth{
|
a := &LoginTokenAuth{
|
||||||
token: make(map[string]loginToken),
|
token: make(map[string]LoginToken),
|
||||||
loginURL: viper.GetString("auth_login_url"),
|
loginURL: viper.GetString("auth_login_url"),
|
||||||
loginTokenLength: viper.GetInt("auth_login_token_length"),
|
loginTokenLength: viper.GetInt("auth_login_token_length"),
|
||||||
loginTokenExpiry: viper.GetDuration("auth_login_token_expiry"),
|
loginTokenExpiry: viper.GetDuration("auth_login_token_expiry"),
|
||||||
|
|
@ -40,8 +40,8 @@ func NewLoginTokenAuth() (*LoginTokenAuth, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateToken creates an in-memory login token referencing account ID. It returns a token containing a random tokenstring and expiry date.
|
// CreateToken creates an in-memory login token referencing account ID. It returns a token containing a random tokenstring and expiry date.
|
||||||
func (a *LoginTokenAuth) CreateToken(id int) loginToken {
|
func (a *LoginTokenAuth) CreateToken(id int) LoginToken {
|
||||||
lt := loginToken{
|
lt := LoginToken{
|
||||||
Token: randStringBytes(a.loginTokenLength),
|
Token: randStringBytes(a.loginTokenLength),
|
||||||
AccountID: id,
|
AccountID: id,
|
||||||
Expiry: time.Now().Add(time.Minute * a.loginTokenExpiry),
|
Expiry: time.Now().Add(time.Minute * a.loginTokenExpiry),
|
||||||
|
|
@ -61,14 +61,14 @@ func (a *LoginTokenAuth) GetAccountID(token string) (int, error) {
|
||||||
return lt.AccountID, nil
|
return lt.AccountID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *LoginTokenAuth) get(token string) (loginToken, bool) {
|
func (a *LoginTokenAuth) get(token string) (LoginToken, bool) {
|
||||||
a.mux.RLock()
|
a.mux.RLock()
|
||||||
lt, ok := a.token[token]
|
lt, ok := a.token[token]
|
||||||
a.mux.RUnlock()
|
a.mux.RUnlock()
|
||||||
return lt, ok
|
return lt, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *LoginTokenAuth) add(lt loginToken) {
|
func (a *LoginTokenAuth) add(lt LoginToken) {
|
||||||
a.mux.Lock()
|
a.mux.Lock()
|
||||||
a.token[lt.Token] = lt
|
a.token[lt.Token] = lt
|
||||||
a.mux.Unlock()
|
a.mux.Unlock()
|
||||||
|
|
|
||||||
|
|
@ -5,16 +5,19 @@ import (
|
||||||
"github.com/go-pg/pg"
|
"github.com/go-pg/pg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// AccountStore implements database operations for account management by user.
|
||||||
type AccountStore struct {
|
type AccountStore struct {
|
||||||
db *pg.DB
|
db *pg.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewAccountStore returns an AccountStore.
|
||||||
func NewAccountStore(db *pg.DB) *AccountStore {
|
func NewAccountStore(db *pg.DB) *AccountStore {
|
||||||
return &AccountStore{
|
return &AccountStore{
|
||||||
db: db,
|
db: db,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get an account by ID.
|
||||||
func (s *AccountStore) Get(id int) (*models.Account, error) {
|
func (s *AccountStore) Get(id int) (*models.Account, error) {
|
||||||
a := models.Account{ID: id}
|
a := models.Account{ID: id}
|
||||||
err := s.db.Model(&a).
|
err := s.db.Model(&a).
|
||||||
|
|
@ -24,6 +27,7 @@ func (s *AccountStore) Get(id int) (*models.Account, error) {
|
||||||
return &a, err
|
return &a, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update an account.
|
||||||
func (s *AccountStore) Update(a *models.Account) error {
|
func (s *AccountStore) Update(a *models.Account) error {
|
||||||
_, err := s.db.Model(a).
|
_, err := s.db.Model(a).
|
||||||
Column("email", "name").
|
Column("email", "name").
|
||||||
|
|
@ -31,6 +35,7 @@ func (s *AccountStore) Update(a *models.Account) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delete an account.
|
||||||
func (s *AccountStore) Delete(a *models.Account) error {
|
func (s *AccountStore) Delete(a *models.Account) error {
|
||||||
err := s.db.RunInTransaction(func(tx *pg.Tx) error {
|
err := s.db.RunInTransaction(func(tx *pg.Tx) error {
|
||||||
if _, err := tx.Model(&models.Token{}).
|
if _, err := tx.Model(&models.Token{}).
|
||||||
|
|
@ -48,6 +53,7 @@ func (s *AccountStore) Delete(a *models.Account) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateToken updates a jwt refresh token.
|
||||||
func (s *AccountStore) UpdateToken(t *models.Token) error {
|
func (s *AccountStore) UpdateToken(t *models.Token) error {
|
||||||
_, err := s.db.Model(t).
|
_, err := s.db.Model(t).
|
||||||
Column("identifier").
|
Column("identifier").
|
||||||
|
|
@ -55,11 +61,13 @@ func (s *AccountStore) UpdateToken(t *models.Token) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteToken deletes a jwt refresh token.
|
||||||
func (s *AccountStore) DeleteToken(t *models.Token) error {
|
func (s *AccountStore) DeleteToken(t *models.Token) error {
|
||||||
err := s.db.Delete(t)
|
err := s.db.Delete(t)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateProfile updates corresponding account profile.
|
||||||
func (s *AccountStore) UpdateProfile(p *models.Profile) error {
|
func (s *AccountStore) UpdateProfile(p *models.Profile) error {
|
||||||
err := s.db.Update(p)
|
err := s.db.Update(p)
|
||||||
return err
|
return err
|
||||||
|
|
|
||||||
|
|
@ -8,19 +8,23 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
// ErrUniqueEmailConstraint provides error message for already registered email address.
|
||||||
ErrUniqueEmailConstraint = errors.New("email already registered")
|
ErrUniqueEmailConstraint = errors.New("email already registered")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// AdmAccountStore implements database operations for account management by admin.
|
||||||
type AdmAccountStore struct {
|
type AdmAccountStore struct {
|
||||||
db *pg.DB
|
db *pg.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewAdmAccountStore returns an AccountStore.
|
||||||
func NewAdmAccountStore(db *pg.DB) *AdmAccountStore {
|
func NewAdmAccountStore(db *pg.DB) *AdmAccountStore {
|
||||||
return &AdmAccountStore{
|
return &AdmAccountStore{
|
||||||
db: db,
|
db: db,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// List applies a filter and returns paginated array of matching results and total count.
|
||||||
func (s *AdmAccountStore) List(f models.AccountFilter) (*[]models.Account, int, error) {
|
func (s *AdmAccountStore) List(f models.AccountFilter) (*[]models.Account, int, error) {
|
||||||
var a []models.Account
|
var a []models.Account
|
||||||
count, err := s.db.Model(&a).
|
count, err := s.db.Model(&a).
|
||||||
|
|
@ -32,6 +36,7 @@ func (s *AdmAccountStore) List(f models.AccountFilter) (*[]models.Account, int,
|
||||||
return &a, count, nil
|
return &a, count, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create creates a new account.
|
||||||
func (s *AdmAccountStore) Create(a *models.Account) error {
|
func (s *AdmAccountStore) Create(a *models.Account) error {
|
||||||
count, _ := s.db.Model(a).
|
count, _ := s.db.Model(a).
|
||||||
Where("email = ?email").
|
Where("email = ?email").
|
||||||
|
|
@ -55,17 +60,20 @@ func (s *AdmAccountStore) Create(a *models.Account) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get account by ID.
|
||||||
func (s *AdmAccountStore) Get(id int) (*models.Account, error) {
|
func (s *AdmAccountStore) Get(id int) (*models.Account, error) {
|
||||||
a := models.Account{ID: id}
|
a := models.Account{ID: id}
|
||||||
err := s.db.Select(&a)
|
err := s.db.Select(&a)
|
||||||
return &a, err
|
return &a, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update account.
|
||||||
func (s *AdmAccountStore) Update(a *models.Account) error {
|
func (s *AdmAccountStore) Update(a *models.Account) error {
|
||||||
err := s.db.Update(a)
|
err := s.db.Update(a)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delete account.
|
||||||
func (s *AdmAccountStore) Delete(a *models.Account) error {
|
func (s *AdmAccountStore) Delete(a *models.Account) error {
|
||||||
err := s.db.RunInTransaction(func(tx *pg.Tx) error {
|
err := s.db.RunInTransaction(func(tx *pg.Tx) error {
|
||||||
if _, err := tx.Model(&models.Token{}).
|
if _, err := tx.Model(&models.Token{}).
|
||||||
|
|
|
||||||
|
|
@ -7,16 +7,19 @@ import (
|
||||||
"github.com/go-pg/pg"
|
"github.com/go-pg/pg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// AuthStore implements database operations for account authentication.
|
||||||
type AuthStore struct {
|
type AuthStore struct {
|
||||||
db *pg.DB
|
db *pg.DB
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewAuthStore return an AuthStore.
|
||||||
func NewAuthStore(db *pg.DB) *AuthStore {
|
func NewAuthStore(db *pg.DB) *AuthStore {
|
||||||
return &AuthStore{
|
return &AuthStore{
|
||||||
db: db,
|
db: db,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetByID returns an account by ID.
|
||||||
func (s *AuthStore) GetByID(id int) (*models.Account, error) {
|
func (s *AuthStore) GetByID(id int) (*models.Account, error) {
|
||||||
a := models.Account{ID: id}
|
a := models.Account{ID: id}
|
||||||
err := s.db.Model(&a).
|
err := s.db.Model(&a).
|
||||||
|
|
@ -26,6 +29,7 @@ func (s *AuthStore) GetByID(id int) (*models.Account, error) {
|
||||||
return &a, err
|
return &a, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetByEmail returns an account by email.
|
||||||
func (s *AuthStore) GetByEmail(e string) (*models.Account, error) {
|
func (s *AuthStore) GetByEmail(e string) (*models.Account, error) {
|
||||||
a := models.Account{Email: e}
|
a := models.Account{Email: e}
|
||||||
err := s.db.Model(&a).
|
err := s.db.Model(&a).
|
||||||
|
|
@ -35,6 +39,7 @@ func (s *AuthStore) GetByEmail(e string) (*models.Account, error) {
|
||||||
return &a, err
|
return &a, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetByRefreshToken returns an account and refresh token by token identifier.
|
||||||
func (s *AuthStore) GetByRefreshToken(t string) (*models.Account, *models.Token, error) {
|
func (s *AuthStore) GetByRefreshToken(t string) (*models.Account, *models.Token, error) {
|
||||||
token := models.Token{Token: t}
|
token := models.Token{Token: t}
|
||||||
err := s.db.Model(&token).
|
err := s.db.Model(&token).
|
||||||
|
|
@ -53,6 +58,7 @@ func (s *AuthStore) GetByRefreshToken(t string) (*models.Account, *models.Token,
|
||||||
return &a, &token, err
|
return &a, &token, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateAccount upates account data related to authentication.
|
||||||
func (s *AuthStore) UpdateAccount(a *models.Account) error {
|
func (s *AuthStore) UpdateAccount(a *models.Account) error {
|
||||||
_, err := s.db.Model(a).
|
_, err := s.db.Model(a).
|
||||||
Column("last_login").
|
Column("last_login").
|
||||||
|
|
@ -60,6 +66,7 @@ func (s *AuthStore) UpdateAccount(a *models.Account) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SaveRefreshToken creates or updates a refresh token.
|
||||||
func (s *AuthStore) SaveRefreshToken(t *models.Token) error {
|
func (s *AuthStore) SaveRefreshToken(t *models.Token) error {
|
||||||
var err error
|
var err error
|
||||||
if t.ID == 0 {
|
if t.ID == 0 {
|
||||||
|
|
@ -70,11 +77,13 @@ func (s *AuthStore) SaveRefreshToken(t *models.Token) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DeleteRefreshToken deletes a refresh token.
|
||||||
func (s *AuthStore) DeleteRefreshToken(t *models.Token) error {
|
func (s *AuthStore) DeleteRefreshToken(t *models.Token) error {
|
||||||
err := s.db.Delete(t)
|
err := s.db.Delete(t)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PurgeExpiredToken deletes expired refresh token.
|
||||||
func (s *AuthStore) PurgeExpiredToken() error {
|
func (s *AuthStore) PurgeExpiredToken() error {
|
||||||
_, err := s.db.Model(&models.Token{}).
|
_, err := s.db.Model(&models.Token{}).
|
||||||
Where("expiry < ?", time.Now()).
|
Where("expiry < ?", time.Now()).
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import (
|
||||||
"github.com/go-pg/migrations"
|
"github.com/go-pg/migrations"
|
||||||
)
|
)
|
||||||
|
|
||||||
const AccountTable = `
|
const accountTable = `
|
||||||
CREATE TABLE accounts (
|
CREATE TABLE accounts (
|
||||||
id serial NOT NULL,
|
id serial NOT NULL,
|
||||||
created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
|
created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
|
||||||
|
|
@ -19,7 +19,7 @@ roles text[] NOT NULL DEFAULT '{"user"}',
|
||||||
PRIMARY KEY (id)
|
PRIMARY KEY (id)
|
||||||
)`
|
)`
|
||||||
|
|
||||||
const TokenTable = `
|
const tokenTable = `
|
||||||
CREATE TABLE tokens (
|
CREATE TABLE tokens (
|
||||||
id serial NOT NULL,
|
id serial NOT NULL,
|
||||||
created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
|
created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
|
||||||
|
|
@ -34,8 +34,8 @@ PRIMARY KEY (id)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
up := []string{
|
up := []string{
|
||||||
AccountTable,
|
accountTable,
|
||||||
TokenTable,
|
tokenTable,
|
||||||
}
|
}
|
||||||
|
|
||||||
down := []string{
|
down := []string{
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import (
|
||||||
"github.com/go-pg/migrations"
|
"github.com/go-pg/migrations"
|
||||||
)
|
)
|
||||||
|
|
||||||
const ProfileTable = `
|
const profileTable = `
|
||||||
CREATE TABLE profiles (
|
CREATE TABLE profiles (
|
||||||
id serial NOT NULL,
|
id serial NOT NULL,
|
||||||
created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
|
created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
|
||||||
|
|
@ -23,7 +23,7 @@ INSERT INTO profiles(account_id) VALUES(2);
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
up := []string{
|
up := []string{
|
||||||
ProfileTable,
|
profileTable,
|
||||||
bootstrapAccountProfiles,
|
bootstrapAccountProfiles,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"github.com/go-pg/pg"
|
"github.com/go-pg/pg"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Migrate runs go-pg migrations
|
||||||
func Migrate(args []string) {
|
func Migrate(args []string) {
|
||||||
db, err := database.DBConn()
|
db, err := database.DBConn()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -33,6 +34,7 @@ func Migrate(args []string) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reset runs reverts all migrations to version 0 and then applies all migrations to latest
|
||||||
func Reset() {
|
func Reset() {
|
||||||
db, err := database.DBConn()
|
db, err := database.DBConn()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import (
|
||||||
"github.com/go-pg/pg"
|
"github.com/go-pg/pg"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DBConn returns a postgres connection pool
|
// DBConn returns a postgres connection pool.
|
||||||
func DBConn() (*pg.DB, error) {
|
func DBConn() (*pg.DB, error) {
|
||||||
|
|
||||||
opts, err := pg.ParseURL(viper.GetString("database_url"))
|
opts, err := pg.ParseURL(viper.GetString("database_url"))
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ package email
|
||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
// ContentLoginToken defines content for login token email template
|
// ContentLoginToken defines content for login token email template.
|
||||||
type ContentLoginToken struct {
|
type ContentLoginToken struct {
|
||||||
Email string
|
Email string
|
||||||
Name string
|
Name string
|
||||||
|
|
@ -11,7 +11,7 @@ type ContentLoginToken struct {
|
||||||
Expiry time.Time
|
Expiry time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoginToken creates and sends a login token email with provided template content
|
// LoginToken creates and sends a login token email with provided template content.
|
||||||
func (m *Mailer) LoginToken(name, address string, content ContentLoginToken) error {
|
func (m *Mailer) LoginToken(name, address string, content ContentLoginToken) error {
|
||||||
msg := &Mail{
|
msg := &Mail{
|
||||||
from: NewEmail(m.fromName, m.from),
|
from: NewEmail(m.fromName, m.from),
|
||||||
|
|
|
||||||
|
|
@ -21,14 +21,14 @@ var (
|
||||||
debug bool
|
debug bool
|
||||||
)
|
)
|
||||||
|
|
||||||
// Mailer is a SMTP mailer
|
// Mailer is a SMTP mailer.
|
||||||
type Mailer struct {
|
type Mailer struct {
|
||||||
client *gomail.Dialer
|
client *gomail.Dialer
|
||||||
templates *template.Template
|
templates *template.Template
|
||||||
from, fromName string
|
from, fromName string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMailer returns a configured SMTP Mailer
|
// NewMailer returns a configured SMTP Mailer.
|
||||||
func NewMailer() (*Mailer, error) {
|
func NewMailer() (*Mailer, error) {
|
||||||
templates, err := parseTemplates()
|
templates, err := parseTemplates()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -58,7 +58,7 @@ func NewMailer() (*Mailer, error) {
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send parses the corrsponding template and send the mail via smtp
|
// Send parses the corrsponding template and sends the mail via smtp.
|
||||||
func (m *Mailer) Send(mail *Mail) error {
|
func (m *Mailer) Send(mail *Mail) error {
|
||||||
buf := new(bytes.Buffer)
|
buf := new(bytes.Buffer)
|
||||||
if err := m.templates.ExecuteTemplate(buf, mail.template, mail.content); err != nil {
|
if err := m.templates.ExecuteTemplate(buf, mail.template, mail.content); err != nil {
|
||||||
|
|
@ -95,7 +95,7 @@ func (m *Mailer) Send(mail *Mail) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mail struct holds all parts of a specific email
|
// Mail struct holds all parts of a specific email.
|
||||||
type Mail struct {
|
type Mail struct {
|
||||||
from *Email
|
from *Email
|
||||||
to *Email
|
to *Email
|
||||||
|
|
@ -104,13 +104,13 @@ type Mail struct {
|
||||||
content interface{}
|
content interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Email struct holds email address and recipient name
|
// Email struct holds email address and recipient name.
|
||||||
type Email struct {
|
type Email struct {
|
||||||
Name string
|
Name string
|
||||||
Address string
|
Address string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewEmail returns an email address
|
// NewEmail returns an email address.
|
||||||
func NewEmail(name string, address string) *Email {
|
func NewEmail(name string, address string) *Email {
|
||||||
return &Email{
|
return &Email{
|
||||||
Name: name,
|
Name: name,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,10 @@ import (
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Logger *logrus.Logger
|
var (
|
||||||
|
// Logger is a configured logrus.Logger.
|
||||||
|
Logger *logrus.Logger
|
||||||
|
)
|
||||||
|
|
||||||
// StructuredLogger is a structured logrus Logger.
|
// StructuredLogger is a structured logrus Logger.
|
||||||
type StructuredLogger struct {
|
type StructuredLogger struct {
|
||||||
|
|
@ -47,6 +50,7 @@ func NewStructuredLogger(logger *logrus.Logger) func(next http.Handler) http.Han
|
||||||
return middleware.RequestLogger(&StructuredLogger{Logger})
|
return middleware.RequestLogger(&StructuredLogger{Logger})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewLogEntry sets default request log fields.
|
||||||
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
|
func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
|
||||||
entry := &StructuredLoggerEntry{Logger: logrus.NewEntry(l.Logger)}
|
entry := &StructuredLoggerEntry{Logger: logrus.NewEntry(l.Logger)}
|
||||||
logFields := logrus.Fields{}
|
logFields := logrus.Fields{}
|
||||||
|
|
@ -79,6 +83,7 @@ func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
|
||||||
return entry
|
return entry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StructuredLoggerEntry is a logrus.FieldLogger.
|
||||||
type StructuredLoggerEntry struct {
|
type StructuredLoggerEntry struct {
|
||||||
Logger logrus.FieldLogger
|
Logger logrus.FieldLogger
|
||||||
}
|
}
|
||||||
|
|
@ -93,6 +98,7 @@ func (l *StructuredLoggerEntry) Write(status, bytes int, elapsed time.Duration)
|
||||||
l.Logger.Infoln("request complete")
|
l.Logger.Infoln("request complete")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Panic prints stack trace
|
||||||
func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
|
func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
|
||||||
l.Logger = l.Logger.WithFields(logrus.Fields{
|
l.Logger = l.Logger.WithFields(logrus.Fields{
|
||||||
"stack": string(stack),
|
"stack": string(stack),
|
||||||
|
|
@ -103,17 +109,20 @@ func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) {
|
||||||
// Helper methods used by the application to get the request-scoped
|
// Helper methods used by the application to get the request-scoped
|
||||||
// logger entry and set additional fields between handlers.
|
// logger entry and set additional fields between handlers.
|
||||||
|
|
||||||
|
// GetLogEntry return the request scoped logrus.FieldLogger.
|
||||||
func GetLogEntry(r *http.Request) logrus.FieldLogger {
|
func GetLogEntry(r *http.Request) logrus.FieldLogger {
|
||||||
entry := middleware.GetLogEntry(r).(*StructuredLoggerEntry)
|
entry := middleware.GetLogEntry(r).(*StructuredLoggerEntry)
|
||||||
return entry.Logger
|
return entry.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LogEntrySetField adds a field to the request scoped logrus.FieldLogger.
|
||||||
func LogEntrySetField(r *http.Request, key string, value interface{}) {
|
func LogEntrySetField(r *http.Request, key string, value interface{}) {
|
||||||
if entry, ok := r.Context().Value(middleware.LogEntryCtxKey).(*StructuredLoggerEntry); ok {
|
if entry, ok := r.Context().Value(middleware.LogEntryCtxKey).(*StructuredLoggerEntry); ok {
|
||||||
entry.Logger = entry.Logger.WithField(key, value)
|
entry.Logger = entry.Logger.WithField(key, value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LogEntrySetFields adds multiple fields to the request scoped logrus.FieldLogger.
|
||||||
func LogEntrySetFields(r *http.Request, fields map[string]interface{}) {
|
func LogEntrySetFields(r *http.Request, fields map[string]interface{}) {
|
||||||
if entry, ok := r.Context().Value(middleware.LogEntryCtxKey).(*StructuredLoggerEntry); ok {
|
if entry, ok := r.Context().Value(middleware.LogEntryCtxKey).(*StructuredLoggerEntry); ok {
|
||||||
entry.Logger = entry.Logger.WithFields(fields)
|
entry.Logger = entry.Logger.WithFields(fields)
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import (
|
||||||
"github.com/go-pg/pg/orm"
|
"github.com/go-pg/pg/orm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Account represents an authenticated application user
|
||||||
type Account struct {
|
type Account struct {
|
||||||
ID int `json:"id"`
|
ID int `json:"id"`
|
||||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||||
|
|
@ -25,6 +26,7 @@ type Account struct {
|
||||||
Token []*Token `json:"token,omitempty"`
|
Token []*Token `json:"token,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeInsert hook executed before database insert operation.
|
||||||
func (a *Account) BeforeInsert(db orm.DB) error {
|
func (a *Account) BeforeInsert(db orm.DB) error {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
if a.CreatedAt.IsZero() {
|
if a.CreatedAt.IsZero() {
|
||||||
|
|
@ -37,6 +39,7 @@ func (a *Account) BeforeInsert(db orm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeUpdate hook executed before database update operation.
|
||||||
func (a *Account) BeforeUpdate(db orm.DB) error {
|
func (a *Account) BeforeUpdate(db orm.DB) error {
|
||||||
if err := a.Validate(); err != nil {
|
if err := a.Validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -45,10 +48,12 @@ func (a *Account) BeforeUpdate(db orm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeDelete hook executed before database delete operation.
|
||||||
func (a *Account) BeforeDelete(db orm.DB) error {
|
func (a *Account) BeforeDelete(db orm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate validates Account struct and returns validation errors.
|
||||||
func (a *Account) Validate() error {
|
func (a *Account) Validate() error {
|
||||||
a.Email = strings.TrimSpace(a.Email)
|
a.Email = strings.TrimSpace(a.Email)
|
||||||
a.Email = strings.ToLower(a.Email)
|
a.Email = strings.ToLower(a.Email)
|
||||||
|
|
@ -60,16 +65,19 @@ func (a *Account) Validate() error {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CanLogin returns true if is user is allowed to login.
|
||||||
func (a *Account) CanLogin() bool {
|
func (a *Account) CanLogin() bool {
|
||||||
return a.Active
|
return a.Active
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AccountFilter provides pagination and filtering options on accounts.
|
||||||
type AccountFilter struct {
|
type AccountFilter struct {
|
||||||
orm.Pager
|
orm.Pager
|
||||||
Filters url.Values
|
Filters url.Values
|
||||||
Order []string
|
Order []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Filter applies an AccountFilter on an orm.Query.
|
||||||
func (f *AccountFilter) Filter(q *orm.Query) (*orm.Query, error) {
|
func (f *AccountFilter) Filter(q *orm.Query) (*orm.Query, error) {
|
||||||
q = q.Apply(f.Pager.Paginate)
|
q = q.Apply(f.Pager.Paginate)
|
||||||
q = q.Apply(orm.URLFilters(f.Filters))
|
q = q.Apply(orm.URLFilters(f.Filters))
|
||||||
|
|
@ -77,6 +85,7 @@ func (f *AccountFilter) Filter(q *orm.Query) (*orm.Query, error) {
|
||||||
return q, nil
|
return q, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewAccountFilter returns an AccountFilter with options parsed from request url values.
|
||||||
func NewAccountFilter(v url.Values) AccountFilter {
|
func NewAccountFilter(v url.Values) AccountFilter {
|
||||||
var f AccountFilter
|
var f AccountFilter
|
||||||
f.SetURLValues(v)
|
f.SetURLValues(v)
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import (
|
||||||
"github.com/go-pg/pg/orm"
|
"github.com/go-pg/pg/orm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Profile holds specific application settings linked to an Account.
|
||||||
type Profile struct {
|
type Profile struct {
|
||||||
ID int `json:"id,omitempty"`
|
ID int `json:"id,omitempty"`
|
||||||
AccountID int `json:"-"`
|
AccountID int `json:"-"`
|
||||||
|
|
@ -17,6 +18,7 @@ type Profile struct {
|
||||||
Theme string `json:"theme,omitempty"`
|
Theme string `json:"theme,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeInsert hook executed before database insert operation.
|
||||||
func (p *Profile) BeforeInsert(db orm.DB) error {
|
func (p *Profile) BeforeInsert(db orm.DB) error {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
if p.CreatedAt.IsZero() {
|
if p.CreatedAt.IsZero() {
|
||||||
|
|
@ -26,6 +28,7 @@ func (p *Profile) BeforeInsert(db orm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeUpdate hook executed before database update operation.
|
||||||
func (p *Profile) BeforeUpdate(db orm.DB) error {
|
func (p *Profile) BeforeUpdate(db orm.DB) error {
|
||||||
if err := p.Validate(); err != nil {
|
if err := p.Validate(); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -34,6 +37,7 @@ func (p *Profile) BeforeUpdate(db orm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate validates Profile struct and returns validation errors.
|
||||||
func (p *Profile) Validate() error {
|
func (p *Profile) Validate() error {
|
||||||
|
|
||||||
return validation.ValidateStruct(p,
|
return validation.ValidateStruct(p,
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"github.com/go-pg/pg/orm"
|
"github.com/go-pg/pg/orm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Token holds refresh jwt information.
|
||||||
type Token struct {
|
type Token struct {
|
||||||
ID int `json:"id,omitempty"`
|
ID int `json:"id,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||||
|
|
@ -18,6 +19,7 @@ type Token struct {
|
||||||
Identifier string `json:"identifier,omitempty"`
|
Identifier string `json:"identifier,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeInsert hook executed before database insert operation.
|
||||||
func (t *Token) BeforeInsert(db orm.DB) error {
|
func (t *Token) BeforeInsert(db orm.DB) error {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
if t.CreatedAt.IsZero() {
|
if t.CreatedAt.IsZero() {
|
||||||
|
|
@ -27,6 +29,7 @@ func (t *Token) BeforeInsert(db orm.DB) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BeforeUpdate hook executed before database update operation.
|
||||||
func (t *Token) BeforeUpdate(db orm.DB) error {
|
func (t *Token) BeforeUpdate(db orm.DB) error {
|
||||||
t.UpdatedAt = time.Now()
|
t.UpdatedAt = time.Now()
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue