BrainMinder/cmd/web/application.go

111 lines
2.7 KiB
Go
Raw Permalink Normal View History

2024-08-22 10:13:16 +02:00
package main
import (
"crypto/rand"
"encoding/hex"
"log/slog"
"net/http"
"strconv"
"sync"
"brainminder.speedtech.it/internal/database"
"brainminder.speedtech.it/internal/funcs"
"brainminder.speedtech.it/internal/smtp"
"brainminder.speedtech.it/models"
"github.com/gorilla/sessions"
)
type application struct {
config config
db *database.DB
logger *slog.Logger
mailer *smtp.Mailer
sessionStore *sessions.CookieStore
wg sync.WaitGroup
}
func (app *application) getCurrentNotebok_id(r *http.Request) int64 {
session, _ := app.sessionStore.Get(r, "session")
current_notebook_id := session.Values["current_notebook_id"]
var notebook_id int64 = -1
if current_notebook_id != nil {
notebook_id, _ = strconv.ParseInt(current_notebook_id.(string), 10, 64)
}
return notebook_id
}
func (app *application) saveSessionValue(w http.ResponseWriter, r *http.Request, name string, value any) {
session, err := app.sessionStore.Get(r, "sessions")
if err != nil {
app.serverError(w, r, err)
return
}
session.Values[name] = value
err = session.Save(r, w)
if err != nil {
app.serverError(w, r, err)
return
}
}
func (app *application) getSessionValue(w http.ResponseWriter, r *http.Request, name string) any {
session, err := app.sessionStore.Get(r, "sessions")
if err != nil {
app.serverError(w, r, err)
return nil
}
if value, isMapContainsKey := session.Values[name]; isMapContainsKey {
return value
}
return nil
}
func (app *application) removeSessionValue(w http.ResponseWriter, r *http.Request, name string) {
session, err := app.sessionStore.Get(r, "sessions")
if err != nil {
app.serverError(w, r, err)
return
}
delete(session.Values, name)
err = session.Save(r, w)
if err != nil {
app.serverError(w, r, err)
}
}
func (app *application) getCategoriesAsOptions() []funcs.WidgetOption {
categoryModel := &models.CategoryModel{DB: app.db}
return categoryModel.AllAsOptions()
}
func (app *application) getCategoriesAsMap() map[string]string {
categoryModel := &models.CategoryModel{DB: app.db}
return categoryModel.AllAsMap()
}
func (app *application) getTypesAsOptions(r *http.Request) []funcs.WidgetOption {
typeModel := &models.TypeModel{DB: app.db}
criteria := map[string]any{
"notebook_id": app.getCurrentNotebok_id(r),
}
return typeModel.FindAsOptions(criteria)
}
func (app *application) getNotebooksAsOptions() []funcs.WidgetOption {
notebookModel := &models.NotebookModel{DB: app.db}
return notebookModel.AllAsOptions(false)
}
func (app *application) generateSecureToken(length int) string {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return ""
}
return hex.EncodeToString(b)
}