Skip to content

Instantly share code, notes, and snippets.

@lotusirous
Created October 22, 2022 03:37
Show Gist options
  • Save lotusirous/595417436e1d4c029a4409f3a63c8dfc to your computer and use it in GitHub Desktop.
Save lotusirous/595417436e1d4c029a4409f3a63c8dfc to your computer and use it in GitHub Desktop.
A mock one time token
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
var issuedTokens = make(map[string]int)
// returns an http.HandlerFunc that processes http requests to ...
func HandleIssueToken(w http.ResponseWriter, r *http.Request) {
token := RandStringRunes(10)
issuedTokens[token] = 0
w.Write([]byte(token))
}
// HandleSample writes a hello message to response.
func HandleAuthorized(w http.ResponseWriter, r *http.Request) {
tok := r.Header.Get("Authorization")
if tok == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
used, ok := issuedTokens[tok]
if !ok {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized, please issuee a new token"))
return
}
if used > 1 {
w.WriteHeader(401)
w.Write([]byte("Token is expired"))
return
}
// dump issused token
for k, v := range issuedTokens {
fmt.Println(k, v)
}
issuedTokens[tok]++
w.Write([]byte("Welcome, you can see this resource"))
}
func main() {
addr := ":1234"
r := http.NewServeMux()
r.HandleFunc("/admin", HandleAuthorized)
r.HandleFunc("/token", HandleIssueToken)
svr := &http.Server{
Addr: addr,
Handler: r,
}
log.Println("server started", addr)
log.Fatal(svr.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment