violet/servers/api.go

61 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-04-21 03:21:46 +01:00
package servers
import (
"code.mrmelon54.com/melon/summer-utils/claims/auth"
"github.com/MrMelon54/violet/utils"
"github.com/julienschmidt/httprouter"
"github.com/mrmelon54/mjwt"
"log"
"net/http"
"time"
)
2023-04-21 15:49:01 +01:00
// NewApiServer creates and runs a http server containing all the API
// endpoints for the software
2023-04-21 03:21:46 +01:00
//
2023-04-21 15:49:01 +01:00
// `/compile` - reloads all domains, routes and redirects
2023-04-22 22:18:39 +01:00
func NewApiServer(conf *Conf, compileTarget utils.MultiCompilable) *http.Server {
2023-04-21 03:21:46 +01:00
r := httprouter.New()
2023-04-21 15:49:01 +01:00
// Endpoint for compile action
2023-04-21 03:21:46 +01:00
r.POST("/compile", func(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
// Get bearer token
bearer := utils.GetBearer(req)
if bearer == "" {
utils.RespondHttpStatus(rw, http.StatusForbidden)
return
}
// Read claims from mjwt
2023-04-22 22:18:39 +01:00
_, b, err := mjwt.ExtractClaims[auth.AccessTokenClaims](conf.Verify, bearer)
2023-04-21 03:21:46 +01:00
if err != nil {
utils.RespondHttpStatus(rw, http.StatusForbidden)
return
}
// Token must have `violet:compile` perm
if !b.Claims.Perms.Has("violet:compile") {
utils.RespondHttpStatus(rw, http.StatusForbidden)
return
}
// Trigger the compile action
compileTarget.Compile()
rw.WriteHeader(http.StatusAccepted)
})
// Create and run http server
s := &http.Server{
2023-04-24 01:35:23 +01:00
Addr: conf.ApiListen,
2023-04-21 03:21:46 +01:00
Handler: r,
ReadTimeout: time.Minute,
ReadHeaderTimeout: time.Minute,
WriteTimeout: time.Minute,
IdleTimeout: time.Minute,
MaxHeaderBytes: 2500,
}
log.Printf("[API] Starting API server on: '%s'\n", s.Addr)
go utils.RunBackgroundHttp("API", s)
return s
}