Compare commits

..

1 Commits

Author SHA1 Message Date
efim
258d2b560c feat: adding a license for pushing to repo 2023-10-08 13:41:45 +00:00
7 changed files with 52 additions and 104 deletions

View File

@@ -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: 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:

View File

@@ -148,7 +148,7 @@ and
#+end_src #+end_src
is what i need for it to pick up pb_data from work directory, cool 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 need to pass data and migration location as params
and address on which to serve, cool and address on which to serve, cool
i suppose i suppose
@@ -174,52 +174,16 @@ cool
oh, but if i'm using nginx i'll need my own certificate, that makes sence oh, but if i'm using nginx i'll need my own certificate, that makes sence
*** maybe things are ok? *** maybe things are ok?
let's try to plaintext deploy? 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 ** 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 ** TODO add readme and comments
** DONE configure tls / ssl / https on franzk deployment ** TODO 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 )
can it be configured on render.com? 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
** TODO maybe add middleware so that 401 would be a page, and not json ** 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? ** TODO get icons for the auth providers. surely they are accessible from the pocketbase itself?
http://localhost:8090/_/images/oauth2/apple.svg http://localhost:8090/_/images/oauth2/apple.svg
yes. yes.
** TODO read and add ok logging
** TODO figure out and enbale migrations ** TODO figure out and enbale migrations
https://pocketbase.io/docs/go-migrations/#enable-go-migrations https://pocketbase.io/docs/go-migrations/#enable-go-migrations

View File

@@ -42,8 +42,8 @@
nixosModules.auth-pocketbase-attempt = { config, pkgs, ... }: nixosModules.auth-pocketbase-attempt = { config, pkgs, ... }:
let let
cfg = config.services.${pname}; cfg = config.services.${pname};
lib = nixpkgs.lib; lib = pkgs.lib;
shortName = "pb-auth-example-app"; shortName = "pb-auth-example-group";
in { in {
options.services.${pname} = { options.services.${pname} = {
enable = lib.mkEnableOption enable = lib.mkEnableOption
@@ -70,27 +70,17 @@
description = description =
"Whether pocketbase should serve on https and issue own certs. Main case for true - when not under nginx"; "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 config = lib.mkIf cfg.enable {
username = "${shortName}-user"; users.groups."${shortName}-group" = { };
groupname = "${shortName}-group"; users.users."${shortName}-user" = {
in lib.mkIf cfg.enable { isSystemUser = true;
users.groups."${groupname}" = { }; group = "${shortName}-group";
users.users."${username}" = {
isNormalUser = true; # needed to allow for home dir
group = "${groupname}";
}; };
systemd.services.${shortName} = let systemd.services.${shortName} = let
protocol = if cfg.usePbTls then "https" else "http"; protocol = if cfg.usePbTls then "https" else "http";
serverHost = if cfg.useNginx then "127.0.0.1" else cfg.host; serverHost = if cfg.useNginx then "127.0.0.1" else cfg.host;
serveCliArg = servedAddress = "${protocol}://${serverHost}:${cfg.port}";
"--${protocol} ${serverHost}:${toString cfg.port}";
in { in {
description = "Exercise app ${pname}"; description = "Exercise app ${pname}";
wantedBy = [ "multi-user.target" ]; wantedBy = [ "multi-user.target" ];
@@ -99,32 +89,12 @@
startLimitBurst = 10; startLimitBurst = 10;
serviceConfig = { serviceConfig = {
ExecStart = ExecStart =
"${packages.auth-pocketbase-attempt}/bin/${pname} serve ${serveCliArg} --dir=/home/${ "${packages.auth-pocketbase-attempt}/bin/${pname} serve ${servedAddress} --dir=/home/${
"${username}" config.users.users."${shortName}-user"
}"; }";
Restart = "on-failure"; Restart = "on-failure";
User = "${username}"; User = "${shortName}-user";
Group = "${groupname}"; Group = "${shortName}-group";
};
};
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;
'';
};
}; };
}; };
}; };

11
main.go
View File

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

View File

@@ -1,9 +1,9 @@
package middleware package middleware
import ( import (
"fmt"
"log" "log"
"net/http" "net/http"
"github.com/labstack/echo/v5" "github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase" "github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis" "github.com/pocketbase/pocketbase/apis"
@@ -15,9 +15,7 @@ import (
const AuthCookieName = "Auth" const AuthCookieName = "Auth"
func AddCookieSessionMiddleware(app *pocketbase.PocketBase, isTlsEnabled bool) { func AddCookieSessionMiddleware(app *pocketbase.PocketBase) {
log.Println("Warning: starting server with cookie Secure = false!")
app.OnBeforeServe().Add(func(e *core.ServeEvent) error { app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.Use(loadAuthContextFromCookie(app)) e.Router.Use(loadAuthContextFromCookie(app))
return nil return nil
@@ -25,12 +23,14 @@ func AddCookieSessionMiddleware(app *pocketbase.PocketBase, isTlsEnabled bool) {
// fires for every auth collection // fires for every auth collection
app.OnRecordAuthRequest().Add(func(e *core.RecordAuthEvent) error { 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{ e.HttpContext.SetCookie(&http.Cookie{
Name: AuthCookieName, Name: AuthCookieName,
Value: e.Token, Value: e.Token,
Path: "/", Path: "/",
Secure: isTlsEnabled,
HttpOnly: true,
}) })
e.HttpContext.SetCookie(&http.Cookie{ e.HttpContext.SetCookie(&http.Cookie{
Name: "username", Name: "username",
@@ -39,16 +39,17 @@ func AddCookieSessionMiddleware(app *pocketbase.PocketBase, isTlsEnabled bool) {
return nil return nil
}) })
app.OnAdminAuthRequest().Add(func(e *core.AdminAuthEvent) error { 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{ e.HttpContext.SetCookie(&http.Cookie{
Name: AuthCookieName, Name: AuthCookieName,
Value: e.Token, Value: e.Token,
Path: "/", Path: "/",
Secure: isTlsEnabled,
HttpOnly: true,
}) })
return nil return nil
}) })
app.OnBeforeServe().Add(getLogoutRoute(app, isTlsEnabled)) app.OnBeforeServe().Add(getLogoutRoute(app))
} }
func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc { func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
@@ -73,6 +74,14 @@ func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
if err == nil && admin != nil { if err == nil && admin != nil {
// "authenticate" the admin // "authenticate" the admin
c.Set(apis.ContextAdminKey, 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: case tokens.TypeAuthRecord:
@@ -83,6 +92,15 @@ func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
if err == nil && record != nil { if err == nil && record != nil {
// "authenticate" the app user // "authenticate" the app user
c.Set(apis.ContextAuthRecordKey, record) 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)
} }
} }
@@ -92,7 +110,7 @@ func loadAuthContextFromCookie(app core.App) echo.MiddlewareFunc {
} }
// render and return login page with configured oauth providers // render and return login page with configured oauth providers
func getLogoutRoute(app *pocketbase.PocketBase, isTlsEnabled bool) func(*core.ServeEvent) error { func getLogoutRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error {
return func (e *core.ServeEvent) error { return func (e *core.ServeEvent) error {
e.Router.GET("/logout", func(c echo.Context) error { e.Router.GET("/logout", func(c echo.Context) error {
c.SetCookie(&http.Cookie{ c.SetCookie(&http.Cookie{
@@ -100,8 +118,6 @@ func getLogoutRoute(app *pocketbase.PocketBase, isTlsEnabled bool) func(*core.S
Value: "", Value: "",
Path: "/", Path: "/",
MaxAge: -1, MaxAge: -1,
Secure: isTlsEnabled,
HttpOnly: true,
}) })
c.Response().Header().Add("HX-Trigger", "auth-change-event") c.Response().Header().Add("HX-Trigger", "auth-change-event")
return c.JSON(http.StatusOK, map[string]string{"message": "session cookie removed"}) return c.JSON(http.StatusOK, map[string]string{"message": "session cookie removed"})

View File

@@ -3,6 +3,7 @@ package pages
import ( import (
"bytes" "bytes"
"embed" "embed"
"fmt"
"html/template" "html/template"
"math/rand" "math/rand"
"net/http" "net/http"
@@ -46,6 +47,8 @@ func getIndexPageRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error
record := info.AuthRecord // nil if not authenticated as regular auth record record := info.AuthRecord // nil if not authenticated as regular auth record
isGuest := admin == nil && record == nil isGuest := admin == nil && record == nil
coolMessage := fmt.Sprintf("got admin %v and record %v. is guest: %t", admin, record, isGuest)
fmt.Print(coolMessage)
username := "" username := ""
switch { switch {
@@ -62,6 +65,7 @@ func getIndexPageRoute(app *pocketbase.PocketBase) func(*core.ServeEvent) error
oauthProviderNames = append(oauthProviderNames, name) oauthProviderNames = append(oauthProviderNames, name)
} }
} }
fmt.Printf(">> enabled providers names %+v\n", oauthProviderNames)
indexPageData := struct { indexPageData := struct {
IsGuest, IsAdmin bool IsGuest, IsAdmin bool

View File

@@ -46,8 +46,7 @@
</dialog> </dialog>
<script defer type="text/javascript"> <script defer type="text/javascript">
async function callOauth(providerName) { async function callOauth(providerName) {
const baseUrl = window.location.protocol + "//" + window.location.host; const pb = new PocketBase("http://127.0.0.1:8090");
const pb = new PocketBase(baseUrl);
// This method initializes a one-off realtime subscription and will // This method initializes a one-off realtime subscription and will
// open a popup window with the OAuth2 vendor page to authenticate. // open a popup window with the OAuth2 vendor page to authenticate.