2021-09-16 20:38:28 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2021-09-19 21:20:37 +00:00
|
|
|
"openmediacenter/apiGo/database/settings"
|
2021-09-16 20:38:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
VideoNode = "video"
|
2021-09-19 21:20:37 +00:00
|
|
|
TagNode = "tags"
|
|
|
|
SettingsNode = "settings"
|
2021-09-16 20:38:28 +00:00
|
|
|
ActorNode = "actor"
|
|
|
|
TVShowNode = "tv"
|
|
|
|
LoginNode = "login"
|
|
|
|
)
|
|
|
|
|
|
|
|
func AddHandler(action string, apiNode string, perm uint8, handler func(ctx Context)) {
|
|
|
|
http.Handle(fmt.Sprintf("/api/%s/%s", apiNode, action), http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
2021-09-19 21:20:37 +00:00
|
|
|
srvPwd := settings.GetPassword()
|
|
|
|
if srvPwd == nil {
|
|
|
|
// no password set
|
|
|
|
ctx := &apicontext{writer: writer, responseWritten: false, request: request, userid: -1, permid: PermUnauthorized}
|
|
|
|
callHandler(ctx, handler, writer)
|
|
|
|
} else {
|
|
|
|
tokenheader := request.Header.Get("Token")
|
2021-09-16 20:38:28 +00:00
|
|
|
|
2021-09-19 21:20:37 +00:00
|
|
|
id := -1
|
|
|
|
permid := PermUnauthorized
|
2021-09-16 20:38:28 +00:00
|
|
|
|
2021-09-19 21:20:37 +00:00
|
|
|
// check token if token provided
|
|
|
|
if tokenheader != "" {
|
|
|
|
id, permid = TokenValid(request.Header.Get("Token"))
|
|
|
|
}
|
2021-09-16 20:38:28 +00:00
|
|
|
|
2021-09-19 21:20:37 +00:00
|
|
|
ctx := &apicontext{writer: writer, responseWritten: false, request: request, userid: id, permid: permid}
|
2021-09-16 20:38:28 +00:00
|
|
|
|
2021-09-19 21:20:37 +00:00
|
|
|
// check if rights are sufficient to perform the action
|
|
|
|
if permid <= perm {
|
|
|
|
callHandler(ctx, handler, writer)
|
|
|
|
} else {
|
|
|
|
ctx.Error("insufficient permissions")
|
2021-09-16 20:38:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
2021-09-19 21:20:37 +00:00
|
|
|
func callHandler(ctx *apicontext, handler func(ctx Context), writer http.ResponseWriter) {
|
|
|
|
handler(ctx)
|
|
|
|
|
|
|
|
if !ctx.responseWritten {
|
|
|
|
// none of the response functions called so send default response
|
|
|
|
ctx.Error("Unknown server Error occured")
|
|
|
|
writer.WriteHeader(501)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-21 08:45:52 +00:00
|
|
|
func ServerInit(port uint16) error {
|
2021-09-16 20:38:28 +00:00
|
|
|
// initialize auth service and add corresponding auth routes
|
|
|
|
InitOAuth()
|
2021-09-21 08:45:52 +00:00
|
|
|
|
|
|
|
fmt.Printf("OpenMediacenter server up and running on port %d\n", port)
|
|
|
|
return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
|
2021-09-16 20:38:28 +00:00
|
|
|
}
|