Add go backend

This commit is contained in:
2022-12-18 13:42:21 +13:00
parent 5719891df8
commit 99f88d6adf
15 changed files with 1179 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package middleware
import (
"net/http"
"os"
"golang.org/x/crypto/bcrypt"
)
func BasicAuth(f http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
hash, err := HashPassword(os.Getenv("PASSWORD"))
if err == nil && ok {
if username == os.Getenv("USERNAME") && CheckPasswordHash(password, hash) {
f(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

58
api/middleware/jwt.go Normal file
View File

@@ -0,0 +1,58 @@
package middleware
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/golang-jwt/jwt"
)
var secret = []byte(os.Getenv("SECRET"))
func Auth(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// get token
authheader, ok := r.Header["Authorization"]
if !ok {
http.Error(w, "Missing token", http.StatusBadRequest)
return
}
tokenString := strings.Split(authheader[0], " ")[1]
//parse token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return secret, nil
})
if err != nil {
http.Error(w, "Bad token", http.StatusBadRequest)
return
}
// check if path is allowed
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid && r.URL.Path == claims["path"] {
log.Println(r.URL.Path)
f(w, r)
} else {
log.Println(err)
http.Error(w, "Forbidden", http.StatusUnauthorized)
}
// it's all good
}
}
func GenerateToken(path string) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"path": path,
})
tokenString, err := token.SignedString(secret)
if err != nil {
panic(err)
}
fmt.Println(tokenString)
}