fix: move implementation to "internal" package
Some checks failed
Build Docker Image / Build-Docker-Image (push) Has been cancelled
Some checks failed
Build Docker Image / Build-Docker-Image (push) Has been cancelled
This commit is contained in:
136
internal/handler/account.go
Normal file
136
internal/handler/account.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
t "spend-sparrow/internal/template/account"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type Account interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type AccountImpl struct {
|
||||
s service.Account
|
||||
r *Render
|
||||
}
|
||||
|
||||
func NewAccount(s service.Account, r *Render) Account {
|
||||
return AccountImpl{
|
||||
s: s,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /account", h.handleAccountPage())
|
||||
r.Handle("GET /account/{id}", h.handleAccountItemComp())
|
||||
r.Handle("POST /account/{id}", h.handleUpdateAccount())
|
||||
r.Handle("DELETE /account/{id}", h.handleDeleteAccount())
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleAccountPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
accounts, err := h.s.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
comp := t.Account(accounts)
|
||||
h.r.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleAccountItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "new" {
|
||||
comp := t.EditAccount(nil)
|
||||
h.r.Render(r, w, comp)
|
||||
return
|
||||
}
|
||||
|
||||
account, err := h.s.Get(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var comp templ.Component
|
||||
if r.URL.Query().Get("edit") == "true" {
|
||||
comp = t.EditAccount(account)
|
||||
} else {
|
||||
comp = t.AccountItem(account)
|
||||
}
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleUpdateAccount() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
account *types.Account
|
||||
err error
|
||||
)
|
||||
id := r.PathValue("id")
|
||||
name := r.FormValue("name")
|
||||
if id == "new" {
|
||||
account, err = h.s.Add(user, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
account, err = h.s.UpdateName(user, id, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
comp := t.AccountItem(account)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h AccountImpl) handleDeleteAccount() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
|
||||
err := h.s.Delete(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
377
internal/handler/auth.go
Normal file
377
internal/handler/auth.go
Normal file
@@ -0,0 +1,377 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/log"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/template/auth"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Auth interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type AuthImpl struct {
|
||||
service service.Auth
|
||||
render *Render
|
||||
}
|
||||
|
||||
func NewAuth(service service.Auth, render *Render) Auth {
|
||||
return AuthImpl{
|
||||
service: service,
|
||||
render: render,
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) Handle(router *http.ServeMux) {
|
||||
router.Handle("GET /auth/signin", handler.handleSignInPage())
|
||||
router.Handle("POST /api/auth/signin", handler.handleSignIn())
|
||||
|
||||
router.Handle("/auth/signup", handler.handleSignUpPage())
|
||||
router.Handle("/auth/verify", handler.handleSignUpVerifyPage())
|
||||
router.Handle("/api/auth/verify-resend", handler.handleVerifyResendComp())
|
||||
router.Handle("/auth/verify-email", handler.handleSignUpVerifyResponsePage())
|
||||
router.Handle("/api/auth/signup", handler.handleSignUp())
|
||||
|
||||
router.Handle("POST /api/auth/signout", handler.handleSignOut())
|
||||
|
||||
router.Handle("/auth/delete-account", handler.handleDeleteAccountPage())
|
||||
router.Handle("/api/auth/delete-account", handler.handleDeleteAccountComp())
|
||||
|
||||
router.Handle("GET /auth/change-password", handler.handleChangePasswordPage())
|
||||
router.Handle("POST /api/auth/change-password", handler.handleChangePasswordComp())
|
||||
|
||||
router.Handle("GET /auth/forgot-password", handler.handleForgotPasswordPage())
|
||||
router.Handle("POST /api/auth/forgot-password", handler.handleForgotPasswordComp())
|
||||
router.Handle("POST /api/auth/forgot-password-actual", handler.handleForgotPasswordResponseComp())
|
||||
}
|
||||
|
||||
var (
|
||||
securityWaitDuration = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
func (handler AuthImpl) handleSignInPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user != nil {
|
||||
if !user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/auth/verify")
|
||||
} else {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.SignInOrUpComp(true)
|
||||
|
||||
handler.render.RenderLayout(r, w, comp, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignIn() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := utils.WaitMinimumTime(securityWaitDuration, func() (*types.User, error) {
|
||||
session := middleware.GetSession(r)
|
||||
email := r.FormValue("email")
|
||||
password := r.FormValue("password")
|
||||
|
||||
session, user, err := handler.service.SignIn(session, email, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cookie := middleware.CreateSessionCookie(session.Id)
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
return user, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrInvalidCredentials) {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Invalid email or password", http.StatusUnauthorized)
|
||||
} else {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "An error occurred", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
} else {
|
||||
utils.DoRedirect(w, r, "/auth/verify")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUpPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
|
||||
if user != nil {
|
||||
if !user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/auth/verify")
|
||||
} else {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
signUpComp := auth.SignInOrUpComp(false)
|
||||
handler.render.RenderLayout(r, w, signUpComp, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUpVerifyPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
if user.EmailVerified {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
return
|
||||
}
|
||||
|
||||
signIn := auth.VerifyComp()
|
||||
handler.render.RenderLayout(r, w, signIn, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleVerifyResendComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
go handler.service.SendVerificationMail(user.Id, user.Email)
|
||||
|
||||
_, err := w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
||||
if err != nil {
|
||||
log.Error("Could not write response: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUpVerifyResponsePage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.URL.Query().Get("token")
|
||||
|
||||
err := handler.service.VerifyUserEmail(token)
|
||||
|
||||
isVerified := err == nil
|
||||
comp := auth.VerifyResponseComp(isVerified)
|
||||
|
||||
var status int
|
||||
if isVerified {
|
||||
status = http.StatusOK
|
||||
} else {
|
||||
status = http.StatusBadRequest
|
||||
}
|
||||
|
||||
handler.render.RenderLayoutWithStatus(r, w, comp, nil, status)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignUp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var email = r.FormValue("email")
|
||||
var password = r.FormValue("password")
|
||||
|
||||
_, err := utils.WaitMinimumTime(securityWaitDuration, func() (interface{}, error) {
|
||||
log.Info("Signing up %v", email)
|
||||
user, err := handler.service.SignUp(email, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Info("Sending verification email to %v", user.Email)
|
||||
go handler.service.SendVerificationMail(user.Id, user.Email)
|
||||
return nil, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, types.ErrInternal):
|
||||
utils.TriggerToastWithStatus(w, r, "error", "An error occurred", http.StatusInternalServerError)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidEmail):
|
||||
utils.TriggerToastWithStatus(w, r, "error", "The email provided is invalid", http.StatusBadRequest)
|
||||
return
|
||||
case errors.Is(err, service.ErrInvalidPassword):
|
||||
utils.TriggerToastWithStatus(w, r, "error", service.ErrInvalidPassword.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// If err is "service.ErrAccountExists", then just continue
|
||||
}
|
||||
|
||||
utils.TriggerToastWithStatus(w, r, "success", "An activation link has been send to your email", http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleSignOut() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
session := middleware.GetSession(r)
|
||||
|
||||
if session != nil {
|
||||
err := handler.service.SignOut(session.Id)
|
||||
if err != nil {
|
||||
http.Error(w, "An error occurred", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c := http.Cookie{
|
||||
Name: "id",
|
||||
Value: "",
|
||||
MaxAge: -1,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
|
||||
http.SetCookie(w, &c)
|
||||
utils.DoRedirect(w, r, "/")
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleDeleteAccountPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.DeleteAccountComp()
|
||||
handler.render.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleDeleteAccountComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
password := r.FormValue("password")
|
||||
|
||||
err := handler.service.DeleteAccount(user, password)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrInvalidCredentials) {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Password not correct", http.StatusBadRequest)
|
||||
} else {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
utils.DoRedirect(w, r, "/")
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleChangePasswordPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
isPasswordReset := r.URL.Query().Has("token")
|
||||
|
||||
user := middleware.GetUser(r)
|
||||
|
||||
if user == nil && !isPasswordReset {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.ChangePasswordComp(isPasswordReset)
|
||||
handler.render.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleChangePasswordComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
session := middleware.GetSession(r)
|
||||
user := middleware.GetUser(r)
|
||||
if session == nil || user == nil {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Unathorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
currPass := r.FormValue("current-password")
|
||||
newPass := r.FormValue("new-password")
|
||||
|
||||
err := handler.service.ChangePassword(user, session.Id, currPass, newPass)
|
||||
if err != nil {
|
||||
utils.TriggerToastWithStatus(w, r, "error", err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
utils.TriggerToastWithStatus(w, r, "success", "Password changed", http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleForgotPasswordPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user != nil {
|
||||
utils.DoRedirect(w, r, "/")
|
||||
return
|
||||
}
|
||||
|
||||
comp := auth.ResetPasswordComp()
|
||||
handler.render.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleForgotPasswordComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
email := r.FormValue("email")
|
||||
if email == "" {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Please enter an email", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := utils.WaitMinimumTime(securityWaitDuration, func() (interface{}, error) {
|
||||
err := handler.service.SendForgotPasswordMail(email)
|
||||
return nil, err
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
} else {
|
||||
utils.TriggerToastWithStatus(w, r, "info", "If the address exists, an email has been sent.", http.StatusOK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (handler AuthImpl) handleForgotPasswordResponseComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
pageUrl, err := url.Parse(r.Header.Get("Hx-Current-Url"))
|
||||
if err != nil {
|
||||
log.Error("Could not get current URL: %v", err)
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
token := pageUrl.Query().Get("token")
|
||||
newPass := r.FormValue("new-password")
|
||||
|
||||
err = handler.service.ForgotPassword(token, newPass)
|
||||
if err != nil {
|
||||
utils.TriggerToastWithStatus(w, r, "error", err.Error(), http.StatusBadRequest)
|
||||
} else {
|
||||
utils.TriggerToastWithStatus(w, r, "success", "Password changed", http.StatusOK)
|
||||
}
|
||||
}
|
||||
}
|
||||
35
internal/handler/error.go
Normal file
35
internal/handler/error.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/db"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func handleError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
utils.TriggerToastWithStatus(w, r, "error", "You are not autorized to perform this operation.", http.StatusUnauthorized)
|
||||
return
|
||||
case errors.Is(err, service.ErrBadRequest):
|
||||
utils.TriggerToastWithStatus(w, r, "error", extractErrorMessage(err), http.StatusBadRequest)
|
||||
return
|
||||
case errors.Is(err, db.ErrNotFound):
|
||||
utils.TriggerToastWithStatus(w, r, "error", extractErrorMessage(err), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func extractErrorMessage(err error) string {
|
||||
errMsg := err.Error()
|
||||
if errMsg == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.SplitN(errMsg, ":", 2)[0]
|
||||
}
|
||||
80
internal/handler/middleware/authenticate.go
Normal file
80
internal/handler/middleware/authenticate.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/types"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
var SessionKey ContextKey = "session"
|
||||
var UserKey ContextKey = "user"
|
||||
|
||||
func Authenticate(service service.Auth) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sessionId := getSessionID(r)
|
||||
session, user, _ := service.SignInSession(sessionId)
|
||||
|
||||
var err error
|
||||
// Always sign in anonymous
|
||||
// This way, we can always generate csrf tokens
|
||||
if session == nil {
|
||||
session, err = service.SignInAnonymous()
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
cookie := CreateSessionCookie(session.Id)
|
||||
http.SetCookie(w, &cookie)
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
ctx = context.WithValue(ctx, UserKey, user)
|
||||
ctx = context.WithValue(ctx, SessionKey, session)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func GetUser(r *http.Request) *types.User {
|
||||
obj := r.Context().Value(UserKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
user, ok := obj.(*types.User)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func GetSession(r *http.Request) *types.Session {
|
||||
obj := r.Context().Value(SessionKey)
|
||||
if obj == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
session, ok := obj.(*types.Session)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
func getSessionID(r *http.Request) string {
|
||||
cookie, err := r.Cookie("id")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return cookie.Value
|
||||
}
|
||||
18
internal/handler/middleware/cache_control.go
Normal file
18
internal/handler/middleware/cache_control.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func CacheControl(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
shouldCache := strings.HasPrefix(r.URL.Path, "/static")
|
||||
|
||||
if !shouldCache {
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
63
internal/handler/middleware/cross_site_request_forgery.go
Normal file
63
internal/handler/middleware/cross_site_request_forgery.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"spend-sparrow/internal/log"
|
||||
"spend-sparrow/internal/service"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
)
|
||||
|
||||
type csrfResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
auth service.Auth
|
||||
session *types.Session
|
||||
}
|
||||
|
||||
func newCsrfResponseWriter(w http.ResponseWriter, auth service.Auth, session *types.Session) *csrfResponseWriter {
|
||||
return &csrfResponseWriter{
|
||||
ResponseWriter: w,
|
||||
auth: auth,
|
||||
session: session,
|
||||
}
|
||||
}
|
||||
|
||||
func (rr *csrfResponseWriter) Write(data []byte) (int, error) {
|
||||
dataStr := string(data)
|
||||
csrfToken, err := rr.auth.GetCsrfToken(rr.session)
|
||||
if err == nil {
|
||||
dataStr = strings.ReplaceAll(dataStr, "CSRF_TOKEN", csrfToken)
|
||||
}
|
||||
|
||||
return rr.ResponseWriter.Write([]byte(dataStr))
|
||||
}
|
||||
|
||||
func CrossSiteRequestForgery(auth service.Auth) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session := GetSession(r)
|
||||
|
||||
if r.Method == http.MethodPost ||
|
||||
r.Method == http.MethodPut ||
|
||||
r.Method == http.MethodDelete ||
|
||||
r.Method == http.MethodPatch {
|
||||
csrfToken := r.Header.Get("Csrf-Token")
|
||||
|
||||
if session == nil || csrfToken == "" || !auth.IsCsrfTokenValid(csrfToken, session.Id) {
|
||||
log.Info("CSRF-Token \"%s\" not correct", csrfToken)
|
||||
if r.Header.Get("Hx-Request") == "true" {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "CSRF-Token not correct", http.StatusBadRequest)
|
||||
} else {
|
||||
http.Error(w, "CSRF-Token not correct", http.StatusBadRequest)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
responseWriter := newCsrfResponseWriter(w, auth, session)
|
||||
next.ServeHTTP(responseWriter, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
15
internal/handler/middleware/default.go
Normal file
15
internal/handler/middleware/default.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func CreateSessionCookie(sessionId string) http.Cookie {
|
||||
return http.Cookie{
|
||||
Name: "id",
|
||||
Value: sessionId,
|
||||
MaxAge: 60 * 60 * 8, // 8 hours
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/service"
|
||||
)
|
||||
|
||||
func GenerateRecurringTransactions(transactionRecurring service.TransactionRecurring) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user := GetUser(r)
|
||||
if user == nil || r.Method != http.MethodGet {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
_ = transactionRecurring.GenerateTransactions(user)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
40
internal/handler/middleware/gzip.go
Normal file
40
internal/handler/middleware/gzip.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"spend-sparrow/internal/log"
|
||||
)
|
||||
|
||||
type gzipResponseWriter struct {
|
||||
io.Writer
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
||||
return w.Writer.Write(b)
|
||||
}
|
||||
|
||||
func Gzip(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
gz := gzip.NewWriter(w)
|
||||
wrapper := gzipResponseWriter{Writer: gz, ResponseWriter: w}
|
||||
|
||||
next.ServeHTTP(wrapper, r)
|
||||
|
||||
err := gz.Close()
|
||||
if err != nil && !errors.Is(err, http.ErrBodyNotAllowed) {
|
||||
log.Error("Gzip: could not close Writer: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
47
internal/handler/middleware/logger.go
Normal file
47
internal/handler/middleware/logger.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"spend-sparrow/internal/log"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
)
|
||||
|
||||
var (
|
||||
metrics = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "mefit_request_total",
|
||||
Help: "The total number of requests processed",
|
||||
},
|
||||
[]string{"path", "method", "status"},
|
||||
)
|
||||
)
|
||||
|
||||
type WrappedWriter struct {
|
||||
http.ResponseWriter
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (w *WrappedWriter) WriteHeader(code int) {
|
||||
w.StatusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Log(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
wrapped := &WrappedWriter{
|
||||
ResponseWriter: w,
|
||||
StatusCode: http.StatusOK,
|
||||
}
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
log.Info(r.RemoteAddr + " " + strconv.Itoa(wrapped.StatusCode) + " " + r.Method + " " + r.URL.Path + " " + time.Since(start).String())
|
||||
metrics.WithLabelValues(r.URL.Path, r.Method, http.StatusText(wrapped.StatusCode)).Inc()
|
||||
})
|
||||
}
|
||||
40
internal/handler/middleware/security_headers.go
Normal file
40
internal/handler/middleware/security_headers.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"spend-sparrow/internal/types"
|
||||
)
|
||||
|
||||
func SecurityHeaders(serverSettings *types.Settings) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Access-Control-Allow-Origin", serverSettings.BaseUrl)
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'none'; "+
|
||||
"script-src 'self'; "+
|
||||
"font-src 'self'; "+
|
||||
"connect-src 'self'; "+
|
||||
"img-src 'self'; "+
|
||||
"style-src 'self'; "+
|
||||
"form-action 'self'; "+
|
||||
"frame-ancestors 'none'; ",
|
||||
)
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
|
||||
w.Header().Set("Permissions-Policy", "geolocation=(), camera=(), microphone=(), interest-cohort=()")
|
||||
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
14
internal/handler/middleware/wrapper.go
Normal file
14
internal/handler/middleware/wrapper.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// Chain list of handlers together.
|
||||
func Wrapper(next http.Handler, handlers ...func(http.Handler) http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
lastHandler := next
|
||||
for _, handler := range handlers {
|
||||
lastHandler = handler(lastHandler)
|
||||
}
|
||||
lastHandler.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
52
internal/handler/render.go
Normal file
52
internal/handler/render.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"spend-sparrow/internal/log"
|
||||
"spend-sparrow/internal/template"
|
||||
"spend-sparrow/internal/template/auth"
|
||||
"spend-sparrow/internal/types"
|
||||
|
||||
"net/http"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type Render struct {
|
||||
}
|
||||
|
||||
func NewRender() *Render {
|
||||
return &Render{}
|
||||
}
|
||||
|
||||
func (render *Render) RenderWithStatus(r *http.Request, w http.ResponseWriter, comp templ.Component, status int) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(status)
|
||||
err := comp.Render(r.Context(), w)
|
||||
if err != nil {
|
||||
log.Error("Failed to render layout: %v", err)
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func (render *Render) Render(r *http.Request, w http.ResponseWriter, comp templ.Component) {
|
||||
render.RenderWithStatus(r, w, comp, http.StatusOK)
|
||||
}
|
||||
|
||||
func (render *Render) RenderLayout(r *http.Request, w http.ResponseWriter, slot templ.Component, user *types.User) {
|
||||
render.RenderLayoutWithStatus(r, w, slot, user, http.StatusOK)
|
||||
}
|
||||
|
||||
func (render *Render) RenderLayoutWithStatus(r *http.Request, w http.ResponseWriter, slot templ.Component, user *types.User, status int) {
|
||||
userComp := render.getUserComp(user)
|
||||
layout := template.Layout(slot, userComp, user != nil, r.URL.Path)
|
||||
|
||||
render.RenderWithStatus(r, w, layout, status)
|
||||
}
|
||||
|
||||
func (render *Render) getUserComp(user *types.User) templ.Component {
|
||||
if user != nil {
|
||||
return auth.UserComp(user.Email)
|
||||
} else {
|
||||
return auth.UserComp("")
|
||||
}
|
||||
}
|
||||
57
internal/handler/root_and_404.go
Normal file
57
internal/handler/root_and_404.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/template"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type Index interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type IndexImpl struct {
|
||||
render *Render
|
||||
}
|
||||
|
||||
func NewIndex(render *Render) Index {
|
||||
return IndexImpl{
|
||||
render: render,
|
||||
}
|
||||
}
|
||||
|
||||
func (handler IndexImpl) Handle(router *http.ServeMux) {
|
||||
router.Handle("/", handler.handleRootAnd404())
|
||||
router.Handle("/empty", handler.handleEmpty())
|
||||
}
|
||||
|
||||
func (handler IndexImpl) handleRootAnd404() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
|
||||
var comp templ.Component
|
||||
|
||||
var status int
|
||||
if r.URL.Path != "/" {
|
||||
comp = template.NotFound()
|
||||
status = http.StatusNotFound
|
||||
} else {
|
||||
if user != nil {
|
||||
comp = template.Dashboard()
|
||||
} else {
|
||||
comp = template.Index()
|
||||
}
|
||||
status = http.StatusOK
|
||||
}
|
||||
|
||||
handler.render.RenderLayoutWithStatus(r, w, comp, user, status)
|
||||
}
|
||||
}
|
||||
|
||||
func (handler IndexImpl) handleEmpty() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Return nothing
|
||||
}
|
||||
}
|
||||
286
internal/handler/transaction.go
Normal file
286
internal/handler/transaction.go
Normal file
@@ -0,0 +1,286 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
t "spend-sparrow/internal/template/transaction"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Transaction interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type TransactionImpl struct {
|
||||
s service.Transaction
|
||||
account service.Account
|
||||
treasureChest service.TreasureChest
|
||||
r *Render
|
||||
}
|
||||
|
||||
func NewTransaction(s service.Transaction, account service.Account, treasureChest service.TreasureChest, r *Render) Transaction {
|
||||
return TransactionImpl{
|
||||
s: s,
|
||||
account: account,
|
||||
treasureChest: treasureChest,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /transaction", h.handleTransactionPage())
|
||||
r.Handle("GET /transaction/{id}", h.handleTransactionItemComp())
|
||||
r.Handle("POST /transaction/{id}", h.handleUpdateTransaction())
|
||||
r.Handle("POST /transaction/recalculate", h.handleRecalculate())
|
||||
r.Handle("DELETE /transaction/{id}", h.handleDeleteTransaction())
|
||||
}
|
||||
|
||||
func (h TransactionImpl) handleTransactionPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
filter := types.TransactionItemsFilter{
|
||||
AccountId: r.URL.Query().Get("account-id"),
|
||||
TreasureChestId: r.URL.Query().Get("treasure-chest-id"),
|
||||
Error: r.URL.Query().Get("error"),
|
||||
}
|
||||
|
||||
transactions, err := h.s.GetAll(user, filter)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
accounts, err := h.account.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.treasureChest.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
accountMap, treasureChestMap := h.getTransactionData(accounts, treasureChests)
|
||||
|
||||
items := t.TransactionItems(transactions, accountMap, treasureChestMap)
|
||||
if utils.IsHtmx(r) {
|
||||
h.r.Render(r, w, items)
|
||||
} else {
|
||||
comp := t.Transaction(items, filter, accounts, treasureChests)
|
||||
h.r.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) handleTransactionItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
accounts, err := h.account.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.treasureChest.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "new" {
|
||||
comp := t.EditTransaction(nil, accounts, treasureChests)
|
||||
h.r.Render(r, w, comp)
|
||||
return
|
||||
}
|
||||
|
||||
transaction, err := h.s.Get(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var comp templ.Component
|
||||
if r.URL.Query().Get("edit") == "true" {
|
||||
comp = t.EditTransaction(transaction, accounts, treasureChests)
|
||||
} else {
|
||||
accountMap, treasureChestMap := h.getTransactionData(accounts, treasureChests)
|
||||
comp = t.TransactionItem(transaction, accountMap, treasureChestMap)
|
||||
}
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) handleUpdateTransaction() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
id uuid.UUID
|
||||
err error
|
||||
)
|
||||
|
||||
idStr := r.PathValue("id")
|
||||
if idStr != "new" {
|
||||
id, err = uuid.Parse(idStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse Id: %w", service.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
accountIdStr := r.FormValue("account-id")
|
||||
var accountId *uuid.UUID
|
||||
if accountIdStr != "" {
|
||||
i, err := uuid.Parse(accountIdStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse account id: %w", service.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
accountId = &i
|
||||
}
|
||||
|
||||
treasureChestIdStr := r.FormValue("treasure-chest-id")
|
||||
var treasureChestId *uuid.UUID
|
||||
if treasureChestIdStr != "" {
|
||||
i, err := uuid.Parse(treasureChestIdStr)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse treasure chest id: %w", service.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
treasureChestId = &i
|
||||
}
|
||||
|
||||
valueF, err := strconv.ParseFloat(r.FormValue("value"), 64)
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse value: %w", service.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
value := int64(valueF * service.DECIMALS_MULTIPLIER)
|
||||
|
||||
timestamp, err := time.Parse("2006-01-02", r.FormValue("timestamp"))
|
||||
if err != nil {
|
||||
handleError(w, r, fmt.Errorf("could not parse timestamp: %w", service.ErrBadRequest))
|
||||
return
|
||||
}
|
||||
|
||||
input := types.Transaction{
|
||||
Id: id,
|
||||
AccountId: accountId,
|
||||
TreasureChestId: treasureChestId,
|
||||
Value: value,
|
||||
Timestamp: timestamp,
|
||||
Party: r.FormValue("party"),
|
||||
Description: r.FormValue("description"),
|
||||
}
|
||||
|
||||
var transaction *types.Transaction
|
||||
if idStr == "new" {
|
||||
transaction, err = h.s.Add(nil, user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
transaction, err = h.s.Update(user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
accounts, err := h.account.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.treasureChest.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
accountMap, treasureChestMap := h.getTransactionData(accounts, treasureChests)
|
||||
comp := t.TransactionItem(transaction, accountMap, treasureChestMap)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) handleRecalculate() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
err := h.s.RecalculateBalances(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
utils.TriggerToastWithStatus(w, r, "success", "Balances recalculated, please refresh", http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) handleDeleteTransaction() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
|
||||
err := h.s.Delete(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionImpl) getTransactionData(accounts []*types.Account, treasureChests []*types.TreasureChest) (map[uuid.UUID]string, map[uuid.UUID]string) {
|
||||
accountMap := make(map[uuid.UUID]string, 0)
|
||||
for _, account := range accounts {
|
||||
accountMap[account.Id] = account.Name
|
||||
}
|
||||
treasureChestMap := make(map[uuid.UUID]string, 0)
|
||||
root := ""
|
||||
for _, treasureChest := range treasureChests {
|
||||
if treasureChest.ParentId == nil {
|
||||
root = treasureChest.Name + " > "
|
||||
treasureChestMap[treasureChest.Id] = treasureChest.Name
|
||||
} else {
|
||||
treasureChestMap[treasureChest.Id] = root + treasureChest.Name
|
||||
}
|
||||
}
|
||||
return accountMap, treasureChestMap
|
||||
}
|
||||
130
internal/handler/transaction_recurring.go
Normal file
130
internal/handler/transaction_recurring.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
t "spend-sparrow/internal/template/transaction_recurring"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
)
|
||||
|
||||
type TransactionRecurring interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type TransactionRecurringImpl struct {
|
||||
s service.TransactionRecurring
|
||||
r *Render
|
||||
}
|
||||
|
||||
func NewTransactionRecurring(s service.TransactionRecurring, r *Render) TransactionRecurring {
|
||||
return TransactionRecurringImpl{
|
||||
s: s,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /transaction-recurring", h.handleTransactionRecurringItemComp())
|
||||
r.Handle("POST /transaction-recurring/{id}", h.handleUpdateTransactionRecurring())
|
||||
r.Handle("DELETE /transaction-recurring/{id}", h.handleDeleteTransactionRecurring())
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) handleTransactionRecurringItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.URL.Query().Get("id")
|
||||
accountId := r.URL.Query().Get("account-id")
|
||||
treasureChestId := r.URL.Query().Get("treasure-chest-id")
|
||||
h.renderItems(w, r, user, id, accountId, treasureChestId)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) handleUpdateTransactionRecurring() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
input := types.TransactionRecurringInput{
|
||||
Id: r.PathValue("id"),
|
||||
IntervalMonths: r.FormValue("interval-months"),
|
||||
NextExecution: r.FormValue("next-execution"),
|
||||
Party: r.FormValue("party"),
|
||||
Description: r.FormValue("description"),
|
||||
AccountId: r.FormValue("account-id"),
|
||||
TreasureChestId: r.FormValue("treasure-chest-id"),
|
||||
Value: r.FormValue("value"),
|
||||
}
|
||||
|
||||
if input.Id == "new" {
|
||||
_, err := h.s.Add(user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
_, err := h.s.Update(user, input)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
h.renderItems(w, r, user, "", input.AccountId, input.TreasureChestId)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) handleDeleteTransactionRecurring() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
accountId := r.URL.Query().Get("account-id")
|
||||
treasureChestId := r.URL.Query().Get("treasure-chest-id")
|
||||
|
||||
err := h.s.Delete(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
h.renderItems(w, r, user, "", accountId, treasureChestId)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TransactionRecurringImpl) renderItems(w http.ResponseWriter, r *http.Request, user *types.User, id, accountId, treasureChestId string) {
|
||||
var transactionsRecurring []*types.TransactionRecurring
|
||||
var err error
|
||||
if accountId == "" && treasureChestId == "" {
|
||||
utils.TriggerToastWithStatus(w, r, "error", "Please select an account or treasure chest", http.StatusBadRequest)
|
||||
}
|
||||
if accountId != "" {
|
||||
transactionsRecurring, err = h.s.GetAllByAccount(user, accountId)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
transactionsRecurring, err = h.s.GetAllByTreasureChest(user, treasureChestId)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
comp := t.TransactionRecurringItems(transactionsRecurring, id, accountId, treasureChestId)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
188
internal/handler/treasure_chest.go
Normal file
188
internal/handler/treasure_chest.go
Normal file
@@ -0,0 +1,188 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"spend-sparrow/internal/handler/middleware"
|
||||
"spend-sparrow/internal/service"
|
||||
tr "spend-sparrow/internal/template/transaction_recurring"
|
||||
t "spend-sparrow/internal/template/treasurechest"
|
||||
"spend-sparrow/internal/types"
|
||||
"spend-sparrow/internal/utils"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type TreasureChest interface {
|
||||
Handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type TreasureChestImpl struct {
|
||||
s service.TreasureChest
|
||||
transactionRecurring service.TransactionRecurring
|
||||
r *Render
|
||||
}
|
||||
|
||||
func NewTreasureChest(s service.TreasureChest, transactionRecurring service.TransactionRecurring, r *Render) TreasureChest {
|
||||
return TreasureChestImpl{
|
||||
s: s,
|
||||
transactionRecurring: transactionRecurring,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) Handle(r *http.ServeMux) {
|
||||
r.Handle("GET /treasurechest", h.handleTreasureChestPage())
|
||||
r.Handle("GET /treasurechest/{id}", h.handleTreasureChestItemComp())
|
||||
r.Handle("POST /treasurechest/{id}", h.handleUpdateTreasureChest())
|
||||
r.Handle("DELETE /treasurechest/{id}", h.handleDeleteTreasureChest())
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleTreasureChestPage() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.s.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
transactionsRecurring, err := h.transactionRecurring.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
monthlySums := h.calculateMonthlySums(treasureChests, transactionsRecurring)
|
||||
|
||||
comp := t.TreasureChest(treasureChests, monthlySums)
|
||||
h.r.RenderLayout(r, w, comp, user)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleTreasureChestItemComp() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests, err := h.s.GetAll(user)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "new" {
|
||||
comp := t.EditTreasureChest(nil, treasureChests, nil)
|
||||
h.r.Render(r, w, comp)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChest, err := h.s.Get(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
transactionsRecurring, err := h.transactionRecurring.GetAllByTreasureChest(user, treasureChest.Id.String())
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
transactionsRec := tr.TransactionRecurringItems(transactionsRecurring, "", "", treasureChest.Id.String())
|
||||
|
||||
var comp templ.Component
|
||||
if r.URL.Query().Get("edit") == "true" {
|
||||
comp = t.EditTreasureChest(treasureChest, treasureChests, transactionsRec)
|
||||
} else {
|
||||
monthlySums := h.calculateMonthlySums(treasureChests, transactionsRecurring)
|
||||
comp = t.TreasureChestItem(treasureChest, monthlySums)
|
||||
}
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleUpdateTreasureChest() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
treasureChest *types.TreasureChest
|
||||
err error
|
||||
)
|
||||
id := r.PathValue("id")
|
||||
parentId := r.FormValue("parent-id")
|
||||
name := r.FormValue("name")
|
||||
if id == "new" {
|
||||
treasureChest, err = h.s.Add(user, parentId, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
treasureChest, err = h.s.Update(user, id, parentId, name)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
transactionsRecurring, err := h.transactionRecurring.GetAllByTreasureChest(user, treasureChest.Id.String())
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
treasureChests := make([]*types.TreasureChest, 1)
|
||||
treasureChests[0] = treasureChest
|
||||
monthlySums := h.calculateMonthlySums(treasureChests, transactionsRecurring)
|
||||
comp := t.TreasureChestItem(treasureChest, monthlySums)
|
||||
h.r.Render(r, w, comp)
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) handleDeleteTreasureChest() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user := middleware.GetUser(r)
|
||||
if user == nil {
|
||||
utils.DoRedirect(w, r, "/auth/signin")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
|
||||
err := h.s.Delete(user, id)
|
||||
if err != nil {
|
||||
handleError(w, r, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h TreasureChestImpl) calculateMonthlySums(
|
||||
treasureChests []*types.TreasureChest,
|
||||
transactionsRecurring []*types.TransactionRecurring,
|
||||
) map[uuid.UUID]int64 {
|
||||
monthlySums := make(map[uuid.UUID]int64)
|
||||
for _, tc := range treasureChests {
|
||||
monthlySums[tc.Id] = 0
|
||||
}
|
||||
for _, t := range transactionsRecurring {
|
||||
if t.TreasureChestId != nil && t.Value > 0 && t.IntervalMonths > 0 {
|
||||
monthlySums[*t.TreasureChestId] += t.Value / t.IntervalMonths
|
||||
}
|
||||
}
|
||||
return monthlySums
|
||||
}
|
||||
Reference in New Issue
Block a user