hatecomputers.club/api/api_keys.go

85 lines
2.4 KiB
Go

package api
import (
"log"
"net/http"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/database"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/utils"
)
const MAX_USER_API_KEYS = 5
func ListAPIKeysContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain {
return func(success Continuation, failure Continuation) ContinuationChain {
apiKeys, err := database.ListUserAPIKeys(context.DBConn, context.User.ID)
if err != nil {
log.Println(err)
resp.WriteHeader(http.StatusInternalServerError)
return failure(context, req, resp)
}
(*context.TemplateData)["APIKeys"] = apiKeys
return success(context, req, resp)
}
}
func CreateAPIKeyContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain {
return func(success Continuation, failure Continuation) ContinuationChain {
formErrors := FormError{
Errors: []string{},
}
apiKeys, err := database.ListUserAPIKeys(context.DBConn, context.User.ID)
if err != nil {
log.Println(err)
resp.WriteHeader(http.StatusInternalServerError)
return failure(context, req, resp)
}
if len(apiKeys) >= MAX_USER_API_KEYS {
formErrors.Errors = append(formErrors.Errors, "max api keys reached")
}
_, err = database.SaveAPIKey(context.DBConn, &database.UserApiKey{
UserID: context.User.ID,
Key: utils.RandomId(),
})
if err != nil {
log.Println(err)
resp.WriteHeader(http.StatusInternalServerError)
return failure(context, req, resp)
}
http.Redirect(resp, req, "/keys", http.StatusFound)
return success(context, req, resp)
}
}
func DeleteAPIKeyContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain {
return func(success Continuation, failure Continuation) ContinuationChain {
key := req.FormValue("key")
apiKey, err := database.GetAPIKey(context.DBConn, key)
if err != nil {
log.Println(err)
resp.WriteHeader(http.StatusInternalServerError)
return failure(context, req, resp)
}
if (apiKey == nil) || (apiKey.UserID != context.User.ID) {
resp.WriteHeader(http.StatusUnauthorized)
return failure(context, req, resp)
}
err = database.DeleteAPIKey(context.DBConn, key)
if err != nil {
log.Println(err)
resp.WriteHeader(http.StatusInternalServerError)
return failure(context, req, resp)
}
http.Redirect(resp, req, "/keys", http.StatusFound)
return success(context, req, resp)
}
}