Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions api/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ type ApplicationParams struct {
//
// example: 5
DefaultPriority int `form:"defaultPriority" query:"defaultPriority" json:"defaultPriority"`
// Whether the application may update its own messages with its application token.
// Defaults to false on create. When omitted on update, the current value is kept.
//
// example: false
AllowMessageUpdate *bool `form:"allowMessageUpdate" query:"allowMessageUpdate" json:"allowMessageUpdate"`
// The sortKey for the application. Uses fractional indexing.
//
// example: a1
Expand Down Expand Up @@ -108,6 +113,9 @@ func (a *ApplicationAPI) CreateApplication(ctx *gin.Context) {
UserID: auth.GetUserID(ctx),
Internal: false,
}
if applicationParams.AllowMessageUpdate != nil {
app.AllowMessageUpdate = *applicationParams.AllowMessageUpdate
}

if err := a.DB.CreateApplication(&app); err != nil {
handleApplicationError(ctx, err)
Expand Down Expand Up @@ -273,6 +281,9 @@ func (a *ApplicationAPI) UpdateApplication(ctx *gin.Context) {
app.Description = applicationParams.Description
app.Name = applicationParams.Name
app.DefaultPriority = applicationParams.DefaultPriority
if applicationParams.AllowMessageUpdate != nil {
app.AllowMessageUpdate = *applicationParams.AllowMessageUpdate
}
if applicationParams.SortKey != "" {
app.SortKey = applicationParams.SortKey
}
Expand Down
53 changes: 52 additions & 1 deletion api/application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func (s *ApplicationSuite) Test_ensureApplicationHasCorrectJsonRepresentation()
SortKey: "a1",
CreatedAt: testdb.Now,
}
test.JSONEquals(s.T(), actual, `{"id":1,"token":"Aasdasfgeeg","name":"myapp","description":"mydesc", "image": "asd", "internal":true, "defaultPriority":0, "createdAt":"2020-01-01T00:00:00Z", "lastUsed":null, "sortKey":"a1"}`)
test.JSONEquals(s.T(), actual, `{"id":1,"token":"Aasdasfgeeg","name":"myapp","description":"mydesc", "image": "asd", "internal":true, "defaultPriority":0, "createdAt":"2020-01-01T00:00:00Z", "lastUsed":null, "sortKey":"a1", "allowMessageUpdate":false}`)
}

func (s *ApplicationSuite) Test_CreateApplication_expectBadRequestOnEmptyName() {
Expand Down Expand Up @@ -879,3 +879,54 @@ func (d *failingUpdateAppDB) UpdateApplication(*model.Application) error {
type errReader struct{ err error }

func (r errReader) Read([]byte) (int, error) { return 0, r.err }

func (s *ApplicationSuite) Test_CreateApplication_messageUpdatesDisabledByDefault() {
s.db.User(5)

test.WithUser(s.ctx, 5)
s.withFormData("name=app")
s.a.CreateApplication(s.ctx)

assert.Equal(s.T(), 200, s.recorder.Code)
if apps, err := s.db.GetApplicationsByUser(5); assert.NoError(s.T(), err) && assert.Len(s.T(), apps, 1) {
assert.False(s.T(), apps[0].AllowMessageUpdate)
}
}

func (s *ApplicationSuite) Test_CreateApplication_allowMessageUpdate() {
s.db.User(5)

test.WithUser(s.ctx, 5)
s.withFormData("name=app&allowMessageUpdate=true")
s.a.CreateApplication(s.ctx)

assert.Equal(s.T(), 200, s.recorder.Code)
if apps, err := s.db.GetApplicationsByUser(5); assert.NoError(s.T(), err) && assert.Len(s.T(), apps, 1) {
assert.True(s.T(), apps[0].AllowMessageUpdate)
}
}

func (s *ApplicationSuite) Test_UpdateApplication_allowMessageUpdate() {
s.db.User(5).NewAppWithToken(2, "app-2")
test.WithUser(s.ctx, 5)
s.ctx.Params = gin.Params{{Key: "id", Value: "2"}}

s.withFormData("name=name&allowMessageUpdate=true")
s.a.UpdateApplication(s.ctx)
assert.Equal(s.T(), 200, s.recorder.Code)
if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) {
assert.True(s.T(), app.AllowMessageUpdate)
}

s.withFormData("name=other")
s.a.UpdateApplication(s.ctx)
if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) {
assert.True(s.T(), app.AllowMessageUpdate, "omitting the field keeps the value")
}

s.withFormData("name=other&allowMessageUpdate=false")
s.a.UpdateApplication(s.ctx)
if app, err := s.db.GetApplicationByID(2); assert.NoError(s.T(), err) {
assert.False(s.T(), app.AllowMessageUpdate)
}
}
121 changes: 113 additions & 8 deletions api/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type MessageDatabase interface {
DeleteMessagesByUser(userID uint) error
DeleteMessagesByApplication(applicationID uint) error
CreateMessage(message *model.Message) error
UpdateMessage(message *model.Message) error
}

var timeNow = time.Now
Expand All @@ -33,10 +34,16 @@ type Notifier interface {
Notify(userID uint, message *model.MessageExternal)
}

// MessageNotifier notifies when a message was created or updated.
type MessageNotifier interface {
Notifier
NotifyUpdated(userID uint, message *model.MessageExternal)
}

// The MessageAPI provides handlers for managing messages.
type MessageAPI struct {
DB MessageDatabase
Notifier Notifier
Notifier MessageNotifier
}

type pagingParams struct {
Expand Down Expand Up @@ -390,8 +397,112 @@ func (a *MessageAPI) CreateMessage(ctx *gin.Context) {
ctx.JSON(200, created)
}

// UpdateMessage updates a message, authentication via application token is required.
// swagger:operation PUT /message/{id} message updateMessage
//
// Update a message.
//
// Updating has to be enabled per application (`allowMessageUpdate`), it is disabled
// by default. Otherwise 403 is returned.
//
// Only the application that created the message can update it. The message keeps
// its id and creation date. Title, message, priority and extras are replaced with
// the values from the request body, the same defaults as for creating a message apply:
// an omitted title or priority falls back to the application defaults and omitted
// extras are removed. Any "appid" in the body is ignored.
//
// Clients connected to the stream with `updates=true` receive the updated message.
//
// ---
// consumes: [application/json]
// produces: [application/json]
// security: [appTokenAuthorizationHeader: [], appTokenHeader: [], appTokenQuery: []]
// parameters:
// - name: id
// in: path
// description: the message id
// required: true
// type: integer
// format: int64
// - name: body
// in: body
// description: the new content of the message
// required: true
// schema:
// $ref: "#/definitions/CreateMessage"
// responses:
// 200:
// description: Ok
// schema:
// $ref: "#/definitions/Message"
// 400:
// description: Bad Request
// schema:
// $ref: "#/definitions/Error"
// 401:
// description: Unauthorized
// schema:
// $ref: "#/definitions/Error"
// 403:
// description: Forbidden
// schema:
// $ref: "#/definitions/Error"
// 404:
// description: Not Found
// schema:
// $ref: "#/definitions/Error"
func (a *MessageAPI) UpdateMessage(ctx *gin.Context) {
withID(ctx, "id", func(id uint) {
update := model.CreateMessage{}
if err := ctx.Bind(&update); err != nil {
return
}

app := auth.GetApplication(ctx)
if app == nil || !app.AllowMessageUpdate {
ctx.AbortWithError(403, errors.New("updating messages is not enabled for this application"))
return
}
msg, err := a.DB.GetMessageByID(id)
if success := successOrAbort(ctx, 500, err); !success {
return
}
if msg == nil || msg.ApplicationID != app.ID {
ctx.AbortWithError(404, errors.New("message does not exist"))
return
}

applyApplicationDefaults(app, &update)
updated := toInternalMessage(&update)
now := timeNow()
msg.Title = updated.Title
msg.Message = updated.Message
msg.Priority = updated.Priority
msg.Extras = updated.Extras
msg.Updated = &now
if success := successOrAbort(ctx, 500, a.DB.UpdateMessage(msg)); !success {
return
}

external := toExternalMessage(msg)
a.Notifier.NotifyUpdated(app.UserID, external)
ctx.JSON(200, external)
})
}

// createMessage fills in defaults from the application, stores the message and notifies the user.
func (a *MessageAPI) createMessage(app *model.Application, message *model.CreateMessage) (*model.MessageExternal, error) {
applyApplicationDefaults(app, message)
msgInternal := toInternalMessage(message)
if err := a.DB.CreateMessage(msgInternal); err != nil {
return nil, err
}
a.Notifier.Notify(app.UserID, toExternalMessage(msgInternal))
return toExternalMessage(msgInternal), nil
}

// applyApplicationDefaults sets the application id and fills in the title and priority from the application if unset.
func applyApplicationDefaults(app *model.Application, message *model.CreateMessage) {
message.ApplicationID = app.ID
if strings.TrimSpace(message.Title) == "" {
message.Title = app.Name
Expand All @@ -400,13 +511,6 @@ func (a *MessageAPI) createMessage(app *model.Application, message *model.Create
if message.Priority == nil {
message.Priority = &app.DefaultPriority
}

msgInternal := toInternalMessage(message)
if err := a.DB.CreateMessage(msgInternal); err != nil {
return nil, err
}
a.Notifier.Notify(app.UserID, toExternalMessage(msgInternal))
return toExternalMessage(msgInternal), nil
}

func toInternalMessage(msg *model.CreateMessage) *model.Message {
Expand Down Expand Up @@ -434,6 +538,7 @@ func toExternalMessage(msg *model.Message) *model.MessageExternal {
Title: msg.Title,
Priority: &msg.Priority,
Date: msg.Date,
Updated: msg.Updated,
}
if len(msg.Extras) != 0 {
res.Extras = make(map[string]any)
Expand Down
Loading