feat: securing the cookies

This commit is contained in:
efim 2023-10-09 04:22:09 +00:00
parent e4c79b2155
commit 2a3d00839f
3 changed files with 22 additions and 7 deletions

View File

@ -212,7 +212,7 @@ https://github.com/efim/dotfiles/commit/b3695148082d8c9850a781aaa7a88920bdb1fa7f
this is all that's needed to enable tls
mind blown
** TODO somehow set cookie to httpOnly & secure
** DONE somehow set cookie to httpOnly & secure
with ability to disable for development session
** TODO maybe add middleware so that 401 would be a page, and not json

View File

@ -2,6 +2,7 @@ package main
import (
"log"
"strings"
"github.com/pocketbase/pocketbase"
"sunshine.industries/auth-pocketbase-attempt/middleware"
@ -10,7 +11,11 @@ import (
func main() {
app := pocketbase.New()
middleware.AddCookieSessionMiddleware(app)
servedName := app.Settings().Meta.AppUrl
isTlsEnabled := strings.HasPrefix(servedName, "https://")
middleware.AddCookieSessionMiddleware(app, isTlsEnabled)
pages.AddPageRoutes(app)
if err := app.Start(); err != nil {

View File

@ -1,7 +1,9 @@
package middleware
import (
"log"
"net/http"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
@ -13,7 +15,9 @@ import (
const AuthCookieName = "Auth"
func AddCookieSessionMiddleware(app *pocketbase.PocketBase) {
func AddCookieSessionMiddleware(app *pocketbase.PocketBase, isTlsEnabled bool) {
log.Println("Warning: starting server with cookie Secure = false!")
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.Use(loadAuthContextFromCookie(app))
return nil
@ -25,6 +29,8 @@ func AddCookieSessionMiddleware(app *pocketbase.PocketBase) {
Name: AuthCookieName,
Value: e.Token,
Path: "/",
Secure: isTlsEnabled,
HttpOnly: true,
})
e.HttpContext.SetCookie(&http.Cookie{
Name: "username",
@ -37,10 +43,12 @@ func AddCookieSessionMiddleware(app *pocketbase.PocketBase) {
Name: AuthCookieName,
Value: e.Token,
Path: "/",
Secure: isTlsEnabled,
HttpOnly: true,
})
return nil
})
app.OnBeforeServe().Add(getLogoutRoute(app))
app.OnBeforeServe().Add(getLogoutRoute(app, isTlsEnabled))
}
func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
@ -84,7 +92,7 @@ func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
}
// render and return login page with configured oauth providers
func getLogoutRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error {
func getLogoutRoute(app *pocketbase.PocketBase, isTlsEnabled bool) func(*core.ServeEvent) error {
return func (e *core.ServeEvent) error {
e.Router.GET("/logout", func(c echo.Context) error {
c.SetCookie(&http.Cookie{
@ -92,6 +100,8 @@ func getLogoutRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error {
Value: "",
Path: "/",
MaxAge: -1,
Secure: isTlsEnabled,
HttpOnly: true,
})
c.Response().Header().Add("HX-Trigger", "auth-change-event")
return c.JSON(http.StatusOK, map[string]string{"message": "session cookie removed"})