summaryrefslogtreecommitdiff
path: root/api/api_keys.go
diff options
context:
space:
mode:
Diffstat (limited to 'api/api_keys.go')
-rw-r--r--api/api_keys.go84
1 files changed, 84 insertions, 0 deletions
diff --git a/api/api_keys.go b/api/api_keys.go
new file mode 100644
index 0000000..17ed6c9
--- /dev/null
+++ b/api/api_keys.go
@@ -0,0 +1,84 @@
+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)
+ }
+}