quintodrome/api/validation.go

60 lines
1.4 KiB
Go
Raw Normal View History

package api
import (
2016-03-09 17:05:23 -09:00
"encoding/hex"
"strings"
2016-03-15 13:06:23 -08:00
"fmt"
"github.com/astaxie/beego"
"github.com/deluan/gosonic/api/responses"
)
type ControllerInterface interface {
GetString(key string, def ...string) string
CustomAbort(status int, body string)
SendError(errorCode int, message ...interface{})
}
2016-03-15 13:06:23 -08:00
func Validate(controller BaseAPIController) {
if beego.AppConfig.String("disableValidation") != "true" {
checkParameters(controller)
authenticate(controller)
2016-02-24 15:16:42 -09:00
// TODO Validate version
}
}
2016-03-15 13:06:23 -08:00
func checkParameters(c BaseAPIController) {
2016-02-25 14:52:07 -09:00
requiredParameters := []string{"u", "p", "v", "c"}
2016-02-25 14:52:07 -09:00
for _, p := range requiredParameters {
if c.GetString(p) == "" {
2016-03-15 13:06:23 -08:00
logWarn(c, fmt.Sprintf(`Missing required parameter "%s"`, p))
2016-03-23 08:35:10 -08:00
abortRequest(c, responses.ErrorMissingParameter)
}
}
}
2016-03-15 13:06:23 -08:00
func authenticate(c BaseAPIController) {
user := c.GetString("u")
2016-03-09 17:05:23 -09:00
pass := c.GetString("p")
if strings.HasPrefix(pass, "enc:") {
e := strings.TrimPrefix(pass, "enc:")
if dec, err := hex.DecodeString(e); err == nil {
pass = string(dec)
}
}
2016-02-25 14:52:07 -09:00
if user != beego.AppConfig.String("user") || pass != beego.AppConfig.String("password") {
2016-03-15 13:06:23 -08:00
logWarn(c, fmt.Sprintf(`Invalid login for user "%s"`, user))
2016-03-23 08:35:10 -08:00
abortRequest(c, responses.ErrorAuthenticationFail)
}
}
2016-03-15 13:06:23 -08:00
func abortRequest(c BaseAPIController, code int) {
c.SendError(code)
2016-02-25 14:52:07 -09:00
}
2016-03-15 13:06:23 -08:00
func logWarn(c BaseAPIController, msg string) {
beego.Warn(fmt.Sprintf("%s?%s: %s", c.Ctx.Request.URL.Path, c.Ctx.Request.URL.RawQuery, msg))
}