server.go 1.88 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package server

import (
	"log"
	"net/http"

	"git.autistici.org/ai3/go-common/serverutil"

	"git.autistici.org/id/keystore"
)

var emptyResponse struct{}

type keyStoreServer struct {
15
	*KeyStore
ale's avatar
ale committed
16
17
18
19
20
21
22
23
24
25
26
}

func (s *keyStoreServer) handleOpen(w http.ResponseWriter, r *http.Request) {
	var req keystore.OpenRequest
	if !serverutil.DecodeJSONRequest(w, r, &req) {
		return
	}

	err := s.KeyStore.Open(r.Context(), req.Username, req.Password, req.TTL)
	if err != nil {
		log.Printf("Open(%s) error: %v", req.Username, err)
27
		http.Error(w, err.Error(), http.StatusInternalServerError)
ale's avatar
ale committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
		return
	}

	serverutil.EncodeJSONResponse(w, &emptyResponse)
}

func (s *keyStoreServer) handleGet(w http.ResponseWriter, r *http.Request) {
	var req keystore.GetRequest
	if !serverutil.DecodeJSONRequest(w, r, &req) {
		return
	}

	key, err := s.KeyStore.Get(req.Username, req.SSOTicket)
	if err != nil {
		log.Printf("Get(%s) error: %v", req.Username, err)
43
44
45
46
47
48
49
50
51
		// Return an appropriate error code.
		switch err {
		case errUnauthorized, errBadUser:
			http.Error(w, err.Error(), http.StatusUnauthorized)
		case errNoKeys:
			http.NotFound(w, r)
		default:
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
ale's avatar
ale committed
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
		return
	}

	serverutil.EncodeJSONResponse(w, &keystore.GetResponse{Key: key})
}

func (s *keyStoreServer) handleClose(w http.ResponseWriter, r *http.Request) {
	var req keystore.CloseRequest
	if !serverutil.DecodeJSONRequest(w, r, &req) {
		return
	}

	s.KeyStore.Close(req.Username)

	serverutil.EncodeJSONResponse(w, &emptyResponse)
}

func (s *keyStoreServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/api/open":
		s.handleOpen(w, r)
	case "/api/get_key":
		s.handleGet(w, r)
	case "/api/close":
		s.handleClose(w, r)
	default:
		http.NotFound(w, r)
	}
}

82
83
// NewServer wraps the HTTP API around a KeyStore.
func NewServer(ks *KeyStore) http.Handler {
ale's avatar
ale committed
84
85
	return &keyStoreServer{ks}
}