package keys import ( "log" "net/http" "git.hatecomputers.club/hatecomputers/hatecomputers.club/api/types" "git.hatecomputers.club/hatecomputers/hatecomputers.club/database" "git.hatecomputers.club/hatecomputers/hatecomputers.club/utils" ) const MAX_USER_API_KEYS = 5 func ListAPIKeysContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain { return func(success types.Continuation, failure types.Continuation) types.ContinuationChain { typesKeys, 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"] = typesKeys return success(context, req, resp) } } func CreateAPIKeyContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain { return func(success types.Continuation, failure types.Continuation) types.ContinuationChain { formErrors := types.FormError{ Errors: []string{}, } numKeys, err := database.CountUserAPIKeys(context.DBConn, context.User.ID) if err != nil { log.Println(err) resp.WriteHeader(http.StatusInternalServerError) return failure(context, req, resp) } if numKeys >= MAX_USER_API_KEYS { formErrors.Errors = append(formErrors.Errors, "max types keys reached") } if len(formErrors.Errors) > 0 { (*context.TemplateData)["FormError"] = formErrors return failure(context, req, resp) } _, 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) } return success(context, req, resp) } } func DeleteAPIKeyContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain { return func(success types.Continuation, failure types.Continuation) types.ContinuationChain { key := req.FormValue("key") typesKey, err := database.GetAPIKey(context.DBConn, key) if err != nil { log.Println(err) resp.WriteHeader(http.StatusInternalServerError) return failure(context, req, resp) } if (typesKey == nil) || (typesKey.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) } }