diff options
Diffstat (limited to 'pkg/database')
-rw-r--r-- | pkg/database/migrations.go | 6 | ||||
-rw-r--r-- | pkg/database/sessions.go | 33 | ||||
-rw-r--r-- | pkg/database/sessions_test.go | 89 |
3 files changed, 128 insertions, 0 deletions
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) + } + }) + } +} |