fix: restructure env handling for better testing capabillities #181 #195
@@ -2,11 +2,12 @@ package handler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"me-fit/service"
|
"me-fit/service"
|
||||||
|
"me-fit/types"
|
||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
"time"
|
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type HandlerAuth interface {
|
type HandlerAuth interface {
|
||||||
@@ -16,31 +17,33 @@ type HandlerAuth interface {
|
|||||||
type HandlerAuthImpl struct {
|
type HandlerAuthImpl struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
service service.ServiceAuth
|
service service.ServiceAuth
|
||||||
|
serverSettings *types.ServerSettings
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandlerAuth(db *sql.DB, service service.ServiceAuth) HandlerAuth {
|
func NewHandlerAuth(db *sql.DB, service service.ServiceAuth, serverSettings *types.ServerSettings) HandlerAuth {
|
||||||
return HandlerAuthImpl{
|
return HandlerAuthImpl{
|
||||||
db: db,
|
db: db,
|
||||||
service: service,
|
service: service,
|
||||||
|
serverSettings: serverSettings,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (handler HandlerAuthImpl) handle(router *http.ServeMux) {
|
func (handler HandlerAuthImpl) handle(router *http.ServeMux) {
|
||||||
// Don't use auth middleware for these routes, as it makes redirecting very difficult, if the mail is not yet verified
|
// Don't use auth middleware for these routes, as it makes redirecting very difficult, if the mail is not yet verified
|
||||||
router.Handle("/auth/signin", service.HandleSignInPage(handler.db))
|
router.Handle("/auth/signin", service.HandleSignInPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/auth/signup", service.HandleSignUpPage(handler.db))
|
router.Handle("/auth/signup", service.HandleSignUpPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/auth/verify", service.HandleSignUpVerifyPage(handler.db)) // Hint for the user to verify their email
|
router.Handle("/auth/verify", service.HandleSignUpVerifyPage(handler.db, handler.serverSettings)) // Hint for the user to verify their email
|
||||||
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(handler.db))
|
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(handler.db)) // The link contained in the email
|
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(handler.db)) // The link contained in the email
|
||||||
router.Handle("/auth/change-password", service.HandleChangePasswordPage(handler.db))
|
router.Handle("/auth/change-password", service.HandleChangePasswordPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/auth/reset-password", service.HandleResetPasswordPage(handler.db))
|
router.Handle("/auth/reset-password", service.HandleResetPasswordPage(handler.db, handler.serverSettings))
|
||||||
router.Handle("/api/auth/signup", service.HandleSignUpComp(handler.db))
|
router.Handle("/api/auth/signup", service.HandleSignUpComp(handler.db, handler.serverSettings))
|
||||||
router.Handle("/api/auth/signin", handler.handleSignIn())
|
router.Handle("/api/auth/signin", handler.handleSignIn())
|
||||||
router.Handle("/api/auth/signout", service.HandleSignOutComp(handler.db))
|
router.Handle("/api/auth/signout", service.HandleSignOutComp(handler.db))
|
||||||
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(handler.db))
|
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(handler.db, handler.serverSettings))
|
||||||
router.Handle("/api/auth/verify-resend", service.HandleVerifyResendComp(handler.db))
|
router.Handle("/api/auth/verify-resend", service.HandleVerifyResendComp(handler.db, handler.serverSettings))
|
||||||
router.Handle("/api/auth/change-password", service.HandleChangePasswordComp(handler.db))
|
router.Handle("/api/auth/change-password", service.HandleChangePasswordComp(handler.db))
|
||||||
router.Handle("/api/auth/reset-password", service.HandleResetPasswordComp(handler.db))
|
router.Handle("/api/auth/reset-password", service.HandleResetPasswordComp(handler.db, handler.serverSettings))
|
||||||
router.Handle("/api/auth/reset-password-actual", service.HandleActualResetPasswordComp(handler.db))
|
router.Handle("/api/auth/reset-password-actual", service.HandleActualResetPasswordComp(handler.db))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,26 +4,27 @@ import (
|
|||||||
"me-fit/db"
|
"me-fit/db"
|
||||||
"me-fit/middleware"
|
"me-fit/middleware"
|
||||||
"me-fit/service"
|
"me-fit/service"
|
||||||
|
"me-fit/types"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetHandler(d *sql.DB) http.Handler {
|
func GetHandler(d *sql.DB, serverSettings *types.ServerSettings) http.Handler {
|
||||||
var router = http.NewServeMux()
|
var router = http.NewServeMux()
|
||||||
|
|
||||||
router.HandleFunc("/", service.HandleIndexAnd404(d))
|
router.HandleFunc("/", service.HandleIndexAnd404(d, serverSettings))
|
||||||
|
|
||||||
handlerAuth := NewHandlerAuth(d, service.NewServiceAuthImpl(db.NewDbAuthSqlite(d)))
|
handlerAuth := NewHandlerAuth(d, service.NewServiceAuthImpl(db.NewDbAuthSqlite(d)), serverSettings)
|
||||||
|
|
||||||
// Serve static files (CSS, JS and images)
|
// Serve static files (CSS, JS and images)
|
||||||
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
||||||
|
|
||||||
handleWorkout(d, router)
|
handleWorkout(d, router, serverSettings)
|
||||||
|
|
||||||
handlerAuth.handle(router)
|
handlerAuth.handle(router)
|
||||||
|
|
||||||
return middleware.Logging(middleware.EnableCors(router))
|
return middleware.Logging(middleware.EnableCors(serverSettings, router))
|
||||||
}
|
}
|
||||||
|
|
||||||
func auth(db *sql.DB, h http.Handler) http.Handler {
|
func auth(db *sql.DB, h http.Handler) http.Handler {
|
||||||
|
|||||||
@@ -2,13 +2,14 @@ package handler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"me-fit/service"
|
"me-fit/service"
|
||||||
|
"me-fit/types"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func handleWorkout(db *sql.DB, router *http.ServeMux) {
|
func handleWorkout(db *sql.DB, router *http.ServeMux, serverSettings *types.ServerSettings) {
|
||||||
router.Handle("/workout", auth(db, service.HandleWorkoutPage(db)))
|
router.Handle("/workout", auth(db, service.HandleWorkoutPage(db, serverSettings)))
|
||||||
router.Handle("POST /api/workout", auth(db, service.HandleWorkoutNewComp(db)))
|
router.Handle("POST /api/workout", auth(db, service.HandleWorkoutNewComp(db)))
|
||||||
router.Handle("GET /api/workout", auth(db, service.HandleWorkoutGetComp(db)))
|
router.Handle("GET /api/workout", auth(db, service.HandleWorkoutGetComp(db)))
|
||||||
router.Handle("DELETE /api/workout/{id}", auth(db, service.HandleWorkoutDeleteComp(db)))
|
router.Handle("DELETE /api/workout/{id}", auth(db, service.HandleWorkoutDeleteComp(db)))
|
||||||
|
|||||||
21
main.go
21
main.go
@@ -2,7 +2,9 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"me-fit/handler"
|
"me-fit/handler"
|
||||||
|
"me-fit/types"
|
||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
|
"os"
|
||||||
|
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
@@ -20,21 +22,22 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
run(context.Background())
|
err := godotenv.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Error loading .env file")
|
||||||
|
}
|
||||||
|
|
||||||
|
run(context.Background(), os.Getenv)
|
||||||
}
|
}
|
||||||
|
|
||||||
func run(ctx context.Context) {
|
func run(ctx context.Context, env func(string) string) {
|
||||||
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
slog.Info("Starting server...")
|
slog.Info("Starting server...")
|
||||||
|
|
||||||
// init env
|
// init server settings
|
||||||
err := godotenv.Load()
|
serverSettings := types.NewServerSettingsFromEnv(env)
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Error loading .env file")
|
|
||||||
}
|
|
||||||
utils.MustInitEnv()
|
|
||||||
|
|
||||||
// init db
|
// init db
|
||||||
db, err := sql.Open("sqlite3", "./data.db")
|
db, err := sql.Open("sqlite3", "./data.db")
|
||||||
@@ -51,7 +54,7 @@ func run(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
Addr: ":8080",
|
Addr: ":8080",
|
||||||
Handler: handler.GetHandler(db),
|
Handler: handler.GetHandler(db, serverSettings),
|
||||||
}
|
}
|
||||||
go startServer(prometheusServer)
|
go startServer(prometheusServer)
|
||||||
go startServer(httpServer)
|
go startServer(httpServer)
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"me-fit/utils"
|
"me-fit/types"
|
||||||
|
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func EnableCors(next http.Handler) http.Handler {
|
func EnableCors(serverSettings *types.ServerSettings, next http.Handler) http.Handler {
|
||||||
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Access-Control-Allow-Origin", utils.BaseUrl)
|
w.Header().Set("Access-Control-Allow-Origin", serverSettings.BaseUrl)
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
|
||||||
|
|
||||||
if r.Method == "OPTIONS" {
|
if r.Method == "OPTIONS" {
|
||||||
|
|||||||
@@ -77,14 +77,14 @@ func (service ServiceAuthImpl) SignIn(email string, password string) (*User, err
|
|||||||
return NewUser(user), nil
|
return NewUser(user), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSignInPage(db *sql.DB) http.HandlerFunc {
|
func HandleSignInPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
|
||||||
if user == nil {
|
if user == nil {
|
||||||
userComp := UserInfoComp(nil)
|
userComp := UserInfoComp(nil)
|
||||||
signIn := auth.SignInOrUpComp(true)
|
signIn := auth.SignInOrUpComp(true)
|
||||||
err := template.Layout(signIn, userComp).Render(r.Context(), w)
|
err := template.Layout(signIn, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render sign in page", err)
|
utils.LogError("Failed to render sign in page", err)
|
||||||
@@ -99,14 +99,14 @@ func HandleSignInPage(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSignUpPage(db *sql.DB) http.HandlerFunc {
|
func HandleSignUpPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
|
||||||
if user == nil {
|
if user == nil {
|
||||||
userComp := UserInfoComp(nil)
|
userComp := UserInfoComp(nil)
|
||||||
signUpComp := auth.SignInOrUpComp(false)
|
signUpComp := auth.SignInOrUpComp(false)
|
||||||
err := template.Layout(signUpComp, userComp).Render(r.Context(), w)
|
err := template.Layout(signUpComp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render sign up page", err)
|
utils.LogError("Failed to render sign up page", err)
|
||||||
@@ -121,7 +121,7 @@ func HandleSignUpPage(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSignUpVerifyPage(db *sql.DB) http.HandlerFunc {
|
func HandleSignUpVerifyPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
@@ -131,7 +131,7 @@ func HandleSignUpVerifyPage(db *sql.DB) http.HandlerFunc {
|
|||||||
} else {
|
} else {
|
||||||
userComp := UserInfoComp(user)
|
userComp := UserInfoComp(user)
|
||||||
signIn := auth.VerifyComp()
|
signIn := auth.VerifyComp()
|
||||||
err := template.Layout(signIn, userComp).Render(r.Context(), w)
|
err := template.Layout(signIn, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render verify page", err)
|
utils.LogError("Failed to render verify page", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
@@ -140,7 +140,7 @@ func HandleSignUpVerifyPage(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleDeleteAccountPage(db *sql.DB) http.HandlerFunc {
|
func HandleDeleteAccountPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
// An unverified email should be able to delete their account
|
// An unverified email should be able to delete their account
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
@@ -149,7 +149,7 @@ func HandleDeleteAccountPage(db *sql.DB) http.HandlerFunc {
|
|||||||
} else {
|
} else {
|
||||||
userComp := UserInfoComp(user)
|
userComp := UserInfoComp(user)
|
||||||
comp := auth.DeleteAccountComp()
|
comp := auth.DeleteAccountComp()
|
||||||
err := template.Layout(comp, userComp).Render(r.Context(), w)
|
err := template.Layout(comp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render delete account page", err)
|
utils.LogError("Failed to render delete account page", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
@@ -200,7 +200,7 @@ func HandleSignUpVerifyResponsePage(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleChangePasswordPage(db *sql.DB) http.HandlerFunc {
|
func HandleChangePasswordPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
isPasswordReset := r.URL.Query().Has("token")
|
isPasswordReset := r.URL.Query().Has("token")
|
||||||
@@ -211,7 +211,7 @@ func HandleChangePasswordPage(db *sql.DB) http.HandlerFunc {
|
|||||||
} else {
|
} else {
|
||||||
userComp := UserInfoComp(user)
|
userComp := UserInfoComp(user)
|
||||||
comp := auth.ChangePasswordComp(isPasswordReset)
|
comp := auth.ChangePasswordComp(isPasswordReset)
|
||||||
err := template.Layout(comp, userComp).Render(r.Context(), w)
|
err := template.Layout(comp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render change password page", err)
|
utils.LogError("Failed to render change password page", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
@@ -220,7 +220,7 @@ func HandleChangePasswordPage(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleResetPasswordPage(db *sql.DB) http.HandlerFunc {
|
func HandleResetPasswordPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
@@ -229,7 +229,7 @@ func HandleResetPasswordPage(db *sql.DB) http.HandlerFunc {
|
|||||||
} else {
|
} else {
|
||||||
userComp := UserInfoComp(nil)
|
userComp := UserInfoComp(nil)
|
||||||
comp := auth.ResetPasswordComp()
|
comp := auth.ResetPasswordComp()
|
||||||
err := template.Layout(comp, userComp).Render(r.Context(), w)
|
err := template.Layout(comp, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render change password page", err)
|
utils.LogError("Failed to render change password page", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
@@ -247,7 +247,7 @@ func UserInfoComp(user *types.User) templ.Component {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSignUpComp(db *sql.DB) http.HandlerFunc {
|
func HandleSignUpComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var email = r.FormValue("email")
|
var email = r.FormValue("email")
|
||||||
var password = r.FormValue("password")
|
var password = r.FormValue("password")
|
||||||
@@ -304,7 +304,7 @@ func HandleSignUpComp(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Send verification email as a goroutine
|
// Send verification email as a goroutine
|
||||||
go sendVerificationEmail(db, userId.String(), email)
|
go sendVerificationEmail(db, userId.String(), email, serverSettings)
|
||||||
|
|
||||||
utils.DoRedirect(w, r, "/auth/verify")
|
utils.DoRedirect(w, r, "/auth/verify")
|
||||||
}
|
}
|
||||||
@@ -339,7 +339,8 @@ func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleDeleteAccountComp(db *sql.DB) http.HandlerFunc {
|
func HandleDeleteAccountComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
|
mailService := NewMailService(serverSettings)
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
@@ -399,13 +400,13 @@ func HandleDeleteAccountComp(db *sql.DB) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
go utils.SendMail(user.Email, "Account deleted", "Your account has been deleted")
|
go mailService.SendMail(user.Email, "Account deleted", "Your account has been deleted")
|
||||||
|
|
||||||
utils.DoRedirect(w, r, "/")
|
utils.DoRedirect(w, r, "/")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleVerifyResendComp(db *sql.DB) http.HandlerFunc {
|
func HandleVerifyResendComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
if user == nil || user.EmailVerified {
|
if user == nil || user.EmailVerified {
|
||||||
@@ -413,7 +414,7 @@ func HandleVerifyResendComp(db *sql.DB) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
go sendVerificationEmail(db, user.Id.String(), user.Email)
|
go sendVerificationEmail(db, user.Id.String(), user.Email, serverSettings)
|
||||||
|
|
||||||
w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
w.Write([]byte("<p class=\"mt-8\">Verification email sent</p>"))
|
||||||
}
|
}
|
||||||
@@ -535,7 +536,8 @@ func HandleActualResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
utils.TriggerToast(w, r, "success", "Password changed")
|
utils.TriggerToast(w, r, "success", "Password changed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func HandleResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
func HandleResetPasswordComp(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
|
mailService := NewMailService(serverSettings)
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
email := r.FormValue("email")
|
email := r.FormValue("email")
|
||||||
@@ -571,19 +573,20 @@ func HandleResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
if i != 0 {
|
if i != 0 {
|
||||||
var mail strings.Builder
|
var mail strings.Builder
|
||||||
err = tempMail.ResetPassword(token).Render(context.Background(), &mail)
|
err = tempMail.ResetPassword(serverSettings.BaseUrl, token).Render(context.Background(), &mail)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Could not render reset password email", err)
|
utils.LogError("Could not render reset password email", err)
|
||||||
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
utils.SendMail(email, "Reset Password", mail.String())
|
mailService.SendMail(email, "Reset Password", mail.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
utils.TriggerToast(w, r, "info", "If the email exists, an email has been sent")
|
utils.TriggerToast(w, r, "info", "If the email exists, an email has been sent")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func sendVerificationEmail(db *sql.DB, userId string, email string) {
|
|
||||||
|
func sendVerificationEmail(db *sql.DB, userId string, email string, serverSettings *types.ServerSettings) {
|
||||||
|
|
||||||
var token string
|
var token string
|
||||||
err := db.QueryRow("SELECT token FROM user_token WHERE user_uuid = ? AND type = 'email_verify'", userId).Scan(&token)
|
err := db.QueryRow("SELECT token FROM user_token WHERE user_uuid = ? AND type = 'email_verify'", userId).Scan(&token)
|
||||||
@@ -607,12 +610,13 @@ func sendVerificationEmail(db *sql.DB, userId string, email string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var w strings.Builder
|
var w strings.Builder
|
||||||
err = tempMail.Register(token).Render(context.Background(), &w)
|
err = tempMail.Register(serverSettings.BaseUrl, token).Render(context.Background(), &w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Could not render welcome email", err)
|
utils.LogError("Could not render welcome email", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
utils.SendMail(email, "Welcome to ME-FIT", w.String())
|
mailService := NewMailService(serverSettings)
|
||||||
|
mailService.SendMail(email, "Welcome to ME-FIT", w.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) error {
|
func TryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) error {
|
||||||
|
|||||||
@@ -3,13 +3,14 @@ package service
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
|
"me-fit/types"
|
||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/a-h/templ"
|
"github.com/a-h/templ"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleIndexAnd404(db *sql.DB) http.HandlerFunc {
|
func HandleIndexAnd404(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
|
||||||
@@ -17,10 +18,10 @@ func HandleIndexAnd404(db *sql.DB) http.HandlerFunc {
|
|||||||
userComp := UserInfoComp(user)
|
userComp := UserInfoComp(user)
|
||||||
|
|
||||||
if r.URL.Path != "/" {
|
if r.URL.Path != "/" {
|
||||||
comp = template.Layout(template.NotFound(), userComp)
|
comp = template.Layout(template.NotFound(), userComp, serverSettings.Environment)
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
} else {
|
} else {
|
||||||
comp = template.Layout(template.Index(), userComp)
|
comp = template.Layout(template.Index(), userComp, serverSettings.Environment)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := comp.Render(r.Context(), w)
|
err := comp.Render(r.Context(), w)
|
||||||
|
|||||||
29
service/mail.go
Normal file
29
service/mail.go
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"me-fit/types"
|
||||||
|
"net/smtp"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MailService struct {
|
||||||
|
serverSettings *types.ServerSettings
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMailService(serverSettings *types.ServerSettings) MailService {
|
||||||
|
return MailService{serverSettings: serverSettings}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m MailService) SendMail(to string, subject string, message string) error {
|
||||||
|
if m.serverSettings.Smtp == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
s := m.serverSettings.Smtp
|
||||||
|
|
||||||
|
auth := smtp.PlainAuth("", s.User, s.Pass, s.Host)
|
||||||
|
|
||||||
|
msg := fmt.Sprintf("From: %v <%v>\nTo: %v\nSubject: %v\nMIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n%v", s.FromName, s.FromMail, to, subject, message)
|
||||||
|
|
||||||
|
return smtp.SendMail(s.Host+":"+s.Port, auth, s.FromMail, []string{to}, []byte(msg))
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
"me-fit/template/workout"
|
"me-fit/template/workout"
|
||||||
|
"me-fit/types"
|
||||||
"me-fit/utils"
|
"me-fit/utils"
|
||||||
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
@@ -12,7 +13,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleWorkoutPage(db *sql.DB) http.HandlerFunc {
|
func HandleWorkoutPage(db *sql.DB, serverSettings *types.ServerSettings) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
user := utils.GetUser(r)
|
user := utils.GetUser(r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
@@ -23,7 +24,7 @@ func HandleWorkoutPage(db *sql.DB) http.HandlerFunc {
|
|||||||
currentDate := time.Now().Format("2006-01-02")
|
currentDate := time.Now().Format("2006-01-02")
|
||||||
inner := workout.WorkoutComp(currentDate)
|
inner := workout.WorkoutComp(currentDate)
|
||||||
userComp := UserInfoComp(user)
|
userComp := UserInfoComp(user)
|
||||||
err := template.Layout(inner, userComp).Render(r.Context(), w)
|
err := template.Layout(inner, userComp, serverSettings.Environment).Render(r.Context(), w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render workout page", err)
|
utils.LogError("Failed to render workout page", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package template
|
package template
|
||||||
|
|
||||||
import "me-fit/utils"
|
templ Layout(slot templ.Component, user templ.Component, environment string) {
|
||||||
|
|
||||||
templ Layout(slot templ.Component, user templ.Component) {
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -11,7 +9,7 @@ templ Layout(slot templ.Component, user templ.Component) {
|
|||||||
<link rel="icon" href="/static/favicon.svg"/>
|
<link rel="icon" href="/static/favicon.svg"/>
|
||||||
<link rel="stylesheet" href="/static/css/tailwind.css"/>
|
<link rel="stylesheet" href="/static/css/tailwind.css"/>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||||
if utils.Environment == "prod" {
|
if environment == "prod" {
|
||||||
<script defer src="https://umami.me-fit.eu/script.js" data-website-id="3c8efb09-44e4-4372-8a1e-c3bc675cd89a"></script>
|
<script defer src="https://umami.me-fit.eu/script.js" data-website-id="3c8efb09-44e4-4372-8a1e-c3bc675cd89a"></script>
|
||||||
}
|
}
|
||||||
<script src="/static/js/htmx.min.js"></script>
|
<script src="/static/js/htmx.min.js"></script>
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
package mail;
|
package mail;
|
||||||
|
|
||||||
import (
|
import "net/url"
|
||||||
"me-fit/utils"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
templ Register(token string) {
|
templ Register(baseUrl string, token string) {
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -15,7 +12,7 @@ templ Register(token string) {
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h4>Thank you for Sign Up!</h4>
|
<h4>Thank you for Sign Up!</h4>
|
||||||
<p>Click <a href={ templ.URL(utils.BaseUrl + "/auth/verify-email?token=" + url.QueryEscape(token)) }>here</a> to verify your account.</p>
|
<p>Click <a href={ templ.URL(baseUrl + "/auth/verify-email?token=" + url.QueryEscape(token)) }>here</a> to verify your account.</p>
|
||||||
<p>Kind regards</p>
|
<p>Kind regards</p>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
package mail;
|
package mail;
|
||||||
|
|
||||||
import (
|
import "net/url"
|
||||||
"me-fit/utils"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
templ ResetPassword(token string) {
|
templ ResetPassword(baseUrl string, token string) {
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -15,7 +12,7 @@ templ ResetPassword(token string) {
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h4>Reset your password</h4>
|
<h4>Reset your password</h4>
|
||||||
<p>Click <a href={ templ.URL(utils.BaseUrl + "/auth/change-password?token=" + url.QueryEscape(token)) }>here</a> to change your password.</p>
|
<p>Click <a href={ templ.URL(baseUrl + "/auth/change-password?token=" + url.QueryEscape(token)) }>here</a> to change your password.</p>
|
||||||
<p>Kind regards</p>
|
<p>Kind regards</p>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
76
types/settings.go
Normal file
76
types/settings.go
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"log/slog"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServerSettings struct {
|
||||||
|
BaseUrl string
|
||||||
|
Environment string
|
||||||
|
Smtp *SmtpSettings
|
||||||
|
}
|
||||||
|
|
||||||
|
type SmtpSettings struct {
|
||||||
|
Host string
|
||||||
|
Port string
|
||||||
|
User string
|
||||||
|
Pass string
|
||||||
|
FromMail string
|
||||||
|
FromName string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServerSettingsFromEnv(env func(string) string) *ServerSettings {
|
||||||
|
var smtp *SmtpSettings
|
||||||
|
if env("SMTP_ENABLED") == "true" {
|
||||||
|
smtp = &SmtpSettings{
|
||||||
|
Host: env("SMTP_HOST"),
|
||||||
|
Port: env("SMTP_PORT"),
|
||||||
|
User: env("SMTP_USER"),
|
||||||
|
Pass: env("SMTP_PASS"),
|
||||||
|
FromMail: env("SMTP_FROM_MAIL"),
|
||||||
|
FromName: env("SMTP_FROM_NAME"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if smtp.Host == "" {
|
||||||
|
log.Fatal("SMTP_HOST must be set")
|
||||||
|
}
|
||||||
|
if smtp.Port == "" {
|
||||||
|
log.Fatal("SMTP_PORT must be set")
|
||||||
|
}
|
||||||
|
if smtp.User == "" {
|
||||||
|
log.Fatal("SMTP_USER must be set")
|
||||||
|
}
|
||||||
|
if smtp.Pass == "" {
|
||||||
|
log.Fatal("SMTP_PASS must be set")
|
||||||
|
}
|
||||||
|
if smtp.FromMail == "" {
|
||||||
|
log.Fatal("SMTP_FROM_MAIL must be set")
|
||||||
|
}
|
||||||
|
if smtp.FromName == "" {
|
||||||
|
log.Fatal("SMTP_FROM_NAME must be set")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
settings := &ServerSettings{
|
||||||
|
BaseUrl: env("BASE_URL"),
|
||||||
|
Environment: env("ENVIRONMENT"),
|
||||||
|
Smtp: smtp,
|
||||||
|
}
|
||||||
|
|
||||||
|
if settings.BaseUrl == "" {
|
||||||
|
log.Fatal("BASE_URL must be set")
|
||||||
|
}
|
||||||
|
if settings.Environment == "" {
|
||||||
|
log.Fatal("ENVIRONMENT must be set")
|
||||||
|
}
|
||||||
|
|
||||||
|
if settings.Environment == "prod" && settings.Smtp == nil {
|
||||||
|
log.Fatal("SMTP must be enabled in production")
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("BASE_URL is " + settings.BaseUrl)
|
||||||
|
slog.Info("ENVIRONMENT is " + settings.Environment)
|
||||||
|
|
||||||
|
return settings
|
||||||
|
}
|
||||||
57
utils/env.go
57
utils/env.go
@@ -1,57 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"log/slog"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
SmtpHost string
|
|
||||||
SmtpPort string
|
|
||||||
SmtpUser string
|
|
||||||
SmtpPass string
|
|
||||||
SmtpFromMail string
|
|
||||||
SmtpFromName string
|
|
||||||
BaseUrl string
|
|
||||||
Environment string
|
|
||||||
)
|
|
||||||
|
|
||||||
func MustInitEnv() {
|
|
||||||
SmtpHost = os.Getenv("SMTP_HOST")
|
|
||||||
SmtpPort = os.Getenv("SMTP_PORT")
|
|
||||||
SmtpUser = os.Getenv("SMTP_USER")
|
|
||||||
SmtpPass = os.Getenv("SMTP_PASS")
|
|
||||||
SmtpFromMail = os.Getenv("SMTP_FROM_MAIL")
|
|
||||||
SmtpFromName = os.Getenv("SMTP_FROM_NAME")
|
|
||||||
BaseUrl = os.Getenv("BASE_URL")
|
|
||||||
Environment = os.Getenv("ENVIRONMENT")
|
|
||||||
|
|
||||||
if SmtpHost == "" {
|
|
||||||
log.Fatal("SMTP_HOST must be set")
|
|
||||||
}
|
|
||||||
if SmtpPort == "" {
|
|
||||||
log.Fatal("SMTP_PORT must be set")
|
|
||||||
}
|
|
||||||
if SmtpUser == "" {
|
|
||||||
log.Fatal("SMTP_USER must be set")
|
|
||||||
}
|
|
||||||
if SmtpPass == "" {
|
|
||||||
log.Fatal("SMTP_PASS must be set")
|
|
||||||
}
|
|
||||||
if SmtpFromMail == "" {
|
|
||||||
log.Fatal("SMTP_FROM_MAIL must be set")
|
|
||||||
}
|
|
||||||
if SmtpFromName == "" {
|
|
||||||
log.Fatal("SMTP_FROM_NAME must be set")
|
|
||||||
}
|
|
||||||
if BaseUrl == "" {
|
|
||||||
log.Fatal("BASE_URL must be set")
|
|
||||||
}
|
|
||||||
if Environment == "" {
|
|
||||||
log.Fatal("ENVIRONMENT must be set")
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("BASE_URL is " + BaseUrl)
|
|
||||||
slog.Info("ENVIRONMENT is " + Environment)
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package utils
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/smtp"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SendMail(to string, subject string, message string) error {
|
|
||||||
|
|
||||||
auth := smtp.PlainAuth("", SmtpUser, SmtpPass, SmtpHost)
|
|
||||||
|
|
||||||
msg := fmt.Sprintf("From: %v <%v>\nTo: %v\nSubject: %v\nMIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n%v", SmtpFromName, SmtpFromMail, to, subject, message)
|
|
||||||
|
|
||||||
return smtp.SendMail(SmtpHost+":"+SmtpPort, auth, SmtpFromMail, []string{to}, []byte(msg))
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user