summaryrefslogtreecommitdiff
path: root/api/api_keys.go
blob: d63604416417e8f4c8613a9e86d0833bfc51e2fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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{},
		}

		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 api 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 *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)
	}
}