2023-09-09 01:38:10 +01:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/1f349/tulip/database"
|
2024-03-11 12:39:52 +00:00
|
|
|
"github.com/1f349/tulip/database/types"
|
2023-09-09 01:38:10 +01:00
|
|
|
"github.com/1f349/tulip/pages"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/julienschmidt/httprouter"
|
|
|
|
"net/http"
|
2024-02-09 15:24:40 +00:00
|
|
|
"time"
|
2023-09-09 01:38:10 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func (h *HttpServer) Home(rw http.ResponseWriter, req *http.Request, _ httprouter.Params, auth UserAuth) {
|
|
|
|
rw.Header().Set("Content-Type", "text/html")
|
2024-02-09 15:24:40 +00:00
|
|
|
lNonce := uuid.NewString()
|
|
|
|
http.SetCookie(rw, &http.Cookie{
|
|
|
|
Name: "tulip-nonce",
|
|
|
|
Value: lNonce,
|
|
|
|
Path: "/",
|
|
|
|
Expires: time.Now().Add(10 * time.Minute),
|
|
|
|
Secure: true,
|
2024-02-15 14:44:25 +00:00
|
|
|
SameSite: http.SameSiteLaxMode,
|
2024-02-09 15:24:40 +00:00
|
|
|
})
|
|
|
|
|
2023-09-09 01:38:10 +01:00
|
|
|
if auth.IsGuest() {
|
2023-09-15 13:06:31 +01:00
|
|
|
pages.RenderPageTemplate(rw, "index-guest", map[string]any{
|
2023-10-10 18:06:43 +01:00
|
|
|
"ServiceName": h.conf.ServiceName,
|
2023-09-15 13:06:31 +01:00
|
|
|
})
|
2023-09-09 01:38:10 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-11 12:39:52 +00:00
|
|
|
var userWithName string
|
|
|
|
var userRole types.UserRole
|
2023-11-25 15:08:44 +00:00
|
|
|
var hasTwoFactor bool
|
2024-03-11 12:39:52 +00:00
|
|
|
if h.DbTx(rw, func(tx *database.Queries) (err error) {
|
|
|
|
userWithName, err = tx.GetUserDisplayName(req.Context(), auth.ID)
|
2023-09-09 01:38:10 +01:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to get user display name: %w", err)
|
|
|
|
}
|
2024-03-12 21:04:25 +00:00
|
|
|
hasTwoFactor, err = tx.HasOtp(req.Context(), auth.ID)
|
2023-11-25 15:08:44 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to get user two factor state: %w", err)
|
|
|
|
}
|
2024-03-11 12:39:52 +00:00
|
|
|
userRole, err = tx.GetUserRole(req.Context(), auth.ID)
|
2024-02-09 15:24:40 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to get user role: %w", err)
|
|
|
|
}
|
2023-09-09 01:38:10 +01:00
|
|
|
return
|
|
|
|
}) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
pages.RenderPageTemplate(rw, "index", map[string]any{
|
2023-10-10 18:06:43 +01:00
|
|
|
"ServiceName": h.conf.ServiceName,
|
2023-09-15 13:06:31 +01:00
|
|
|
"Auth": auth,
|
|
|
|
"User": userWithName,
|
|
|
|
"Nonce": lNonce,
|
2023-11-25 15:08:44 +00:00
|
|
|
"OtpEnabled": hasTwoFactor,
|
2024-03-11 12:39:52 +00:00
|
|
|
"IsAdmin": userRole == types.RoleAdmin,
|
2023-09-09 01:38:10 +01:00
|
|
|
})
|
|
|
|
}
|