1
0
mirror of https://git.sr.ht/~adnano/go-gemini synced 2024-11-10 04:41:38 +01:00
go-gemini/examples/auth.go

85 lines
1.7 KiB
Go
Raw Normal View History

2020-10-12 22:34:52 +02:00
// +build ignore
2020-09-27 23:39:44 +02:00
package main
import (
2020-11-25 20:24:49 +01:00
"crypto/sha512"
"crypto/tls"
2020-09-27 23:39:44 +02:00
"crypto/x509"
"crypto/x509/pkix"
2020-09-27 23:39:44 +02:00
"fmt"
"log"
"time"
2020-09-27 23:39:44 +02:00
2020-10-28 04:35:22 +01:00
"git.sr.ht/~adnano/go-gemini"
2020-09-27 23:39:44 +02:00
)
2020-11-25 20:24:49 +01:00
type User struct {
Name string
2020-09-27 23:39:44 +02:00
}
var (
2020-11-25 20:24:49 +01:00
// Map of certificate hashes to users
users = map[string]*User{}
2020-09-27 23:39:44 +02:00
)
func main() {
2020-10-28 04:35:22 +01:00
var mux gemini.ServeMux
2020-11-25 20:24:49 +01:00
mux.HandleFunc("/", profile)
mux.HandleFunc("/username", changeUsername)
2020-10-21 23:47:34 +02:00
2020-10-28 04:35:22 +01:00
var server gemini.Server
2020-10-28 19:59:45 +01:00
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
2020-10-12 06:13:24 +02:00
log.Fatal(err)
}
server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
return gemini.CreateCertificate(gemini.CertificateOptions{
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: time.Hour,
})
}
2020-10-21 23:47:34 +02:00
server.Register("localhost", &mux)
2020-09-27 23:39:44 +02:00
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
2020-11-25 20:24:49 +01:00
func fingerprint(cert *x509.Certificate) string {
b := sha512.Sum512(cert.Raw)
return string(b[:])
2020-09-27 23:39:44 +02:00
}
2020-11-25 20:24:49 +01:00
func profile(w *gemini.ResponseWriter, r *gemini.Request) {
if r.Certificate == nil {
2020-11-01 20:47:26 +01:00
w.WriteStatus(gemini.StatusCertificateRequired)
2020-10-21 23:47:34 +02:00
return
}
2020-11-25 20:24:49 +01:00
fingerprint := fingerprint(r.Certificate.Leaf)
user, ok := users[fingerprint]
2020-10-21 23:47:34 +02:00
if !ok {
2020-11-25 20:24:49 +01:00
user = &User{}
users[fingerprint] = user
2020-10-21 23:47:34 +02:00
}
2020-11-25 20:24:49 +01:00
fmt.Fprintln(w, "Username:", user.Name)
fmt.Fprintln(w, "=> /username Change username")
2020-09-27 23:39:44 +02:00
}
2020-11-25 20:24:49 +01:00
func changeUsername(w *gemini.ResponseWriter, r *gemini.Request) {
if r.Certificate == nil {
2020-11-01 20:47:26 +01:00
w.WriteStatus(gemini.StatusCertificateRequired)
2020-10-21 23:47:34 +02:00
return
}
2020-09-27 23:39:44 +02:00
2020-11-25 20:24:49 +01:00
username, ok := gemini.Input(r)
2020-10-21 23:47:34 +02:00
if !ok {
2020-11-25 20:24:49 +01:00
w.WriteHeader(gemini.StatusInput, "Username")
2020-10-21 23:47:34 +02:00
return
}
2020-11-25 20:24:49 +01:00
users[fingerprint(r.Certificate.Leaf)].Name = username
2020-11-26 01:10:01 +01:00
w.WriteHeader(gemini.StatusRedirect, "/")
2020-09-27 23:39:44 +02:00
}