Refactoring
This commit is contained in:
@@ -36,5 +36,5 @@ func (app *App) Shutdown() {
|
||||
}
|
||||
|
||||
func (app *App) RegisterPlugin(plugin Plugin) {
|
||||
app.worker.addPlugin(plugin.name, plugin.fn)
|
||||
app.worker.addPlugin(plugin.name, plugin.connect, &app.worker)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ const (
|
||||
defCacheUsername = "default"
|
||||
defCachePassword = "12345678"
|
||||
defDbURL = "postgres://postgres:12345678@db-postgres:5432/egommerce"
|
||||
defMongoDbURL = "mongodb://mongodb:12345678@db-mongo:27017"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -33,7 +32,6 @@ type Config struct {
|
||||
CacheAddr string `json:"cache_addr"`
|
||||
CacheUsername string `json:"cache_username"`
|
||||
CachePassword string `json:"cache_password"`
|
||||
MongoDbUrl string `json:"mongodb_url"`
|
||||
}
|
||||
|
||||
func NewConfig(name string) *Config {
|
||||
@@ -47,7 +45,6 @@ func NewConfig(name string) *Config {
|
||||
c.CacheUsername = cnf.GetEnv("API_CACHE_USERNAME", defCacheUsername)
|
||||
c.CachePassword = cnf.GetEnv("API_CACHE_PASSWORD", defCachePassword)
|
||||
c.DbURL = cnf.GetEnv("API_DATABASE_URL", defDbURL)
|
||||
c.MongoDbUrl = cnf.GetEnv("API_MONGO_URL", defMongoDbURL)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -11,13 +11,6 @@ type (
|
||||
Start() error
|
||||
OnShutdown()
|
||||
|
||||
addPlugin(name string, fn PluginFn)
|
||||
addPlugin(name string, fn PluginConnectFn, w *WorkerInterface)
|
||||
}
|
||||
|
||||
Plugin struct {
|
||||
name string
|
||||
fn PluginFn
|
||||
}
|
||||
|
||||
PluginFn func() any
|
||||
)
|
||||
|
||||
@@ -3,12 +3,19 @@ package app
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
redis "github.com/go-redis/redis/v8"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
db "github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type (
|
||||
Plugin struct {
|
||||
name string
|
||||
connect PluginConnectFn
|
||||
}
|
||||
|
||||
PluginConnectFn func(w *WorkerInterface) any // returns connection handle
|
||||
)
|
||||
|
||||
type PluginManager struct {
|
||||
@@ -21,44 +28,83 @@ func NewPluginManager() *PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
func (pm *PluginManager) addPlugin(name string, fn PluginFn) {
|
||||
pm.plugins[name] = fn()
|
||||
func (pm *PluginManager) addPlugin(name string, fn PluginConnectFn, w *WorkerInterface) {
|
||||
pm.plugins[name] = fn(w)
|
||||
}
|
||||
|
||||
func (pm *PluginManager) getCache() *redis.Client {
|
||||
func (pm *PluginManager) GetCache() *redis.Client {
|
||||
return (pm.plugins["cache"]).(*redis.Client)
|
||||
}
|
||||
|
||||
func (pm *PluginManager) getDatabase() *pgxpool.Pool {
|
||||
func (pm *PluginManager) GetDatabase() *pgxpool.Pool {
|
||||
return (pm.plugins["database"]).(*pgxpool.Pool)
|
||||
}
|
||||
|
||||
func CachePlugin(cnf *Config) Plugin {
|
||||
func CachePlugin(cnf *Config, w WorkerInterface) Plugin {
|
||||
connectFn := func(w WorkerInterface) *redis.Client {
|
||||
log.Println("establishing api-cache connection...")
|
||||
|
||||
return redis.NewClient(&redis.Options{
|
||||
Addr: cnf.CacheAddr,
|
||||
Username: cnf.CacheUsername,
|
||||
Password: cnf.CachePassword,
|
||||
DB: 0, // TODO
|
||||
DialTimeout: 100 * time.Millisecond, // TODO
|
||||
})
|
||||
}
|
||||
|
||||
// checking if the connection is still alive and try to reconnect when it is not
|
||||
go func(conn *redis.Client) {
|
||||
tick := time.NewTicker(5 * time.Second) // is 5 seconds is not too much?
|
||||
defer tick.Stop()
|
||||
|
||||
for range tick.C {
|
||||
if err := conn.Ping(context.Background()).Err(); err != nil {
|
||||
log.Println("lost connection with api-cache. Reconnecting...")
|
||||
conn = connectFn(w)
|
||||
}
|
||||
}
|
||||
}(connectFn(w))
|
||||
|
||||
return Plugin{
|
||||
name: "cache",
|
||||
fn: func() any {
|
||||
return redis.NewClient(&redis.Options{
|
||||
Addr: cnf.CacheAddr,
|
||||
Username: cnf.CacheUsername,
|
||||
Password: cnf.CachePassword,
|
||||
DB: 0, // TODO
|
||||
DialTimeout: 100 * time.Millisecond, // TODO
|
||||
})
|
||||
connect: func(w *WorkerInterface) any {
|
||||
return connectFn(*w)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func DatabasePlugin(cnf *Config) Plugin {
|
||||
func DatabasePlugin(cnf *Config, w WorkerInterface) Plugin {
|
||||
connectFn := func(w WorkerInterface) *pgxpool.Pool {
|
||||
log.Println("establishing db-postgres connection...")
|
||||
|
||||
conn, err := pgxpool.New(context.Background(), cnf.DbURL)
|
||||
if err != nil {
|
||||
log.Printf("failed to connect to the database: %s. Err: %s\n", cnf.DbURL, err.Error())
|
||||
return nil
|
||||
// os.Exit(1)
|
||||
}
|
||||
|
||||
return conn
|
||||
}
|
||||
|
||||
// checking if the connection is still alive and try to reconnect when it is not
|
||||
go func(conn *pgxpool.Pool) {
|
||||
tick := time.NewTicker(5 * time.Second) // is 5 seconds is not too much?
|
||||
defer tick.Stop()
|
||||
|
||||
for range tick.C {
|
||||
if err := conn.Ping(context.Background()); err != nil {
|
||||
log.Println("lost connection with db-postgres. Reconnecting...")
|
||||
conn = connectFn(w)
|
||||
}
|
||||
}
|
||||
}(connectFn(w))
|
||||
|
||||
return Plugin{
|
||||
name: "database",
|
||||
fn: func() any {
|
||||
dbConn, err := db.New(context.Background(), cnf.DbURL)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to the Database: %s. Err: %v\n", cnf.DbURL, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return dbConn
|
||||
connect: func(w *WorkerInterface) any {
|
||||
return connectFn(*w)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,11 +22,11 @@ func NewScheduler(c *Config) *Scheduler {
|
||||
}
|
||||
|
||||
func (c *Scheduler) Start() error { // STILL NEEDS REFACTORING ;)
|
||||
userRepo := repository.NewUserRepository(c.getDatabase())
|
||||
roleRepo := repository.NewRoleRepository(c.getDatabase())
|
||||
urlRepo := repository.NewURLAccessRepository(c.getDatabase())
|
||||
authSrv := service.NewAuthService(userRepo, c.getCache())
|
||||
guardSrv := service.NewGuardService(authSrv, c.getCache(), userRepo, roleRepo, urlRepo)
|
||||
userRepo := repository.NewUserRepository(c.GetDatabase())
|
||||
roleRepo := repository.NewRoleRepository(c.GetDatabase())
|
||||
urlRepo := repository.NewURLAccessRepository(c.GetDatabase())
|
||||
authSrv := service.NewAuthService(userRepo, c.GetCache())
|
||||
guardSrv := service.NewGuardService(authSrv, c.GetCache(), userRepo, roleRepo, urlRepo)
|
||||
|
||||
job := scheduler.NewCachePermissionsJob(guardSrv)
|
||||
sch := clockwerk.New()
|
||||
@@ -39,6 +39,6 @@ func (c *Scheduler) Start() error { // STILL NEEDS REFACTORING ;)
|
||||
func (c *Scheduler) OnShutdown() {
|
||||
log.Println("Scheduler is going down...")
|
||||
|
||||
c.getDatabase().Close()
|
||||
c.getCache().Close()
|
||||
c.GetDatabase().Close()
|
||||
c.GetCache().Close()
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ func (s *Server) Start() error {
|
||||
|
||||
crt, err := tls.LoadX509KeyPair("certs/identity-svc.crt", "certs/identity-svc.key")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
log.Fatal("failed to load certificates: ", err)
|
||||
}
|
||||
|
||||
tlsCnf := &tls.Config{Certificates: []tls.Certificate{crt}}
|
||||
@@ -74,8 +74,8 @@ func (s *Server) Start() error {
|
||||
func (s *Server) OnShutdown() {
|
||||
log.Printf("Server %s is going down...", s.ID)
|
||||
|
||||
s.getDatabase().Close()
|
||||
s.getCache().Close()
|
||||
s.GetDatabase().Close()
|
||||
s.GetCache().Close()
|
||||
|
||||
s.Shutdown()
|
||||
}
|
||||
@@ -84,13 +84,13 @@ func (s *Server) setupRouter() {
|
||||
s.Options("*", defaultCORS)
|
||||
s.Use(defaultCORS)
|
||||
|
||||
s.Get("/health", http.HealthHandlerFn(s.getDatabase(), s.getCache()))
|
||||
s.Get("/health", http.HealthHandlerFn(s.GetDatabase(), s.GetCache()))
|
||||
|
||||
s.Group("/v1").
|
||||
Post("/login", http.LoginHandlerFn(s.getDatabase(), s.getCache())).
|
||||
Post("/refresh", http.RefreshHandlerFn(s.getDatabase(), s.getCache())). // add JWTProtected() and get token from Auth Bearer header not from the body?
|
||||
Post("/register", http.RegisterHandlerFn(s.getDatabase(), s.getCache())).
|
||||
Get("/access", JWTProtected(), http.AccessHandlerFn(s.getDatabase(), s.getCache()))
|
||||
Post("/login", http.LoginHandlerFn(s.GetDatabase(), s.GetCache())).
|
||||
Post("/refresh", http.RefreshHandlerFn(s.GetDatabase(), s.GetCache())). // add JWTProtected() and get token from Auth Bearer header not from the body?
|
||||
Post("/register", http.RegisterHandlerFn(s.GetDatabase(), s.GetCache())).
|
||||
Get("/access", JWTProtected(), http.AccessHandlerFn(s.GetDatabase(), s.GetCache()))
|
||||
}
|
||||
|
||||
func (s *Server) setupMiddleware() {
|
||||
|
||||
@@ -15,10 +15,10 @@ func main() {
|
||||
}
|
||||
|
||||
cnf := app.NewConfig("identity-scheduler")
|
||||
w := app.NewScheduler(cnf)
|
||||
a := app.NewApp(w)
|
||||
a.RegisterPlugin(app.CachePlugin(cnf))
|
||||
a.RegisterPlugin(app.DatabasePlugin(cnf))
|
||||
srv := app.NewScheduler(cnf)
|
||||
a := app.NewApp(srv)
|
||||
a.RegisterPlugin(app.CachePlugin(cnf, srv))
|
||||
a.RegisterPlugin(app.DatabasePlugin(cnf, srv))
|
||||
|
||||
while := make(chan struct{})
|
||||
err := a.Start(while)
|
||||
|
||||
@@ -15,10 +15,10 @@ func main() {
|
||||
}
|
||||
|
||||
cnf := app.NewConfig("identity-svc")
|
||||
w := app.NewServer(cnf)
|
||||
a := app.NewApp(w)
|
||||
a.RegisterPlugin(app.CachePlugin(cnf))
|
||||
a.RegisterPlugin(app.DatabasePlugin(cnf))
|
||||
srv := app.NewServer(cnf)
|
||||
a := app.NewApp(srv)
|
||||
a.RegisterPlugin(app.CachePlugin(cnf, srv))
|
||||
a.RegisterPlugin(app.DatabasePlugin(cnf, srv))
|
||||
|
||||
while := make(chan struct{})
|
||||
err := a.Start(while)
|
||||
|
||||
@@ -5,7 +5,7 @@ go 1.24.0
|
||||
toolchain go1.24.1
|
||||
|
||||
require (
|
||||
git.ego.freeddns.org/egommerce/api-entities v0.3.34
|
||||
git.ego.freeddns.org/egommerce/api-entities v0.3.36
|
||||
git.ego.freeddns.org/egommerce/go-api-pkg v0.5.3
|
||||
github.com/georgysavva/scany/v2 v2.1.4
|
||||
github.com/go-pg/migrations/v8 v8.1.0
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
git.ego.freeddns.org/egommerce/api-entities v0.3.34 h1:WftM9cvV3JmbS1DlHCIiV3tsYIpALj9IXo90mkgZNWQ=
|
||||
git.ego.freeddns.org/egommerce/api-entities v0.3.34/go.mod h1:IqynARw+06GOm4eZGZuepmbi7bUxWBnOB4jd5cI7jf8=
|
||||
git.ego.freeddns.org/egommerce/api-entities v0.3.36 h1:vqIR7CCcRmO7xBpRUnmQuF0DlXozpbBf5w7ud62otvw=
|
||||
git.ego.freeddns.org/egommerce/api-entities v0.3.36/go.mod h1:IqynARw+06GOm4eZGZuepmbi7bUxWBnOB4jd5cI7jf8=
|
||||
git.ego.freeddns.org/egommerce/go-api-pkg v0.5.3 h1:so+OWWVJEg6JZ5XOSmCpfW7Pd7IL6ETH0QsC6zCwndo=
|
||||
git.ego.freeddns.org/egommerce/go-api-pkg v0.5.3/go.mod h1:T3ia8iprzlTRznPVXYCgEzQb/1UvIcdn9FHabE58vy0=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
|
||||
@@ -15,7 +15,7 @@ type HealthResponse struct {
|
||||
|
||||
func HealthHandlerFn(db *pgxpool.Pool, cache *redis.Client) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
// Only 404 indicate service as not-healthy
|
||||
// Default behavior of k8s is only 404 indicate service as not-healthy
|
||||
err := db.Ping(context.Background())
|
||||
if err != nil {
|
||||
return c.SendStatus(http.StatusNotFound)
|
||||
|
||||
@@ -18,7 +18,6 @@ func LoginHandlerFn(db *pgxpool.Pool, cache *redis.Client) fiber.Handler {
|
||||
req := new(identityDTO.AuthLoginRequestDTO)
|
||||
if err := c.BodyParser(req); err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(&commonDTO.ErrorResponseDTO{Error: "error parsing input"})
|
||||
// return srv.Error(c, fiber.StatusBadRequest, "error parsing input")
|
||||
}
|
||||
|
||||
userRepo := repository.NewUserRepository(db)
|
||||
@@ -26,8 +25,7 @@ func LoginHandlerFn(db *pgxpool.Pool, cache *redis.Client) fiber.Handler {
|
||||
|
||||
token, err := ui.NewLoginActionUI(authSrv).Execute(req)
|
||||
if err != nil { // TODO: handle other response status codes -- add struct to decorate error with code and message
|
||||
return c.Status(fiber.StatusBadRequest).JSON(commonDTO.ErrorResponseDTO{Error: err.Error()})
|
||||
// return srv.Error(c, fiber.StatusBadRequest, err.Error())
|
||||
return c.Status(fiber.StatusBadRequest).JSON(&commonDTO.ErrorResponseDTO{Error: err.Error()})
|
||||
}
|
||||
|
||||
return c.JSON(&identityDTO.AuthLoginResponseDTO{Token: token})
|
||||
|
||||
@@ -43,11 +43,6 @@ func NewAuthService(userRepo repository.UserRepositoryInterface, cache *redis.Cl
|
||||
func (a *AuthService) Login(login, passwd string) (string, error) {
|
||||
user, err := a.userRepo.FindByUsername(login)
|
||||
if err != nil {
|
||||
// TODO place code below in better place...
|
||||
// if err = database.NoRowsInQuerySet(err); err != nil {
|
||||
// return "", errors.New("no user found")
|
||||
// }
|
||||
|
||||
return "", ErrLoginIncorrect
|
||||
}
|
||||
|
||||
@@ -61,7 +56,6 @@ func (a *AuthService) Login(login, passwd string) (string, error) {
|
||||
return "", ErrUnableToCacheToken
|
||||
}
|
||||
|
||||
// REFACTOR: save uid in cache under "user:$ACCES_TOKEN" key
|
||||
res := a.cache.Set(context.Background(), "user:"+accessToken, user.ID, accessTokenExpireTime)
|
||||
if err := res.Err(); err != nil {
|
||||
fmt.Println("failed to save user:$ACCESS_TOKEN in cache: ", err.Error())
|
||||
@@ -73,8 +67,8 @@ func (a *AuthService) Login(login, passwd string) (string, error) {
|
||||
}
|
||||
|
||||
func (a *AuthService) RefreshToken(accessToken string) (string, error) {
|
||||
// POSSIBLE BIG SECURITY ISSUE- WHEN REFRESH WITH ABANDONED (or EXPIRED)
|
||||
// ACCESS TOKEN WE GET NEW ACCESS TOKEN
|
||||
// POSSIBLE BIG SECURITY ISSUE - WHEN REFRESH WITH ABANDONED (or EXPIRED)
|
||||
// ACCESS TOKEN WE CAN GET A NEW ACCESS TOKEN
|
||||
token, claims, err := jwtSrv.ValidateAccessToken(accessToken)
|
||||
if err != nil || !token.Valid {
|
||||
return "", ErrInvalidAccessToken
|
||||
|
||||
@@ -15,19 +15,19 @@ import (
|
||||
|
||||
type GuardService struct {
|
||||
authSrv *AuthService
|
||||
cache *redis.Client
|
||||
userRepo *repository.UserRepository
|
||||
roleRepo *repository.RoleRepository
|
||||
urlRepo *repository.URLAccessRepository
|
||||
cache *redis.Client
|
||||
}
|
||||
|
||||
func NewGuardService(authSrv *AuthService, cache *redis.Client, userRepo *repository.UserRepository, roleRepo *repository.RoleRepository, urlRepo *repository.URLAccessRepository) *GuardService {
|
||||
return &GuardService{
|
||||
authSrv: authSrv,
|
||||
cache: cache,
|
||||
userRepo: userRepo,
|
||||
roleRepo: roleRepo,
|
||||
urlRepo: urlRepo,
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,5 +78,3 @@ func (g *GuardService) CacheAllPermissions() error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// func (g *GuardService) fetchURLAccessFromCache() {}
|
||||
|
||||
@@ -15,8 +15,8 @@ func NewLoginActionUI(authSrv *service.AuthService) *LoginActionUI {
|
||||
}
|
||||
}
|
||||
|
||||
func (ui *LoginActionUI) Execute(data *identityDTO.AuthLoginRequestDTO) (string, error) {
|
||||
token, err := ui.authSrv.Login(data.Username, data.Password)
|
||||
func (ui *LoginActionUI) Execute(dto *identityDTO.AuthLoginRequestDTO) (string, error) {
|
||||
token, err := ui.authSrv.Login(dto.Username, dto.Password)
|
||||
if err != nil {
|
||||
// TODO: handle other response status codes -- add struct to decorate error with code and message
|
||||
if err == service.ErrUnableToCacheToken {
|
||||
|
||||
Reference in New Issue
Block a user