server.go 2.32 KB
Newer Older
1
2
3
4
5
6
7
package server

import (
	"fmt"
	"io/ioutil"
	"net/http"

8
	"github.com/go-chi/chi"
9
10
11
12
13
14
15
16
17
18
19
20
21
	"github.com/go-errors/errors"
	"github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/irmaserver"
	"github.com/privacybydesign/irmago/irmaserver/irmarequestor"
)

var server *http.Server

func Start(port int, conf *irmaserver.Configuration) error {
	if err := irmarequestor.Initialize(conf); err != nil {
		return err
	}

22
	router := chi.NewRouter()
23

24
25
	// Mount server for irmaclient
	router.Mount("/irma/", irmarequestor.HttpHandlerFunc("/irma/"))
26

27
28
29
30
	// Server routes
	router.Post("/create", handleCreate)
	router.Get("/status/{token}", handleStatus)
	router.Get("/result/{token}", handleResult)
31

32
33
	// Start server
	server = &http.Server{Addr: fmt.Sprintf(":%d", port), Handler: router}
34
35
36
37
38
39
40
41
	server.ListenAndServe()
	return nil
}

func Stop() {
	server.Close()
}

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
func handleCreate(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		irmaserver.WriteError(w, irmaserver.ErrorInvalidRequest, err.Error())
		return
	}
	request, err := parseRequest(body)
	if err != nil {
		irmaserver.WriteError(w, irmaserver.ErrorInvalidRequest, err.Error())
		return
	}

	qr, _, err := irmarequestor.StartSession(request, nil)
	if err != nil {
		irmaserver.WriteError(w, irmaserver.ErrorInvalidRequest, err.Error())
		return
	}

	irmaserver.WriteJson(w, qr)
}

func handleStatus(w http.ResponseWriter, r *http.Request) {
	res := irmarequestor.GetSessionResult(chi.URLParam(r, "token"))
	if res == nil {
		irmaserver.WriteError(w, irmaserver.ErrorSessionUnknown, "")
		return
	}
	irmaserver.WriteJson(w, res.Status)
}

func handleResult(w http.ResponseWriter, r *http.Request) {
	res := irmarequestor.GetSessionResult(chi.URLParam(r, "token"))
	if res == nil {
		irmaserver.WriteError(w, irmaserver.ErrorSessionUnknown, "")
		return
	}
	irmaserver.WriteJson(w, res)
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
}

func parseRequest(bts []byte) (request irma.SessionRequest, err error) {
	request = &irma.DisclosureRequest{}
	if err = irma.UnmarshalValidate(bts, request); err == nil {
		return request, nil
	}
	request = &irma.SignatureRequest{}
	if err = irma.UnmarshalValidate(bts, request); err == nil {
		return request, nil
	}
	request = &irma.IssuanceRequest{}
	if err = irma.UnmarshalValidate(bts, request); err == nil {
		return request, nil
	}
	return nil, errors.New("Invalid session type")
}