Micropub endpoint for my blog https://jlelse.blog/posts/hugo-micropub/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

97 lines
2.4 KiB

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
client := http.DefaultClient
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
res, err := client.Do(req)
if err != nil {
return false, errors.New("error sending the request for checking token access")
}
// parse the response
indieAuthRes := &IndieAuthRes{}
err = json.NewDecoder(res.Body).Decode(&indieAuthRes)
res.Body.Close()
if err != nil {
return false, errors.New("Error parsing the response into json for checking token access " + err.Error())
}
// verify results of the response
if indieAuthRes.Me != BlogUrl {
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
}
func CheckAuthorization(token string) bool {
if ok, err := checkAccess(token); ok {
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
}
return UnsupportedType, errors.New("content-type " + contentType + " is not supported, use application/x-www-form-urlencoded or multipart/form-data")
}
return UnsupportedType, errors.New("content-type is not provided in the request")
}