Compare commits
1 Commits
8842235372
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
258d2b560c |
@@ -1,4 +1,4 @@
|
||||
The MIT License (MIT) Copyright (c) 2023 - present, Efim Nefedov
|
||||
The MIT License (MIT) Copyright (c) 2022 - present, Efim Nefedov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
@@ -148,7 +148,7 @@ and
|
||||
#+end_src
|
||||
is what i need for it to pick up pb_data from work directory, cool
|
||||
|
||||
** DONE write nixos module
|
||||
** TODO write nixos module
|
||||
need to pass data and migration location as params
|
||||
and address on which to serve, cool
|
||||
i suppose
|
||||
@@ -174,90 +174,19 @@ cool
|
||||
oh, but if i'm using nginx i'll need my own certificate, that makes sence
|
||||
*** maybe things are ok?
|
||||
let's try to plaintext deploy?
|
||||
*** quoting of the '' in multiline string
|
||||
https://nixos.org/manual/nix/stable/language/values.html
|
||||
*** not accessible still
|
||||
sudo journalctl -u nginx --since "1 day ago"
|
||||
*** oh, i forgot to add subname in gandi ui
|
||||
now works
|
||||
*** now i need a way to pass in the hostname
|
||||
because front-end is setting up js 'new PocketBase' with 127.0.0.1 connection
|
||||
*** adding a custom flag:
|
||||
https://github.com/pocketbase/pocketbase/discussions/1900
|
||||
** DONE change some additional config to option :
|
||||
${optionalString config.proxyWebsockets ''
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
''}
|
||||
( also in planning poker repo )
|
||||
|
||||
https://github.com/NixOS/nixpkgs/blob/nixos-23.05/nixos/modules/services/web-servers/nginx/default.nix#L428
|
||||
|
||||
|
||||
** TODO add docker image from nix
|
||||
*** CANCELLED add cli for port and host
|
||||
*** TODO add cli for port and host
|
||||
** TODO add readme and comments
|
||||
** DONE configure tls / ssl / https on franzk deployment
|
||||
https://nixos.org/manual/nixos/stable/#module-security-acme-nginx
|
||||
( and also same here https://nixos.wiki/wiki/Nginx )
|
||||
|
||||
** TODO configure tls / ssl / https on franzk deployment
|
||||
can it be configured on render.com?
|
||||
omg
|
||||
line 112 & 113 in project config:
|
||||
http://git.sunshine.industries/efim/go-ssr-pocketbase-oauth-attempt/commit/875de35177462f21732e3ba108a94d77a543da05
|
||||
|
||||
and this in my server config:
|
||||
https://github.com/efim/dotfiles/commit/b3695148082d8c9850a781aaa7a88920bdb1fa7f
|
||||
|
||||
this is all that's needed to enable tls
|
||||
mind blown
|
||||
** DONE somehow set cookie to httpOnly & secure
|
||||
with ability to disable for development session
|
||||
*** a complication
|
||||
since i'm under the nginx, i can't just match on the serving address :
|
||||
#+begin_src
|
||||
[efim@franzk:~]$ systemctl status pb-auth-example-app.service
|
||||
● pb-auth-example-app.service - Exercise app auth-pocketbase-attempt
|
||||
Loaded: loaded (/etc/systemd/system/pb-auth-example-app.service; enabled; preset: enabled)
|
||||
Active: active (running) since Mon 2023-10-09 04:29:20 UTC; 1min 17s ago
|
||||
Main PID: 411857 (auth-pocketbase)
|
||||
Tasks: 13 (limit: 629145)
|
||||
Memory: 28.3M
|
||||
CPU: 148ms
|
||||
CGroup: /system.slice/pb-auth-example-app.service
|
||||
└─411857 /nix/store/czq95bjhwszasncp8f04d9yn4m0xf4kw-auth-pocketbase-attempt-0.0.1/bin/auth-pocketbase-attempt serve --http 127.0.0.1:45001 --dir=/home/pb-auth-example-app-user
|
||||
|
||||
Oct 09 04:29:20 franzk systemd[1]: Started Exercise app auth-pocketbase-attempt.
|
||||
Oct 09 04:29:20 franzk auth-pocketbase-attempt[411857]: 2023/10/09 04:29:20 Warning: starting server with cookie Secure = false!
|
||||
Oct 09 04:29:20 franzk auth-pocketbase-attempt[411857]: 2023/10/09 04:29:20 Server started at http://127.0.0.1:45001
|
||||
Oct 09 04:29:20 franzk auth-pocketbase-attempt[411857]: ├─ REST API: http://127.0.0.1:45001/api/
|
||||
Oct 09 04:29:20 franzk auth-pocketbase-attempt[411857]: └─ Admin UI: http://127.0.0.1:45001/_/
|
||||
#+end_src
|
||||
*** so, custom arg is required, hello
|
||||
https://github.com/pocketbase/pocketbase/discussions/1900
|
||||
*** holy cow, Firefox and later Chrome will accept Secure cookie on localhost
|
||||
https://stackoverflow.com/questions/62307431/firefox-sends-secure-cookies-to-localhost
|
||||
|
||||
see: except on localhost : https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
|
||||
|
||||
|
||||
** DONE prettying up server responses for "we show html" land
|
||||
let's do this also, yes
|
||||
*** DONE logout should push root url in htmx
|
||||
*** DONE lets make 404 page and return it
|
||||
*** DONE lets make 401 page and return it
|
||||
*** DONE and let's make NavInfo init common for reuse
|
||||
** TODO maybe add middleware so that 401 would be a page, and not json
|
||||
** TODO get icons for the auth providers. surely they are accessible from the pocketbase itself?
|
||||
http://localhost:8090/_/images/oauth2/apple.svg
|
||||
yes.
|
||||
** TODO read and add ok logging
|
||||
** TODO figure out and enbale migrations
|
||||
https://pocketbase.io/docs/go-migrations/#enable-go-migrations
|
||||
|
||||
if i understood correctly, when i enable migration generation
|
||||
i would be able to modify locally run instance via admin interface,
|
||||
go files with migration would be generated, i'll have to import them somewhere in my main module, and then after building/packaging when i run `serve` on production the migrations would run on the production data
|
||||
** adding google oauth
|
||||
support article : https://developers.google.com/identity/sign-in/web/sign-in
|
||||
settings are in : https://console.cloud.google.com/apis/credentials
|
||||
|
||||
54
flake.nix
54
flake.nix
@@ -42,8 +42,8 @@
|
||||
nixosModules.auth-pocketbase-attempt = { config, pkgs, ... }:
|
||||
let
|
||||
cfg = config.services.${pname};
|
||||
lib = nixpkgs.lib;
|
||||
shortName = "pb-auth-example-app";
|
||||
lib = pkgs.lib;
|
||||
shortName = "pb-auth-example-group";
|
||||
in {
|
||||
options.services.${pname} = {
|
||||
enable = lib.mkEnableOption
|
||||
@@ -70,27 +70,17 @@
|
||||
description =
|
||||
"Whether pocketbase should serve on https and issue own certs. Main case for true - when not under nginx";
|
||||
};
|
||||
useHostTls = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description =
|
||||
"Whether virtual host should enable NixOS ACME certs";
|
||||
};
|
||||
};
|
||||
config = let
|
||||
username = "${shortName}-user";
|
||||
groupname = "${shortName}-group";
|
||||
in lib.mkIf cfg.enable {
|
||||
users.groups."${groupname}" = { };
|
||||
users.users."${username}" = {
|
||||
isNormalUser = true; # needed to allow for home dir
|
||||
group = "${groupname}";
|
||||
config = lib.mkIf cfg.enable {
|
||||
users.groups."${shortName}-group" = { };
|
||||
users.users."${shortName}-user" = {
|
||||
isSystemUser = true;
|
||||
group = "${shortName}-group";
|
||||
};
|
||||
systemd.services.${shortName} = let
|
||||
protocol = if cfg.usePbTls then "https" else "http";
|
||||
serverHost = if cfg.useNginx then "127.0.0.1" else cfg.host;
|
||||
serveCliArg =
|
||||
"--${protocol} ${serverHost}:${toString cfg.port}";
|
||||
servedAddress = "${protocol}://${serverHost}:${cfg.port}";
|
||||
in {
|
||||
description = "Exercise app ${pname}";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
@@ -99,32 +89,12 @@
|
||||
startLimitBurst = 10;
|
||||
serviceConfig = {
|
||||
ExecStart =
|
||||
"${packages.auth-pocketbase-attempt}/bin/${pname} serve ${serveCliArg} --dir=/home/${
|
||||
"${username}"
|
||||
"${packages.auth-pocketbase-attempt}/bin/${pname} serve ${servedAddress} --dir=/home/${
|
||||
config.users.users."${shortName}-user"
|
||||
}";
|
||||
Restart = "on-failure";
|
||||
User = "${username}";
|
||||
Group = "${groupname}";
|
||||
};
|
||||
};
|
||||
services.nginx = lib.mkIf cfg.useNginx {
|
||||
virtualHosts.${cfg.host} = {
|
||||
forceSSL = cfg.useHostTls;
|
||||
enableACME = cfg.useHostTls;
|
||||
locations."/" = {
|
||||
proxyPass = "http://127.0.0.1:${toString cfg.port}";
|
||||
# taken from https://pocketbase.io/docs/going-to-production/
|
||||
proxyWebsockets = true;
|
||||
extraConfig = ''
|
||||
# check http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
|
||||
proxy_read_timeout 360s;
|
||||
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
'';
|
||||
};
|
||||
User = "${shortName}-user";
|
||||
Group = "${shortName}-group";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
13
main.go
13
main.go
@@ -1,20 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"log"
|
||||
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"sunshine.industries/auth-pocketbase-attempt/middleware"
|
||||
"sunshine.industries/auth-pocketbase-attempt/pages"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := pocketbase.New()
|
||||
|
||||
middleware.AddCookieSessionMiddleware(app)
|
||||
middleware.AddErrorsMiddleware(app)
|
||||
pages.AddPageRoutes(app)
|
||||
|
||||
if err := app.Start(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := app.Start(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
@@ -22,12 +23,14 @@ func AddCookieSessionMiddleware(app *pocketbase.PocketBase) {
|
||||
|
||||
// fires for every auth collection
|
||||
app.OnRecordAuthRequest().Add(func(e *core.RecordAuthEvent) error {
|
||||
log.Println(e.HttpContext)
|
||||
log.Println(e.Record)
|
||||
log.Println(e.Token)
|
||||
log.Println(e.Meta)
|
||||
e.HttpContext.SetCookie(&http.Cookie{
|
||||
Name: AuthCookieName,
|
||||
Value: e.Token,
|
||||
Path: "/",
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
})
|
||||
e.HttpContext.SetCookie(&http.Cookie{
|
||||
Name: "username",
|
||||
@@ -36,12 +39,13 @@ func AddCookieSessionMiddleware(app *pocketbase.PocketBase) {
|
||||
return nil
|
||||
})
|
||||
app.OnAdminAuthRequest().Add(func(e *core.AdminAuthEvent) error {
|
||||
log.Println(e.HttpContext)
|
||||
log.Println(e.Admin)
|
||||
log.Println(e.Token)
|
||||
e.HttpContext.SetCookie(&http.Cookie{
|
||||
Name: AuthCookieName,
|
||||
Value: e.Token,
|
||||
Path: "/",
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
})
|
||||
return nil
|
||||
})
|
||||
@@ -70,6 +74,14 @@ func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
|
||||
if err == nil && admin != nil {
|
||||
// "authenticate" the admin
|
||||
c.Set(apis.ContextAdminKey, admin)
|
||||
someData := struct {
|
||||
username string
|
||||
email string
|
||||
} {
|
||||
admin.Email,
|
||||
admin.Created.String(),
|
||||
}
|
||||
fmt.Printf("triggering the middlewar for cookie %v and err %v\n", someData, err)
|
||||
}
|
||||
|
||||
case tokens.TypeAuthRecord:
|
||||
@@ -80,6 +92,15 @@ func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
|
||||
if err == nil && record != nil {
|
||||
// "authenticate" the app user
|
||||
c.Set(apis.ContextAuthRecordKey, record)
|
||||
someData := struct {
|
||||
username string
|
||||
email string
|
||||
} {
|
||||
record.Username(),
|
||||
record.Email(),
|
||||
}
|
||||
fmt.Printf("triggering the middlewar for cookie %v and err %v\n", someData, err)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,11 +118,9 @@ func getLogoutRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error {
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
})
|
||||
c.Response().Header().Add("HX-Trigger", "auth-change-event")
|
||||
return c.NoContent(http.StatusOK)
|
||||
return c.JSON(http.StatusOK, map[string]string{"message": "session cookie removed"})
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
"log"
|
||||
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
)
|
||||
|
||||
func AddErrorsMiddleware(app *pocketbase.PocketBase) {
|
||||
app.OnBeforeApiError().Add(func(e *core.ApiErrorEvent) error {
|
||||
log.Printf("in before api error with %+v with response %v and error %+v", e, e.HttpContext.Response(), e.Error)
|
||||
// oh, i guess i could do redirect?
|
||||
return renderErrorPage(e)
|
||||
})
|
||||
}
|
||||
|
||||
var redirectTemplate = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="refresh" content="0; url='/error/{{ . }}'" />
|
||||
</head>
|
||||
<body>
|
||||
<p>Redirecting to error page</p>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
var tmpl = template.Must( template.New("redirect-to-error").Parse(redirectTemplate) )
|
||||
|
||||
func renderErrorPage(e *core.ApiErrorEvent) error {
|
||||
errorMessage := e.Error.Error()
|
||||
log.Printf("in error to html middleware for %s with status %+v", errorMessage, e)
|
||||
|
||||
errorCode := 500
|
||||
switch errorMessage {
|
||||
case "Not Found.":
|
||||
// not authorized
|
||||
errorCode = 404
|
||||
case "The request requires admin or record authorization token to be set.":
|
||||
// not found
|
||||
errorCode = 401
|
||||
}
|
||||
|
||||
var instantiatedTemplate bytes.Buffer
|
||||
if err := tmpl.Execute(&instantiatedTemplate, errorCode); err != nil {
|
||||
// couldn't execute the template
|
||||
return e.HttpContext.HTML(200, "Error 500")
|
||||
}
|
||||
|
||||
return e.HttpContext.HTML(200, instantiatedTemplate.String())
|
||||
}
|
||||
@@ -3,10 +3,10 @@ package pages
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/pocketbase/pocketbase"
|
||||
@@ -22,8 +22,7 @@ var staticFilesFS embed.FS
|
||||
|
||||
func AddPageRoutes(app *pocketbase.PocketBase) {
|
||||
app.OnBeforeServe().Add(getIndexPageRoute(app))
|
||||
app.OnBeforeServe().Add(getSomePageRoute(app))
|
||||
app.OnBeforeServe().Add(getErrorPageRoute(app))
|
||||
app.OnBeforeServe().Add(somePageRoute)
|
||||
|
||||
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
|
||||
e.Router.StaticFS("/static", staticFilesFS)
|
||||
@@ -43,13 +42,43 @@ func getIndexPageRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error
|
||||
return func(e *core.ServeEvent) error {
|
||||
e.Router.GET("/", func(c echo.Context) error {
|
||||
// first collect data
|
||||
navInfoData := initNavInfoData(app, c)
|
||||
info := apis.RequestInfo(c)
|
||||
admin := info.Admin // nil if not authenticated as admin
|
||||
record := info.AuthRecord // nil if not authenticated as regular auth record
|
||||
|
||||
isGuest := admin == nil && record == nil
|
||||
coolMessage := fmt.Sprintf("got admin %v and record %v. is guest: %t", admin, record, isGuest)
|
||||
fmt.Print(coolMessage)
|
||||
|
||||
username := ""
|
||||
switch {
|
||||
case admin != nil:
|
||||
username = admin.Email
|
||||
case record != nil:
|
||||
username = record.Username()
|
||||
}
|
||||
|
||||
oauthProviders := app.Settings().NamedAuthProviderConfigs()
|
||||
oauthProviderNames := make([]string, 0, len(oauthProviders))
|
||||
for name, config := range oauthProviders {
|
||||
if config.Enabled {
|
||||
oauthProviderNames = append(oauthProviderNames, name)
|
||||
}
|
||||
}
|
||||
fmt.Printf(">> enabled providers names %+v\n", oauthProviderNames)
|
||||
|
||||
indexPageData := struct {
|
||||
BackendMessage string
|
||||
NavInfo navInfo
|
||||
IsGuest, IsAdmin bool
|
||||
Username string
|
||||
EnabledOauthProviders []string
|
||||
NavInfo navInfo
|
||||
}{
|
||||
BackendMessage: "Hello from the backend!",
|
||||
NavInfo: navInfoData,
|
||||
IsAdmin: admin != nil,
|
||||
NavInfo: navInfo{
|
||||
IsGuest: isGuest,
|
||||
Username: username,
|
||||
EnabledOauthProviders: oauthProviderNames,
|
||||
},
|
||||
}
|
||||
|
||||
// then render template with it
|
||||
@@ -76,112 +105,44 @@ func stringWithCharset(length int, charset string) string {
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
func getSomePageRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error {
|
||||
return func(e *core.ServeEvent) error {
|
||||
e.Router.GET("/somepage", func(c echo.Context) error {
|
||||
// get data
|
||||
// and since i'm using 'base.gohtml' with Nav, i'll need Nav info
|
||||
navInfoData := initNavInfoData(app, c)
|
||||
func somePageRoute(e *core.ServeEvent) error {
|
||||
e.Router.GET("/somepage", func(c echo.Context) error {
|
||||
// get data
|
||||
// and since i'm using 'base.gohtml' with Nav, i'll need Nav info
|
||||
|
||||
somePageData := struct {
|
||||
RandomNumber int
|
||||
RandomString string
|
||||
NavInfo navInfo
|
||||
}{
|
||||
RandomNumber: rand.Int(),
|
||||
RandomString: stringWithCharset(25, charset),
|
||||
NavInfo: navInfoData,
|
||||
}
|
||||
info := apis.RequestInfo(c)
|
||||
admin := info.Admin // nil if not authenticated as admin
|
||||
record := info.AuthRecord // nil if not authenticated as regular auth record
|
||||
|
||||
// then render template with it
|
||||
templateName := "templates/somepage.gohtml"
|
||||
tmpl := template.Must(template.ParseFS(templatesFS, "templates/base.gohtml", templateName))
|
||||
var instantiatedTemplate bytes.Buffer
|
||||
if err := tmpl.Execute(&instantiatedTemplate, somePageData); err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "error parsing template"})
|
||||
}
|
||||
|
||||
return c.HTML(http.StatusOK, instantiatedTemplate.String())
|
||||
}, apis.RequireAdminOrRecordAuth())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func getErrorPageRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error {
|
||||
return func(e *core.ServeEvent) error {
|
||||
e.Router.GET("/error/:code", func(c echo.Context) error {
|
||||
// get data
|
||||
code := c.PathParam("code")
|
||||
codeNum, err := strconv.ParseInt(code, 10, 64)
|
||||
if err != nil {
|
||||
codeNum = 500
|
||||
}
|
||||
errorText := http.StatusText(int(codeNum))
|
||||
if errorText == "" {
|
||||
codeNum = 500
|
||||
errorText = http.StatusText(500)
|
||||
}
|
||||
|
||||
// and since i'm using 'base.gohtml' with Nav, i'll need Nav info
|
||||
navInfoData := initNavInfoData(app, c)
|
||||
|
||||
somePageData := struct {
|
||||
NavInfo navInfo
|
||||
ErrorCode int64
|
||||
ErrorText string
|
||||
}{
|
||||
NavInfo: navInfoData,
|
||||
ErrorCode: codeNum,
|
||||
ErrorText: errorText,
|
||||
}
|
||||
|
||||
// then render template with it
|
||||
templateName := "templates/errors/error.gohtml"
|
||||
switch codeNum {
|
||||
case 404:
|
||||
templateName = "templates/errors/404.gohtml"
|
||||
case 401:
|
||||
templateName = "templates/errors/401.gohtml"
|
||||
}
|
||||
tmpl := template.Must(template.ParseFS(templatesFS, "templates/base.gohtml", templateName))
|
||||
var instantiatedTemplate bytes.Buffer
|
||||
if err := tmpl.Execute(&instantiatedTemplate, somePageData); err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "error parsing template"})
|
||||
}
|
||||
|
||||
return c.HTML(int(codeNum), instantiatedTemplate.String())
|
||||
})
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func initNavInfoData(app *pocketbase.PocketBase, c echo.Context) navInfo {
|
||||
// first collect data
|
||||
info := apis.RequestInfo(c)
|
||||
admin := info.Admin // nil if not authenticated as admin
|
||||
record := info.AuthRecord // nil if not authenticated as regular auth record
|
||||
|
||||
isGuest := admin == nil && record == nil
|
||||
|
||||
username := ""
|
||||
switch {
|
||||
case admin != nil:
|
||||
username = admin.Email
|
||||
case record != nil:
|
||||
username = record.Username()
|
||||
}
|
||||
|
||||
oauthProviders := app.Settings().NamedAuthProviderConfigs()
|
||||
oauthProviderNames := make([]string, 0, len(oauthProviders))
|
||||
for name, config := range oauthProviders {
|
||||
if config.Enabled {
|
||||
oauthProviderNames = append(oauthProviderNames, name)
|
||||
username := ""
|
||||
switch {
|
||||
case admin != nil:
|
||||
username = admin.Email
|
||||
case record != nil:
|
||||
username = record.Username()
|
||||
}
|
||||
}
|
||||
|
||||
return navInfo{
|
||||
IsGuest: isGuest,
|
||||
Username: username,
|
||||
EnabledOauthProviders: oauthProviderNames,
|
||||
}
|
||||
somePageData := struct {
|
||||
RandomNumber int
|
||||
RandomString string
|
||||
NavInfo navInfo
|
||||
}{
|
||||
RandomNumber: rand.Int(),
|
||||
RandomString: stringWithCharset(25, charset),
|
||||
NavInfo: navInfo{
|
||||
Username: username,
|
||||
},
|
||||
}
|
||||
|
||||
// then render template with it
|
||||
templateName := "templates/somepage.gohtml"
|
||||
tmpl := template.Must(template.ParseFS(templatesFS, "templates/base.gohtml", templateName))
|
||||
var instantiatedTemplate bytes.Buffer
|
||||
if err := tmpl.Execute(&instantiatedTemplate, somePageData); err != nil {
|
||||
return c.JSON(http.StatusInternalServerError, map[string]string{"message": "error parsing template"})
|
||||
}
|
||||
|
||||
return c.HTML(http.StatusOK, instantiatedTemplate.String())
|
||||
}, apis.RequireAdminOrRecordAuth())
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
></script>
|
||||
<script defer src="/static/static/public/htmx.min.js"></script>
|
||||
</head>
|
||||
<body hx-get="/" hx-trigger="auth-change-event" hx-push-url="true">
|
||||
<body hx-get="/" hx-trigger="auth-change-event">
|
||||
<!--[if lt IE 8]>
|
||||
<p class="browserupgrade">
|
||||
You are using an <strong>outdated</strong> browser. Please
|
||||
@@ -46,8 +46,7 @@
|
||||
</dialog>
|
||||
<script defer type="text/javascript">
|
||||
async function callOauth(providerName) {
|
||||
const baseUrl = window.location.protocol + "//" + window.location.host;
|
||||
const pb = new PocketBase(baseUrl);
|
||||
const pb = new PocketBase("http://127.0.0.1:8090");
|
||||
|
||||
// This method initializes a one-off realtime subscription and will
|
||||
// open a popup window with the OAuth2 vendor page to authenticate.
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
{{ define "title" }}
|
||||
Not Authorized
|
||||
{{ end }}
|
||||
|
||||
{{ define "main" }}
|
||||
<main hx-boost="true" class="px-10 pt-10 flex flex-col gap-y-10">
|
||||
The page you are trying to access requires authorization.
|
||||
Please log in.
|
||||
</main>
|
||||
{{ end }}
|
||||
@@ -1,9 +0,0 @@
|
||||
{{ define "title" }}
|
||||
Page Not Found
|
||||
{{ end }}
|
||||
|
||||
{{ define "main" }}
|
||||
<main hx-boost="true" class="px-10 pt-10 flex flex-col gap-y-10">
|
||||
Error 404 means the page was not found
|
||||
</main>
|
||||
{{ end }}
|
||||
@@ -1,10 +0,0 @@
|
||||
{{ define "title" }}
|
||||
Error occurred
|
||||
{{ end }}
|
||||
|
||||
{{ define "main" }}
|
||||
<main hx-boost="true" class="px-10 pt-10 flex flex-col gap-y-10">
|
||||
<p> Error {{ .ErrorCode }} occurred! </p>
|
||||
<p> {{ .ErrorText }} </p>
|
||||
</main>
|
||||
{{ end }}
|
||||
@@ -13,7 +13,6 @@
|
||||
</li>
|
||||
</ul>
|
||||
{{ else }}
|
||||
<p>Rendering this on the backend, passing values from the code: {{ .BackendMessage }}</p>
|
||||
<p>There will be some content only for authorized users</p>
|
||||
{{ end }}
|
||||
</main>
|
||||
|
||||
Reference in New Issue
Block a user