From cd972844336521e072c746a531b0afa4e21c8187 Mon Sep 17 00:00:00 2001 From: Kevin Marques Date: Thu, 4 Jul 2024 20:26:13 -0300 Subject: [PATCH] :recycle: refactoring (models): Now all provider methods is returning some kind of JSON struct by default --- internal/api/auth.go | 26 ++++++++-------------- internal/models/providers.go | 9 ++------ internal/models/sqlite.go | 34 ++++++++++++++++------------- test/models/sqlite_test.go | 42 ++++++++++++++++++------------------ 4 files changed, 51 insertions(+), 60 deletions(-) diff --git a/internal/api/auth.go b/internal/api/auth.go index 8677f7b..623fdec 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -43,19 +43,19 @@ func (ac AuthController) RegisterNewUser(w http.ResponseWriter, r *http.Request) // Register and respond. - response, err := ac.Database.RegisterNewUser(form) + resp, err := ac.Database.RegisterNewUser(form) if err != nil { utils.WriteGenericJsonError(w, http.StatusBadRequest, err) return } - responseJson, err := utils.JsonMarshalString(response) + respJson, err := utils.JsonMarshalString(resp) if err != nil { utils.WriteGenericJsonError(w, http.StatusConflict, err) return } - fmt.Fprint(w, string(responseJson)) + fmt.Fprint(w, string(respJson)) } func (ac AuthController) RefreshUserSessionToken(w http.ResponseWriter, r *http.Request) { @@ -82,7 +82,7 @@ func (ac AuthController) RefreshUserSessionToken(w http.ResponseWriter, r *http. // Authorize with acess session token string. if sessionToken != "" { - newSessionToken, err := ac.Database.AuthorizeUserWithSessionToken(sessionToken) + resp, err := ac.Database.AuthorizeUserWithSessionToken(sessionToken) if err != nil { if err = ac.updateSessionTokenWithCredentials(w, username, password); err != nil { utils.WriteGenericJsonError(w, http.StatusUnauthorized, @@ -91,16 +91,12 @@ func (ac AuthController) RefreshUserSessionToken(w http.ResponseWriter, r *http. return } - response := models.SessionToken{ - SessionToken: newSessionToken, - } - - responseJsonBytes, err := json.Marshal(response) + respJson, err := utils.JsonMarshalString(resp) if err != nil { utils.WriteGenericJsonError(w, http.StatusInternalServerError, err) } - fmt.Fprint(w, string(responseJsonBytes)) + fmt.Fprint(w, respJson) return } @@ -116,22 +112,18 @@ func (ac AuthController) updateSessionTokenWithCredentials(w http.ResponseWriter return errors.New(UNSPECIFIED_AUTHORIZATION_FIELD_ERROR) } - newSessionToken, err := ac.Database.AuthorizeUserWithCredentials(username, password) + resp, err := ac.Database.AuthorizeUserWithCredentials(username, password) if err != nil { utils.WriteGenericJsonError(w, http.StatusUnauthorized, err) return nil } - response := models.SessionToken{ - SessionToken: newSessionToken, - } - - responseJsonBytes, err := json.Marshal(response) + respJson, err := utils.JsonMarshalString(resp) if err != nil { return err } - fmt.Fprint(w, string(responseJsonBytes)) + fmt.Fprint(w, respJson) return nil } diff --git a/internal/models/providers.go b/internal/models/providers.go index 5aec9cb..c1c0173 100644 --- a/internal/models/providers.go +++ b/internal/models/providers.go @@ -16,14 +16,9 @@ const ( type GenericDatabaseProvider interface { Connect(url string) error - - // This function will return the public ID of the inserted user and its - // session token ID (which has an expiration date defined by the - // models.SESSION_MAX_DURATION constant) RegisterNewUser(form RegisterForm) (RegisterResponse, error) - - AuthorizeUserWithSessionToken(sessionToken string) (string, error) - AuthorizeUserWithCredentials(username, password string) (string, error) + AuthorizeUserWithSessionToken(sessionToken string) (SessionToken, error) + AuthorizeUserWithCredentials(username, password string) (SessionToken, error) } type RegisterForm struct { diff --git a/internal/models/sqlite.go b/internal/models/sqlite.go index 4b31ca8..26ca794 100644 --- a/internal/models/sqlite.go +++ b/internal/models/sqlite.go @@ -74,10 +74,10 @@ func (s *Sqlite) RegisterNewUser(form RegisterForm) (RegisterResponse, error) { }, nil } -func (s *Sqlite) AuthorizeUserWithSessionToken(sessionToken string) (string, error) { +func (s *Sqlite) AuthorizeUserWithSessionToken(sessionToken string) (SessionToken, error) { newSessionToken, newExpirationDate, err := utils.GenerateNewSessionToken(SESSION_MAX_DURATION) if err != nil { - return "", err + return SessionToken{}, err } statement, err := s.Conn.Prepare(`UPDATE users @@ -89,34 +89,36 @@ func (s *Sqlite) AuthorizeUserWithSessionToken(sessionToken string) (string, err session_token IS ?3 AND session_expires > ?4`) if err != nil { - return "", err + return SessionToken{}, err } rows, err := statement.Exec(newSessionToken, newExpirationDate, sessionToken, time.Now()) if err != nil { - return "", err + return SessionToken{}, err } rowsAffected, err := rows.RowsAffected() if err != nil { - return "", err + return SessionToken{}, err } if rowsAffected < 1 { - return "", errors.New(CANNOT_MATCH_TOKEN_TO_USERNAME_ERROR) + return SessionToken{}, errors.New(CANNOT_MATCH_TOKEN_TO_USERNAME_ERROR) } - return newSessionToken, nil + return SessionToken{ + SessionToken: newSessionToken, + }, nil } -func (s *Sqlite) AuthorizeUserWithCredentials(username, password string) (string, error) { +func (s *Sqlite) AuthorizeUserWithCredentials(username, password string) (SessionToken, error) { if err := s.comparePassword(username, password); err != nil { - return "", err + return SessionToken{}, err } newSessionToken, newExpirationDate, err := utils.GenerateNewSessionToken(SESSION_MAX_DURATION) if err != nil { - return "", err + return SessionToken{}, err } statement, err := s.Conn.Prepare(`UPDATE users @@ -127,24 +129,26 @@ func (s *Sqlite) AuthorizeUserWithCredentials(username, password string) (string WHERE username IS ?3`) if err != nil { - return "", err + return SessionToken{}, err } rows, err := statement.Exec(newSessionToken, newExpirationDate, username) if err != nil { - return "", err + return SessionToken{}, err } rowsAffected, err := rows.RowsAffected() if err != nil { - return "", err + return SessionToken{}, err } if rowsAffected < 1 { - return "", errors.New(INVALID_AUTH_CREDENTIALS_ERROR) + return SessionToken{}, errors.New(INVALID_AUTH_CREDENTIALS_ERROR) } - return newSessionToken, nil + return SessionToken{ + SessionToken: newSessionToken, + }, nil } func (s *Sqlite) comparePassword(username, password string) error { diff --git a/test/models/sqlite_test.go b/test/models/sqlite_test.go index ceef8e8..949ac5f 100644 --- a/test/models/sqlite_test.go +++ b/test/models/sqlite_test.go @@ -84,7 +84,7 @@ func TestSqliteRegisterUser(t *testing.T) { t.Run(testDescription, func(t *testing.T) { t.Log("Try to register a the new user to the database.") - response, err := db.RegisterNewUser(models.RegisterForm{ + resp, err := db.RegisterNewUser(models.RegisterForm{ Fullname: user.fullname, Username: user.username, Password: user.password, @@ -96,8 +96,8 @@ func TestSqliteRegisterUser(t *testing.T) { } assert.NoError(t, err) - assert.NotEmpty(t, response.PublicId) - assert.NotEmpty(t, response.SessionToken) + assert.NotEmpty(t, resp.PublicId) + assert.NotEmpty(t, resp.SessionToken) t.Log("Query the database to verify if the user was inserted with success.") @@ -120,10 +120,10 @@ func TestSqliteRegisterUser(t *testing.T) { t.Log("Comparing the selected user details with the provided data.") - assert.Equal(t, response.PublicId, dbField.publicID) - assert.Equal(t, response.Fullname, dbField.fullname) - assert.Equal(t, response.Username, dbField.username) - assert.Equal(t, response.SessionToken, dbField.sessionToken) + assert.Equal(t, resp.PublicId, dbField.publicID) + assert.Equal(t, resp.Fullname, dbField.fullname) + assert.Equal(t, resp.Username, dbField.username) + assert.Equal(t, resp.SessionToken, dbField.sessionToken) t.Log("Verifying the password hash.") @@ -183,9 +183,9 @@ func TestSqliteAuthorizeUserWithSessionToken(t *testing.T) { t.Log("Try to authorize with the session token string.") - newSessionToken, err := db.AuthorizeUserWithSessionToken(sessionToken) + resp, err := db.AuthorizeUserWithSessionToken(sessionToken) assert.NoError(t, err) - assert.NotEmpty(t, newSessionToken) + assert.NotEmpty(t, resp.SessionToken) t.Log("Query the database to verify if the session_token & session_expires fields were updated.") @@ -201,7 +201,7 @@ func TestSqliteAuthorizeUserWithSessionToken(t *testing.T) { t.Log("Verify if the session token was updated with success.") - assert.Equal(t, newSessionToken, dbSessionToken) + assert.Equal(t, resp.SessionToken, dbSessionToken) assert.NotEqual(t, sessionToken, dbSessionToken) t.Log("Verify if the session expiration date is within the expected range.") @@ -217,9 +217,9 @@ func TestSqliteAuthorizeUserWithSessionTokenFail(t *testing.T) { t.Log("Should fail with a invalid session token string.") - newSessiontoken, err := db.AuthorizeUserWithSessionToken("blah-blah-blah-blah-blah") + resp, err := db.AuthorizeUserWithSessionToken("blah-blah-blah-blah-blah") assert.NotNil(t, err) - assert.Empty(t, newSessiontoken) + assert.Empty(t, resp) t.Log("Should fail with an expired, but still valid, session token string.") @@ -227,9 +227,9 @@ func TestSqliteAuthorizeUserWithSessionTokenFail(t *testing.T) { "WHERE session_token IS ?", time.Now().Add(-1*time.Hour), sessionToken) assert.NoError(t, err) - sessionToken, err = db.AuthorizeUserWithSessionToken(sessionToken) + resp, err = db.AuthorizeUserWithSessionToken(sessionToken) assert.NotNil(t, err) - assert.Empty(t, sessionToken) + assert.Empty(t, resp) } func TestSqliteAuthorizeUserWithCredentials(t *testing.T) { @@ -239,9 +239,9 @@ func TestSqliteAuthorizeUserWithCredentials(t *testing.T) { t.Log("Try to authorize the user with the credentials.") - newSessionToken, err := db.AuthorizeUserWithCredentials(username, password) + resp, err := db.AuthorizeUserWithCredentials(username, password) assert.NoError(t, err) - assert.NotEmpty(t, newSessionToken) + assert.NotEmpty(t, resp.SessionToken) t.Log("Query the database to verify if the session_token & session_expires fields were updated.") @@ -257,7 +257,7 @@ func TestSqliteAuthorizeUserWithCredentials(t *testing.T) { t.Log("Verify if the session token was updated with success.") - assert.Equal(t, newSessionToken, dbSessionToken) + assert.Equal(t, resp.SessionToken, dbSessionToken) assert.NotEqual(t, sessionToken, dbSessionToken) t.Log("Verify if the session expiration date is within the expected range.") @@ -273,13 +273,13 @@ func TestSqliteAuthorizeUserWithCredentialsFail(t *testing.T) { t.Log("Should fail with an incorrect username.") - sessionToken, err := db.AuthorizeUserWithCredentials("NonExisting", password) + resp, err := db.AuthorizeUserWithCredentials("NonExisting", password) assert.NotNil(t, err) - assert.Empty(t, sessionToken) + assert.Empty(t, resp) t.Log("Should fail with an incorrect password.") - sessionToken, err = db.AuthorizeUserWithCredentials(username, "6607cc3df0ec4abfb2e57f8334ca30e3") + resp, err = db.AuthorizeUserWithCredentials(username, "6607cc3df0ec4abfb2e57f8334ca30e3") assert.NotNil(t, err) - assert.Empty(t, sessionToken) + assert.Empty(t, resp) }