Skip to content

Commit

Permalink
♻️ refactoring (models): Now all provider methods is returning some k…
Browse files Browse the repository at this point in the history
…ind of JSON struct by default
  • Loading branch information
kevinmarquesp committed Jul 4, 2024
1 parent c04fe0c commit cd97284
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 60 deletions.
26 changes: 9 additions & 17 deletions internal/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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,
Expand All @@ -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
}

Expand All @@ -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
}
9 changes: 2 additions & 7 deletions internal/models/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
34 changes: 19 additions & 15 deletions internal/models/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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 {
Expand Down
42 changes: 21 additions & 21 deletions test/models/sqlite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.")

Expand All @@ -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.")

Expand Down Expand Up @@ -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.")

Expand All @@ -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.")
Expand All @@ -217,19 +217,19 @@ 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.")

_, err = db.Conn.Exec("UPDATE users SET session_expires = ?"+
"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) {
Expand All @@ -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.")

Expand All @@ -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.")
Expand All @@ -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)
}

0 comments on commit cd97284

Please sign in to comment.