wo-bisch-web/tracker.go

77 lines
2.0 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"regexp"
)
// tracker handler
func save_tracker_settingsHandler(response http.ResponseWriter, request *http.Request) {
name := getUserName(request)
if name != "" {
deveui, ok := request.URL.Query()["deveui"]
if !ok || len(deveui[0]) < 1 {
log.Println("Url Param 'deveui' is missing")
fmt.Fprintf(response, "{ \"rc\": 1, \"msg\": \"deveui must be specified in URL\" }")
return
}
// Query()["deveui"] will return an array of items,
// we only want the single item.
mydeveui := deveui[0]
if len(mydeveui) != 16 {
log.Println("specified 'deveui' has invalid length")
fmt.Fprintf(response, "{ \"rc\": 8, \"msg\": \"specified deveui has invalid length\" }")
return
}
if !(Contains(getMyDevs(name), mydeveui)) {
log.Println("specified 'deveui' does not belong to this user")
fmt.Fprintf(response, "{ \"rc\": 2, \"msg\": \"specified deveui does not belong to this user\" }")
return
}
log.Println("Url Param 'deveui' is: " + string(mydeveui))
alias, ok2 := request.URL.Query()["alias"]
if !ok2 || len(alias[0]) < 1 {
log.Println("Url Param 'alias' is missing")
fmt.Fprintf(response, "{ \"rc\": 3, \"msg\": \"alias must be specified in URL\" }")
return
}
myalias := alias[0]
// validate alias
match, _ := regexp.MatchString("^[a-zA-Z0-9 ]{1,25}$", myalias)
if !(match) {
log.Println("Url Param 'alias' is not valid")
fmt.Fprintf(response, "{ \"rc\": 9, \"msg\": \"alias is not valid\" }")
return
}
var mydev Dev
mydev.Deveui = mydeveui
mydev.Alias = myalias
// now we try to save the settings
err := updateTrackerSettings(mydev)
if err != nil {
log.Println("Error to Update Device Settings")
fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"error with saving device settings\" }")
return
} else {
fmt.Fprintf(response, "{ \"rc\": 0, \"msg\": \"SUCCESS\" }")
}
} else {
fmt.Fprintf(response, "{ \"rc\": 7, \"msg\": \"Only available for logged in users\" }")
}
}