Support basic auth
This commit is contained in:
parent
9a22f4b3e5
commit
a0eeac4eb1
27
main.go
27
main.go
|
@ -77,6 +77,10 @@ func MigrateDatabase() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func ShortenHandler(w http.ResponseWriter, r *http.Request) {
|
func ShortenHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !checkPassword(w, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
writeShortenedUrl := func(w http.ResponseWriter, slug string) {
|
writeShortenedUrl := func(w http.ResponseWriter, slug string) {
|
||||||
shortenedUrl, err := url.Parse(viper.GetString("shortUrl"))
|
shortenedUrl, err := url.Parse(viper.GetString("shortUrl"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -87,12 +91,6 @@ func ShortenHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
_, _ = w.Write([]byte(shortenedUrl.String()))
|
_, _ = w.Write([]byte(shortenedUrl.String()))
|
||||||
}
|
}
|
||||||
|
|
||||||
password := r.URL.Query().Get("password")
|
|
||||||
if password != viper.GetString("password") {
|
|
||||||
http.Error(w, "Wrong password", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
requestUrl := r.URL.Query().Get("url")
|
requestUrl := r.URL.Query().Get("url")
|
||||||
if requestUrl == "" {
|
if requestUrl == "" {
|
||||||
http.Error(w, "url parameter not set", http.StatusBadRequest)
|
http.Error(w, "url parameter not set", http.StatusBadRequest)
|
||||||
|
@ -138,9 +136,7 @@ func ShortenHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
password := r.URL.Query().Get("password")
|
if !checkPassword(w, r) {
|
||||||
if password != viper.GetString("password") {
|
|
||||||
http.Error(w, "Wrong password", http.StatusBadRequest)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -170,6 +166,19 @@ func DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
_, _ = w.Write([]byte("Slug deleted"))
|
_, _ = w.Write([]byte("Slug deleted"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func checkPassword(w http.ResponseWriter, r *http.Request) bool {
|
||||||
|
if r.URL.Query().Get("password") == viper.GetString("password") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
_, pass, ok := r.BasicAuth()
|
||||||
|
if !(ok && pass == viper.GetString("password")) {
|
||||||
|
w.Header().Set("WWW-Authenticate", `Basic realm="Please enter a password!"`)
|
||||||
|
http.Error(w, "Not authenticated", http.StatusUnauthorized)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func generateSlug() string {
|
func generateSlug() string {
|
||||||
var chars = []rune("0123456789abcdefghijklmnopqrstuvwxyz")
|
var chars = []rune("0123456789abcdefghijklmnopqrstuvwxyz")
|
||||||
s := make([]rune, 6)
|
s := make([]rune, 6)
|
||||||
|
|
Loading…
Reference in New Issue