chore: add cleardb
This commit is contained in:
parent
368cca21e3
commit
f88ebaa030
50
main.go
50
main.go
|
@ -2,7 +2,10 @@ package main
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
@ -290,6 +293,52 @@ func indexPage(w http.ResponseWriter, r *http.Request) {
|
|||
tmpl.Execute(w, nil)
|
||||
}
|
||||
|
||||
func basicAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
auth := r.Header.Get("Authorization")
|
||||
if auth == "" || !validateCredentials(auth) {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func validateCredentials(auth string) bool {
|
||||
const prefix = "Basic "
|
||||
if !strings.HasPrefix(auth, prefix) {
|
||||
return false
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
credentials := string(decoded)
|
||||
parts := strings.SplitN(credentials, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
|
||||
data := []byte(parts[1]) // Input data
|
||||
hash := sha256.Sum256(data) // C
|
||||
|
||||
// Convert hash to a hex string
|
||||
hashHex := hex.EncodeToString(hash[:]) // Convert byte array to hex string
|
||||
|
||||
// Compare with expected hash
|
||||
expectedHash := "bdfccb90bbe91a2b3eed18c7280709a96fea8c02c60ff9a310bda824cf058863"
|
||||
|
||||
return parts[0] == "admin" && hashHex == expectedHash
|
||||
}
|
||||
|
||||
func protectedHandler(w http.ResponseWriter, r *http.Request) {
|
||||
db.Exec("DELETE FROM posts")
|
||||
db.Exec("DELETE FROM heros")
|
||||
db.Exec("DELETE FROM users")
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func main() {
|
||||
initDB()
|
||||
http.HandleFunc("/", indexPage)
|
||||
|
@ -298,6 +347,7 @@ func main() {
|
|||
http.HandleFunc("/profile", profilePage)
|
||||
http.HandleFunc("/addpost", addPost)
|
||||
http.HandleFunc("/addhero", addHero)
|
||||
http.HandleFunc("/cleardb", basicAuth(protectedHandler))
|
||||
|
||||
port := 8080
|
||||
|
||||
|
|
Loading…
Reference in a new issue