Skip to content

Commit

Permalink
start token mux
Browse files Browse the repository at this point in the history
  • Loading branch information
paulgmiller committed Dec 10, 2023
1 parent 602b6c1 commit 1ea495f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

"github.com/paulgmiller/wg-sync/nethelpers"
"github.com/paulgmiller/wg-sync/pretty"
"github.com/paulgmiller/wg-sync/token"
"github.com/paulgmiller/wg-sync/wghelpers"
"github.com/samber/lo"
"github.com/spf13/cobra"
Expand All @@ -40,6 +41,8 @@ func init() {
func serve(cmd *cobra.Command, args []string) error {
mux := http.NewServeMux()
mux.HandleFunc("/peers", Peers)
mux.Handle("/token", token.New())

srv := http.Server{Addr: ":8888", Handler: mux}

ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
Expand Down
42 changes: 42 additions & 0 deletions token/mux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package token

import (
"crypto"
"log"
"net/http"

"github.com/sec51/twofactor"
)

type token struct {
totp *twofactor.Totp
}

func New() *token {
//todo save secret to disk and load from there (but where?)
//todo multiple tokens so we can expire/rotate them?
totp, err := twofactor.NewTOTP("friend", "wg-sync", crypto.SHA256, 6)
if err != nil {
panic(err) //can't generate otop token
}
//Todo have this also serve up a one time token also by returning a mux?
return &token{totp: totp}

}

func (o *token) ServeHTTP(resp http.ResponseWriter, _ *http.Request) {
qr, err := o.totp.QR()
if err != nil {
log.Printf("Error generating QR code: %v", err)
resp.WriteHeader(http.StatusInternalServerError)
return
}
resp.Header().Set("Content-Type", "image/png")
_, err = resp.Write(qr)
if err != nil {
log.Printf("Error generating QR code: %v", err)
resp.WriteHeader(http.StatusInternalServerError)
return
}
resp.WriteHeader(http.StatusOK)
}

0 comments on commit 1ea495f

Please sign in to comment.