summaryrefslogtreecommitdiff
path: root/pkg/rest/mailbox.go
blob: 874ecaa8e769b534d530fcaeba31f2eeccbcf49c (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// This file is part of taler-mailbox, the Taler Mailbox implementation.
// Copyright (C) 2022 Martin Schanzenbach
//
// Taler-mailbox is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Taler-mailbox is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later

package mailbox

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/gorilla/mux"
	"gopkg.in/ini.v1"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"taler.net/taler-go.git/pkg/merchant"
	tos "taler.net/taler-go.git/pkg/rest"
)

// Mailbox is the primary object of the Mailbox service
type Mailbox struct {

	// The main router
	Router *mux.Router

	// The main DB handle
	Db *gorm.DB

	// Our configuration from the config.json
	Cfg *ini.File

	// Merchant object
	Merchant merchant.Merchant
}

// VersionResponse is the JSON response of the /config enpoint
type VersionResponse struct {
	// libtool-style representation of the Merchant protocol version, see
	// https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning
	// The format is "current:revision:age".
	Version string `json:"version"`

	// Name of the protocol.
	Name string `json:"name"` // "taler-mailbox"

	// fee for one month of registration
	MessageFee string `json:"message_fee"`

	// How long will the service store a message
	// before giving up
	DeliveryPeriod uint64 `josn:"delivery_period"`
}

// MailboxRateLimitedResponse is the JSON response when a rate limit is hit
type MailboxRateLimitedResponse struct {

	// Taler error code, TALER_EC_mailbox_REGISTER_RATE_LIMITED.
	Code int `json:"code"`

	// When the client should retry. Currently: In microseconds
	RetryDelay int64 `json:"retry_delay"`

	// The human readable error message.
	Hint string `json:"hint"`
}

type message struct {
	// ORM
	gorm.Model `json:"-"`
}

func (m *Mailbox) configResponse(w http.ResponseWriter, r *http.Request) {
	dpStr := m.Cfg.Section("mailbox").Key("delivery_period").MustString("1w")
	dp, err := time.ParseDuration(dpStr)
	if err != nil {
		log.Fatal(err)
	}

	cfg := VersionResponse{
		Version:        "0:0:0",
		Name:           "taler-mailbox",
		MessageFee:     m.Cfg.Section("mailbox").Key("message_fee").MustString("KUDOS:1"),
		DeliveryPeriod: uint64(dp.Microseconds()),
	}
	w.Header().Set("Content-Type", "application/json")
	response, _ := json.Marshal(cfg)
	w.Write(response)
}

func (m *Mailbox) termsResponse(w http.ResponseWriter, r *http.Request) {
	tos.ServiceTermsResponse(m.Cfg.Section("mailbox"), w, r)
}

func (m *Mailbox) privacyResponse(w http.ResponseWriter, r *http.Request) {
	tos.PrivacyPolicyResponse(m.Cfg.Section("mailbox"), w, r)
}

func (m *Mailbox) setupHandlers() {
	m.Router = mux.NewRouter().StrictSlash(true)

	/* ToS API */
	m.Router.HandleFunc("/terms", m.termsResponse).Methods("GET")
	m.Router.HandleFunc("/privacy", m.privacyResponse).Methods("GET")

	/* Config API */
	m.Router.HandleFunc("/config", m.configResponse).Methods("GET")

}

// Initialize the Mailbox instance with cfgfile
func (m *Mailbox) Initialize(cfgfile string) {
	_cfg, err := ini.Load(cfgfile)
	if err != nil {
		fmt.Printf("Failed to read config: %v", err)
		os.Exit(1)
	}
	m.Cfg = _cfg
	if m.Cfg.Section("mailbox").Key("production").MustBool(false) {
		fmt.Println("Production mode enabled")
	}

	psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		m.Cfg.Section("mailbox-pq").Key("host").MustString("localhost"),
		m.Cfg.Section("mailbox-pq").Key("port").MustInt64(5432),
		m.Cfg.Section("mailbox-pq").Key("user").MustString("taler-mailbox"),
		m.Cfg.Section("mailbox-pq").Key("password").MustString("secret"),
		m.Cfg.Section("mailbox-pq").Key("db_name").MustString("taler-mailbox"))
	_db, err := gorm.Open(postgres.Open(psqlconn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		panic(err)
	}
	m.Db = _db
	if err := m.Db.AutoMigrate(&message{}); err != nil {
		panic(err)
	}

	merchURL := m.Cfg.Section("mailbox").Key("merchant_baseurl_private").MustString("http://merchant.mailbox/instances/myInstance")
	merchToken := m.Cfg.Section("mailbox").Key("merchant_token").MustString("secretAccessToken")
	m.Merchant = merchant.NewMerchant(merchURL, merchToken)
	m.setupHandlers()
}