aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md6
-rw-r--r--go.mod3
-rw-r--r--go.sum2
-rw-r--r--pkg/database/migrations.go6
-rw-r--r--pkg/database/sessions.go33
-rw-r--r--pkg/database/sessions_test.go89
6 files changed, 138 insertions, 1 deletions
diff --git a/README.md b/README.md
index 4015f95..1ea91cb 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,7 @@ A personal instance runs at https://trains.adyxax.org/.
- [Configuration](#configuration)
- [Usage](#usage)
- [Building](#building)
+- [Design Choices](#design-choices)
- [References](#references)
## Dependencies
@@ -78,6 +79,11 @@ To cross-compile for another os or architecture, use :
GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w" ./cmd/trains-webui/
```
+## Design Choices
+
+- Being a small webapp, the only database supported for now is sqlite3
+- Being a small webapp with no expectation of traffic and for simplicity, the user sessions are currently stored in the database
+
## References
- https://www.digital.sncf.com/startup/api
diff --git a/go.mod b/go.mod
index 408cb0c..7d05ed5 100644
--- a/go.mod
+++ b/go.mod
@@ -5,10 +5,11 @@ go 1.16
require (
github.com/DATA-DOG/go-sqlmock v1.5.0
github.com/davecgh/go-spew v1.1.1 // indirect
+ github.com/google/uuid v1.2.0 // indirect
github.com/kr/pretty v0.2.1 // indirect
github.com/mattn/go-sqlite3 v1.14.6
github.com/stretchr/testify v1.7.0
- golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect
+ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
)
diff --git a/go.sum b/go.sum
index c5b34c2..cea06dc 100644
--- a/go.sum
+++ b/go.sum
@@ -3,6 +3,8 @@ github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
+github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
diff --git a/pkg/database/migrations.go b/pkg/database/migrations.go
index 8cc6420..7de255a 100644
--- a/pkg/database/migrations.go
+++ b/pkg/database/migrations.go
@@ -17,6 +17,12 @@ var allMigrations = []func(tx *sql.Tx) error{
email TEXT,
created_at DATE DEFAULT (datetime('now')),
last_login_at DATE DEFAULT NULL
+ );
+ CREATE TABLE sessions (
+ token TEXT NOT NULL UNIQUE,
+ user_id INTEGER NOT NULL,
+ created_at DATE DEFAULT (datetime('now')),
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);`
_, err = tx.Exec(sql)
return err
diff --git a/pkg/database/sessions.go b/pkg/database/sessions.go
new file mode 100644
index 0000000..72930f0
--- /dev/null
+++ b/pkg/database/sessions.go
@@ -0,0 +1,33 @@
+package database
+
+import (
+ "git.adyxax.org/adyxax/trains/pkg/model"
+ "github.com/google/uuid"
+)
+
+func (env *DBEnv) CreateSession(user *model.User) (*string, error) {
+ token := uuid.NewString()
+
+ query := `
+ INSERT INTO sessions
+ (token, user_id)
+ VALUES
+ ($1, $2);`
+ tx, err := env.db.Begin()
+ if err != nil {
+ return nil, newTransactionError("Could not Begin()", err)
+ }
+ _, err = tx.Exec(
+ query,
+ token,
+ user.Id,
+ )
+ if err != nil {
+ tx.Rollback()
+ return nil, newQueryError("Could not run database query: most likely the token already exists in database, or the user id does not exist", err)
+ }
+ if err := tx.Commit(); err != nil {
+ return nil, newTransactionError("Could not commit transaction", err)
+ }
+ return &token, nil
+}
diff --git a/pkg/database/sessions_test.go b/pkg/database/sessions_test.go
new file mode 100644
index 0000000..0b6a370
--- /dev/null
+++ b/pkg/database/sessions_test.go
@@ -0,0 +1,89 @@
+package database
+
+import (
+ "reflect"
+ "testing"
+
+ "git.adyxax.org/adyxax/trains/pkg/model"
+ "github.com/DATA-DOG/go-sqlmock"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestCreateSession(t *testing.T) {
+ // test db setup
+ db, err := InitDB("sqlite3", "file::memory:?_foreign_keys=on")
+ require.NoError(t, err)
+ err = db.Migrate()
+ require.NoError(t, err)
+ userReg1 := model.UserRegistration{
+ Username: "user1",
+ Password: "user1_pass",
+ Email: "user1",
+ }
+ user1, err := db.CreateUser(&userReg1)
+ require.NoError(t, err)
+ user2 := *user1
+ user2.Id++ // we want a token request for an invalid user id
+ // Test cases
+ testCases := []struct {
+ name string
+ input *model.User
+ expectedError interface{}
+ }{
+ {"Normal user", user1, nil},
+ {"A normal user can request multiple tokens", user1, nil},
+ {"a non existant user id triggers an error", &user2, &QueryError{}},
+ }
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ valid, err := db.CreateSession(tc.input)
+ if tc.expectedError != nil {
+ require.Error(t, err)
+ assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError))
+ require.Nil(t, valid)
+ } else {
+ require.NoError(t, err)
+ assert.NotNil(t, valid)
+ }
+ })
+ }
+}
+
+func TestCreateSessionWithSQLMock(t *testing.T) {
+ // Transaction begin error
+ dbBeginError, _, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
+ }
+ defer dbBeginError.Close()
+ // Transaction commit error
+ dbCommitError, mockCommitError, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
+ }
+ defer dbCommitError.Close()
+ mockCommitError.ExpectBegin()
+ mockCommitError.ExpectExec(`INSERT INTO`).WillReturnResult(sqlmock.NewResult(1, 1))
+ // Test cases
+ testCases := []struct {
+ name string
+ db *DBEnv
+ expectedError interface{}
+ }{
+ {"begin transaction error", &DBEnv{db: dbBeginError}, &TransactionError{}},
+ {"commit transaction error", &DBEnv{db: dbCommitError}, &TransactionError{}},
+ }
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ valid, err := tc.db.CreateSession(&model.User{})
+ if tc.expectedError != nil {
+ require.Error(t, err)
+ assert.Equalf(t, reflect.TypeOf(err), reflect.TypeOf(tc.expectedError), "Invalid error type. Got %s but expected %s", reflect.TypeOf(err), reflect.TypeOf(tc.expectedError))
+ require.Nil(t, valid)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}