hugo-micropub/validation.go

98 lines
2.4 KiB
Go
Raw Normal View History

2019-11-07 10:00:24 +00:00
package main
import (
"encoding/json"
"errors"
"net/http"
"strings"
)
type ContentType int
const (
WwwForm ContentType = iota
Json
Multipart
UnsupportedType
)
const (
indieAuthTokenUrl = "https://tokens.indieauth.com/token"
)
type IndieAuthRes struct {
Me string `json:"me"`
ClientId string `json:"client_id"`
Scope string `json:"scope"`
Issue int `json:"issued_at"`
Nonce int `json:"nonce"`
}
func checkAccess(token string) (bool, error) {
if token == "" {
return false, errors.New("token string is empty")
}
// form the request to check the token
2020-04-20 21:04:01 +00:00
client := http.DefaultClient
2019-11-07 10:00:24 +00:00
req, err := http.NewRequest("GET", indieAuthTokenUrl, nil)
if err != nil {
return false, errors.New("error making the request for checking token access")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", token)
// send the request
2019-11-19 09:04:22 +00:00
res, err := client.Do(req)
2019-11-07 10:00:24 +00:00
if err != nil {
return false, errors.New("error sending the request for checking token access")
}
// parse the response
2020-04-20 21:04:01 +00:00
indieAuthRes := &IndieAuthRes{}
err = json.NewDecoder(res.Body).Decode(&indieAuthRes)
res.Body.Close()
2019-11-07 10:00:24 +00:00
if err != nil {
return false, errors.New("Error parsing the response into json for checking token access " + err.Error())
}
// verify results of the response
2019-12-06 09:32:30 +00:00
if indieAuthRes.Me != BlogUrl {
2019-11-07 10:00:24 +00:00
return false, errors.New("me does not match")
}
scopes := strings.Fields(indieAuthRes.Scope)
postPresent := false
for _, scope := range scopes {
if scope == "post" || scope == "create" || scope == "update" {
postPresent = true
break
}
}
if !postPresent {
return false, errors.New("post is not present in the scope")
}
return true, nil
}
2020-01-01 12:44:44 +00:00
func CheckAuthorization(token string) bool {
if ok, err := checkAccess(token); ok {
2019-11-07 10:00:24 +00:00
return true
} else if err != nil {
return false
} else {
return false
}
}
func GetContentType(contentType string) (ContentType, error) {
if contentType != "" {
if strings.Contains(contentType, "application/x-www-form-urlencoded") {
return WwwForm, nil
}
if strings.Contains(contentType, "application/json") {
return Json, nil
}
if strings.Contains(contentType, "multipart/form-data") {
return Multipart, nil
}
2019-11-07 11:10:45 +00:00
return UnsupportedType, errors.New("content-type " + contentType + " is not supported, use application/x-www-form-urlencoded or multipart/form-data")
2019-11-07 10:00:24 +00:00
}
return UnsupportedType, errors.New("content-type is not provided in the request")
}