Skip to content

Commit

Permalink
Merge pull request #20 from CameronRP/basic-authentication
Browse files Browse the repository at this point in the history
Added basic authentication for the API
  • Loading branch information
CameronRP authored Sep 14, 2018
2 parents 242a618 + 9748118 commit 371167a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
21 changes: 17 additions & 4 deletions cmd/managementd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,25 @@ func main() {

// API
apiObj := api.NewAPI(config.CPTVDir)
router.HandleFunc("/api/recordings", apiObj.GetRecordings).Methods("GET")
router.HandleFunc("/api/recording/{id}", apiObj.GetRecording).Methods("GET")
router.HandleFunc("/api/recording/{id}", apiObj.DeleteRecording).Methods("DELETE")
router.HandleFunc("/api/camera/snapshot", apiObj.TakeSnapshot).Methods("PUT")
apiRouter := router.PathPrefix("/api").Subrouter()
apiRouter.HandleFunc("/recordings", apiObj.GetRecordings).Methods("GET")
apiRouter.HandleFunc("/recording/{id}", apiObj.GetRecording).Methods("GET")
apiRouter.HandleFunc("/recording/{id}", apiObj.DeleteRecording).Methods("DELETE")
apiRouter.HandleFunc("/camera/snapshot", apiObj.TakeSnapshot).Methods("PUT")
apiRouter.Use(basicAuth)

listenAddr := fmt.Sprintf(":%d", config.Port)
log.Printf("listening on %s", listenAddr)
log.Fatal(http.ListenAndServe(listenAddr, router))
}

func basicAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userPassEncoded := "YWRtaW46ZmVhdGhlcnM=" // admin:feathers base64 encoded.
if r.Header.Get("Authorization") == "Basic "+userPassEncoded {
next.ServeHTTP(w, r)
} else {
http.Error(w, "Forbidden", http.StatusForbidden)
}
})
}
1 change: 1 addition & 0 deletions static/js/camera.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ function restartCameraViewing() {
async function updateSnapshotLoop() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("PUT", "/api/camera/snapshot", true);
xmlHttp.setRequestHeader("Authorization", "Basic "+btoa("admin:feathers"))
xmlHttp.onload = async function() {
if (xmlHttp.status == 200) {
let snapshot = document.getElementById("snapshot-image")
Expand Down

0 comments on commit 371167a

Please sign in to comment.