Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Endpoint and UI improvements to update client name #164

Merged
merged 2 commits into from
Mar 16, 2019
Merged
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
60 changes: 60 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type ClientDatabase interface {
GetClientByID(id uint) *model.Client
GetClientsByUser(userID uint) []*model.Client
DeleteClientByID(id uint) error
UpdateClient(client *model.Client) error
}

// The ClientAPI provides handlers for managing clients and applications.
Expand All @@ -24,6 +25,65 @@ type ClientAPI struct {
NotifyDeleted func(uint, string)
}

// UpdateClient updates a client by its id.
// swagger:operation PUT /client/{id} client updateClient
//
// Update a client.
//
// ---
// consumes: [application/json]
// produces: [application/json]
// security: [clientTokenHeader: [], clientTokenQuery: [], basicAuth: []]
// parameters:
// - name: body
// in: body
// description: the client to update
// required: true
// schema:
// $ref: "#/definitions/Client"
// - name: id
// in: path
// description: the client id
// required: true
// type: integer
// responses:
// 200:
// description: Ok
// schema:
// $ref: "#/definitions/Client"
// 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 *ClientAPI) UpdateClient(ctx *gin.Context) {
withID(ctx, "id", func(id uint) {
if client := a.DB.GetClientByID(id); client != nil && client.UserID == auth.GetUserID(ctx) {
newValues := &model.Client{}
if err := ctx.Bind(newValues); err == nil {
client.Name = newValues.Name

a.DB.UpdateClient(client)

ctx.JSON(200, client)
}
} else {
ctx.AbortWithError(404, fmt.Errorf("client with id %d doesn't exists", id))
}
})
}

// CreateClient creates a client and returns the access token.
// swagger:operation POST /client client createClient
//
Expand Down
34 changes: 34 additions & 0 deletions api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,40 @@ func (s *ClientSuite) Test_DeleteClient() {
assert.True(s.T(), s.notified)
}

func (s *ClientSuite) Test_UpdateClient_expectSuccess() {
s.db.User(5).NewClientWithToken(1, firstClientToken)

test.WithUser(s.ctx, 5)
s.withFormData("name=firefox")
s.ctx.Params = gin.Params{{Key: "id", Value: "1"}}
s.a.UpdateClient(s.ctx)

expected := &model.Client{
ID: 1,
Token: firstClientToken,
UserID: 5,
Name: "firefox",
}

assert.Equal(s.T(), 200, s.recorder.Code)
assert.Equal(s.T(), expected, s.db.GetClientByID(1))
}

func (s *ClientSuite) Test_UpdateClient_expectNotFound() {
test.WithUser(s.ctx, 5)
s.ctx.Params = gin.Params{{Key: "id", Value: "2"}}
s.a.UpdateClient(s.ctx)

assert.Equal(s.T(), 404, s.recorder.Code)
}

func (s *ClientSuite) Test_UpdateClient_WithMissingAttributes_expectBadRequest() {
test.WithUser(s.ctx, 5)
s.a.UpdateClient(s.ctx)

assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *ClientSuite) withFormData(formData string) {
s.ctx.Request = httptest.NewRequest("POST", "/token", strings.NewReader(formData))
s.ctx.Request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
Expand Down
5 changes: 5 additions & 0 deletions database/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,8 @@ func (d *GormDatabase) GetClientsByUser(userID uint) []*model.Client {
func (d *GormDatabase) DeleteClientByID(id uint) error {
return d.DB.Where("id = ?", id).Delete(&model.Client{}).Error
}

// UpdateClient updates a client.
func (d *GormDatabase) UpdateClient(client *model.Client) error {
return d.DB.Save(client).Error
}
5 changes: 5 additions & 0 deletions database/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ func (s *DatabaseSuite) TestClient() {
newClient = s.db.GetClientByToken(client.Token)
assert.Equal(s.T(), client, newClient)

updateClient := &model.Client{ID: client.ID, UserID: user.ID, Token: "C0000000000", Name: "new_name"}
s.db.UpdateClient(updateClient)
updatedClient := s.db.GetClientByID(client.ID)
assert.Equal(s.T(), updateClient, updatedClient)

s.db.DeleteClientByID(client.ID)

clients = s.db.GetClientsByUser(user.ID)
Expand Down
2 changes: 1 addition & 1 deletion docs/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//
// Schemes: http, https
// Host: localhost
// Version: 2.0.0
// Version: 2.0.1
// License: MIT https://github.com/gotify/server/blob/master/LICENSE
//
// Consumes:
Expand Down
76 changes: 75 additions & 1 deletion docs/spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"name": "MIT",
"url": "https://github.com/gotify/server/blob/master/LICENSE"
},
"version": "2.0.0"
"version": "2.0.1"
},
"host": "localhost",
"paths": {
Expand Down Expand Up @@ -599,6 +599,80 @@
}
},
"/client/{id}": {
"put": {
"security": [
{
"clientTokenHeader": []
},
{
"clientTokenQuery": []
},
{
"basicAuth": []
}
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"client"
],
"summary": "Update a client.",
"operationId": "updateClient",
"parameters": [
{
"description": "the client to update",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/Client"
}
},
{
"type": "integer",
"description": "the client id",
"name": "id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "Ok",
"schema": {
"$ref": "#/definitions/Client"
}
},
"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"
}
}
}
},
"delete": {
"security": [
{
Expand Down
2 changes: 2 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Co
client.POST("", clientHandler.CreateClient)

client.DELETE("/:id", clientHandler.DeleteClient)

client.PUT("/:id", clientHandler.UpdateClient)
}

message := clientAuth.Group("/message")
Expand Down
7 changes: 7 additions & 0 deletions ui/src/client/ClientStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ export class ClientStore extends BaseStore<IClient> {
.then(() => this.snack('Client deleted'));
}

@action
public update = async (id: number, name: string): Promise<void> => {
await axios.put(`${config.get('url')}client/${id}`, {name});
await this.refresh();
this.snack('Client updated');
};

@action
public createNoNotifcation = async (name: string): Promise<IClient> => {
const client = await axios.post(`${config.get('url')}client`, {name});
Expand Down
22 changes: 21 additions & 1 deletion ui/src/client/Clients.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Delete from '@material-ui/icons/Delete';
import Edit from '@material-ui/icons/Edit';
import React, {Component, SFC} from 'react';
import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage';
import ToggleVisibility from '../common/ToggleVisibility';
import AddClientDialog from './AddClientDialog';
import UpdateDialog from './UpdateClientDialog';
import {observer} from 'mobx-react';
import {observable} from 'mobx';
import {inject, Stores} from '../inject';
Expand All @@ -22,12 +24,15 @@ class Clients extends Component<Stores<'clientStore'>> {
private showDialog = false;
@observable
private deleteId: false | number = false;
@observable
private updateId: false | number = false;

public componentDidMount = () => this.props.clientStore.refresh();

public render() {
const {
deleteId,
updateId,
showDialog,
props: {clientStore},
} = this;
Expand All @@ -47,6 +52,7 @@ class Clients extends Component<Stores<'clientStore'>> {
<TableCell>Name</TableCell>
<TableCell style={{width: 200}}>token</TableCell>
<TableCell />
<TableCell />
</TableRow>
</TableHead>
<TableBody>
Expand All @@ -56,6 +62,7 @@ class Clients extends Component<Stores<'clientStore'>> {
key={client.id}
name={client.name}
value={client.token}
fEdit={() => (this.updateId = client.id)}
fDelete={() => (this.deleteId = client.id)}
/>
);
Expand All @@ -70,6 +77,13 @@ class Clients extends Component<Stores<'clientStore'>> {
fOnSubmit={clientStore.create}
/>
)}
{updateId !== false && (
<UpdateDialog
fClose={() => (this.updateId = false)}
fOnSubmit={(name) => clientStore.update(updateId, name)}
initialName={clientStore.getByID(updateId).name}
/>
)}
{deleteId !== false && (
<ConfirmDialog
title="Confirm Delete"
Expand All @@ -86,10 +100,11 @@ class Clients extends Component<Stores<'clientStore'>> {
interface IRowProps {
name: string;
value: string;
fEdit: VoidFunction;
fDelete: VoidFunction;
}

const Row: SFC<IRowProps> = ({name, value, fDelete}) => (
const Row: SFC<IRowProps> = ({name, value, fEdit, fDelete}) => (
<TableRow>
<TableCell>{name}</TableCell>
<TableCell>
Expand All @@ -99,6 +114,11 @@ const Row: SFC<IRowProps> = ({name, value, fDelete}) => (
/>
</TableCell>
<TableCell numeric padding="none">
<IconButton onClick={fEdit} className="edit">
<Edit />
</IconButton>
</TableCell>
<TableCell>
<IconButton onClick={fDelete} className="delete">
<Delete />
</IconButton>
Expand Down
Loading