Skip to content
This repository was archived by the owner on Sep 2, 2024. It is now read-only.

Commit 665dc6b

Browse files
committed
added db increase and allowed sending email for verified domain
1 parent 1d2e2d9 commit 665dc6b

File tree

10 files changed

+159
-19
lines changed

10 files changed

+159
-19
lines changed

Makefile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ start: build
88
@./cmd/staticbackend
99

1010
deploy: build
11-
@cd cmd && rm -rf staticbackend && CGO_ENABLED=0 go build -o staticbackend
1211
scp cmd/staticbackend sb-poc:/home/dstpierre/sb
1312
scp -qr ./templates/* sb-poc:/home/dstpierre/templates/
1413

db.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,36 @@ func (database *Database) update(w http.ResponseWriter, r *http.Request) {
251251
respond(w, http.StatusOK, result)
252252
}
253253

254+
func (database *Database) increase(w http.ResponseWriter, r *http.Request) {
255+
conf, auth, err := middleware.Extract(r, true)
256+
if err != nil {
257+
http.Error(w, err.Error(), http.StatusBadRequest)
258+
return
259+
}
260+
261+
curDB := database.client.Database(conf.Name)
262+
263+
// /db/col/id
264+
col := getURLPart(r.URL.Path, 2)
265+
id := getURLPart(r.URL.Path, 3)
266+
267+
var v = new(struct {
268+
Field string `json:"field"`
269+
Range int `json:"range"`
270+
})
271+
if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
272+
http.Error(w, err.Error(), http.StatusInternalServerError)
273+
return
274+
}
275+
276+
if err := database.base.Increase(auth, curDB, col, id, v.Field, v.Range); err != nil {
277+
http.Error(w, err.Error(), http.StatusInternalServerError)
278+
return
279+
}
280+
281+
respond(w, http.StatusOK, true)
282+
}
283+
254284
func (database *Database) del(w http.ResponseWriter, r *http.Request) {
255285
conf, auth, err := middleware.Extract(r, true)
256286
if err != nil {

db/base.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,50 @@ func (b *Base) Update(auth internal.Auth, db *mongo.Database, col, id string, do
323323
return result, nil
324324
}
325325

326+
func (b *Base) Increase(auth internal.Auth, db *mongo.Database, col, id, field string, n int) error {
327+
oid, err := primitive.ObjectIDFromHex(id)
328+
if err != nil {
329+
return err
330+
}
331+
332+
filter := bson.M{internal.FieldID: oid}
333+
334+
// if they are not "root", we use permission
335+
if auth.Role < 100 {
336+
switch internal.WritePermission(col) {
337+
case internal.PermGroup:
338+
filter[internal.FieldAccountID] = auth.AccountID
339+
case internal.PermOwner:
340+
filter[internal.FieldAccountID] = auth.AccountID
341+
filter[internal.FieldOwnerID] = auth.UserID
342+
}
343+
}
344+
345+
update := bson.M{"$inc": bson.M{field: n}}
346+
347+
ctx := context.Background()
348+
res := db.Collection(col).FindOneAndUpdate(ctx, filter, update)
349+
if err := res.Err(); err != nil {
350+
return err
351+
}
352+
353+
var result bson.M
354+
sr := db.Collection(col).FindOne(ctx, filter)
355+
if err := sr.Decode(&result); err != nil {
356+
return err
357+
} else if err := sr.Err(); err != nil {
358+
return err
359+
}
360+
361+
result["id"] = result[internal.FieldID]
362+
delete(result, internal.FieldID)
363+
delete(result, internal.FieldOwnerID)
364+
365+
b.PublishDocument("db-"+col, internal.MsgTypeDBUpdated, result)
366+
367+
return nil
368+
}
369+
326370
func (b *Base) Delete(auth internal.Auth, db *mongo.Database, col, id string) (int64, error) {
327371
oid, err := primitive.ObjectIDFromHex(id)
328372
if err != nil {

db_test.go

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import (
1313
"time"
1414
)
1515

16-
// dbPost post on behalf of adminToken by default (use params[0] true for root)
17-
func dbPost(t *testing.T, hf func(http.ResponseWriter, *http.Request), repo string, v interface{}, params ...bool) *http.Response {
16+
// dbReq post on behalf of adminToken by default (use params[0] true for root)
17+
func dbReq(t *testing.T, hf func(http.ResponseWriter, *http.Request), method, path string, v interface{}, params ...bool) *http.Response {
1818
if params == nil {
1919
params = make([]bool, 0)
2020
}
@@ -28,7 +28,7 @@ func dbPost(t *testing.T, hf func(http.ResponseWriter, *http.Request), repo stri
2828
t.Fatal("error marshaling post data:", err)
2929
}
3030

31-
req := httptest.NewRequest("POST", "/db/"+repo, bytes.NewReader(b))
31+
req := httptest.NewRequest(method, path, bytes.NewReader(b))
3232
w := httptest.NewRecorder()
3333

3434
req.Header.Set("SB-PUBLIC-KEY", pubKey)
@@ -97,6 +97,7 @@ type Task struct {
9797
Title string `json:"title"`
9898
Done bool `json:"done"`
9999
Created time.Time `json:"created"`
100+
Count int `json:"count"`
100101
}
101102

102103
func TestDBCreate(t *testing.T) {
@@ -106,7 +107,8 @@ func TestDBCreate(t *testing.T) {
106107
Created: time.Now(),
107108
}
108109

109-
resp := dbPost(t, database.add, "tasks", task)
110+
resp := dbReq(t, database.add, "POST", "/db/tasks", task)
111+
defer resp.Body.Close()
110112

111113
if resp.StatusCode > 299 {
112114
t.Fatal(GetResponseBody(t, resp))
@@ -154,3 +156,49 @@ func TestDBListCollections(t *testing.T) {
154156
t.Errorf("expected len to be > than 2 got %d", len(names))
155157
}
156158
}
159+
160+
func TestDBIncrease(t *testing.T) {
161+
task :=
162+
Task{
163+
Title: "item created",
164+
Created: time.Now(),
165+
Count: 1,
166+
}
167+
168+
resp := dbReq(t, database.add, "POST", "/db/tasks", task)
169+
defer resp.Body.Close()
170+
171+
if resp.StatusCode > 299 {
172+
t.Fatal(GetResponseBody(t, resp))
173+
}
174+
175+
var createdTask Task
176+
if err := parseBody(resp.Body, &createdTask); err != nil {
177+
t.Fatal(err)
178+
}
179+
180+
var data = new(struct {
181+
Field string `json:"field"`
182+
Range int `json:"range"`
183+
})
184+
data.Field = "count"
185+
data.Range = 4
186+
187+
resp = dbReq(t, database.increase, "PUT", "/inc/tasks/"+createdTask.ID, data)
188+
189+
if resp.StatusCode > 299 {
190+
t.Fatal(GetResponseBody(t, resp))
191+
}
192+
193+
resp = dbReq(t, database.get, "GET", "/db/tasks/"+createdTask.ID, nil)
194+
if resp.StatusCode > 299 {
195+
t.Fatal(GetResponseBody(t, resp))
196+
}
197+
198+
var increased Task
199+
if err := parseBody(resp.Body, &increased); err != nil {
200+
t.Fatal(err)
201+
} else if increased.Count != 5 {
202+
t.Errorf("expected count to be 5 got %d", increased.Count)
203+
}
204+
}

email/ses.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ func (AWSSES) Send(data internal.SendMailData) error {
3434
// Create an SES session.
3535
svc := ses.New(sess)
3636

37+
from := fmt.Sprintf("%s <%s>", data.FromName, data.From)
38+
3739
// Assemble the email.
3840
input := &ses.SendEmailInput{
3941
Destination: &ses.Destination{
@@ -58,7 +60,7 @@ func (AWSSES) Send(data internal.SendMailData) error {
5860
Data: aws.String(data.Subject),
5961
},
6062
},
61-
Source: aws.String(data.From),
63+
Source: aws.String(from),
6264
ReplyToAddresses: aws.StringSlice([]string{data.ReplyTo}),
6365
// Uncomment to use a configuration set
6466
//ConfigurationSetName: aws.String(ConfigurationSet),

functions_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func TestFunctionsExecuteDBOperations(t *testing.T) {
6868
Code: code,
6969
TriggerTopic: "web",
7070
}
71-
addResp := dbPost(t, funexec.add, "", data, true)
71+
addResp := dbReq(t, funexec.add, "POST", "/", data, true)
7272
if addResp.StatusCode != http.StatusOK {
7373
b, err := io.ReadAll(addResp.Body)
7474
if err != nil {
@@ -80,7 +80,7 @@ func TestFunctionsExecuteDBOperations(t *testing.T) {
8080
t.Errorf("add: expected status 200 got %s", addResp.Status)
8181
}
8282

83-
execResp := dbPost(t, funexec.exec, "", data, true)
83+
execResp := dbReq(t, funexec.exec, "POST", "/", data, true)
8484
if execResp.StatusCode != http.StatusOK {
8585
b, err := io.ReadAll(execResp.Body)
8686
if err != nil {

hub_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ func TestWebSocketDBEvents(t *testing.T) {
208208
Title: "websocket test",
209209
Created: time.Now(),
210210
}
211-
resp := dbPost(t, database.add, "test", task)
211+
resp := dbReq(t, database.add, "POST", "/db/test", task)
212212
if resp.StatusCode > 299 {
213213
t.Fatal(GetResponseBody(t, resp))
214214
}
@@ -290,7 +290,7 @@ func TestWebSocketDBPermission(t *testing.T) {
290290
Title: "websocket test",
291291
Created: time.Now(),
292292
}
293-
resp := dbPost(t, database.add, "permtest_700_", task)
293+
resp := dbReq(t, database.add, "POST", "/db/permtest_700_", task)
294294
if resp.StatusCode > 299 {
295295
t.Fatal(GetResponseBody(t, resp))
296296
}

sendmail.go

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,6 @@ func sudoSendMail(w http.ResponseWriter, r *http.Request) {
1717
return
1818
}
1919

20-
// all email are sent from the env var MAIL_FROM
21-
from := data.From
22-
if len(data.ReplyTo) > 0 {
23-
from = data.ReplyTo
24-
}
25-
26-
data.From = FromEmail
27-
data.ReplyTo = from
28-
2920
// if only body is provided
3021
if len(data.Body) > 0 {
3122
data.HTMLBody = data.Body

sendmail_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package staticbackend
2+
3+
import (
4+
"staticbackend/email"
5+
"staticbackend/internal"
6+
"testing"
7+
)
8+
9+
func Test_Sendmail_AWS(t *testing.T) {
10+
emailer := &email.AWSSES{}
11+
12+
data := internal.SendMailData{
13+
FromName: "My name here",
14+
15+
16+
ToName: "Dominic St-Pierre",
17+
Subject: "From unit test",
18+
HTMLBody: "<h1>hello</h1><p>working</p>",
19+
TextBody: "Hello\nworking",
20+
ReplyTo: "[email protected]",
21+
}
22+
if err := emailer.Send(data); err != nil {
23+
t.Error(err)
24+
}
25+
}

server.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ func Start(dbHost, port string) {
133133
// database routes
134134
http.Handle("/db/", middleware.Chain(http.HandlerFunc(database.dbreq), stdAuth...))
135135
http.Handle("/query/", middleware.Chain(http.HandlerFunc(database.query), stdAuth...))
136+
http.Handle("/inc/", middleware.Chain(http.HandlerFunc(database.increase), stdAuth...))
136137
http.Handle("/sudoquery/", middleware.Chain(http.HandlerFunc(database.query), stdRoot...))
137138
http.Handle("/sudolistall/", middleware.Chain(http.HandlerFunc(database.listCollections), stdRoot...))
138139
http.Handle("/sudo/", middleware.Chain(http.HandlerFunc(database.dbreq), stdRoot...))

0 commit comments

Comments
 (0)