gosh

package module
v0.0.0-...-32e2de6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 19, 2024 License: MIT-0 Imports: 12 Imported by: 0

README

GOSH

GOSH (Golang, OAuth2, SQLite, HTMX)

Getting started

  1. Installation
go get github.com/gregckrausellc/gosh
  1. Generate TLS certificate and key

The cookies used by GOSH are all set in secure mode, which requires HTTPS.

openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out server.crt -keyout server.key
  1. Example usage
package main

import (
	// Standard library
	"database/sql"
	"log"
	"net/http"
	"os"

	// Third party
	"github.com/gregckrausellc/gosh"
	_ "github.com/mattn/go-sqlite3"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
)

func main() {
	db, err := sql.Open("sqlite3", "./gosh.db")
	if err != nil {
		log.Fatal(err)
	}

	defer db.Close()

	gosh.InitializeUserTable(db)

	googleConfig := &oauth2.Config{
		ClientID:     os.Getenv("GOOGLE_OAUTH_CLIENT_ID"),
		ClientSecret: os.Getenv("GOOGLE_OAUTH_CLIENT_SECRET"),
		Scopes:       []string{"openid"},
		Endpoint:     google.Endpoint,
		RedirectURL:  "https://localhost:443/auth/google/redirect",
	}

	mux := http.NewServeMux()

	mux.HandleFunc("/auth/login", func(w http.ResponseWriter, r *http.Request) {
		w.Write(gosh.LoginPage)
	})
	mux.HandleFunc("/auth/google/login", func(w http.ResponseWriter, r *http.Request) {
		gosh.LoginHandler(w, r, googleConfig, gosh.GOOGLE)
	})
	mux.HandleFunc("/auth/google/redirect", func(w http.ResponseWriter, r *http.Request) {
		gosh.RedirectHandler(w, r, gosh.GOOGLE)
	})
	mux.HandleFunc("/auth/google/exchange", func(w http.ResponseWriter, r *http.Request) {
		gosh.ExchangeHandler(w, r, googleConfig, db)
	})

	mux.HandleFunc("/protected", func(w http.ResponseWriter, r *http.Request) {
		w.Write(
			[]byte("<html><body><h1>This route requires authentication</h1></body></html>"),
		)
	})

	protectedMux := gosh.AuthMiddleware(mux, db)

	log.Fatal(http.ListenAndServeTLS(":443", "server.crt", "server.key", protectedMux))
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL