From e514f437701a28ce3933f5b288e5b00d64b95a5c Mon Sep 17 00:00:00 2001 From: Sung Won Cho Date: Thu, 7 Jan 2021 21:17:55 +1100 Subject: [PATCH] Rename database to models --- Makefile | 2 +- SELF_HOSTING.md | 4 +- pkg/server/api/auth.go | 18 +-- pkg/server/api/auth_test.go | 74 +++++------ pkg/server/api/helpers.go | 4 +- pkg/server/api/notes.go | 16 +-- pkg/server/api/notes_test.go | 40 +++--- pkg/server/api/routes.go | 6 +- pkg/server/api/user.go | 40 +++--- pkg/server/api/user_test.go | 116 +++++++++--------- pkg/server/api/v3_auth.go | 12 +- pkg/server/api/v3_auth_test.go | 64 +++++----- pkg/server/api/v3_books.go | 24 ++-- pkg/server/api/v3_books_test.go | 76 ++++++------ pkg/server/api/v3_notes.go | 16 +-- pkg/server/api/v3_notes_test.go | 44 +++---- pkg/server/api/v3_sync.go | 22 ++-- pkg/server/app/books.go | 14 +-- pkg/server/app/books_test.go | 24 ++-- pkg/server/app/helpers.go | 4 +- pkg/server/app/helpers_test.go | 4 +- pkg/server/app/notes.go | 18 +-- pkg/server/app/notes_test.go | 34 ++--- pkg/server/app/sessions.go | 14 +-- pkg/server/app/users.go | 48 ++++---- pkg/server/app/users_test.go | 20 +-- pkg/server/context/user.go | 14 +-- pkg/server/controllers/helpers.go | 4 +- pkg/server/controllers/notes.go | 4 +- pkg/server/controllers/users.go | 4 +- pkg/server/handlers/auth.go | 14 +-- pkg/server/handlers/helpers_test.go | 26 ++-- pkg/server/job/remind/inactive.go | 14 +-- pkg/server/job/remind/inactive_test.go | 36 +++--- pkg/server/mailer/templates/main.go | 4 +- pkg/server/mailer/tokens.go | 8 +- pkg/server/main.go | 6 +- pkg/server/{database => models}/consts.go | 2 +- pkg/server/{database => models}/database.go | 2 +- pkg/server/{database => models}/errors.go | 2 +- pkg/server/{database => models}/migrate.go | 4 +- .../{database => models}/migrate/main.go | 6 +- .../{database => models}/migrations/.gitkeep | 0 .../20190819115834-full-text-search.sql | 0 ...0191028103522-create-weekly-repetition.sql | 0 ...20191225185502-populate-digest-version.sql | 0 ...191226093447-add-digest-id-primary-key.sql | 0 ...9-use-id-in-digest-notes-joining-table.sql | 0 ...20191226152111-delete-outdated-digests.sql | 0 .../20200522170529-remove-billing-columns.sql | 0 pkg/server/{database => models}/models.go | 2 +- pkg/server/{database => models}/notes.go | 2 +- .../scripts/create-migration.sh | 0 .../scripts/install-sql-migrate.sh | 0 .../{database => models}/sql-migrate.yml | 0 pkg/server/{database => models}/types.go | 2 +- pkg/server/operations/notes.go | 10 +- pkg/server/operations/notes_test.go | 30 ++--- pkg/server/permissions/permissions.go | 4 +- pkg/server/permissions/permissions_test.go | 8 +- pkg/server/presenters/book.go | 6 +- pkg/server/presenters/email_preference.go | 4 +- pkg/server/presenters/note.go | 6 +- pkg/server/routes/auth.go | 14 +-- pkg/server/session/session.go | 4 +- pkg/server/session/session_test.go | 14 +-- pkg/server/testutils/main.go | 48 ++++---- pkg/server/tmpl/app_test.go | 6 +- pkg/server/tmpl/data.go | 4 +- pkg/server/tmpl/data_test.go | 6 +- pkg/server/token/token.go | 10 +- pkg/server/token/token_test.go | 8 +- pkg/server/views/data.go | 4 +- 73 files changed, 550 insertions(+), 550 deletions(-) rename pkg/server/{database => models}/consts.go (98%) rename pkg/server/{database => models}/database.go (98%) rename pkg/server/{database => models}/errors.go (91%) rename pkg/server/{database => models}/migrate.go (94%) rename pkg/server/{database => models}/migrate/main.go (93%) rename pkg/server/{database => models}/migrations/.gitkeep (100%) rename pkg/server/{database => models}/migrations/20190819115834-full-text-search.sql (100%) rename pkg/server/{database => models}/migrations/20191028103522-create-weekly-repetition.sql (100%) rename pkg/server/{database => models}/migrations/20191225185502-populate-digest-version.sql (100%) rename pkg/server/{database => models}/migrations/20191226093447-add-digest-id-primary-key.sql (100%) rename pkg/server/{database => models}/migrations/20191226105659-use-id-in-digest-notes-joining-table.sql (100%) rename pkg/server/{database => models}/migrations/20191226152111-delete-outdated-digests.sql (100%) rename pkg/server/{database => models}/migrations/20200522170529-remove-billing-columns.sql (100%) rename pkg/server/{database => models}/models.go (99%) rename pkg/server/{database => models}/notes.go (98%) rename pkg/server/{database => models}/scripts/create-migration.sh (100%) rename pkg/server/{database => models}/scripts/install-sql-migrate.sh (100%) rename pkg/server/{database => models}/sql-migrate.yml (100%) rename pkg/server/{database => models}/types.go (98%) diff --git a/Makefile b/Makefile index c7a3eccd..e209938e 100644 --- a/Makefile +++ b/Makefile @@ -176,7 +176,7 @@ ifndef filename $(error filename is required. Usage: make filename=your-filename create-migration) endif - @(cd ${currentDir}/pkg/server/database && ./scripts/create-migration.sh $(filename)) + @(cd ${currentDir}/pkg/server/models && ./scripts/create-migration.sh $(filename)) .PHONY: create-migration clean: diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md index 072a85cb..7ea5993d 100644 --- a/SELF_HOSTING.md +++ b/SELF_HOSTING.md @@ -4,7 +4,7 @@ This guide documents the steps for installing the Dnote server on your own machi ## Overview -Dnote server comes as a single binary file that you can simply download and run. It uses Postgres as the database. +Dnote server comes as a single binary file that you can simply download and run. It uses Postgres as the models. ## Installation @@ -37,7 +37,7 @@ DisableRegistration=false dnote-server start ``` -Replace `$user`, `$password` with the credentials of the Postgres user that owns the `dnote` database. +Replace `$user`, `$password` with the credentials of the Postgres user that owns the `dnote` models. Replace `$webURL` with the full URL to your server, without a trailing slash (e.g. `https://your.server`). diff --git a/pkg/server/api/auth.go b/pkg/server/api/auth.go index 914e1233..7a98db24 100644 --- a/pkg/server/api/auth.go +++ b/pkg/server/api/auth.go @@ -23,7 +23,7 @@ import ( "net/http" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/log" @@ -40,13 +40,13 @@ type GetMeResponse struct { } func (a *API) getMe(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return } - var account database.Account + var account models.Account if err := a.App.DB.Where("user_id = ?", user.ID).First(&account).Error; err != nil { handlers.DoError(w, "finding account", err, http.StatusInternalServerError) return @@ -77,7 +77,7 @@ func (a *API) createResetToken(w http.ResponseWriter, r *http.Request) { return } - var account database.Account + var account models.Account conn := a.App.DB.Where("email = ?", params.Email).First(&account) if conn.RecordNotFound() { return @@ -87,7 +87,7 @@ func (a *API) createResetToken(w http.ResponseWriter, r *http.Request) { return } - resetToken, err := token.Create(a.App.DB, account.UserID, database.TokenTypeResetPassword) + resetToken, err := token.Create(a.App.DB, account.UserID, models.TokenTypeResetPassword) if err != nil { handlers.DoError(w, errors.Wrap(err, "generating token").Error(), nil, http.StatusInternalServerError) return @@ -116,8 +116,8 @@ func (a *API) resetPassword(w http.ResponseWriter, r *http.Request) { return } - var token database.Token - conn := a.App.DB.Where("value = ? AND type =? AND used_at IS NULL", params.Token, database.TokenTypeResetPassword).First(&token) + var token models.Token + conn := a.App.DB.Where("value = ? AND type =? AND used_at IS NULL", params.Token, models.TokenTypeResetPassword).First(&token) if conn.RecordNotFound() { http.Error(w, "invalid token", http.StatusBadRequest) return @@ -147,7 +147,7 @@ func (a *API) resetPassword(w http.ResponseWriter, r *http.Request) { return } - var account database.Account + var account models.Account if err := a.App.DB.Where("user_id = ?", token.UserID).First(&account).Error; err != nil { tx.Rollback() handlers.DoError(w, errors.Wrap(err, "finding user").Error(), nil, http.StatusInternalServerError) @@ -173,7 +173,7 @@ func (a *API) resetPassword(w http.ResponseWriter, r *http.Request) { tx.Commit() - var user database.User + var user models.User if err := a.App.DB.Where("id = ?", account.UserID).First(&user).Error; err != nil { handlers.DoError(w, errors.Wrap(err, "finding user").Error(), nil, http.StatusInternalServerError) return diff --git a/pkg/server/api/auth_test.go b/pkg/server/api/auth_test.go index ec5666db..da901e3c 100644 --- a/pkg/server/api/auth_test.go +++ b/pkg/server/api/auth_test.go @@ -28,7 +28,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/session" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" @@ -53,8 +53,8 @@ func TestGetMe(t *testing.T) { a2 := testutils.SetupAccountData(u2, "bob@example.com", "somepassword") testCases := []struct { - user database.User - account database.Account + user models.User + account models.Account expectedPro bool }{ { @@ -93,7 +93,7 @@ func TestGetMe(t *testing.T) { } assert.DeepEqual(t, payload, expectedPayload, "payload mismatch") - var user database.User + var user models.User testutils.MustExec(t, testutils.DB.Where("id = ?", tc.user.ID).First(&user), "finding user") assert.NotEqual(t, user.LastLoginAt, nil, "LastLoginAt mismatch") }) @@ -124,10 +124,10 @@ func TestCreateResetToken(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusOK, "Status code mismtach") var tokenCount int - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting tokens") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting tokens") - var resetToken database.Token - testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", u.ID, database.TokenTypeResetPassword).First(&resetToken), "finding reset token") + var resetToken models.Token + testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", u.ID, models.TokenTypeResetPassword).First(&resetToken), "finding reset token") assert.Equal(t, tokenCount, 1, "reset_token count mismatch") assert.NotEqual(t, resetToken.Value, nil, "reset_token value mismatch") @@ -158,7 +158,7 @@ func TestCreateResetToken(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusOK, "Status code mismtach") var tokenCount int - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting tokens") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting tokens") assert.Equal(t, tokenCount, 0, "reset_token count mismatch") }) } @@ -176,30 +176,30 @@ func TestResetPassword(t *testing.T) { u := testutils.SetupUserData() a := testutils.SetupAccountData(u, "alice@example.com", "oldpassword") - tok := database.Token{ + tok := models.Token{ UserID: u.ID, Value: "MivFxYiSMMA4An9dP24DNQ==", - Type: database.TokenTypeResetPassword, + Type: models.TokenTypeResetPassword, } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") - otherTok := database.Token{ + otherTok := models.Token{ UserID: u.ID, Value: "somerandomvalue", - Type: database.TokenTypeEmailVerification, + Type: models.TokenTypeEmailVerification, } testutils.MustExec(t, testutils.DB.Save(&otherTok), "preparing another token") dat := `{"token": "MivFxYiSMMA4An9dP24DNQ==", "password": "newpassword"}` req := testutils.MakeReq(server.URL, "PATCH", "/reset-password", dat) - s1 := database.Session{ + s1 := models.Session{ Key: "some-session-key-1", UserID: u.ID, ExpiresAt: time.Now().Add(time.Hour * 10 * 24), } testutils.MustExec(t, testutils.DB.Save(&s1), "preparing user session 1") - s2 := &database.Session{ + s2 := &models.Session{ Key: "some-session-key-2", UserID: u.ID, ExpiresAt: time.Now().Add(time.Hour * 10 * 24), @@ -207,7 +207,7 @@ func TestResetPassword(t *testing.T) { testutils.MustExec(t, testutils.DB.Save(&s2), "preparing user session 2") anotherUser := testutils.SetupUserData() - testutils.MustExec(t, testutils.DB.Save(&database.Session{ + testutils.MustExec(t, testutils.DB.Save(&models.Session{ Key: "some-session-key-3", UserID: anotherUser.ID, ExpiresAt: time.Now().Add(time.Hour * 10 * 24), @@ -219,8 +219,8 @@ func TestResetPassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "Status code mismatch") - var resetToken, verificationToken database.Token - var account database.Account + var resetToken, verificationToken models.Token + var account models.Account testutils.MustExec(t, testutils.DB.Where("value = ?", "MivFxYiSMMA4An9dP24DNQ==").First(&resetToken), "finding reset token") testutils.MustExec(t, testutils.DB.Where("value = ?", "somerandomvalue").First(&verificationToken), "finding reset token") testutils.MustExec(t, testutils.DB.Where("id = ?", a.ID).First(&account), "finding account") @@ -231,15 +231,15 @@ func TestResetPassword(t *testing.T) { assert.Equal(t, verificationToken.UsedAt, (*time.Time)(nil), "verificationToken UsedAt mismatch") var s1Count, s2Count int - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Where("id = ?", s1.ID).Count(&s1Count), "counting s1") - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Where("id = ?", s2.ID).Count(&s2Count), "counting s2") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Where("id = ?", s1.ID).Count(&s1Count), "counting s1") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Where("id = ?", s2.ID).Count(&s2Count), "counting s2") assert.Equal(t, s1Count, 0, "s1 should have been deleted") assert.Equal(t, s2Count, 0, "s2 should have been deleted") var userSessionCount, anotherUserSessionCount int - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Where("user_id = ?", u.ID).Count(&userSessionCount), "counting user session") - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Where("user_id = ?", anotherUser.ID).Count(&anotherUserSessionCount), "counting anotherUser session") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Where("user_id = ?", u.ID).Count(&userSessionCount), "counting user session") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Where("user_id = ?", anotherUser.ID).Count(&anotherUserSessionCount), "counting anotherUser session") assert.Equal(t, userSessionCount, 1, "should have created a new user session") assert.Equal(t, anotherUserSessionCount, 1, "anotherUser session count mismatch") @@ -257,10 +257,10 @@ func TestResetPassword(t *testing.T) { u := testutils.SetupUserData() a := testutils.SetupAccountData(u, "alice@example.com", "somepassword") - tok := database.Token{ + tok := models.Token{ UserID: u.ID, Value: "MivFxYiSMMA4An9dP24DNQ==", - Type: database.TokenTypeResetPassword, + Type: models.TokenTypeResetPassword, } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -273,8 +273,8 @@ func TestResetPassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusBadRequest, "Status code mismatch") - var resetToken database.Token - var account database.Account + var resetToken models.Token + var account models.Account testutils.MustExec(t, testutils.DB.Where("value = ?", "MivFxYiSMMA4An9dP24DNQ==").First(&resetToken), "finding reset token") testutils.MustExec(t, testutils.DB.Where("id = ?", a.ID).First(&account), "finding account") @@ -295,10 +295,10 @@ func TestResetPassword(t *testing.T) { u := testutils.SetupUserData() a := testutils.SetupAccountData(u, "alice@example.com", "somepassword") - tok := database.Token{ + tok := models.Token{ UserID: u.ID, Value: "MivFxYiSMMA4An9dP24DNQ==", - Type: database.TokenTypeResetPassword, + Type: models.TokenTypeResetPassword, } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") testutils.MustExec(t, testutils.DB.Model(&tok).Update("created_at", time.Now().Add(time.Minute*-11)), "Failed to prepare reset_token created_at") @@ -312,8 +312,8 @@ func TestResetPassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusGone, "Status code mismatch") - var resetToken database.Token - var account database.Account + var resetToken models.Token + var account models.Account testutils.MustExec(t, testutils.DB.Where("value = ?", "MivFxYiSMMA4An9dP24DNQ==").First(&resetToken), "failed to find reset_token") testutils.MustExec(t, testutils.DB.Where("id = ?", a.ID).First(&account), "failed to find account") assert.Equal(t, a.Password, account.Password, "password should not have been updated") @@ -334,10 +334,10 @@ func TestResetPassword(t *testing.T) { a := testutils.SetupAccountData(u, "alice@example.com", "somepassword") usedAt := time.Now().Add(time.Hour * -11).UTC() - tok := database.Token{ + tok := models.Token{ UserID: u.ID, Value: "MivFxYiSMMA4An9dP24DNQ==", - Type: database.TokenTypeResetPassword, + Type: models.TokenTypeResetPassword, UsedAt: &usedAt, } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -352,8 +352,8 @@ func TestResetPassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusBadRequest, "Status code mismatch") - var resetToken database.Token - var account database.Account + var resetToken models.Token + var account models.Account testutils.MustExec(t, testutils.DB.Where("value = ?", "MivFxYiSMMA4An9dP24DNQ==").First(&resetToken), "failed to find reset_token") testutils.MustExec(t, testutils.DB.Where("id = ?", a.ID).First(&account), "failed to find account") assert.Equal(t, a.Password, account.Password, "password should not have been updated") @@ -380,10 +380,10 @@ func TestResetPassword(t *testing.T) { u := testutils.SetupUserData() a := testutils.SetupAccountData(u, "alice@example.com", "somepassword") - tok := database.Token{ + tok := models.Token{ UserID: u.ID, Value: "MivFxYiSMMA4An9dP24DNQ==", - Type: database.TokenTypeEmailVerification, + Type: models.TokenTypeEmailVerification, } testutils.MustExec(t, testutils.DB.Save(&tok), "Failed to prepare reset_token") testutils.MustExec(t, testutils.DB.Model(&tok).Update("created_at", time.Now().Add(time.Minute*-11)), "Failed to prepare reset_token created_at") @@ -397,8 +397,8 @@ func TestResetPassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusBadRequest, "Status code mismatch") - var resetToken database.Token - var account database.Account + var resetToken models.Token + var account models.Account testutils.MustExec(t, testutils.DB.Where("value = ?", "MivFxYiSMMA4An9dP24DNQ==").First(&resetToken), "failed to find reset_token") testutils.MustExec(t, testutils.DB.Where("id = ?", a.ID).First(&account), "failed to find account") diff --git a/pkg/server/api/helpers.go b/pkg/server/api/helpers.go index 8137939f..090ed645 100644 --- a/pkg/server/api/helpers.go +++ b/pkg/server/api/helpers.go @@ -22,7 +22,7 @@ import ( "net/http" "strings" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) @@ -41,7 +41,7 @@ func paginate(conn *gorm.DB, page int) *gorm.DB { return conn } -func getBookIDs(books []database.Book) []int { +func getBookIDs(books []models.Book) []int { ret := []int{} for _, book := range books { diff --git a/pkg/server/api/notes.go b/pkg/server/api/notes.go index 8a745e41..91d92736 100644 --- a/pkg/server/api/notes.go +++ b/pkg/server/api/notes.go @@ -26,7 +26,7 @@ import ( "strings" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/operations" @@ -75,7 +75,7 @@ ts_headline('english_nostop', notes.body, plainto_tsquery('english_nostop', ?), `, search, headlineOpts) } -func respondWithNote(w http.ResponseWriter, note database.Note) { +func respondWithNote(w http.ResponseWriter, note models.Note) { presentedNote := presenters.PresentNote(note) handlers.RespondJSON(w, http.StatusOK, presentedNote) @@ -137,7 +137,7 @@ type dateRange struct { } func (a *API) getNotes(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -157,15 +157,15 @@ func respondGetNotes(db *gorm.DB, userID int, query url.Values, w http.ResponseW conn := getNotesBaseQuery(db, userID, q) var total int - if err := conn.Model(database.Note{}).Count(&total).Error; err != nil { + if err := conn.Model(models.Note{}).Count(&total).Error; err != nil { handlers.DoError(w, "counting total", err, http.StatusInternalServerError) return } - notes := []database.Note{} + notes := []models.Note{} if total != 0 { conn = orderGetNotes(conn) - conn = database.PreloadNote(conn) + conn = models.PreloadNote(conn) conn = paginate(conn, q.Page) if err := conn.Find(¬es).Error; err != nil { @@ -307,13 +307,13 @@ func escapeSearchQuery(searchQuery string) string { } func (a *API) legacyGetNotes(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return } - var notes []database.Note + var notes []models.Note if err := a.App.DB.Where("user_id = ? AND encrypted = true", user.ID).Find(¬es).Error; err != nil { handlers.DoError(w, "finding notes", err, http.StatusInternalServerError) return diff --git a/pkg/server/api/notes_test.go b/pkg/server/api/notes_test.go index d0b0617b..ee45c5c0 100644 --- a/pkg/server/api/notes_test.go +++ b/pkg/server/api/notes_test.go @@ -29,13 +29,13 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/presenters" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) -func getExpectedNotePayload(n database.Note, b database.Book, u database.User) presenters.Note { +func getExpectedNotePayload(n models.Note, b models.Book, u models.User) presenters.Note { return presenters.Note{ UUID: n.UUID, CreatedAt: n.CreatedAt, @@ -66,23 +66,23 @@ func TestGetNotes(t *testing.T) { user := testutils.SetupUserData() anotherUser := testutils.SetupUserData() - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - b2 := database.Book{ + b2 := models.Book{ UserID: user.ID, Label: "css", } testutils.MustExec(t, testutils.DB.Save(&b2), "preparing b2") - b3 := database.Book{ + b3 := models.Book{ UserID: anotherUser.ID, Label: "css", } testutils.MustExec(t, testutils.DB.Save(&b3), "preparing b3") - n1 := database.Note{ + n1 := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "n1 content", @@ -91,7 +91,7 @@ func TestGetNotes(t *testing.T) { AddedOn: time.Date(2018, time.August, 10, 23, 0, 0, 0, time.UTC).UnixNano(), } testutils.MustExec(t, testutils.DB.Save(&n1), "preparing n1") - n2 := database.Note{ + n2 := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "n2 content", @@ -100,7 +100,7 @@ func TestGetNotes(t *testing.T) { AddedOn: time.Date(2018, time.August, 11, 22, 0, 0, 0, time.UTC).UnixNano(), } testutils.MustExec(t, testutils.DB.Save(&n2), "preparing n2") - n3 := database.Note{ + n3 := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "n3 content", @@ -109,7 +109,7 @@ func TestGetNotes(t *testing.T) { AddedOn: time.Date(2017, time.January, 10, 23, 0, 0, 0, time.UTC).UnixNano(), } testutils.MustExec(t, testutils.DB.Save(&n3), "preparing n3") - n4 := database.Note{ + n4 := models.Note{ UserID: user.ID, BookUUID: b2.UUID, Body: "n4 content", @@ -118,7 +118,7 @@ func TestGetNotes(t *testing.T) { AddedOn: time.Date(2018, time.September, 10, 23, 0, 0, 0, time.UTC).UnixNano(), } testutils.MustExec(t, testutils.DB.Save(&n4), "preparing n4") - n5 := database.Note{ + n5 := models.Note{ UserID: anotherUser.ID, BookUUID: b3.UUID, Body: "n5 content", @@ -127,7 +127,7 @@ func TestGetNotes(t *testing.T) { AddedOn: time.Date(2018, time.August, 10, 23, 0, 0, 0, time.UTC).UnixNano(), } testutils.MustExec(t, testutils.DB.Save(&n5), "preparing n5") - n6 := database.Note{ + n6 := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "", @@ -149,7 +149,7 @@ func TestGetNotes(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var n2Record, n1Record database.Note + var n2Record, n1Record models.Note testutils.MustExec(t, testutils.DB.Where("uuid = ?", n2.UUID).First(&n2Record), "finding n2Record") testutils.MustExec(t, testutils.DB.Where("uuid = ?", n1.UUID).First(&n1Record), "finding n1Record") @@ -176,27 +176,27 @@ func TestGetNote(t *testing.T) { user := testutils.SetupUserData() anotherUser := testutils.SetupUserData() - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - privateNote := database.Note{ + privateNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "privateNote content", Public: false, } testutils.MustExec(t, testutils.DB.Save(&privateNote), "preparing privateNote") - publicNote := database.Note{ + publicNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "publicNote content", Public: true, } testutils.MustExec(t, testutils.DB.Save(&publicNote), "preparing publicNote") - deletedNote := database.Note{ + deletedNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Deleted: true, @@ -217,7 +217,7 @@ func TestGetNote(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var n1Record database.Note + var n1Record models.Note testutils.MustExec(t, testutils.DB.Where("uuid = ?", privateNote.UUID).First(&n1Record), "finding n1Record") expected := getExpectedNotePayload(n1Record, b1, user) @@ -238,7 +238,7 @@ func TestGetNote(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var n2Record database.Note + var n2Record models.Note testutils.MustExec(t, testutils.DB.Where("uuid = ?", publicNote.UUID).First(&n2Record), "finding n2Record") expected := getExpectedNotePayload(n2Record, b1, user) @@ -259,7 +259,7 @@ func TestGetNote(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var n2Record database.Note + var n2Record models.Note testutils.MustExec(t, testutils.DB.Where("uuid = ?", publicNote.UUID).First(&n2Record), "finding n2Record") expected := getExpectedNotePayload(n2Record, b1, user) @@ -297,7 +297,7 @@ func TestGetNote(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var n2Record database.Note + var n2Record models.Note testutils.MustExec(t, testutils.DB.Where("uuid = ?", publicNote.UUID).First(&n2Record), "finding n2Record") expected := getExpectedNotePayload(n2Record, b1, user) diff --git a/pkg/server/api/routes.go b/pkg/server/api/routes.go index a1d8385d..26802285 100644 --- a/pkg/server/api/routes.go +++ b/pkg/server/api/routes.go @@ -23,7 +23,7 @@ import ( "os" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/gorilla/mux" "github.com/pkg/errors" @@ -73,8 +73,8 @@ func NewRouter(a *API) (*mux.Router, error) { {Method: "PATCH", Pattern: "/reset-password", HandlerFunc: a.resetPassword, RateLimit: true}, {Method: "PATCH", Pattern: "/account/profile", HandlerFunc: handlers.Auth(app, a.updateProfile, nil), RateLimit: true}, {Method: "PATCH", Pattern: "/account/password", HandlerFunc: handlers.Auth(app, a.updatePassword, nil), RateLimit: true}, - {Method: "GET", Pattern: "/account/email-preference", HandlerFunc: handlers.TokenAuth(app, a.getEmailPreference, database.TokenTypeEmailPreference, nil), RateLimit: true}, - {Method: "PATCH", Pattern: "/account/email-preference", HandlerFunc: handlers.TokenAuth(app, a.updateEmailPreference, database.TokenTypeEmailPreference, nil), RateLimit: true}, + {Method: "GET", Pattern: "/account/email-preference", HandlerFunc: handlers.TokenAuth(app, a.getEmailPreference, models.TokenTypeEmailPreference, nil), RateLimit: true}, + {Method: "PATCH", Pattern: "/account/email-preference", HandlerFunc: handlers.TokenAuth(app, a.updateEmailPreference, models.TokenTypeEmailPreference, nil), RateLimit: true}, {Method: "GET", Pattern: "/notes", HandlerFunc: handlers.Auth(app, a.getNotes, nil), RateLimit: false}, {Method: "GET", Pattern: "/notes/{noteUUID}", HandlerFunc: a.getNote, RateLimit: true}, {Method: "GET", Pattern: "/calendar", HandlerFunc: handlers.Auth(app, a.getCalendar, nil), RateLimit: true}, diff --git a/pkg/server/api/user.go b/pkg/server/api/user.go index 04e41149..57b77e47 100644 --- a/pkg/server/api/user.go +++ b/pkg/server/api/user.go @@ -23,7 +23,7 @@ import ( "net/http" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/log" @@ -43,13 +43,13 @@ type updateProfilePayload struct { // updateProfile updates user func (a *API) updateProfile(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return } - var account database.Account + var account models.Account if err := a.App.DB.Where("user_id = ?", user.ID).First(&account).Error; err != nil { handlers.DoError(w, "getting account", nil, http.StatusInternalServerError) return @@ -135,7 +135,7 @@ func respondWithCalendar(db *gorm.DB, w http.ResponseWriter, userID int) { } func (a *API) getCalendar(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -145,13 +145,13 @@ func (a *API) getCalendar(w http.ResponseWriter, r *http.Request) { } func (a *API) createVerificationToken(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return } - var account database.Account + var account models.Account err := a.App.DB.Where("user_id = ?", user.ID).First(&account).Error if err != nil { handlers.DoError(w, "finding account", err, http.StatusInternalServerError) @@ -167,7 +167,7 @@ func (a *API) createVerificationToken(w http.ResponseWriter, r *http.Request) { return } - tok, err := token.Create(a.App.DB, account.UserID, database.TokenTypeEmailVerification) + tok, err := token.Create(a.App.DB, account.UserID, models.TokenTypeEmailVerification) if err != nil { handlers.DoError(w, "saving token", err, http.StatusInternalServerError) return @@ -197,9 +197,9 @@ func (a *API) verifyEmail(w http.ResponseWriter, r *http.Request) { return } - var token database.Token + var token models.Token if err := a.App.DB. - Where("value = ? AND type = ?", params.Token, database.TokenTypeEmailVerification). + Where("value = ? AND type = ?", params.Token, models.TokenTypeEmailVerification). First(&token).Error; err != nil { http.Error(w, "invalid token", http.StatusBadRequest) return @@ -216,7 +216,7 @@ func (a *API) verifyEmail(w http.ResponseWriter, r *http.Request) { return } - var account database.Account + var account models.Account if err := a.App.DB.Where("user_id = ?", token.UserID).First(&account).Error; err != nil { handlers.DoError(w, "finding account", err, http.StatusInternalServerError) return @@ -240,7 +240,7 @@ func (a *API) verifyEmail(w http.ResponseWriter, r *http.Request) { } tx.Commit() - var user database.User + var user models.User if err := a.App.DB.Where("id = ?", token.UserID).First(&user).Error; err != nil { handlers.DoError(w, "finding user", err, http.StatusInternalServerError) return @@ -272,7 +272,7 @@ func (p emailPreferernceParams) getProductUpdate() bool { } func (a *API) updateEmailPreference(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -284,8 +284,8 @@ func (a *API) updateEmailPreference(w http.ResponseWriter, r *http.Request) { return } - var pref database.EmailPreference - if err := a.App.DB.Where(database.EmailPreference{UserID: user.ID}).FirstOrCreate(&pref).Error; err != nil { + var pref models.EmailPreference + if err := a.App.DB.Where(models.EmailPreference{UserID: user.ID}).FirstOrCreate(&pref).Error; err != nil { handlers.DoError(w, "finding pref", err, http.StatusInternalServerError) return } @@ -305,7 +305,7 @@ func (a *API) updateEmailPreference(w http.ResponseWriter, r *http.Request) { return } - token, ok := r.Context().Value(helpers.KeyToken).(database.Token) + token, ok := r.Context().Value(helpers.KeyToken).(models.Token) if ok { // Mark token as used if the user was authenticated by token if err := tx.Model(&token).Update("used_at", time.Now()).Error; err != nil { @@ -321,14 +321,14 @@ func (a *API) updateEmailPreference(w http.ResponseWriter, r *http.Request) { } func (a *API) getEmailPreference(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return } - var pref database.EmailPreference - if err := a.App.DB.Where(database.EmailPreference{UserID: user.ID}).First(&pref).Error; err != nil { + var pref models.EmailPreference + if err := a.App.DB.Where(models.EmailPreference{UserID: user.ID}).First(&pref).Error; err != nil { handlers.DoError(w, "finding pref", err, http.StatusInternalServerError) return } @@ -343,7 +343,7 @@ type updatePasswordPayload struct { } func (a *API) updatePassword(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -359,7 +359,7 @@ func (a *API) updatePassword(w http.ResponseWriter, r *http.Request) { return } - var account database.Account + var account models.Account if err := a.App.DB.Where("user_id = ?", user.ID).First(&account).Error; err != nil { handlers.DoError(w, "getting account", nil, http.StatusInternalServerError) return diff --git a/pkg/server/api/user_test.go b/pkg/server/api/user_test.go index 19376300..04716ce9 100644 --- a/pkg/server/api/user_test.go +++ b/pkg/server/api/user_test.go @@ -28,7 +28,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/presenters" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" @@ -56,7 +56,7 @@ func TestUpdatePassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "Status code mismsatch") - var account database.Account + var account models.Account testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") passwordErr := bcrypt.CompareHashAndPassword([]byte(account.Password.String), []byte("newpassword")) @@ -84,7 +84,7 @@ func TestUpdatePassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "Status code mismsatch") - var account database.Account + var account models.Account testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&account), "finding account") assert.Equal(t, a.Password.String, account.Password.String, "password should not have been updated") }) @@ -110,7 +110,7 @@ func TestUpdatePassword(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusBadRequest, "Status code mismsatch") - var account database.Account + var account models.Account testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&account), "finding account") assert.Equal(t, a.Password.String, account.Password.String, "password should not have been updated") }) @@ -138,12 +138,12 @@ func TestCreateVerificationToken(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusCreated, "status code mismatch") - var account database.Account - var token database.Token + var account models.Account + var token models.Token var tokenCount int testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") - testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, database.TokenTypeEmailVerification).First(&token), "finding token") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting token") + testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, models.TokenTypeEmailVerification).First(&token), "finding token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting token") assert.Equal(t, account.EmailVerified, false, "email_verified should not have been updated") assert.NotEqual(t, token.Value, "", "token Value mismatch") @@ -175,10 +175,10 @@ func TestCreateVerificationToken(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusGone, "Status code mismatch") - var account database.Account + var account models.Account var tokenCount int testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting token") assert.Equal(t, account.EmailVerified, true, "email_verified should not have been updated") assert.Equal(t, tokenCount, 0, "token count mismatch") @@ -198,9 +198,9 @@ func TestVerifyEmail(t *testing.T) { user := testutils.SetupUserData() testutils.SetupAccountData(user, "alice@example.com", "pass1234") - tok := database.Token{ + tok := models.Token{ UserID: user.ID, - Type: database.TokenTypeEmailVerification, + Type: models.TokenTypeEmailVerification, Value: "someTokenValue", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -214,12 +214,12 @@ func TestVerifyEmail(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "Status code mismatch") - var account database.Account - var token database.Token + var account models.Account + var token models.Token var tokenCount int testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") - testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, database.TokenTypeEmailVerification).First(&token), "finding token") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting token") + testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, models.TokenTypeEmailVerification).First(&token), "finding token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting token") assert.Equal(t, account.EmailVerified, true, "email_verified mismatch") assert.NotEqual(t, token.Value, "", "token value should not have been updated") @@ -241,9 +241,9 @@ func TestVerifyEmail(t *testing.T) { testutils.SetupAccountData(user, "alice@example.com", "pass1234") usedAt := time.Now().Add(time.Hour * -11).UTC() - tok := database.Token{ + tok := models.Token{ UserID: user.ID, - Type: database.TokenTypeEmailVerification, + Type: models.TokenTypeEmailVerification, Value: "someTokenValue", UsedAt: &usedAt, } @@ -258,12 +258,12 @@ func TestVerifyEmail(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusBadRequest, "") - var account database.Account - var token database.Token + var account models.Account + var token models.Token var tokenCount int testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") - testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, database.TokenTypeEmailVerification).First(&token), "finding token") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting token") + testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, models.TokenTypeEmailVerification).First(&token), "finding token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting token") assert.Equal(t, account.EmailVerified, false, "email_verified mismatch") assert.NotEqual(t, token.UsedAt, nil, "token used_at mismatch") @@ -284,9 +284,9 @@ func TestVerifyEmail(t *testing.T) { user := testutils.SetupUserData() testutils.SetupAccountData(user, "alice@example.com", "pass1234") - tok := database.Token{ + tok := models.Token{ UserID: user.ID, - Type: database.TokenTypeEmailVerification, + Type: models.TokenTypeEmailVerification, Value: "someTokenValue", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -301,12 +301,12 @@ func TestVerifyEmail(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusGone, "") - var account database.Account - var token database.Token + var account models.Account + var token models.Token var tokenCount int testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") - testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, database.TokenTypeEmailVerification).First(&token), "finding token") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting token") + testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, models.TokenTypeEmailVerification).First(&token), "finding token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting token") assert.Equal(t, account.EmailVerified, false, "email_verified mismatch") assert.Equal(t, tokenCount, 1, "token count mismatch") @@ -328,9 +328,9 @@ func TestVerifyEmail(t *testing.T) { a.EmailVerified = true testutils.MustExec(t, testutils.DB.Save(&a), "preparing account") - tok := database.Token{ + tok := models.Token{ UserID: user.ID, - Type: database.TokenTypeEmailVerification, + Type: models.TokenTypeEmailVerification, Value: "someTokenValue", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -344,12 +344,12 @@ func TestVerifyEmail(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusConflict, "") - var account database.Account - var token database.Token + var account models.Account + var token models.Token var tokenCount int testutils.MustExec(t, testutils.DB.Where("user_id = ?", user.ID).First(&account), "finding account") - testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, database.TokenTypeEmailVerification).First(&token), "finding token") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&tokenCount), "counting token") + testutils.MustExec(t, testutils.DB.Where("user_id = ? AND type = ?", user.ID, models.TokenTypeEmailVerification).First(&token), "finding token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&tokenCount), "counting token") assert.Equal(t, account.EmailVerified, true, "email_verified mismatch") assert.Equal(t, tokenCount, 1, "token count mismatch") @@ -380,8 +380,8 @@ func TestUpdateEmail(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var user database.User - var account database.Account + var user models.User + var account models.Account testutils.MustExec(t, testutils.DB.Where("id = ?", u.ID).First(&user), "finding user") testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&account), "finding account") @@ -411,8 +411,8 @@ func TestUpdateEmail(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "Status code mismsatch") - var user database.User - var account database.Account + var user models.User + var account models.Account testutils.MustExec(t, testutils.DB.Where("id = ?", u.ID).First(&user), "finding user") testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&account), "finding account") @@ -442,7 +442,7 @@ func TestUpdateEmailPreference(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var preference database.EmailPreference + var preference models.EmailPreference testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding account") assert.Equal(t, preference.InactiveReminder, true, "preference mismatch") }) @@ -458,9 +458,9 @@ func TestUpdateEmailPreference(t *testing.T) { u := testutils.SetupUserData() testutils.SetupEmailPreferenceData(u, false) - tok := database.Token{ + tok := models.Token{ UserID: u.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "someTokenValue", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -474,11 +474,11 @@ func TestUpdateEmailPreference(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var preference database.EmailPreference + var preference models.EmailPreference var preferenceCount int - var token database.Token + var token models.Token testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding preference") - testutils.MustExec(t, testutils.DB.Model(database.EmailPreference{}).Count(&preferenceCount), "counting preference") + testutils.MustExec(t, testutils.DB.Model(models.EmailPreference{}).Count(&preferenceCount), "counting preference") testutils.MustExec(t, testutils.DB.Where("id = ?", tok.ID).First(&token), "failed to find token") assert.Equal(t, preferenceCount, 1, "preference count mismatch") @@ -497,9 +497,9 @@ func TestUpdateEmailPreference(t *testing.T) { u := testutils.SetupUserData() testutils.SetupEmailPreferenceData(u, true) - tok := database.Token{ + tok := models.Token{ UserID: u.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "someTokenValue", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -514,7 +514,7 @@ func TestUpdateEmailPreference(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "") - var preference database.EmailPreference + var preference models.EmailPreference testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding preference") assert.Equal(t, preference.InactiveReminder, true, "email mismatch") }) @@ -533,9 +533,9 @@ func TestUpdateEmailPreference(t *testing.T) { testutils.SetupEmailPreferenceData(u, true) usedAt := time.Now().Add(-11 * time.Minute) - tok := database.Token{ + tok := models.Token{ UserID: u.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "someTokenValue", UsedAt: &usedAt, } @@ -550,7 +550,7 @@ func TestUpdateEmailPreference(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "") - var preference database.EmailPreference + var preference models.EmailPreference testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding preference") assert.Equal(t, preference.InactiveReminder, true, "email mismatch") }) @@ -569,9 +569,9 @@ func TestUpdateEmailPreference(t *testing.T) { u := testutils.SetupUserData() testutils.SetupEmailPreferenceData(u, true) usedAt := time.Now().Add(-9 * time.Minute) - tok := database.Token{ + tok := models.Token{ UserID: u.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "someTokenValue", UsedAt: &usedAt, } @@ -587,7 +587,7 @@ func TestUpdateEmailPreference(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var preference database.EmailPreference + var preference models.EmailPreference testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding preference") assert.Equal(t, preference.InactiveReminder, false, "InactiveReminder mismatch") }) @@ -614,7 +614,7 @@ func TestUpdateEmailPreference(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "") - var preference database.EmailPreference + var preference models.EmailPreference testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding preference") assert.Equal(t, preference.InactiveReminder, true, "email mismatch") }) @@ -631,9 +631,9 @@ func TestUpdateEmailPreference(t *testing.T) { defer server.Close() u := testutils.SetupUserData() - tok := database.Token{ + tok := models.Token{ UserID: u.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "someTokenValue", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") @@ -648,10 +648,10 @@ func TestUpdateEmailPreference(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusOK, "") var preferenceCount int - testutils.MustExec(t, testutils.DB.Model(database.EmailPreference{}).Count(&preferenceCount), "counting preference") + testutils.MustExec(t, testutils.DB.Model(models.EmailPreference{}).Count(&preferenceCount), "counting preference") assert.Equal(t, preferenceCount, 1, "preference count mismatch") - var preference database.EmailPreference + var preference models.EmailPreference testutils.MustExec(t, testutils.DB.Where("user_id = ?", u.ID).First(&preference), "finding preference") assert.Equal(t, preference.InactiveReminder, false, "email mismatch") }) diff --git a/pkg/server/api/v3_auth.go b/pkg/server/api/v3_auth.go index 1c9ab145..671aa3fa 100644 --- a/pkg/server/api/v3_auth.go +++ b/pkg/server/api/v3_auth.go @@ -23,7 +23,7 @@ import ( "net/http" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/log" "github.com/jinzhu/gorm" @@ -51,9 +51,9 @@ func setSessionCookie(w http.ResponseWriter, key string, expires time.Time) { http.SetCookie(w, &cookie) } -func touchLastLoginAt(db *gorm.DB, user database.User) error { +func touchLastLoginAt(db *gorm.DB, user models.User) error { t := time.Now() - if err := db.Model(&user).Update(database.User{LastLoginAt: &t}).Error; err != nil { + if err := db.Model(&user).Update(models.User{LastLoginAt: &t}).Error; err != nil { return errors.Wrap(err, "updating last_login_at") } @@ -77,7 +77,7 @@ func (a *API) signin(w http.ResponseWriter, r *http.Request) { return } - var account database.Account + var account models.Account conn := a.App.DB.Where("email = ?", params.Email).First(&account) if conn.RecordNotFound() { http.Error(w, ErrLoginFailure.Error(), http.StatusUnauthorized) @@ -94,7 +94,7 @@ func (a *API) signin(w http.ResponseWriter, r *http.Request) { return } - var user database.User + var user models.User err = a.App.DB.Where("id = ?", account.UserID).First(&user).Error if err != nil { handlers.DoError(w, "finding user", err, http.StatusInternalServerError) @@ -179,7 +179,7 @@ func (a *API) register(w http.ResponseWriter, r *http.Request) { } var count int - if err := a.App.DB.Model(database.Account{}).Where("email = ?", params.Email).Count(&count).Error; err != nil { + if err := a.App.DB.Model(models.Account{}).Where("email = ?", params.Email).Count(&count).Error; err != nil { handlers.DoError(w, "checking duplicate user", err, http.StatusInternalServerError) return } diff --git a/pkg/server/api/v3_auth_test.go b/pkg/server/api/v3_auth_test.go index f08eea2b..00d824cf 100644 --- a/pkg/server/api/v3_auth_test.go +++ b/pkg/server/api/v3_auth_test.go @@ -29,7 +29,7 @@ import ( "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" @@ -43,8 +43,8 @@ func assertSessionResp(t *testing.T, res *http.Response) { } var sessionCount int - var session database.Session - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Count(&sessionCount), "counting session") + var session models.Session + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Count(&sessionCount), "counting session") testutils.MustExec(t, testutils.DB.First(&session), "getting session") assert.Equal(t, sessionCount, 1, "sessionCount mismatch") @@ -117,14 +117,14 @@ func TestRegister(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusCreated, "") - var account database.Account + var account models.Account testutils.MustExec(t, testutils.DB.Where("email = ?", tc.email).First(&account), "finding account") assert.Equal(t, account.Email.String, tc.email, "Email mismatch") assert.NotEqual(t, account.UserID, 0, "UserID mismatch") passwordErr := bcrypt.CompareHashAndPassword([]byte(account.Password.String), []byte(tc.password)) assert.Equal(t, passwordErr, nil, "Password mismatch") - var user database.User + var user models.User testutils.MustExec(t, testutils.DB.Where("id = ?", account.UserID).First(&user), "finding user") assert.Equal(t, user.Cloud, tc.expectedPro, "Cloud mismatch") assert.Equal(t, user.MaxUSN, 0, "MaxUSN mismatch") @@ -159,8 +159,8 @@ func TestRegisterMissingParams(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusBadRequest, "Status mismatch") var accountCount, userCount int - testutils.MustExec(t, testutils.DB.Model(&database.Account{}).Count(&accountCount), "counting account") - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") + testutils.MustExec(t, testutils.DB.Model(&models.Account{}).Count(&accountCount), "counting account") + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") assert.Equal(t, accountCount, 0, "accountCount mismatch") assert.Equal(t, userCount, 0, "userCount mismatch") @@ -186,8 +186,8 @@ func TestRegisterMissingParams(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusBadRequest, "Status mismatch") var accountCount, userCount int - testutils.MustExec(t, testutils.DB.Model(&database.Account{}).Count(&accountCount), "counting account") - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") + testutils.MustExec(t, testutils.DB.Model(&models.Account{}).Count(&accountCount), "counting account") + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") assert.Equal(t, accountCount, 0, "accountCount mismatch") assert.Equal(t, userCount, 0, "userCount mismatch") @@ -216,11 +216,11 @@ func TestRegisterDuplicateEmail(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusBadRequest, "status code mismatch") var accountCount, userCount, verificationTokenCount int - testutils.MustExec(t, testutils.DB.Model(&database.Account{}).Count(&accountCount), "counting account") - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&verificationTokenCount), "counting verification token") + testutils.MustExec(t, testutils.DB.Model(&models.Account{}).Count(&accountCount), "counting account") + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&verificationTokenCount), "counting verification token") - var user database.User + var user models.User testutils.MustExec(t, testutils.DB.Where("id = ?", u.ID).First(&user), "finding user") assert.Equal(t, accountCount, 1, "account count mismatch") @@ -252,8 +252,8 @@ func TestRegisterDisabled(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusForbidden, "status code mismatch") var accountCount, userCount int - testutils.MustExec(t, testutils.DB.Model(&database.Account{}).Count(&accountCount), "counting account") - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") + testutils.MustExec(t, testutils.DB.Model(&models.Account{}).Count(&accountCount), "counting account") + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") assert.Equal(t, accountCount, 0, "account count mismatch") assert.Equal(t, userCount, 0, "user count mismatch") @@ -282,8 +282,8 @@ func TestSignIn(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var user database.User - testutils.MustExec(t, testutils.DB.Model(&database.User{}).First(&user), "finding user") + var user models.User + testutils.MustExec(t, testutils.DB.Model(&models.User{}).First(&user), "finding user") assert.NotEqual(t, user.LastLoginAt, nil, "LastLoginAt mismatch") // after register, should sign in user @@ -312,12 +312,12 @@ func TestSignIn(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "") - var user database.User - testutils.MustExec(t, testutils.DB.Model(&database.User{}).First(&user), "finding user") + var user models.User + testutils.MustExec(t, testutils.DB.Model(&models.User{}).First(&user), "finding user") assert.Equal(t, user.LastLoginAt, (*time.Time)(nil), "LastLoginAt mismatch") var sessionCount int - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Count(&sessionCount), "counting session") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Count(&sessionCount), "counting session") assert.Equal(t, sessionCount, 0, "sessionCount mismatch") }) @@ -344,12 +344,12 @@ func TestSignIn(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "") - var user database.User - testutils.MustExec(t, testutils.DB.Model(&database.User{}).First(&user), "finding user") + var user models.User + testutils.MustExec(t, testutils.DB.Model(&models.User{}).First(&user), "finding user") assert.DeepEqual(t, user.LastLoginAt, (*time.Time)(nil), "LastLoginAt mismatch") var sessionCount int - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Count(&sessionCount), "counting session") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Count(&sessionCount), "counting session") assert.Equal(t, sessionCount, 0, "sessionCount mismatch") }) @@ -374,7 +374,7 @@ func TestSignIn(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusUnauthorized, "") var sessionCount int - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Count(&sessionCount), "counting session") + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Count(&sessionCount), "counting session") assert.Equal(t, sessionCount, 0, "sessionCount mismatch") }) } @@ -388,13 +388,13 @@ func TestSignout(t *testing.T) { testutils.SetupAccountData(aliceUser, "alice@example.com", "pass1234") anotherUser := testutils.SetupUserData() - session1 := database.Session{ + session1 := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: aliceUser.ID, ExpiresAt: time.Now().Add(time.Hour * 24), } testutils.MustExec(t, testutils.DB.Save(&session1), "preparing session1") - session2 := database.Session{ + session2 := models.Session{ Key: "MDCpbvCRg7W2sH6S870wqLqZDZTObYeVd0PzOekfo/A=", UserID: anotherUser.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -417,8 +417,8 @@ func TestSignout(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusNoContent, "Status mismatch") var sessionCount int - var s2 database.Session - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Count(&sessionCount), "counting session") + var s2 models.Session + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Count(&sessionCount), "counting session") testutils.MustExec(t, testutils.DB.Where("key = ?", "MDCpbvCRg7W2sH6S870wqLqZDZTObYeVd0PzOekfo/A=").First(&s2), "getting s2") assert.Equal(t, sessionCount, 1, "sessionCount mismatch") @@ -440,13 +440,13 @@ func TestSignout(t *testing.T) { testutils.SetupAccountData(aliceUser, "alice@example.com", "pass1234") anotherUser := testutils.SetupUserData() - session1 := database.Session{ + session1 := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: aliceUser.ID, ExpiresAt: time.Now().Add(time.Hour * 24), } testutils.MustExec(t, testutils.DB.Save(&session1), "preparing session1") - session2 := database.Session{ + session2 := models.Session{ Key: "MDCpbvCRg7W2sH6S870wqLqZDZTObYeVd0PzOekfo/A=", UserID: anotherUser.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -468,8 +468,8 @@ func TestSignout(t *testing.T) { assert.StatusCodeEquals(t, res, http.StatusNoContent, "Status mismatch") var sessionCount int - var postSession1, postSession2 database.Session - testutils.MustExec(t, testutils.DB.Model(&database.Session{}).Count(&sessionCount), "counting session") + var postSession1, postSession2 models.Session + testutils.MustExec(t, testutils.DB.Model(&models.Session{}).Count(&sessionCount), "counting session") testutils.MustExec(t, testutils.DB.Where("key = ?", "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=").First(&postSession1), "getting postSession1") testutils.MustExec(t, testutils.DB.Where("key = ?", "MDCpbvCRg7W2sH6S870wqLqZDZTObYeVd0PzOekfo/A=").First(&postSession2), "getting postSession2") diff --git a/pkg/server/api/v3_books.go b/pkg/server/api/v3_books.go index 962d38af..a9325bec 100644 --- a/pkg/server/api/v3_books.go +++ b/pkg/server/api/v3_books.go @@ -24,7 +24,7 @@ import ( "net/http" "net/url" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/presenters" @@ -52,7 +52,7 @@ func validateCreateBookPayload(p createBookPayload) error { // CreateBook creates a new book func (a *API) CreateBook(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { return } @@ -71,7 +71,7 @@ func (a *API) CreateBook(w http.ResponseWriter, r *http.Request) { } var bookCount int - err = a.App.DB.Model(database.Book{}). + err = a.App.DB.Model(models.Book{}). Where("user_id = ? AND label = ?", user.ID, params.Name). Count(&bookCount).Error if err != nil { @@ -100,7 +100,7 @@ func (a *API) BooksOptions(w http.ResponseWriter, r *http.Request) { } func respondWithBooks(db *gorm.DB, userID int, query url.Values, w http.ResponseWriter) { - var books []database.Book + var books []models.Book conn := db.Where("user_id = ? AND NOT deleted", userID).Order("label ASC") name := query.Get("name") encryptedStr := query.Get("encrypted") @@ -131,7 +131,7 @@ func respondWithBooks(db *gorm.DB, userID int, query url.Values, w http.Response // GetBooks returns books for the user func (a *API) GetBooks(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { return } @@ -143,7 +143,7 @@ func (a *API) GetBooks(w http.ResponseWriter, r *http.Request) { // GetBook returns a book for the user func (a *API) GetBook(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { return } @@ -151,7 +151,7 @@ func (a *API) GetBook(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) bookUUID := vars["bookUUID"] - var book database.Book + var book models.Book conn := a.App.DB.Where("uuid = ? AND user_id = ?", bookUUID, user.ID).First(&book) if conn.RecordNotFound() { @@ -178,7 +178,7 @@ type UpdateBookResp struct { // UpdateBook updates a book func (a *API) UpdateBook(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { return } @@ -188,7 +188,7 @@ func (a *API) UpdateBook(w http.ResponseWriter, r *http.Request) { tx := a.App.DB.Begin() - var book database.Book + var book models.Book if err := tx.Where("user_id = ? AND uuid = ?", user.ID, uuid).First(&book).Error; err != nil { handlers.DoError(w, "finding book", err, http.StatusInternalServerError) return @@ -223,7 +223,7 @@ type DeleteBookResp struct { // DeleteBook removes a book func (a *API) DeleteBook(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { return } @@ -233,13 +233,13 @@ func (a *API) DeleteBook(w http.ResponseWriter, r *http.Request) { tx := a.App.DB.Begin() - var book database.Book + var book models.Book if err := tx.Where("user_id = ? AND uuid = ?", user.ID, uuid).First(&book).Error; err != nil { handlers.DoError(w, "finding book", err, http.StatusInternalServerError) return } - var notes []database.Note + var notes []models.Note if err := tx.Where("book_uuid = ? AND NOT deleted", uuid).Order("usn ASC").Find(¬es).Error; err != nil { handlers.DoError(w, "finding notes", err, http.StatusInternalServerError) return diff --git a/pkg/server/api/v3_books_test.go b/pkg/server/api/v3_books_test.go index 0dbeaae3..0100830e 100644 --- a/pkg/server/api/v3_books_test.go +++ b/pkg/server/api/v3_books_test.go @@ -27,7 +27,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/presenters" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" @@ -47,28 +47,28 @@ func TestGetBooks(t *testing.T) { user := testutils.SetupUserData() anotherUser := testutils.SetupUserData() - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", USN: 1123, Deleted: false, } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - b2 := database.Book{ + b2 := models.Book{ UserID: user.ID, Label: "css", USN: 1125, Deleted: false, } testutils.MustExec(t, testutils.DB.Save(&b2), "preparing b2") - b3 := database.Book{ + b3 := models.Book{ UserID: anotherUser.ID, Label: "css", USN: 1128, Deleted: false, } testutils.MustExec(t, testutils.DB.Save(&b3), "preparing b3") - b4 := database.Book{ + b4 := models.Book{ UserID: user.ID, Label: "", USN: 1129, @@ -88,7 +88,7 @@ func TestGetBooks(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var b1Record, b2Record database.Book + var b1Record, b2Record models.Book testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&b1Record), "finding b1") testutils.MustExec(t, testutils.DB.Where("id = ?", b2.ID).First(&b2Record), "finding b2") testutils.MustExec(t, testutils.DB.Where("id = ?", b2.ID).First(&b2Record), "finding b2") @@ -128,17 +128,17 @@ func TestGetBooksByName(t *testing.T) { anotherUser := testutils.SetupUserData() req := testutils.MakeReq(server.URL, "GET", "/v3/books?name=js", "") - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - b2 := database.Book{ + b2 := models.Book{ UserID: user.ID, Label: "css", } testutils.MustExec(t, testutils.DB.Save(&b2), "preparing b2") - b3 := database.Book{ + b3 := models.Book{ UserID: anotherUser.ID, Label: "js", } @@ -155,7 +155,7 @@ func TestGetBooksByName(t *testing.T) { t.Fatal(errors.Wrap(err, "decoding payload")) } - var b1Record database.Book + var b1Record models.Book testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&b1Record), "finding b1") expected := []presenters.Book{ @@ -215,20 +215,20 @@ func TestDeleteBook(t *testing.T) { anotherUser := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&anotherUser).Update("max_usn", 109), "preparing another user max_usn") - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", USN: 1, } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing a book data") - b2 := database.Book{ + b2 := models.Book{ UserID: user.ID, Label: tc.label, USN: 2, Deleted: tc.deleted, } testutils.MustExec(t, testutils.DB.Save(&b2), "preparing a book data") - b3 := database.Book{ + b3 := models.Book{ UserID: anotherUser.ID, Label: "linux", USN: 3, @@ -244,14 +244,14 @@ func TestDeleteBook(t *testing.T) { n3Body = "n3 content" } - n1 := database.Note{ + n1 := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "n1 content", USN: 4, } testutils.MustExec(t, testutils.DB.Save(&n1), "preparing a note data") - n2 := database.Note{ + n2 := models.Note{ UserID: user.ID, BookUUID: b2.UUID, Body: n2Body, @@ -259,7 +259,7 @@ func TestDeleteBook(t *testing.T) { Deleted: tc.deleted, } testutils.MustExec(t, testutils.DB.Save(&n2), "preparing a note data") - n3 := database.Note{ + n3 := models.Note{ UserID: user.ID, BookUUID: b2.UUID, Body: n3Body, @@ -267,7 +267,7 @@ func TestDeleteBook(t *testing.T) { Deleted: tc.deleted, } testutils.MustExec(t, testutils.DB.Save(&n3), "preparing a note data") - n4 := database.Note{ + n4 := models.Note{ UserID: user.ID, BookUUID: b2.UUID, Body: "", @@ -275,7 +275,7 @@ func TestDeleteBook(t *testing.T) { Deleted: true, } testutils.MustExec(t, testutils.DB.Save(&n4), "preparing a note data") - n5 := database.Note{ + n5 := models.Note{ UserID: anotherUser.ID, BookUUID: b3.UUID, Body: "n5 content", @@ -294,13 +294,13 @@ func TestDeleteBook(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var b1Record, b2Record, b3Record database.Book - var n1Record, n2Record, n3Record, n4Record, n5Record database.Note - var userRecord database.User + var b1Record, b2Record, b3Record models.Book + var n1Record, n2Record, n3Record, n4Record, n5Record models.Note + var userRecord models.User var bookCount, noteCount int - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&b1Record), "finding b1") testutils.MustExec(t, testutils.DB.Where("id = ?", b2.ID).First(&b2Record), "finding b2") testutils.MustExec(t, testutils.DB.Where("id = ?", b3.ID).First(&b3Record), "finding b3") @@ -374,11 +374,11 @@ func TestCreateBook(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusCreated, "") - var bookRecord database.Book - var userRecord database.User + var bookRecord models.Book + var userRecord models.User var bookCount, noteCount int - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.First(&bookRecord), "finding book") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user record") @@ -424,7 +424,7 @@ func TestCreateBookDuplicate(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("max_usn", 101), "preparing user max_usn") - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", USN: 58, @@ -438,11 +438,11 @@ func TestCreateBookDuplicate(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusConflict, "") - var bookRecord database.Book + var bookRecord models.Book var bookCount, noteCount int - var userRecord database.User - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + var userRecord models.User + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.First(&bookRecord), "finding book") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user record") @@ -504,14 +504,14 @@ func TestUpdateBook(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("max_usn", 101), "preparing user max_usn") - b1 := database.Book{ + b1 := models.Book{ UUID: tc.bookUUID, UserID: user.ID, Label: tc.bookLabel, Deleted: tc.bookDeleted, } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - b2 := database.Book{ + b2 := models.Book{ UUID: b2UUID, UserID: user.ID, Label: "js", @@ -526,11 +526,11 @@ func TestUpdateBook(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, fmt.Sprintf("status code mismatch for test case %d", idx)) - var bookRecord database.Book - var userRecord database.User + var bookRecord models.Book + var userRecord models.User var noteCount, bookCount int - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&bookRecord), "finding book") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user record") diff --git a/pkg/server/api/v3_notes.go b/pkg/server/api/v3_notes.go index b6e7c750..8fc62bc2 100644 --- a/pkg/server/api/v3_notes.go +++ b/pkg/server/api/v3_notes.go @@ -24,7 +24,7 @@ import ( "net/http" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/presenters" @@ -52,7 +52,7 @@ func (a *API) UpdateNote(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) noteUUID := vars["noteUUID"] - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -70,7 +70,7 @@ func (a *API) UpdateNote(w http.ResponseWriter, r *http.Request) { return } - var note database.Note + var note models.Note if err := a.App.DB.Where("uuid = ? AND user_id = ?", noteUUID, user.ID).First(¬e).Error; err != nil { handlers.DoError(w, "finding note", err, http.StatusInternalServerError) return @@ -89,7 +89,7 @@ func (a *API) UpdateNote(w http.ResponseWriter, r *http.Request) { return } - var book database.Book + var book models.Book if err := tx.Where("uuid = ? AND user_id = ?", note.BookUUID, user.ID).First(&book).Error; err != nil { tx.Rollback() handlers.DoError(w, fmt.Sprintf("finding book %s to preload", note.BookUUID), err, http.StatusInternalServerError) @@ -119,13 +119,13 @@ func (a *API) DeleteNote(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) noteUUID := vars["noteUUID"] - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return } - var note database.Note + var note models.Note if err := a.App.DB.Where("uuid = ? AND user_id = ?", noteUUID, user.ID).Preload("Book").First(¬e).Error; err != nil { handlers.DoError(w, "finding note", err, http.StatusInternalServerError) return @@ -171,7 +171,7 @@ type CreateNoteResp struct { // CreateNote creates a note func (a *API) CreateNote(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -190,7 +190,7 @@ func (a *API) CreateNote(w http.ResponseWriter, r *http.Request) { return } - var book database.Book + var book models.Book if err := a.App.DB.Where("uuid = ? AND user_id = ?", params.BookUUID, user.ID).First(&book).Error; err != nil { handlers.DoError(w, "finding book", err, http.StatusInternalServerError) return diff --git a/pkg/server/api/v3_notes_test.go b/pkg/server/api/v3_notes_test.go index 3c57fe27..0449d3e3 100644 --- a/pkg/server/api/v3_notes_test.go +++ b/pkg/server/api/v3_notes_test.go @@ -26,7 +26,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" ) @@ -44,7 +44,7 @@ func TestCreateNote(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("max_usn", 101), "preparing user max_usn") - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", USN: 58, @@ -59,12 +59,12 @@ func TestCreateNote(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusCreated, "") - var noteRecord database.Note - var bookRecord database.Book - var userRecord database.User + var noteRecord models.Note + var bookRecord models.Book + var userRecord models.User var bookCount, noteCount int - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.First(¬eRecord), "finding note") testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&bookRecord), "finding book") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user record") @@ -249,20 +249,20 @@ func TestUpdateNote(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("max_usn", 101), "preparing user max_usn") - b1 := database.Book{ + b1 := models.Book{ UUID: b1UUID, UserID: user.ID, Label: "css", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - b2 := database.Book{ + b2 := models.Book{ UUID: b2UUID, UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b2), "preparing b2") - note := database.Note{ + note := models.Note{ UserID: user.ID, UUID: tc.noteUUID, BookUUID: tc.noteBookUUID, @@ -280,12 +280,12 @@ func TestUpdateNote(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "status code mismatch for test case") - var bookRecord database.Book - var noteRecord database.Note - var userRecord database.User + var bookRecord models.Book + var noteRecord models.Note + var userRecord models.User var noteCount, bookCount int - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.Where("uuid = ?", note.UUID).First(¬eRecord), "finding note") testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&bookRecord), "finding book") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user record") @@ -345,13 +345,13 @@ func TestDeleteNote(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("max_usn", 981), "preparing user max_usn") - b1 := database.Book{ + b1 := models.Book{ UUID: b1UUID, UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - note := database.Note{ + note := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: tc.content, @@ -368,12 +368,12 @@ func TestDeleteNote(t *testing.T) { // Test assert.StatusCodeEquals(t, res, http.StatusOK, "") - var bookRecord database.Book - var noteRecord database.Note - var userRecord database.User + var bookRecord models.Book + var noteRecord models.Note + var userRecord models.User var bookCount, noteCount int - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting books") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting books") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes") testutils.MustExec(t, testutils.DB.Where("uuid = ?", note.UUID).First(¬eRecord), "finding note") testutils.MustExec(t, testutils.DB.Where("id = ?", b1.ID).First(&bookRecord), "finding book") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user record") diff --git a/pkg/server/api/v3_sync.go b/pkg/server/api/v3_sync.go index a04f41fa..dd70ae90 100644 --- a/pkg/server/api/v3_sync.go +++ b/pkg/server/api/v3_sync.go @@ -26,7 +26,7 @@ import ( "strconv" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/log" @@ -66,7 +66,7 @@ type SyncFragNote struct { } // NewFragNote presents the given note as a SyncFragNote -func NewFragNote(note database.Note) SyncFragNote { +func NewFragNote(note models.Note) SyncFragNote { return SyncFragNote{ UUID: note.UUID, USN: note.USN, @@ -94,7 +94,7 @@ type SyncFragBook struct { } // NewFragBook presents the given book as a SyncFragBook -func NewFragBook(book database.Book) SyncFragBook { +func NewFragBook(book models.Book) SyncFragBook { return SyncFragBook{ UUID: book.UUID, USN: book.USN, @@ -122,11 +122,11 @@ func (e *queryParamError) Error() string { } func (a *API) newFragment(userID, userMaxUSN, afterUSN, limit int) (SyncFragment, error) { - var notes []database.Note + var notes []models.Note if err := a.App.DB.Where("user_id = ? AND usn > ? AND usn <= ?", userID, afterUSN, userMaxUSN).Order("usn ASC").Limit(limit).Find(¬es).Error; err != nil { return SyncFragment{}, nil } - var books []database.Book + var books []models.Book if err := a.App.DB.Where("user_id = ? AND usn > ? AND usn <= ?", userID, afterUSN, userMaxUSN).Order("usn ASC").Limit(limit).Find(&books).Error; err != nil { return SyncFragment{}, nil } @@ -168,16 +168,16 @@ func (a *API) newFragment(userID, userMaxUSN, afterUSN, limit int) (SyncFragment fragMaxUSN = item.usn switch v := item.val.(type) { - case database.Note: - note := item.val.(database.Note) + case models.Note: + note := item.val.(models.Note) if note.Deleted { fragExpungedNotes = append(fragExpungedNotes, note.UUID) } else { fragNotes = append(fragNotes, NewFragNote(note)) } - case database.Book: - book := item.val.(database.Book) + case models.Book: + book := item.val.(models.Book) if book.Deleted { fragExpungedBooks = append(fragExpungedBooks, book.UUID) @@ -249,7 +249,7 @@ type GetSyncFragmentResp struct { // GetSyncFragment responds with a sync fragment func (a *API) GetSyncFragment(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return @@ -282,7 +282,7 @@ type GetSyncStateResp struct { // GetSyncState responds with a sync fragment func (a *API) GetSyncState(w http.ResponseWriter, r *http.Request) { - user, ok := r.Context().Value(helpers.KeyUser).(database.User) + user, ok := r.Context().Value(helpers.KeyUser).(models.User) if !ok { handlers.DoError(w, "No authenticated user found", nil, http.StatusInternalServerError) return diff --git a/pkg/server/app/books.go b/pkg/server/app/books.go index 2fa0a9b1..936f0ee9 100644 --- a/pkg/server/app/books.go +++ b/pkg/server/app/books.go @@ -19,28 +19,28 @@ package app import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/helpers" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) // CreateBook creates a book with the next usn and updates the user's max_usn -func (a *App) CreateBook(user database.User, name string) (database.Book, error) { +func (a *App) CreateBook(user models.User, name string) (models.Book, error) { tx := a.DB.Begin() nextUSN, err := incrementUserUSN(tx, user.ID) if err != nil { tx.Rollback() - return database.Book{}, errors.Wrap(err, "incrementing user max_usn") + return models.Book{}, errors.Wrap(err, "incrementing user max_usn") } uuid, err := helpers.GenUUID() if err != nil { - return database.Book{}, err + return models.Book{}, err } - book := database.Book{ + book := models.Book{ UUID: uuid, UserID: user.ID, Label: name, @@ -59,7 +59,7 @@ func (a *App) CreateBook(user database.User, name string) (database.Book, error) } // DeleteBook marks a book deleted with the next usn and updates the user's max_usn -func (a *App) DeleteBook(tx *gorm.DB, user database.User, book database.Book) (database.Book, error) { +func (a *App) DeleteBook(tx *gorm.DB, user models.User, book models.Book) (models.Book, error) { if user.ID != book.UserID { return book, errors.New("Not allowed") } @@ -82,7 +82,7 @@ func (a *App) DeleteBook(tx *gorm.DB, user database.User, book database.Book) (d } // UpdateBook updaates the book, the usn and the user's max_usn -func (a *App) UpdateBook(tx *gorm.DB, user database.User, book database.Book, label *string) (database.Book, error) { +func (a *App) UpdateBook(tx *gorm.DB, user models.User, book models.Book, label *string) (models.Book, error) { if user.ID != book.UserID { return book, errors.New("Not allowed") } diff --git a/pkg/server/app/books_test.go b/pkg/server/app/books_test.go index 17c2ddcb..e0f1887b 100644 --- a/pkg/server/app/books_test.go +++ b/pkg/server/app/books_test.go @@ -24,7 +24,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -72,10 +72,10 @@ func TestCreateBook(t *testing.T) { } var bookCount int - var bookRecord database.Book - var userRecord database.User + var bookRecord models.Book + var userRecord models.User - if err := testutils.DB.Model(&database.Book{}).Count(&bookCount).Error; err != nil { + if err := testutils.DB.Model(&models.Book{}).Count(&bookCount).Error; err != nil { t.Fatal(errors.Wrap(err, "counting books")) } if err := testutils.DB.First(&bookRecord).Error; err != nil { @@ -128,7 +128,7 @@ func TestDeleteBook(t *testing.T) { anotherUser := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&anotherUser).Update("max_usn", 55), fmt.Sprintf("preparing user max_usn for test case %d", idx)) - book := database.Book{UserID: user.ID, Label: "js", Deleted: false} + book := models.Book{UserID: user.ID, Label: "js", Deleted: false} testutils.MustExec(t, testutils.DB.Save(&book), fmt.Sprintf("preparing book for test case %d", idx)) tx := testutils.DB.Begin() @@ -141,10 +141,10 @@ func TestDeleteBook(t *testing.T) { tx.Commit() var bookCount int - var bookRecord database.Book - var userRecord database.User + var bookRecord models.Book + var userRecord models.User - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), fmt.Sprintf("counting books for test case %d", idx)) + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), fmt.Sprintf("counting books for test case %d", idx)) testutils.MustExec(t, testutils.DB.First(&bookRecord), fmt.Sprintf("finding book for test case %d", idx)) testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), fmt.Sprintf("finding user for test case %d", idx)) @@ -206,7 +206,7 @@ func TestUpdateBook(t *testing.T) { anotherUser := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&anotherUser).Update("max_usn", 55), fmt.Sprintf("preparing user max_usn for test case %d", idx)) - b := database.Book{UserID: user.ID, Deleted: false, Label: tc.expectedLabel} + b := models.Book{UserID: user.ID, Deleted: false, Label: tc.expectedLabel} testutils.MustExec(t, testutils.DB.Save(&b), fmt.Sprintf("preparing book for test case %d", idx)) c := clock.NewMock() @@ -224,9 +224,9 @@ func TestUpdateBook(t *testing.T) { tx.Commit() var bookCount int - var bookRecord database.Book - var userRecord database.User - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), fmt.Sprintf("counting books for test case %d", idx)) + var bookRecord models.Book + var userRecord models.User + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), fmt.Sprintf("counting books for test case %d", idx)) testutils.MustExec(t, testutils.DB.First(&bookRecord), fmt.Sprintf("finding book for test case %d", idx)) testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), fmt.Sprintf("finding user for test case %d", idx)) diff --git a/pkg/server/app/helpers.go b/pkg/server/app/helpers.go index ea72d107..56ff97f5 100644 --- a/pkg/server/app/helpers.go +++ b/pkg/server/app/helpers.go @@ -19,7 +19,7 @@ package app import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) @@ -31,7 +31,7 @@ func incrementUserUSN(tx *gorm.DB, userID int) (int, error) { return 0, errors.Wrap(err, "incrementing user max_usn") } - var user database.User + var user models.User if err := tx.Select("max_usn").Where("id = ?", userID).First(&user).Error; err != nil { return 0, errors.Wrap(err, "getting the updated user max_usn") } diff --git a/pkg/server/app/helpers_test.go b/pkg/server/app/helpers_test.go index b0b32d23..e2b71774 100644 --- a/pkg/server/app/helpers_test.go +++ b/pkg/server/app/helpers_test.go @@ -23,7 +23,7 @@ import ( "testing" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -60,7 +60,7 @@ func TestIncremenetUserUSN(t *testing.T) { tx.Commit() // test - var userRecord database.User + var userRecord models.User testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), fmt.Sprintf("finding user for test case %d", idx)) assert.Equal(t, userRecord.MaxUSN, tc.expectedMaxUSN, fmt.Sprintf("user max_usn mismatch for case %d", idx)) diff --git a/pkg/server/app/notes.go b/pkg/server/app/notes.go index f3dbc86e..01f4c7e5 100644 --- a/pkg/server/app/notes.go +++ b/pkg/server/app/notes.go @@ -19,7 +19,7 @@ package app import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/helpers" "github.com/jinzhu/gorm" "github.com/pkg/errors" @@ -27,13 +27,13 @@ import ( // CreateNote creates a note with the next usn and updates the user's max_usn. // It returns the created note. -func (a *App) CreateNote(user database.User, bookUUID, content string, addedOn *int64, editedOn *int64, public bool, client string) (database.Note, error) { +func (a *App) CreateNote(user models.User, bookUUID, content string, addedOn *int64, editedOn *int64, public bool, client string) (models.Note, error) { tx := a.DB.Begin() nextUSN, err := incrementUserUSN(tx, user.ID) if err != nil { tx.Rollback() - return database.Note{}, errors.Wrap(err, "incrementing user max_usn") + return models.Note{}, errors.Wrap(err, "incrementing user max_usn") } var noteAddedOn int64 @@ -52,10 +52,10 @@ func (a *App) CreateNote(user database.User, bookUUID, content string, addedOn * uuid, err := helpers.GenUUID() if err != nil { - return database.Note{}, err + return models.Note{}, err } - note := database.Note{ + note := models.Note{ UUID: uuid, BookUUID: bookUUID, UserID: user.ID, @@ -112,7 +112,7 @@ func (r UpdateNoteParams) GetPublic() bool { } // UpdateNote creates a note with the next usn and updates the user's max_usn -func (a *App) UpdateNote(tx *gorm.DB, user database.User, note database.Note, p *UpdateNoteParams) (database.Note, error) { +func (a *App) UpdateNote(tx *gorm.DB, user models.User, note models.Note, p *UpdateNoteParams) (models.Note, error) { nextUSN, err := incrementUserUSN(tx, user.ID) if err != nil { return note, errors.Wrap(err, "incrementing user max_usn") @@ -142,7 +142,7 @@ func (a *App) UpdateNote(tx *gorm.DB, user database.User, note database.Note, p } // DeleteNote marks a note deleted with the next usn and updates the user's max_usn -func (a *App) DeleteNote(tx *gorm.DB, user database.User, note database.Note) (database.Note, error) { +func (a *App) DeleteNote(tx *gorm.DB, user models.User, note models.Note) (models.Note, error) { nextUSN, err := incrementUserUSN(tx, user.ID) if err != nil { return note, errors.Wrap(err, "incrementing user max_usn") @@ -161,8 +161,8 @@ func (a *App) DeleteNote(tx *gorm.DB, user database.User, note database.Note) (d } // GetUserNoteByUUID retrives a digest by the uuid for the given user -func (a *App) GetUserNoteByUUID(userID int, uuid string) (*database.Note, error) { - var ret database.Note +func (a *App) GetUserNoteByUUID(userID int, uuid string) (*models.Note, error) { + var ret models.Note conn := a.DB.Where("user_id = ? AND uuid = ?", userID, uuid).First(&ret) if conn.RecordNotFound() { diff --git a/pkg/server/app/notes_test.go b/pkg/server/app/notes_test.go index 4ce6c701..88186d7f 100644 --- a/pkg/server/app/notes_test.go +++ b/pkg/server/app/notes_test.go @@ -25,7 +25,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -82,7 +82,7 @@ func TestCreateNote(t *testing.T) { anotherUser := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&anotherUser).Update("max_usn", 55), fmt.Sprintf("preparing user max_usn for test case %d", idx)) - b1 := database.Book{UserID: user.ID, Label: "js", Deleted: false} + b1 := models.Book{UserID: user.ID, Label: "js", Deleted: false} testutils.MustExec(t, testutils.DB.Save(&b1), fmt.Sprintf("preparing b1 for test case %d", idx)) a := NewTest(&App{ @@ -97,11 +97,11 @@ func TestCreateNote(t *testing.T) { tx.Commit() var bookCount, noteCount int - var noteRecord database.Note - var userRecord database.User + var noteRecord models.Note + var userRecord models.User - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), fmt.Sprintf("counting book for test case %d", idx)) - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), fmt.Sprintf("counting notes for test case %d", idx)) + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), fmt.Sprintf("counting book for test case %d", idx)) + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), fmt.Sprintf("counting notes for test case %d", idx)) testutils.MustExec(t, testutils.DB.First(¬eRecord), fmt.Sprintf("finding note for test case %d", idx)) testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), fmt.Sprintf("finding user for test case %d", idx)) @@ -145,10 +145,10 @@ func TestUpdateNote(t *testing.T) { anotherUser := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&anotherUser).Update("max_usn", 55), "preparing user max_usn for test case") - b1 := database.Book{UserID: user.ID, Label: "js", Deleted: false} + b1 := models.Book{UserID: user.ID, Label: "js", Deleted: false} testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1 for test case") - note := database.Note{UserID: user.ID, Deleted: false, Body: "test content", BookUUID: b1.UUID} + note := models.Note{UserID: user.ID, Deleted: false, Body: "test content", BookUUID: b1.UUID} testutils.MustExec(t, testutils.DB.Save(¬e), "preparing note for test case") c := clock.NewMock() @@ -170,11 +170,11 @@ func TestUpdateNote(t *testing.T) { tx.Commit() var bookCount, noteCount int - var noteRecord database.Note - var userRecord database.User + var noteRecord models.Note + var userRecord models.User - testutils.MustExec(t, testutils.DB.Model(&database.Book{}).Count(&bookCount), "counting book for test case") - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), "counting notes for test case") + testutils.MustExec(t, testutils.DB.Model(&models.Book{}).Count(&bookCount), "counting book for test case") + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), "counting notes for test case") testutils.MustExec(t, testutils.DB.First(¬eRecord), "finding note for test case") testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), "finding user for test case") @@ -220,10 +220,10 @@ func TestDeleteNote(t *testing.T) { anotherUser := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&anotherUser).Update("max_usn", 55), fmt.Sprintf("preparing user max_usn for test case %d", idx)) - b1 := database.Book{UserID: user.ID, Label: "testBook"} + b1 := models.Book{UserID: user.ID, Label: "testBook"} testutils.MustExec(t, testutils.DB.Save(&b1), fmt.Sprintf("preparing b1 for test case %d", idx)) - note := database.Note{UserID: user.ID, Deleted: false, Body: "test content", BookUUID: b1.UUID} + note := models.Note{UserID: user.ID, Deleted: false, Body: "test content", BookUUID: b1.UUID} testutils.MustExec(t, testutils.DB.Save(¬e), fmt.Sprintf("preparing note for test case %d", idx)) a := NewTest(nil) @@ -237,10 +237,10 @@ func TestDeleteNote(t *testing.T) { tx.Commit() var noteCount int - var noteRecord database.Note - var userRecord database.User + var noteRecord models.Note + var userRecord models.User - testutils.MustExec(t, testutils.DB.Model(&database.Note{}).Count(¬eCount), fmt.Sprintf("counting notes for test case %d", idx)) + testutils.MustExec(t, testutils.DB.Model(&models.Note{}).Count(¬eCount), fmt.Sprintf("counting notes for test case %d", idx)) testutils.MustExec(t, testutils.DB.First(¬eRecord), fmt.Sprintf("finding note for test case %d", idx)) testutils.MustExec(t, testutils.DB.Where("id = ?", user.ID).First(&userRecord), fmt.Sprintf("finding user for test case %d", idx)) diff --git a/pkg/server/app/sessions.go b/pkg/server/app/sessions.go index d4831053..ed979d7c 100644 --- a/pkg/server/app/sessions.go +++ b/pkg/server/app/sessions.go @@ -22,19 +22,19 @@ import ( "time" "github.com/dnote/dnote/pkg/server/crypt" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) // CreateSession returns a new session for the user of the given id -func (a *App) CreateSession(userID int) (database.Session, error) { +func (a *App) CreateSession(userID int) (models.Session, error) { key, err := crypt.GetRandomStr(32) if err != nil { - return database.Session{}, errors.Wrap(err, "generating key") + return models.Session{}, errors.Wrap(err, "generating key") } - session := database.Session{ + session := models.Session{ UserID: userID, Key: key, LastUsedAt: time.Now(), @@ -42,7 +42,7 @@ func (a *App) CreateSession(userID int) (database.Session, error) { } if err := a.DB.Save(&session).Error; err != nil { - return database.Session{}, errors.Wrap(err, "saving session") + return models.Session{}, errors.Wrap(err, "saving session") } return session, nil @@ -51,7 +51,7 @@ func (a *App) CreateSession(userID int) (database.Session, error) { // DeleteUserSessions deletes all existing sessions for the given user. It effectively // invalidates all existing sessions. func (a *App) DeleteUserSessions(db *gorm.DB, userID int) error { - if err := db.Debug().Where("user_id = ?", userID).Delete(&database.Session{}).Error; err != nil { + if err := db.Debug().Where("user_id = ?", userID).Delete(&models.Session{}).Error; err != nil { return errors.Wrap(err, "deleting sessions") } @@ -60,7 +60,7 @@ func (a *App) DeleteUserSessions(db *gorm.DB, userID int) error { // DeleteSession deletes the session that match the given info func (a *App) DeleteSession(sessionKey string) error { - if err := a.DB.Where("key = ?", sessionKey).Delete(&database.Session{}).Error; err != nil { + if err := a.DB.Where("key = ?", sessionKey).Delete(&models.Session{}).Error; err != nil { return errors.Wrap(err, "deleting the session") } diff --git a/pkg/server/app/users.go b/pkg/server/app/users.go index 1d3c9456..576866ac 100644 --- a/pkg/server/app/users.go +++ b/pkg/server/app/users.go @@ -19,7 +19,7 @@ package app import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/log" "github.com/dnote/dnote/pkg/server/token" "github.com/jinzhu/gorm" @@ -28,17 +28,17 @@ import ( ) // TouchLastLoginAt updates the last login timestamp -func (a *App) TouchLastLoginAt(user database.User, tx *gorm.DB) error { +func (a *App) TouchLastLoginAt(user models.User, tx *gorm.DB) error { t := a.Clock.Now() - if err := tx.Model(&user).Update(database.User{LastLoginAt: &t}).Error; err != nil { + if err := tx.Model(&user).Update(models.User{LastLoginAt: &t}).Error; err != nil { return errors.Wrap(err, "updating last_login_at") } return nil } -func createEmailPreference(user database.User, tx *gorm.DB) error { - p := database.EmailPreference{ +func createEmailPreference(user models.User, tx *gorm.DB) error { + p := models.EmailPreference{ UserID: user.ID, } if err := tx.Save(&p).Error; err != nil { @@ -49,21 +49,21 @@ func createEmailPreference(user database.User, tx *gorm.DB) error { } // CreateUser creates a user -func (a *App) CreateUser(email, password string) (database.User, error) { +func (a *App) CreateUser(email, password string) (models.User, error) { tx := a.DB.Begin() var count int - if err := tx.Model(database.Account{}).Where("email = ?", email).Count(&count).Error; err != nil { - return database.User{}, errors.Wrap(err, "counting user") + if err := tx.Model(models.Account{}).Where("email = ?", email).Count(&count).Error; err != nil { + return models.User{}, errors.Wrap(err, "counting user") } if count > 0 { - return database.User{}, ErrDuplicateEmail + return models.User{}, ErrDuplicateEmail } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { tx.Rollback() - return database.User{}, errors.Wrap(err, "hashing password") + return models.User{}, errors.Wrap(err, "hashing password") } // Grant all privileges if self-hosting @@ -74,34 +74,34 @@ func (a *App) CreateUser(email, password string) (database.User, error) { pro = false } - user := database.User{ + user := models.User{ Cloud: pro, } if err = tx.Save(&user).Error; err != nil { tx.Rollback() - return database.User{}, errors.Wrap(err, "saving user") + return models.User{}, errors.Wrap(err, "saving user") } - account := database.Account{ - Email: database.ToNullString(email), - Password: database.ToNullString(string(hashedPassword)), + account := models.Account{ + Email: models.ToNullString(email), + Password: models.ToNullString(string(hashedPassword)), UserID: user.ID, } if err = tx.Save(&account).Error; err != nil { tx.Rollback() - return database.User{}, errors.Wrap(err, "saving account") + return models.User{}, errors.Wrap(err, "saving account") } - if _, err := token.Create(tx, user.ID, database.TokenTypeEmailPreference); err != nil { + if _, err := token.Create(tx, user.ID, models.TokenTypeEmailPreference); err != nil { tx.Rollback() - return database.User{}, errors.Wrap(err, "creating email verificaiton token") + return models.User{}, errors.Wrap(err, "creating email verificaiton token") } if err := createEmailPreference(user, tx); err != nil { tx.Rollback() - return database.User{}, errors.Wrap(err, "creating email preference") + return models.User{}, errors.Wrap(err, "creating email preference") } if err := a.TouchLastLoginAt(user, tx); err != nil { tx.Rollback() - return database.User{}, errors.Wrap(err, "updating last login") + return models.User{}, errors.Wrap(err, "updating last login") } tx.Commit() @@ -110,8 +110,8 @@ func (a *App) CreateUser(email, password string) (database.User, error) { } // Authenticate authenticates a user -func (a *App) Authenticate(email, password string) (*database.User, error) { - var account database.Account +func (a *App) Authenticate(email, password string) (*models.User, error) { + var account models.Account conn := a.DB.Where("email = ?", email).First(&account) if conn.RecordNotFound() { return nil, ErrNotFound @@ -124,7 +124,7 @@ func (a *App) Authenticate(email, password string) (*database.User, error) { return nil, ErrLoginInvalid } - var user database.User + var user models.User err = a.DB.Where("id = ?", account.UserID).First(&user).Error if err != nil { return nil, errors.Wrap(err, "finding user") @@ -134,7 +134,7 @@ func (a *App) Authenticate(email, password string) (*database.User, error) { } // SignIn signs in a user -func (a *App) SignIn(user *database.User) (*database.Session, error) { +func (a *App) SignIn(user *models.User) (*models.Session, error) { err := a.TouchLastLoginAt(*user, a.DB) if err != nil { log.ErrorWrap(err, "touching login timestamp") diff --git a/pkg/server/app/users_test.go b/pkg/server/app/users_test.go index 81864b03..d4f2fd41 100644 --- a/pkg/server/app/users_test.go +++ b/pkg/server/app/users_test.go @@ -24,7 +24,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" @@ -60,8 +60,8 @@ func TestCreateUser_ProValue(t *testing.T) { } var userCount int - var userRecord database.User - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") + var userRecord models.User + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") testutils.MustExec(t, testutils.DB.First(&userRecord), "finding user") assert.Equal(t, userCount, 1, "book count mismatch") @@ -83,12 +83,12 @@ func TestCreateUser(t *testing.T) { } var userCount int - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") assert.Equal(t, userCount, 1, "book count mismatch") var accountCount int - var accountRecord database.Account - testutils.MustExec(t, testutils.DB.Model(&database.Account{}).Count(&accountCount), "counting account") + var accountRecord models.Account + testutils.MustExec(t, testutils.DB.Model(&models.Account{}).Count(&accountCount), "counting account") testutils.MustExec(t, testutils.DB.First(&accountRecord), "finding account") assert.Equal(t, accountCount, 1, "account count mismatch") @@ -101,8 +101,8 @@ func TestCreateUser(t *testing.T) { t.Run("duplicate email", func(t *testing.T) { defer testutils.ClearData(testutils.DB) - aliceUser := database.User{} - aliceAccount := database.Account{UserID: aliceUser.ID, Email: database.ToNullString("alice@example.com")} + aliceUser := models.User{} + aliceAccount := models.Account{UserID: aliceUser.ID, Email: models.ToNullString("alice@example.com")} testutils.MustExec(t, testutils.DB.Save(&aliceUser), "preparing a user") testutils.MustExec(t, testutils.DB.Save(&aliceAccount), "preparing an account") @@ -112,8 +112,8 @@ func TestCreateUser(t *testing.T) { assert.Equal(t, err, ErrDuplicateEmail, "error mismatch") var userCount, accountCount int - testutils.MustExec(t, testutils.DB.Model(&database.User{}).Count(&userCount), "counting user") - testutils.MustExec(t, testutils.DB.Model(&database.Account{}).Count(&accountCount), "counting account") + testutils.MustExec(t, testutils.DB.Model(&models.User{}).Count(&userCount), "counting user") + testutils.MustExec(t, testutils.DB.Model(&models.Account{}).Count(&accountCount), "counting account") assert.Equal(t, userCount, 1, "user count mismatch") assert.Equal(t, accountCount, 1, "account count mismatch") diff --git a/pkg/server/context/user.go b/pkg/server/context/user.go index 510f5d31..df8a7a84 100644 --- a/pkg/server/context/user.go +++ b/pkg/server/context/user.go @@ -3,7 +3,7 @@ package context import ( "context" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) const ( @@ -14,20 +14,20 @@ const ( type privateKey string // WithUser creates a new context with the given user -func WithUser(ctx context.Context, user *database.User) context.Context { +func WithUser(ctx context.Context, user *models.User) context.Context { return context.WithValue(ctx, userKey, user) } // WithToken creates a new context with the given user -func WithToken(ctx context.Context, tok *database.Token) context.Context { +func WithToken(ctx context.Context, tok *models.Token) context.Context { return context.WithValue(ctx, tokenKey, tok) } // User retrieves a user from the given context. It returns a pointer to // a user. If the context does not contain a user, it returns nil. -func User(ctx context.Context) *database.User { +func User(ctx context.Context) *models.User { if temp := ctx.Value(userKey); temp != nil { - if user, ok := temp.(*database.User); ok { + if user, ok := temp.(*models.User); ok { return user } } @@ -36,9 +36,9 @@ func User(ctx context.Context) *database.User { } // Token retrieves a token from the given context. -func Token(ctx context.Context) *database.Token { +func Token(ctx context.Context) *models.Token { if temp := ctx.Value(tokenKey); temp != nil { - if tok, ok := temp.(*database.Token); ok { + if tok, ok := temp.(*models.Token); ok { return tok } } diff --git a/pkg/server/controllers/helpers.go b/pkg/server/controllers/helpers.go index def5960a..f0d69f99 100644 --- a/pkg/server/controllers/helpers.go +++ b/pkg/server/controllers/helpers.go @@ -8,7 +8,7 @@ import ( "time" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/log" "github.com/dnote/dnote/pkg/server/views" "github.com/gorilla/schema" @@ -233,7 +233,7 @@ func handleJSONError(w http.ResponseWriter, err error, msg string) { // respondWithSession makes a HTTP response with the session from the user with the given userID. // It sets the HTTP-Only cookie for browser clients and also sends a JSON response for non-browser clients. -func respondWithSession(w http.ResponseWriter, statusCode int, session *database.Session) { +func respondWithSession(w http.ResponseWriter, statusCode int, session *models.Session) { setSessionCookie(w, session.Key, session.ExpiresAt) response := SessionResponse{ diff --git a/pkg/server/controllers/notes.go b/pkg/server/controllers/notes.go index 92666a1c..3613cd22 100644 --- a/pkg/server/controllers/notes.go +++ b/pkg/server/controllers/notes.go @@ -5,7 +5,7 @@ import ( "github.com/dnote/dnote/pkg/server/app" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/views" // "github.com/nadproject/nad/pkg/server/context" ) @@ -31,7 +31,7 @@ func (n *Notes) Index(w http.ResponseWriter, r *http.Request) { var vd views.Data vd.Yield = struct { - Notes []database.Note + Notes []models.Note }{ Notes: nil, } diff --git a/pkg/server/controllers/users.go b/pkg/server/controllers/users.go index 53dd6f37..65bb7654 100644 --- a/pkg/server/controllers/users.go +++ b/pkg/server/controllers/users.go @@ -5,7 +5,7 @@ import ( "github.com/dnote/dnote/pkg/server/app" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/log" "github.com/dnote/dnote/pkg/server/views" "github.com/pkg/errors" @@ -77,7 +77,7 @@ type LoginForm struct { Password string `schema:"password" json:"password"` } -func (u *Users) login(r *http.Request) (*database.Session, error) { +func (u *Users) login(r *http.Request) (*models.Session, error) { var form LoginForm if err := parseRequestData(r, &form); err != nil { return nil, err diff --git a/pkg/server/handlers/auth.go b/pkg/server/handlers/auth.go index 2917e1b7..4c3d16c2 100644 --- a/pkg/server/handlers/auth.go +++ b/pkg/server/handlers/auth.go @@ -7,16 +7,16 @@ import ( "time" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/log" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) -func authWithToken(db *gorm.DB, r *http.Request, tokenType string, p *AuthParams) (database.User, database.Token, bool, error) { - var user database.User - var token database.Token +func authWithToken(db *gorm.DB, r *http.Request, tokenType string, p *AuthParams) (models.User, models.Token, bool, error) { + var user models.User + var token models.Token query := r.URL.Query() tokenValue := query.Get("token") @@ -132,8 +132,8 @@ func TokenAuth(a *app.App, next http.HandlerFunc, tokenType string, p *AuthParam } // AuthWithSession performs user authentication with session -func AuthWithSession(db *gorm.DB, r *http.Request, p *AuthParams) (database.User, bool, error) { - var user database.User +func AuthWithSession(db *gorm.DB, r *http.Request, p *AuthParams) (models.User, bool, error) { + var user models.User sessionKey, err := GetCredential(r) if err != nil { @@ -143,7 +143,7 @@ func AuthWithSession(db *gorm.DB, r *http.Request, p *AuthParams) (database.User return user, false, nil } - var session database.Session + var session models.Session conn := db.Where("key = ?", sessionKey).First(&session) if conn.RecordNotFound() { diff --git a/pkg/server/handlers/helpers_test.go b/pkg/server/handlers/helpers_test.go index 9c1121bc..0d551422 100644 --- a/pkg/server/handlers/helpers_test.go +++ b/pkg/server/handlers/helpers_test.go @@ -27,7 +27,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/server/app" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -184,13 +184,13 @@ func TestAuthMiddleware(t *testing.T) { defer testutils.ClearData(testutils.DB) user := testutils.SetupUserData() - session := database.Session{ + session := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 24), } testutils.MustExec(t, testutils.DB.Save(&session), "preparing session") - session2 := database.Session{ + session2 := models.Session{ Key: "Vvgm3eBXfXGEFWERI7faiRJ3DAzJw+7DdT9J1LEyNfI=", UserID: user.ID, ExpiresAt: time.Now().Add(-time.Hour * 24), @@ -298,7 +298,7 @@ func TestAuthMiddleware_ProOnly(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("cloud", false), "preparing session") - session := database.Session{ + session := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -413,7 +413,7 @@ func TestAuthMiddleware_RedirectGuestsToLogin(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("cloud", false), "preparing session") - session := database.Session{ + session := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -435,13 +435,13 @@ func TestTokenAuthMiddleWare(t *testing.T) { defer testutils.ClearData(testutils.DB) user := testutils.SetupUserData() - tok := database.Token{ + tok := models.Token{ UserID: user.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "xpwFnc0MdllFUePDq9DLeQ==", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") - session := database.Session{ + session := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -453,7 +453,7 @@ func TestTokenAuthMiddleWare(t *testing.T) { } a := &app.App{DB: testutils.DB} - server := httptest.NewServer(TokenAuth(a, handler, database.TokenTypeEmailPreference, nil)) + server := httptest.NewServer(TokenAuth(a, handler, models.TokenTypeEmailPreference, nil)) defer server.Close() t.Run("with token", func(t *testing.T) { @@ -566,13 +566,13 @@ func TestTokenAuthMiddleWare_ProOnly(t *testing.T) { user := testutils.SetupUserData() testutils.MustExec(t, testutils.DB.Model(&user).Update("cloud", false), "preparing session") - tok := database.Token{ + tok := models.Token{ UserID: user.ID, - Type: database.TokenTypeEmailPreference, + Type: models.TokenTypeEmailPreference, Value: "xpwFnc0MdllFUePDq9DLeQ==", } testutils.MustExec(t, testutils.DB.Save(&tok), "preparing token") - session := database.Session{ + session := models.Session{ Key: "A9xgggqzTHETy++GDi1NpDNe0iyqosPm9bitdeNGkJU=", UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -584,7 +584,7 @@ func TestTokenAuthMiddleWare_ProOnly(t *testing.T) { } a := &app.App{DB: testutils.DB} - server := httptest.NewServer(TokenAuth(a, handler, database.TokenTypeEmailPreference, &AuthParams{ + server := httptest.NewServer(TokenAuth(a, handler, models.TokenTypeEmailPreference, &AuthParams{ ProOnly: true, })) diff --git a/pkg/server/job/remind/inactive.go b/pkg/server/job/remind/inactive.go index e7fc0f03..bb4e5080 100644 --- a/pkg/server/job/remind/inactive.go +++ b/pkg/server/job/remind/inactive.go @@ -22,7 +22,7 @@ import ( "github.com/dnote/dnote/pkg/clock" "github.com/dnote/dnote/pkg/server/app" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/log" "github.com/dnote/dnote/pkg/server/mailer" "github.com/jinzhu/gorm" @@ -44,8 +44,8 @@ type inactiveUserInfo struct { sampleNoteUUID string } -func (c *Context) sampleUserNote(userID int) (database.Note, error) { - var ret database.Note +func (c *Context) sampleUserNote(userID int) (models.Note, error) { + var ret models.Note // FIXME: ordering by random() requires a sequential scan on the whole table and does not scale if err := c.DB.Where("user_id = ?", userID).Order("random() DESC").First(&ret).Error; err != nil { return ret, errors.Wrap(err, "getting a random note") @@ -103,7 +103,7 @@ GROUP BY notes.user_id, accounts.email`, threshold).Rows() } func (c *Context) canNotify(info inactiveUserInfo) (bool, error) { - var pref database.EmailPreference + var pref models.EmailPreference if err := c.DB.Where("user_id = ?", info.userID).First(&pref).Error; err != nil { return false, errors.Wrap(err, "getting email preference") } @@ -112,7 +112,7 @@ func (c *Context) canNotify(info inactiveUserInfo) (bool, error) { return false, nil } - var notif database.Notification + var notif models.Notification conn := c.DB.Where("user_id = ? AND type = ?", info.userID, mailer.EmailTypeInactiveReminder).Order("created_at DESC").First(¬if) if conn.RecordNotFound() { @@ -143,7 +143,7 @@ func (c *Context) process(info inactiveUserInfo) error { return errors.Wrap(err, "getting sender email") } - tok, err := mailer.GetToken(c.DB, info.userID, database.TokenTypeEmailPreference) + tok, err := mailer.GetToken(c.DB, info.userID, models.TokenTypeEmailPreference) if err != nil { return errors.Wrap(err, "getting email token") } @@ -162,7 +162,7 @@ func (c *Context) process(info inactiveUserInfo) error { return errors.Wrap(err, "queueing email") } - if err := c.DB.Create(&database.Notification{ + if err := c.DB.Create(&models.Notification{ Type: mailer.EmailTypeInactiveReminder, UserID: info.userID, }).Error; err != nil { diff --git a/pkg/server/job/remind/inactive_test.go b/pkg/server/job/remind/inactive_test.go index 2f63cdcf..11035189 100644 --- a/pkg/server/job/remind/inactive_test.go +++ b/pkg/server/job/remind/inactive_test.go @@ -26,7 +26,7 @@ import ( "github.com/dnote/dnote/pkg/assert" "github.com/dnote/dnote/pkg/clock" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/mailer" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" @@ -54,14 +54,14 @@ func TestDoInactive(t *testing.T) { u1 := testutils.SetupUserData() a1 := testutils.SetupAccountData(u1, "alice@example.com", "pass1234") testutils.MustExec(t, testutils.DB.Model(&a1).Update("email_verified", true), "setting email verified") - testutils.MustExec(t, testutils.DB.Save(&database.EmailPreference{UserID: u1.ID, InactiveReminder: true}), "preparing email preference") + testutils.MustExec(t, testutils.DB.Save(&models.EmailPreference{UserID: u1.ID, InactiveReminder: true}), "preparing email preference") - b1 := database.Book{ + b1 := models.Book{ UserID: u1.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - n1 := database.Note{ + n1 := models.Note{ BookUUID: b1.UUID, UserID: u1.ID, } @@ -71,14 +71,14 @@ func TestDoInactive(t *testing.T) { u2 := testutils.SetupUserData() a2 := testutils.SetupAccountData(u2, "bob@example.com", "pass1234") testutils.MustExec(t, testutils.DB.Model(&a2).Update("email_verified", true), "setting email verified") - testutils.MustExec(t, testutils.DB.Save(&database.EmailPreference{UserID: u2.ID, InactiveReminder: true}), "preparing email preference") + testutils.MustExec(t, testutils.DB.Save(&models.EmailPreference{UserID: u2.ID, InactiveReminder: true}), "preparing email preference") - b2 := database.Book{ + b2 := models.Book{ UserID: u2.ID, Label: "css", } testutils.MustExec(t, testutils.DB.Save(&b2), "preparing b2") - n2 := database.Note{ + n2 := models.Note{ UserID: u2.ID, BookUUID: b2.UUID, } @@ -89,16 +89,16 @@ func TestDoInactive(t *testing.T) { u3 := testutils.SetupUserData() a3 := testutils.SetupAccountData(u3, "alice@example.com", "pass1234") testutils.MustExec(t, testutils.DB.Model(&a3).Update("email_verified", true), "setting email verified") - emailPref3 := database.EmailPreference{UserID: u3.ID} + emailPref3 := models.EmailPreference{UserID: u3.ID} testutils.MustExec(t, testutils.DB.Save(&emailPref3), "preparing email preference") testutils.MustExec(t, testutils.DB.Model(&emailPref3).Update(map[string]interface{}{"inactive_reminder": false}), "updating email preference") - b3 := database.Book{ + b3 := models.Book{ UserID: u3.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b3), "preparing b3") - n3 := database.Note{ + n3 := models.Note{ BookUUID: b3.UUID, UserID: u3.ID, } @@ -122,18 +122,18 @@ func TestDoInactive_Cooldown(t *testing.T) { defer testutils.ClearData(testutils.DB) // setup sets up an inactive user - setup := func(t *testing.T, now time.Time, email string) database.User { + setup := func(t *testing.T, now time.Time, email string) models.User { u := testutils.SetupUserData() a := testutils.SetupAccountData(u, email, "pass1234") testutils.MustExec(t, testutils.DB.Model(&a).Update("email_verified", true), "setting email verified") - testutils.MustExec(t, testutils.DB.Save(&database.EmailPreference{UserID: u.ID, InactiveReminder: true}), "preparing email preference") + testutils.MustExec(t, testutils.DB.Save(&models.EmailPreference{UserID: u.ID, InactiveReminder: true}), "preparing email preference") - b := database.Book{ + b := models.Book{ UserID: u.ID, Label: "css", } testutils.MustExec(t, testutils.DB.Save(&b), "preparing book") - n := database.Note{ + n := models.Note{ UserID: u.ID, BookUUID: b.UUID, } @@ -149,20 +149,20 @@ func TestDoInactive_Cooldown(t *testing.T) { setup(t, now, "alice@example.com") bob := setup(t, now, "bob@example.com") - bobNotif := database.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: bob.ID} + bobNotif := models.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: bob.ID} testutils.MustExec(t, testutils.DB.Create(&bobNotif), "preparing inactive notification for bob") testutils.MustExec(t, testutils.DB.Model(&bobNotif).Update("created_at", now.AddDate(0, 0, -7)), "preparing created_at for inactive notification for bob") chuck := setup(t, now, "chuck@example.com") - chuckNotif := database.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: chuck.ID} + chuckNotif := models.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: chuck.ID} testutils.MustExec(t, testutils.DB.Create(&chuckNotif), "preparing inactive notification for chuck") testutils.MustExec(t, testutils.DB.Model(&chuckNotif).Update("created_at", now.AddDate(0, 0, -15)), "preparing created_at for inactive notification for chuck") dan := setup(t, now, "dan@example.com") - danNotif1 := database.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: dan.ID} + danNotif1 := models.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: dan.ID} testutils.MustExec(t, testutils.DB.Create(&danNotif1), "preparing inactive notification 1 for dan") testutils.MustExec(t, testutils.DB.Model(&danNotif1).Update("created_at", now.AddDate(0, 0, -10)), "preparing created_at for inactive notification for dan") - danNotif2 := database.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: dan.ID} + danNotif2 := models.Notification{Type: mailer.EmailTypeInactiveReminder, UserID: dan.ID} testutils.MustExec(t, testutils.DB.Create(&danNotif2), "preparing inactive notification 2 for dan") testutils.MustExec(t, testutils.DB.Model(&danNotif2).Update("created_at", now.AddDate(0, 0, -15)), "preparing created_at for inactive notification for dan") diff --git a/pkg/server/mailer/templates/main.go b/pkg/server/mailer/templates/main.go index 5d3d055e..4343ce88 100644 --- a/pkg/server/mailer/templates/main.go +++ b/pkg/server/mailer/templates/main.go @@ -23,7 +23,7 @@ import ( "net/http" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/mailer" "github.com/jinzhu/gorm" "github.com/joho/godotenv" @@ -121,7 +121,7 @@ type Context struct { func main() { c := config.Load() - db := database.Open(c) + db := models.Open(c) defer db.Close() log.Println("Email template development server running on http://127.0.0.1:2300") diff --git a/pkg/server/mailer/tokens.go b/pkg/server/mailer/tokens.go index a2ae431c..050369e3 100644 --- a/pkg/server/mailer/tokens.go +++ b/pkg/server/mailer/tokens.go @@ -22,7 +22,7 @@ import ( "crypto/rand" "encoding/base64" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) @@ -40,8 +40,8 @@ func generateRandomToken(bits int) (string, error) { // GetToken returns an token of the given kind for the user // by first looking up any unused record and creating one if none exists. -func GetToken(db *gorm.DB, userID int, kind string) (database.Token, error) { - var tok database.Token +func GetToken(db *gorm.DB, userID int, kind string) (models.Token, error) { + var tok models.Token conn := db. Where("user_id = ? AND type =? AND used_at IS NULL", userID, kind). First(&tok) @@ -52,7 +52,7 @@ func GetToken(db *gorm.DB, userID int, kind string) (database.Token, error) { } if conn.RecordNotFound() { - tok = database.Token{ + tok = models.Token{ UserID: userID, Type: kind, Value: tokenVal, diff --git a/pkg/server/main.go b/pkg/server/main.go index 6f6e49ed..e091df92 100644 --- a/pkg/server/main.go +++ b/pkg/server/main.go @@ -28,9 +28,9 @@ import ( "github.com/dnote/dnote/pkg/server/app" "github.com/dnote/dnote/pkg/server/config" "github.com/dnote/dnote/pkg/server/controllers" - "github.com/dnote/dnote/pkg/server/database" "github.com/dnote/dnote/pkg/server/job" "github.com/dnote/dnote/pkg/server/mailer" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/routes" "github.com/jinzhu/gorm" @@ -48,7 +48,7 @@ func initDB(c config.Config) *gorm.DB { if err != nil { panic(errors.Wrap(err, "opening database connection")) } - database.InitSchema(db) + models.InitSchema(db) return db } @@ -85,7 +85,7 @@ func startCmd() { app := initApp(cfg) defer app.DB.Close() - if err := database.Migrate(app.DB); err != nil { + if err := models.Migrate(app.DB); err != nil { panic(errors.Wrap(err, "running migrations")) } if err := runJob(app); err != nil { diff --git a/pkg/server/database/consts.go b/pkg/server/models/consts.go similarity index 98% rename from pkg/server/database/consts.go rename to pkg/server/models/consts.go index 69f04711..244fd5b8 100644 --- a/pkg/server/database/consts.go +++ b/pkg/server/models/consts.go @@ -16,7 +16,7 @@ * along with Dnote. If not, see . */ -package database +package models const ( // TokenTypeResetPassword is a type of a token for reseting password diff --git a/pkg/server/database/database.go b/pkg/server/models/database.go similarity index 98% rename from pkg/server/database/database.go rename to pkg/server/models/database.go index 30eea6f5..a7759758 100644 --- a/pkg/server/database/database.go +++ b/pkg/server/models/database.go @@ -16,7 +16,7 @@ * along with Dnote. If not, see . */ -package database +package models import ( "github.com/dnote/dnote/pkg/server/config" diff --git a/pkg/server/database/errors.go b/pkg/server/models/errors.go similarity index 91% rename from pkg/server/database/errors.go rename to pkg/server/models/errors.go index e142a83d..dd212fc6 100644 --- a/pkg/server/database/errors.go +++ b/pkg/server/models/errors.go @@ -1,4 +1,4 @@ -package database +package models import ( "github.com/pkg/errors" diff --git a/pkg/server/database/migrate.go b/pkg/server/models/migrate.go similarity index 94% rename from pkg/server/database/migrate.go rename to pkg/server/models/migrate.go index f26a1400..a62f3bc1 100644 --- a/pkg/server/database/migrate.go +++ b/pkg/server/models/migrate.go @@ -16,7 +16,7 @@ * along with Dnote. If not, see . */ -package database +package models import ( "log" @@ -30,7 +30,7 @@ import ( // Migrate runs the migrations func Migrate(db *gorm.DB) error { migrations := &migrate.PackrMigrationSource{ - Box: packr.New("migrations", "../database/migrations/"), + Box: packr.New("migrations", "../models/migrations/"), } migrate.SetTable(MigrationTableName) diff --git a/pkg/server/database/migrate/main.go b/pkg/server/models/migrate/main.go similarity index 93% rename from pkg/server/database/migrate/main.go rename to pkg/server/models/migrate/main.go index 70614185..eb5adf8a 100644 --- a/pkg/server/database/migrate/main.go +++ b/pkg/server/models/migrate/main.go @@ -24,7 +24,7 @@ import ( "os" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/joho/godotenv" "github.com/pkg/errors" "github.com/rubenv/sql-migrate" @@ -35,7 +35,7 @@ var ( ) func init() { - fmt.Println("Migrating Dnote database...") + fmt.Println("Migrating Dnote models...") // Load env if os.Getenv("GO_ENV") != "PRODUCTION" { @@ -50,7 +50,7 @@ func main() { flag.Parse() c := config.Load() - db := database.Open(c) + db := models.Open(c) migrations := &migrate.FileMigrationSource{ Dir: *migrationDir, diff --git a/pkg/server/database/migrations/.gitkeep b/pkg/server/models/migrations/.gitkeep similarity index 100% rename from pkg/server/database/migrations/.gitkeep rename to pkg/server/models/migrations/.gitkeep diff --git a/pkg/server/database/migrations/20190819115834-full-text-search.sql b/pkg/server/models/migrations/20190819115834-full-text-search.sql similarity index 100% rename from pkg/server/database/migrations/20190819115834-full-text-search.sql rename to pkg/server/models/migrations/20190819115834-full-text-search.sql diff --git a/pkg/server/database/migrations/20191028103522-create-weekly-repetition.sql b/pkg/server/models/migrations/20191028103522-create-weekly-repetition.sql similarity index 100% rename from pkg/server/database/migrations/20191028103522-create-weekly-repetition.sql rename to pkg/server/models/migrations/20191028103522-create-weekly-repetition.sql diff --git a/pkg/server/database/migrations/20191225185502-populate-digest-version.sql b/pkg/server/models/migrations/20191225185502-populate-digest-version.sql similarity index 100% rename from pkg/server/database/migrations/20191225185502-populate-digest-version.sql rename to pkg/server/models/migrations/20191225185502-populate-digest-version.sql diff --git a/pkg/server/database/migrations/20191226093447-add-digest-id-primary-key.sql b/pkg/server/models/migrations/20191226093447-add-digest-id-primary-key.sql similarity index 100% rename from pkg/server/database/migrations/20191226093447-add-digest-id-primary-key.sql rename to pkg/server/models/migrations/20191226093447-add-digest-id-primary-key.sql diff --git a/pkg/server/database/migrations/20191226105659-use-id-in-digest-notes-joining-table.sql b/pkg/server/models/migrations/20191226105659-use-id-in-digest-notes-joining-table.sql similarity index 100% rename from pkg/server/database/migrations/20191226105659-use-id-in-digest-notes-joining-table.sql rename to pkg/server/models/migrations/20191226105659-use-id-in-digest-notes-joining-table.sql diff --git a/pkg/server/database/migrations/20191226152111-delete-outdated-digests.sql b/pkg/server/models/migrations/20191226152111-delete-outdated-digests.sql similarity index 100% rename from pkg/server/database/migrations/20191226152111-delete-outdated-digests.sql rename to pkg/server/models/migrations/20191226152111-delete-outdated-digests.sql diff --git a/pkg/server/database/migrations/20200522170529-remove-billing-columns.sql b/pkg/server/models/migrations/20200522170529-remove-billing-columns.sql similarity index 100% rename from pkg/server/database/migrations/20200522170529-remove-billing-columns.sql rename to pkg/server/models/migrations/20200522170529-remove-billing-columns.sql diff --git a/pkg/server/database/models.go b/pkg/server/models/models.go similarity index 99% rename from pkg/server/database/models.go rename to pkg/server/models/models.go index c7905158..5ce89aa2 100644 --- a/pkg/server/database/models.go +++ b/pkg/server/models/models.go @@ -16,7 +16,7 @@ * along with Dnote. If not, see . */ -package database +package models import ( "time" diff --git a/pkg/server/database/notes.go b/pkg/server/models/notes.go similarity index 98% rename from pkg/server/database/notes.go rename to pkg/server/models/notes.go index 91a850ad..a7b8f4d0 100644 --- a/pkg/server/database/notes.go +++ b/pkg/server/models/notes.go @@ -16,7 +16,7 @@ * along with Dnote. If not, see . */ -package database +package models import ( "github.com/jinzhu/gorm" diff --git a/pkg/server/database/scripts/create-migration.sh b/pkg/server/models/scripts/create-migration.sh similarity index 100% rename from pkg/server/database/scripts/create-migration.sh rename to pkg/server/models/scripts/create-migration.sh diff --git a/pkg/server/database/scripts/install-sql-migrate.sh b/pkg/server/models/scripts/install-sql-migrate.sh similarity index 100% rename from pkg/server/database/scripts/install-sql-migrate.sh rename to pkg/server/models/scripts/install-sql-migrate.sh diff --git a/pkg/server/database/sql-migrate.yml b/pkg/server/models/sql-migrate.yml similarity index 100% rename from pkg/server/database/sql-migrate.yml rename to pkg/server/models/sql-migrate.yml diff --git a/pkg/server/database/types.go b/pkg/server/models/types.go similarity index 98% rename from pkg/server/database/types.go rename to pkg/server/models/types.go index e230c5ac..dd202cbd 100644 --- a/pkg/server/database/types.go +++ b/pkg/server/models/types.go @@ -16,7 +16,7 @@ * along with Dnote. If not, see . */ -package database +package models import ( "database/sql" diff --git a/pkg/server/operations/notes.go b/pkg/server/operations/notes.go index 977236ba..f0757f73 100644 --- a/pkg/server/operations/notes.go +++ b/pkg/server/operations/notes.go @@ -19,7 +19,7 @@ package operations import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/helpers" "github.com/dnote/dnote/pkg/server/permissions" "github.com/jinzhu/gorm" @@ -27,16 +27,16 @@ import ( ) // GetNote retrieves a note for the given user -func GetNote(db *gorm.DB, uuid string, user database.User) (database.Note, bool, error) { - zeroNote := database.Note{} +func GetNote(db *gorm.DB, uuid string, user models.User) (models.Note, bool, error) { + zeroNote := models.Note{} if !helpers.ValidateUUID(uuid) { return zeroNote, false, nil } conn := db.Where("notes.uuid = ? AND deleted = ?", uuid, false) - conn = database.PreloadNote(conn) + conn = models.PreloadNote(conn) - var note database.Note + var note models.Note conn = conn.Find(¬e) if conn.RecordNotFound() { diff --git a/pkg/server/operations/notes_test.go b/pkg/server/operations/notes_test.go index a9f1e816..a64d1e19 100644 --- a/pkg/server/operations/notes_test.go +++ b/pkg/server/operations/notes_test.go @@ -22,7 +22,7 @@ import ( "testing" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -33,13 +33,13 @@ func TestGetNote(t *testing.T) { defer testutils.ClearData(testutils.DB) - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - privateNote := database.Note{ + privateNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "privateNote content", @@ -48,7 +48,7 @@ func TestGetNote(t *testing.T) { } testutils.MustExec(t, testutils.DB.Save(&privateNote), "preparing privateNote") - publicNote := database.Note{ + publicNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "privateNote content", @@ -57,16 +57,16 @@ func TestGetNote(t *testing.T) { } testutils.MustExec(t, testutils.DB.Save(&publicNote), "preparing privateNote") - var privateNoteRecord, publicNoteRecord database.Note + var privateNoteRecord, publicNoteRecord models.Note testutils.MustExec(t, testutils.DB.Where("uuid = ?", privateNote.UUID).Preload("Book").Preload("User").First(&privateNoteRecord), "finding privateNote") testutils.MustExec(t, testutils.DB.Where("uuid = ?", publicNote.UUID).Preload("Book").Preload("User").First(&publicNoteRecord), "finding publicNote") testCases := []struct { name string - user database.User - note database.Note + user models.User + note models.Note expectedOK bool - expectedNote database.Note + expectedNote models.Note }{ { name: "owner accessing private note", @@ -80,7 +80,7 @@ func TestGetNote(t *testing.T) { user: anotherUser, note: privateNote, expectedOK: false, - expectedNote: database.Note{}, + expectedNote: models.Note{}, }, { name: "non-owner accessing public note", @@ -91,14 +91,14 @@ func TestGetNote(t *testing.T) { }, { name: "guest accessing private note", - user: database.User{}, + user: models.User{}, note: privateNote, expectedOK: false, - expectedNote: database.Note{}, + expectedNote: models.Note{}, }, { name: "guest accessing public note", - user: database.User{}, + user: models.User{}, note: publicNote, expectedOK: true, expectedNote: publicNoteRecord, @@ -123,14 +123,14 @@ func TestGetNote_nonexistent(t *testing.T) { defer testutils.ClearData(testutils.DB) - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") n1UUID := "4fd19336-671e-4ff3-8f22-662b80e22edc" - n1 := database.Note{ + n1 := models.Note{ UUID: n1UUID, UserID: user.ID, BookUUID: b1.UUID, @@ -147,5 +147,5 @@ func TestGetNote_nonexistent(t *testing.T) { } assert.Equal(t, ok, false, "ok mismatch") - assert.DeepEqual(t, note, database.Note{}, "note mismatch") + assert.DeepEqual(t, note, models.Note{}, "note mismatch") } diff --git a/pkg/server/permissions/permissions.go b/pkg/server/permissions/permissions.go index e3da80f0..1ce0815c 100644 --- a/pkg/server/permissions/permissions.go +++ b/pkg/server/permissions/permissions.go @@ -19,11 +19,11 @@ package permissions import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) // ViewNote checks if the given user can view the given note -func ViewNote(user *database.User, note database.Note) bool { +func ViewNote(user *models.User, note models.Note) bool { if note.Public { return true } diff --git a/pkg/server/permissions/permissions_test.go b/pkg/server/permissions/permissions_test.go index 3508400c..44f91925 100644 --- a/pkg/server/permissions/permissions_test.go +++ b/pkg/server/permissions/permissions_test.go @@ -23,7 +23,7 @@ import ( "testing" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" ) @@ -42,13 +42,13 @@ func TestViewNote(t *testing.T) { defer testutils.ClearData(testutils.DB) - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - privateNote := database.Note{ + privateNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "privateNote content", @@ -57,7 +57,7 @@ func TestViewNote(t *testing.T) { } testutils.MustExec(t, testutils.DB.Save(&privateNote), "preparing privateNote") - publicNote := database.Note{ + publicNote := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Body: "privateNote content", diff --git a/pkg/server/presenters/book.go b/pkg/server/presenters/book.go index edb1d57c..97ac2e39 100644 --- a/pkg/server/presenters/book.go +++ b/pkg/server/presenters/book.go @@ -21,7 +21,7 @@ package presenters import ( "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) // Book is a result of PresentBooks @@ -34,7 +34,7 @@ type Book struct { } // PresentBook presents a book -func PresentBook(book database.Book) Book { +func PresentBook(book models.Book) Book { return Book{ UUID: book.UUID, USN: book.USN, @@ -45,7 +45,7 @@ func PresentBook(book database.Book) Book { } // PresentBooks presents books -func PresentBooks(books []database.Book) []Book { +func PresentBooks(books []models.Book) []Book { ret := []Book{} for _, book := range books { diff --git a/pkg/server/presenters/email_preference.go b/pkg/server/presenters/email_preference.go index 66569132..1ec084d1 100644 --- a/pkg/server/presenters/email_preference.go +++ b/pkg/server/presenters/email_preference.go @@ -21,7 +21,7 @@ package presenters import ( "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) // EmailPreference is a presented email digest @@ -33,7 +33,7 @@ type EmailPreference struct { } // PresentEmailPreference presents a digest -func PresentEmailPreference(p database.EmailPreference) EmailPreference { +func PresentEmailPreference(p models.EmailPreference) EmailPreference { ret := EmailPreference{ InactiveReminder: p.InactiveReminder, ProductUpdate: p.ProductUpdate, diff --git a/pkg/server/presenters/note.go b/pkg/server/presenters/note.go index 0da9d7a4..3e89f239 100644 --- a/pkg/server/presenters/note.go +++ b/pkg/server/presenters/note.go @@ -21,7 +21,7 @@ package presenters import ( "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) // Note is a result of PresentNote @@ -50,7 +50,7 @@ type NoteUser struct { } // PresentNote presents note -func PresentNote(note database.Note) Note { +func PresentNote(note models.Note) Note { ret := Note{ UUID: note.UUID, CreatedAt: FormatTS(note.CreatedAt), @@ -72,7 +72,7 @@ func PresentNote(note database.Note) Note { } // PresentNotes presents notes -func PresentNotes(notes []database.Note) []Note { +func PresentNotes(notes []models.Note) []Note { ret := []Note{} for _, note := range notes { diff --git a/pkg/server/routes/auth.go b/pkg/server/routes/auth.go index 81bdfd87..fb2b7767 100644 --- a/pkg/server/routes/auth.go +++ b/pkg/server/routes/auth.go @@ -7,15 +7,15 @@ import ( "github.com/dnote/dnote/pkg/server/app" "github.com/dnote/dnote/pkg/server/context" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/log" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) -func authWithToken(db *gorm.DB, r *http.Request, tokenType string, p *AuthParams) (database.User, database.Token, bool, error) { - var user database.User - var token database.Token +func authWithToken(db *gorm.DB, r *http.Request, tokenType string, p *AuthParams) (models.User, models.Token, bool, error) { + var user models.User + var token models.Token query := r.URL.Query() tokenValue := query.Get("token") @@ -131,8 +131,8 @@ func TokenAuth(a *app.App, next http.HandlerFunc, tokenType string, p *AuthParam } // AuthWithSession performs user authentication with session -func AuthWithSession(db *gorm.DB, r *http.Request, p *AuthParams) (database.User, bool, error) { - var user database.User +func AuthWithSession(db *gorm.DB, r *http.Request, p *AuthParams) (models.User, bool, error) { + var user models.User sessionKey, err := GetCredential(r) if err != nil { @@ -142,7 +142,7 @@ func AuthWithSession(db *gorm.DB, r *http.Request, p *AuthParams) (database.User return user, false, nil } - var session database.Session + var session models.Session conn := db.Where("key = ?", sessionKey).First(&session) if conn.RecordNotFound() { diff --git a/pkg/server/session/session.go b/pkg/server/session/session.go index cf0eacd2..bee5a10e 100644 --- a/pkg/server/session/session.go +++ b/pkg/server/session/session.go @@ -1,7 +1,7 @@ package session import ( - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) // Session represents user session @@ -13,7 +13,7 @@ type Session struct { } // New returns a new session for the given user -func New(user database.User, account database.Account) Session { +func New(user models.User, account models.Account) Session { return Session{ UUID: user.UUID, Pro: user.Cloud, diff --git a/pkg/server/session/session_test.go b/pkg/server/session/session_test.go index bd05f51e..52e0824b 100644 --- a/pkg/server/session/session_test.go +++ b/pkg/server/session/session_test.go @@ -23,19 +23,19 @@ import ( "testing" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" ) func TestNew(t *testing.T) { - u1 := database.User{UUID: "0f5f0054-d23f-4be1-b5fb-57673109e9cb", Cloud: true} - a1 := database.Account{Email: database.ToNullString("alice@example.com"), EmailVerified: false} + u1 := models.User{UUID: "0f5f0054-d23f-4be1-b5fb-57673109e9cb", Cloud: true} + a1 := models.Account{Email: models.ToNullString("alice@example.com"), EmailVerified: false} - u2 := database.User{UUID: "718a1041-bbe6-496e-bbe4-ea7e572c295e", Cloud: false} - a2 := database.Account{Email: database.ToNullString("bob@example.com"), EmailVerified: false} + u2 := models.User{UUID: "718a1041-bbe6-496e-bbe4-ea7e572c295e", Cloud: false} + a2 := models.Account{Email: models.ToNullString("bob@example.com"), EmailVerified: false} testCases := []struct { - user database.User - account database.Account + user models.User + account models.Account expectedPro bool }{ { diff --git a/pkg/server/testutils/main.go b/pkg/server/testutils/main.go index ba3cd5ae..cd620576 100644 --- a/pkg/server/testutils/main.go +++ b/pkg/server/testutils/main.go @@ -31,7 +31,7 @@ import ( "time" "github.com/dnote/dnote/pkg/server/config" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" @@ -49,44 +49,44 @@ var DB *gorm.DB func InitTestDB() { c := config.Load() fmt.Println(c.DB.GetConnectionStr()) - db := database.Open(c) + db := models.Open(c) - database.InitSchema(db) + models.InitSchema(db) DB = db } // ClearData deletes all records from the database func ClearData(db *gorm.DB) { - if err := db.Delete(&database.Book{}).Error; err != nil { + if err := db.Delete(&models.Book{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear books")) } - if err := db.Delete(&database.Note{}).Error; err != nil { + if err := db.Delete(&models.Note{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear notes")) } - if err := db.Delete(&database.Notification{}).Error; err != nil { + if err := db.Delete(&models.Notification{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear notifications")) } - if err := db.Delete(&database.User{}).Error; err != nil { + if err := db.Delete(&models.User{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear users")) } - if err := db.Delete(&database.Account{}).Error; err != nil { + if err := db.Delete(&models.Account{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear accounts")) } - if err := db.Delete(&database.Token{}).Error; err != nil { + if err := db.Delete(&models.Token{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear tokens")) } - if err := db.Delete(&database.EmailPreference{}).Error; err != nil { + if err := db.Delete(&models.EmailPreference{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear email preferences")) } - if err := db.Delete(&database.Session{}).Error; err != nil { + if err := db.Delete(&models.Session{}).Error; err != nil { panic(errors.Wrap(err, "Failed to clear sessions")) } } // SetupUserData creates and returns a new user for testing purposes -func SetupUserData() database.User { - user := database.User{ +func SetupUserData() models.User { + user := models.User{ Cloud: true, } @@ -98,19 +98,19 @@ func SetupUserData() database.User { } // SetupAccountData creates and returns a new account for the user -func SetupAccountData(user database.User, email, password string) database.Account { - account := database.Account{ +func SetupAccountData(user models.User, email, password string) models.Account { + account := models.Account{ UserID: user.ID, } if email != "" { - account.Email = database.ToNullString(email) + account.Email = models.ToNullString(email) } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { panic(errors.Wrap(err, "Failed to hash password")) } - account.Password = database.ToNullString(string(hashedPassword)) + account.Password = models.ToNullString(string(hashedPassword)) if err := DB.Save(&account).Error; err != nil { panic(errors.Wrap(err, "Failed to prepare account")) @@ -120,8 +120,8 @@ func SetupAccountData(user database.User, email, password string) database.Accou } // SetupSession creates and returns a new user session -func SetupSession(t *testing.T, user database.User) database.Session { - session := database.Session{ +func SetupSession(t *testing.T, user models.User) models.Session { + session := models.Session{ Key: "Vvgm3eBXfXGEFWERI7faiRJ3DAzJw+7DdT9J1LEyNfI=", UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 24), @@ -134,8 +134,8 @@ func SetupSession(t *testing.T, user database.User) database.Session { } // SetupEmailPreferenceData creates and returns a new email frequency for a user -func SetupEmailPreferenceData(user database.User, inactiveReminder bool) database.EmailPreference { - frequency := database.EmailPreference{ +func SetupEmailPreferenceData(user models.User, inactiveReminder bool) models.EmailPreference { + frequency := models.EmailPreference{ UserID: user.ID, InactiveReminder: inactiveReminder, } @@ -167,13 +167,13 @@ func HTTPDo(t *testing.T, req *http.Request) *http.Response { } // SetReqAuthHeader sets the authorization header in the given request for the given user -func SetReqAuthHeader(t *testing.T, req *http.Request, user database.User) { +func SetReqAuthHeader(t *testing.T, req *http.Request, user models.User) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { t.Fatal(errors.Wrap(err, "reading random bits")) } - session := database.Session{ + session := models.Session{ Key: base64.StdEncoding.EncodeToString(b), UserID: user.ID, ExpiresAt: time.Now().Add(time.Hour * 10 * 24), @@ -186,7 +186,7 @@ func SetReqAuthHeader(t *testing.T, req *http.Request, user database.User) { } // HTTPAuthDo makes an HTTP request with an appropriate authorization header for a user -func HTTPAuthDo(t *testing.T, req *http.Request, user database.User) *http.Response { +func HTTPAuthDo(t *testing.T, req *http.Request, user models.User) *http.Response { SetReqAuthHeader(t, req, user) return HTTPDo(t, req) diff --git a/pkg/server/tmpl/app_test.go b/pkg/server/tmpl/app_test.go index 6a1f08f5..a7c713b7 100644 --- a/pkg/server/tmpl/app_test.go +++ b/pkg/server/tmpl/app_test.go @@ -24,7 +24,7 @@ import ( "testing" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -53,12 +53,12 @@ func TestAppShellExecute(t *testing.T) { defer testutils.ClearData(testutils.DB) user := testutils.SetupUserData() - b1 := database.Book{ + b1 := models.Book{ UserID: user.ID, Label: "js", } testutils.MustExec(t, testutils.DB.Save(&b1), "preparing b1") - n1 := database.Note{ + n1 := models.Note{ UserID: user.ID, BookUUID: b1.UUID, Public: true, diff --git a/pkg/server/tmpl/data.go b/pkg/server/tmpl/data.go index 16c42e81..1de15118 100644 --- a/pkg/server/tmpl/data.go +++ b/pkg/server/tmpl/data.go @@ -27,7 +27,7 @@ import ( "strings" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/handlers" "github.com/dnote/dnote/pkg/server/operations" "github.com/pkg/errors" @@ -47,7 +47,7 @@ type noteMetaTagsData struct { } type notePage struct { - Note database.Note + Note models.Note T *template.Template } diff --git a/pkg/server/tmpl/data_test.go b/pkg/server/tmpl/data_test.go index 768baf80..d0520933 100644 --- a/pkg/server/tmpl/data_test.go +++ b/pkg/server/tmpl/data_test.go @@ -24,7 +24,7 @@ import ( "time" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -45,8 +45,8 @@ func TestNotePageGetData(t *testing.T) { } p := notePage{ - Note: database.Note{ - Book: database.Book{ + Note: models.Note{ + Book: models.Book{ Label: "vocabulary", }, AddedOn: time.Date(2019, time.January, 2, 0, 0, 0, 0, time.UTC).UnixNano(), diff --git a/pkg/server/token/token.go b/pkg/server/token/token.go index 44cad090..53e57070 100644 --- a/pkg/server/token/token.go +++ b/pkg/server/token/token.go @@ -22,7 +22,7 @@ import ( "crypto/rand" "encoding/base64" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) @@ -40,19 +40,19 @@ func generateRandom(bits int) (string, error) { } // Create generates a new token in the database -func Create(db *gorm.DB, userID int, kind string) (database.Token, error) { +func Create(db *gorm.DB, userID int, kind string) (models.Token, error) { val, err := generateRandom(16) if err != nil { - return database.Token{}, errors.Wrap(err, "generating random bytes") + return models.Token{}, errors.Wrap(err, "generating random bytes") } - token := database.Token{ + token := models.Token{ UserID: userID, Value: val, Type: kind, } if err := db.Save(&token).Error; err != nil { - return database.Token{}, errors.Wrap(err, "creating a token for unsubscribing") + return models.Token{}, errors.Wrap(err, "creating a token for unsubscribing") } return token, nil diff --git a/pkg/server/token/token_test.go b/pkg/server/token/token_test.go index 79c643da..518f757a 100644 --- a/pkg/server/token/token_test.go +++ b/pkg/server/token/token_test.go @@ -23,7 +23,7 @@ import ( "testing" "github.com/dnote/dnote/pkg/assert" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/dnote/dnote/pkg/server/testutils" "github.com/pkg/errors" ) @@ -33,7 +33,7 @@ func TestCreate(t *testing.T) { kind string }{ { - kind: database.TokenTypeEmailPreference, + kind: models.TokenTypeEmailPreference, }, } @@ -52,10 +52,10 @@ func TestCreate(t *testing.T) { // Test var count int - testutils.MustExec(t, testutils.DB.Model(&database.Token{}).Count(&count), "counting token") + testutils.MustExec(t, testutils.DB.Model(&models.Token{}).Count(&count), "counting token") assert.Equalf(t, count, 1, "error mismatch") - var tokenRecord database.Token + var tokenRecord models.Token testutils.MustExec(t, testutils.DB.First(&tokenRecord), "finding token") assert.Equalf(t, tokenRecord.UserID, tok.UserID, "UserID mismatch") assert.Equalf(t, tokenRecord.Value, tok.Value, "Value mismatch") diff --git a/pkg/server/views/data.go b/pkg/server/views/data.go index 23d1149b..ef504e4f 100644 --- a/pkg/server/views/data.go +++ b/pkg/server/views/data.go @@ -5,7 +5,7 @@ import ( "net/http" "time" - "github.com/dnote/dnote/pkg/server/database" + "github.com/dnote/dnote/pkg/server/models" "github.com/pkg/errors" ) @@ -33,7 +33,7 @@ type Alert struct { type Data struct { Alert *Alert CSRF template.HTML - User *database.User + User *models.User Yield interface{} }