Skip to content

Commit

Permalink
Basic HTTP authentication
Browse files Browse the repository at this point in the history
Implemented basic login using standard WWW-Authenticate method
  • Loading branch information
gmemstr committed Jul 15, 2017
1 parent a959d7c commit e61bcb9
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 1 deletion.
10 changes: 10 additions & 0 deletions admin.go
@@ -0,0 +1,10 @@
package main

import (
"io/ioutil"
"fmt"
)

func CreateEpisode() {

}
1 change: 1 addition & 0 deletions assets/admin.html
@@ -0,0 +1 @@
admin.html
2 changes: 1 addition & 1 deletion assets/index.html
Expand Up @@ -13,7 +13,7 @@ <h1 id="title" class="title">Loading</h1>

</div>
<footer>
<p>White Rabbit licensed under the GPLv3</p>
<p>White Rabbit licensed under the GPLv3 | <a href="/rss">RSS</a> <a href="/json">JSON</a></p>
</footer>
<script>
get("/json", function(data){
Expand Down
35 changes: 35 additions & 0 deletions webserver.go
Expand Up @@ -5,6 +5,7 @@ import (
"io/ioutil"
"log"
"net/http"
"crypto/subtle"

"github.com/gorilla/mux"
)
Expand Down Expand Up @@ -42,6 +43,39 @@ func HomeHandler(w http.ResponseWriter, r *http.Request) {
}
}


/*
* Code from stackoverflow by user Timmmm
* https://stackoverflow.com/questions/21936332/idiomatic-way-of-requiring-http-basic-auth-in-go/39591234#39591234
*/
func BasicAuth(handler http.HandlerFunc, username, password, realm string) http.HandlerFunc {

return func(w http.ResponseWriter, r *http.Request) {

user, pass, ok := r.BasicAuth()

if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="White Rabbit"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorised.\n"))
return
}

handler(w, r)
}
}

func AdminHandler(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadFile("assets/admin.html")

if err == nil {
w.Write(data)
} else {
w.WriteHeader(404)
w.Write([]byte("404 Something went wrong - " + http.StatusText(404)))
}
}

func main() {
go watch()
r := mux.NewRouter()
Expand All @@ -51,5 +85,6 @@ func main() {
r.HandleFunc("/rss", RssHandler)
r.HandleFunc("/json", JsonHandler)
http.Handle("/", r)
r.HandleFunc("/admin", BasicAuth(AdminHandler, "g", "password", "Login to White Rabbit admin interface"))
log.Fatal(http.ListenAndServe(":8000", r))
}

0 comments on commit e61bcb9

Please sign in to comment.