Renamed container package services.
This commit is contained in:
parent
195d572036
commit
1fe906a6f9
9 changed files with 42 additions and 43 deletions
196
services/auth.go
Normal file
196
services/auth.go
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"goweb/config"
|
||||
"goweb/ent"
|
||||
"goweb/ent/passwordtoken"
|
||||
"goweb/ent/user"
|
||||
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
// authSessionName stores the name of the session which contains authentication data
|
||||
authSessionName = "ua"
|
||||
|
||||
// authSessionKeyUserID stores the key used to store the user ID in the session
|
||||
authSessionKeyUserID = "user_id"
|
||||
|
||||
// authSessionKeyAuthenticated stores the key used to store the authentication status in the session
|
||||
authSessionKeyAuthenticated = "authenticated"
|
||||
)
|
||||
|
||||
// NotAuthenticatedError is an error returned when a user is not authenticated
|
||||
type NotAuthenticatedError struct{}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e NotAuthenticatedError) Error() string {
|
||||
return "user not authenticated"
|
||||
}
|
||||
|
||||
// InvalidPasswordTokenError is an error returned when an invalid token is provided
|
||||
type InvalidPasswordTokenError struct{}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e InvalidPasswordTokenError) Error() string {
|
||||
return "invalid password token"
|
||||
}
|
||||
|
||||
// AuthClient is the client that handles authentication requests
|
||||
type AuthClient struct {
|
||||
config *config.Config
|
||||
orm *ent.Client
|
||||
}
|
||||
|
||||
// NewAuthClient creates a new authentication client
|
||||
func NewAuthClient(cfg *config.Config, orm *ent.Client) *AuthClient {
|
||||
return &AuthClient{
|
||||
config: cfg,
|
||||
orm: orm,
|
||||
}
|
||||
}
|
||||
|
||||
// Login logs in a user of a given ID
|
||||
func (c *AuthClient) Login(ctx echo.Context, userID int) error {
|
||||
sess, err := session.Get(authSessionName, ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sess.Values[authSessionKeyUserID] = userID
|
||||
sess.Values[authSessionKeyAuthenticated] = true
|
||||
return sess.Save(ctx.Request(), ctx.Response())
|
||||
}
|
||||
|
||||
// Logout logs the requesting user out
|
||||
func (c *AuthClient) Logout(ctx echo.Context) error {
|
||||
sess, err := session.Get(authSessionName, ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sess.Values[authSessionKeyAuthenticated] = false
|
||||
return sess.Save(ctx.Request(), ctx.Response())
|
||||
}
|
||||
|
||||
// GetAuthenticatedUserID returns the authenticated user's ID, if the user is logged in
|
||||
func (c *AuthClient) GetAuthenticatedUserID(ctx echo.Context) (int, error) {
|
||||
sess, err := session.Get(authSessionName, ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if sess.Values[authSessionKeyAuthenticated] == true {
|
||||
return sess.Values[authSessionKeyUserID].(int), nil
|
||||
}
|
||||
|
||||
return 0, NotAuthenticatedError{}
|
||||
}
|
||||
|
||||
// GetAuthenticatedUser returns the authenticated user if the user is logged in
|
||||
func (c *AuthClient) GetAuthenticatedUser(ctx echo.Context) (*ent.User, error) {
|
||||
if userID, err := c.GetAuthenticatedUserID(ctx); err == nil {
|
||||
return c.orm.User.Query().
|
||||
Where(user.ID(userID)).
|
||||
Only(ctx.Request().Context())
|
||||
}
|
||||
|
||||
return nil, NotAuthenticatedError{}
|
||||
}
|
||||
|
||||
// HashPassword returns a hash of a given password
|
||||
func (c *AuthClient) HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// CheckPassword check if a given password matches a given hash
|
||||
func (c *AuthClient) CheckPassword(password, hash string) error {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
}
|
||||
|
||||
// GeneratePasswordResetToken generates a password reset token for a given user.
|
||||
// For security purposes, the token itself is not stored in the database but rather
|
||||
// a hash of the token, exactly how passwords are handled. This method returns both
|
||||
// the generated token as well as the token entity which only contains the hash.
|
||||
func (c *AuthClient) GeneratePasswordResetToken(ctx echo.Context, userID int) (string, *ent.PasswordToken, error) {
|
||||
// Generate the token, which is what will go in the URL, but not the database
|
||||
token, err := c.RandomToken(c.config.App.PasswordToken.Length)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// Hash the token, which is what will be stored in the database
|
||||
hash, err := c.HashPassword(token)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
// Create and save the password reset token
|
||||
pt, err := c.orm.PasswordToken.
|
||||
Create().
|
||||
SetHash(hash).
|
||||
SetUserID(userID).
|
||||
Save(ctx.Request().Context())
|
||||
|
||||
return token, pt, err
|
||||
}
|
||||
|
||||
// GetValidPasswordToken returns a valid password token entity for a given user and a given token.
|
||||
// Since the actual token is not stored in the database for security purposes, all non-expired token entities
|
||||
// are fetched from the database belonging to the requesting user and a hash of the provided token is compared
|
||||
// with the hash stored in the database.
|
||||
func (c *AuthClient) GetValidPasswordToken(ctx echo.Context, token string, userID int) (*ent.PasswordToken, error) {
|
||||
// Ensure expired tokens are never returned
|
||||
expiration := time.Now().Add(-c.config.App.PasswordToken.Expiration)
|
||||
|
||||
// Query to find all tokens for te user that haven't expired
|
||||
// We need to get all of them in order to properly match the token to the hashes
|
||||
pts, err := c.orm.PasswordToken.
|
||||
Query().
|
||||
Where(passwordtoken.HasUserWith(user.ID(userID))).
|
||||
Where(passwordtoken.CreatedAtGTE(expiration)).
|
||||
All(ctx.Request().Context())
|
||||
|
||||
if err != nil {
|
||||
ctx.Logger().Error(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check all tokens for a hash match
|
||||
for _, pt := range pts {
|
||||
if err := c.CheckPassword(token, pt.Hash); err == nil {
|
||||
return pt, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, InvalidPasswordTokenError{}
|
||||
}
|
||||
|
||||
// DeletePasswordTokens deletes all password tokens in the database for a belonging to a given user.
|
||||
// This should be called after a successful password reset.
|
||||
func (c *AuthClient) DeletePasswordTokens(ctx echo.Context, userID int) error {
|
||||
_, err := c.orm.PasswordToken.
|
||||
Delete().
|
||||
Where(passwordtoken.HasUserWith(user.ID(userID))).
|
||||
Exec(ctx.Request().Context())
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// RandomToken generates a random token string of a given length
|
||||
func (c *AuthClient) RandomToken(length int) (string, error) {
|
||||
b := make([]byte, (length/2)+1)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
token := hex.EncodeToString(b)
|
||||
return token[:length], nil
|
||||
}
|
||||
123
services/auth_test.go
Normal file
123
services/auth_test.go
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"goweb/ent/passwordtoken"
|
||||
"goweb/ent/user"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAuth(t *testing.T) {
|
||||
// Simulate an HTTP request through the session middleware to initiate the session
|
||||
mw := session.Middleware(sessions.NewCookieStore([]byte("secret")))
|
||||
handler := mw(echo.NotFoundHandler)
|
||||
assert.Error(t, handler(ctx))
|
||||
|
||||
assertNoAuth := func() {
|
||||
_, err := c.Auth.GetAuthenticatedUserID(ctx)
|
||||
assert.True(t, errors.Is(err, NotAuthenticatedError{}))
|
||||
_, err = c.Auth.GetAuthenticatedUser(ctx)
|
||||
assert.True(t, errors.Is(err, NotAuthenticatedError{}))
|
||||
}
|
||||
|
||||
assertNoAuth()
|
||||
|
||||
err := c.Auth.Login(ctx, usr.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
uid, err := c.Auth.GetAuthenticatedUserID(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, usr.ID, uid)
|
||||
|
||||
u, err := c.Auth.GetAuthenticatedUser(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, u.ID, usr.ID)
|
||||
|
||||
err = c.Auth.Logout(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
assertNoAuth()
|
||||
}
|
||||
|
||||
func TestPasswordHashing(t *testing.T) {
|
||||
pw := "testcheckpassword"
|
||||
hash, err := c.Auth.HashPassword(pw)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEqual(t, hash, pw)
|
||||
err = c.Auth.CheckPassword(pw, hash)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestGeneratePasswordResetToken(t *testing.T) {
|
||||
token, pt, err := c.Auth.GeneratePasswordResetToken(ctx, usr.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, token, c.Config.App.PasswordToken.Length)
|
||||
assert.NoError(t, c.Auth.CheckPassword(token, pt.Hash))
|
||||
}
|
||||
|
||||
func TestGetValidPasswordToken(t *testing.T) {
|
||||
// Check that a fake token is not valid
|
||||
_, err := c.Auth.GetValidPasswordToken(ctx, "faketoken", usr.ID)
|
||||
assert.Error(t, err)
|
||||
|
||||
// Generate a valid token and check that it is returned
|
||||
token, pt, err := c.Auth.GeneratePasswordResetToken(ctx, usr.ID)
|
||||
require.NoError(t, err)
|
||||
pt2, err := c.Auth.GetValidPasswordToken(ctx, token, usr.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, pt.ID, pt2.ID)
|
||||
|
||||
// Expire the token by pushed the date far enough back
|
||||
_, err = c.ORM.PasswordToken.
|
||||
Update().
|
||||
SetCreatedAt(time.Now().Add(-(c.Config.App.PasswordToken.Expiration + 10))).
|
||||
Where(passwordtoken.ID(pt.ID)).
|
||||
Save(context.Background())
|
||||
require.NoError(t, err)
|
||||
|
||||
// Expired tokens should not be valid
|
||||
_, err = c.Auth.GetValidPasswordToken(ctx, token, usr.ID)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestDeletePasswordTokens(t *testing.T) {
|
||||
// Create three tokens for the user
|
||||
for i := 0; i < 3; i++ {
|
||||
_, _, err := c.Auth.GeneratePasswordResetToken(ctx, usr.ID)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Delete all tokens for the user
|
||||
err := c.Auth.DeletePasswordTokens(ctx, usr.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Check that no tokens remain
|
||||
count, err := c.ORM.PasswordToken.
|
||||
Query().
|
||||
Where(passwordtoken.HasUserWith(user.ID(usr.ID))).
|
||||
Count(context.Background())
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, count)
|
||||
}
|
||||
|
||||
func TestRandomToken(t *testing.T) {
|
||||
length := 64
|
||||
a, err := c.Auth.RandomToken(length)
|
||||
require.NoError(t, err)
|
||||
b, err := c.Auth.RandomToken(length)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, a, 64)
|
||||
assert.Len(t, b, 64)
|
||||
assert.NotEqual(t, a, b)
|
||||
}
|
||||
133
services/container.go
Normal file
133
services/container.go
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"goweb/mail"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
entsql "entgo.io/ent/dialect/sql"
|
||||
"github.com/eko/gocache/v2/cache"
|
||||
"github.com/eko/gocache/v2/store"
|
||||
"github.com/go-redis/redis/v8"
|
||||
_ "github.com/jackc/pgx/v4/stdlib"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/gommon/log"
|
||||
|
||||
"goweb/config"
|
||||
"goweb/ent"
|
||||
)
|
||||
|
||||
type Container struct {
|
||||
Web *echo.Echo
|
||||
Config *config.Config
|
||||
Cache *cache.Cache
|
||||
Database *sql.DB
|
||||
ORM *ent.Client
|
||||
Mail *mail.Client
|
||||
Auth *AuthClient
|
||||
}
|
||||
|
||||
func NewContainer() *Container {
|
||||
c := new(Container)
|
||||
c.initConfig()
|
||||
c.initWeb()
|
||||
c.initCache()
|
||||
c.initDatabase()
|
||||
c.initORM()
|
||||
c.initMail()
|
||||
c.initAuth()
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Container) initConfig() {
|
||||
cfg, err := config.GetConfig()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to load config: %v", err))
|
||||
}
|
||||
c.Config = &cfg
|
||||
}
|
||||
|
||||
func (c *Container) initWeb() {
|
||||
c.Web = echo.New()
|
||||
|
||||
// Configure logging
|
||||
switch c.Config.App.Environment {
|
||||
case config.EnvProduction:
|
||||
c.Web.Logger.SetLevel(log.WARN)
|
||||
default:
|
||||
c.Web.Logger.SetLevel(log.DEBUG)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Container) initCache() {
|
||||
cacheClient := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", c.Config.Cache.Hostname, c.Config.Cache.Port),
|
||||
Password: c.Config.Cache.Password,
|
||||
})
|
||||
if _, err := cacheClient.Ping(context.Background()).Result(); err != nil {
|
||||
panic(fmt.Sprintf("failed to connect to cache server: %v", err))
|
||||
}
|
||||
cacheStore := store.NewRedis(cacheClient, nil)
|
||||
c.Cache = cache.New(cacheStore)
|
||||
}
|
||||
|
||||
func (c *Container) initDatabase() {
|
||||
var err error
|
||||
|
||||
getAddr := func(dbName string) string {
|
||||
return fmt.Sprintf("postgresql://%s:%s@%s/%s",
|
||||
c.Config.Database.User,
|
||||
c.Config.Database.Password,
|
||||
c.Config.Database.Hostname,
|
||||
dbName,
|
||||
)
|
||||
}
|
||||
|
||||
c.Database, err = sql.Open("pgx", getAddr(c.Config.Database.Database))
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to connect to database: %v", err))
|
||||
}
|
||||
|
||||
// Check if this is a test environment
|
||||
if c.Config.App.Environment == config.EnvTest {
|
||||
// Drop the test database, ignoring errors in case it doesn't yet exist
|
||||
_, _ = c.Database.Exec("DROP DATABASE " + c.Config.Database.TestDatabase)
|
||||
|
||||
// Create the test database
|
||||
if _, err = c.Database.Exec("CREATE DATABASE " + c.Config.Database.TestDatabase); err != nil {
|
||||
panic(fmt.Sprintf("failed to create test database: %v", err))
|
||||
}
|
||||
|
||||
// Connect to the test database
|
||||
if err = c.Database.Close(); err != nil {
|
||||
panic(fmt.Sprintf("failed to close database connection: %v", err))
|
||||
}
|
||||
c.Database, err = sql.Open("pgx", getAddr(c.Config.Database.TestDatabase))
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to connect to database: %v", err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Container) initORM() {
|
||||
drv := entsql.OpenDB(dialect.Postgres, c.Database)
|
||||
c.ORM = ent.NewClient(ent.Driver(drv))
|
||||
if err := c.ORM.Schema.Create(context.Background()); err != nil {
|
||||
panic(fmt.Sprintf("failed to create database schema: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Container) initMail() {
|
||||
var err error
|
||||
c.Mail, err = mail.NewClient(c.Config)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to create mail client: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Container) initAuth() {
|
||||
c.Auth = NewAuthClient(c.Config, c.ORM)
|
||||
}
|
||||
64
services/container_test.go
Normal file
64
services/container_test.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"goweb/config"
|
||||
"goweb/ent"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var (
|
||||
c *Container
|
||||
ctx echo.Context
|
||||
usr *ent.User
|
||||
rec *httptest.ResponseRecorder
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// Set the environment to test
|
||||
config.SwitchEnvironment(config.EnvTest)
|
||||
|
||||
// Create a new container
|
||||
c = NewContainer()
|
||||
|
||||
// Create a web context
|
||||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(""))
|
||||
rec = httptest.NewRecorder()
|
||||
ctx = c.Web.NewContext(req, rec)
|
||||
|
||||
// Create a test user
|
||||
var err error
|
||||
usr, err = c.ORM.User.
|
||||
Create().
|
||||
SetEmail("test@test.dev").
|
||||
SetPassword("abc").
|
||||
SetName("Test User").
|
||||
Save(context.Background())
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Run tests
|
||||
exitVal := m.Run()
|
||||
os.Exit(exitVal)
|
||||
}
|
||||
|
||||
func TestNewContainer(t *testing.T) {
|
||||
assert.NotNil(t, c.Web)
|
||||
assert.NotNil(t, c.Config)
|
||||
assert.NotNil(t, c.Cache)
|
||||
assert.NotNil(t, c.Database)
|
||||
assert.NotNil(t, c.ORM)
|
||||
assert.NotNil(t, c.Mail)
|
||||
assert.NotNil(t, c.Auth)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue