Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add session refresh functionality with tests #22

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,42 @@ const docTemplate = `{
}
}
},
"/sessions/refresh/{account_id}": {
"put": {
"description": "Refresh the session token for a given account ID. Extends the expiration by 12 hours.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"sessions"
],
"summary": "Refresh a session",
"parameters": [
{
"type": "integer",
"description": "Account ID",
"name": "account_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/auth.Session"
}
},
"404": {
"description": "Not Found",
"schema": {}
}
}
}
},
"/sessions/{id}": {
"get": {
"description": "Get a session by its ID",
Expand Down
36 changes: 36 additions & 0 deletions docs/swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,42 @@
}
}
},
"/sessions/refresh/{account_id}": {
"put": {
"description": "Refresh the session token for a given account ID. Extends the expiration by 12 hours.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"sessions"
],
"summary": "Refresh a session",
"parameters": [
{
"type": "integer",
"description": "Account ID",
"name": "account_id",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/auth.Session"
}
},
"404": {
"description": "Not Found",
"schema": {}
}
}
}
},
"/sessions/{id}": {
"get": {
"description": "Get a session by its ID",
Expand Down
25 changes: 25 additions & 0 deletions docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -595,4 +595,29 @@ paths:
summary: Get a session
tags:
- sessions
/sessions/refresh/{account_id}:
put:
consumes:
- application/json
description: Refresh the session token for a given account ID. Extends the expiration
by 12 hours.
parameters:
- description: Account ID
in: path
name: account_id
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/auth.Session'
"404":
description: Not Found
schema: {}
summary: Refresh a session
tags:
- sessions
swagger: "2.0"
7 changes: 7 additions & 0 deletions internal/account/get_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ func GetAccount(w http.ResponseWriter, r *http.Request, db *sqlx.DB, store *auth
return errors.New("session has expired")
}

// Refresh the session
_, err = store.RefreshSession(session.AccountID)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return errors.New("an error occurred while refreshing the session: " + err.Error())
}

var (
name string
info string
Expand Down
35 changes: 35 additions & 0 deletions internal/auth/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,38 @@ func generateSessionID() (string, error) {
func (s *Session) IsExpired() bool {
return time.Now().After(s.ExpiresAt)
}

// RefreshSession refreshes the session token for a given account ID
// @Summary Refresh a session
// @Description Refresh the session token for a given account ID. Extends the expiration by 12 hours.
// @Tags sessions
// @Accept json
// @Produce json
// @Param account_id path int true "Account ID"
// @Success 200 {object} Session
// @Failure 404 {object} error
// @Router /sessions/refresh/{account_id} [put]
func (s *SessionStore) RefreshSession(accountID int) (*Session, error) {
var session Session
query := `SELECT * FROM sessions WHERE account_id = $1 ORDER BY created_at DESC LIMIT 1`
err := s.DB.Get(&session, query, accountID)
if err != nil {
if err == sql.ErrNoRows {
log.Printf("No session found for account ID %d", accountID)
return nil, errors.New("No session found")
}
log.Printf("Error retrieving session for account ID %d: %v", accountID, err)
return nil, err
}

session.ExpiresAt = time.Now().Add(12 * time.Hour)
updateQuery := `UPDATE sessions SET expires_at = :expires_at WHERE id = :id`
_, err = s.DB.NamedExec(updateQuery, session)
if err != nil {
log.Printf("Error refreshing session for account ID %d: %v", accountID, err)
return nil, err
}

log.Printf("Session refreshed: %v", session)
return &session, nil
}
110 changes: 106 additions & 4 deletions internal/auth/sessions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ func TestCreateSession_Error(t *testing.T) {
store := NewSessionStore(sqlxDB)

accountID := 1
mock.ExpectExec("INSERT INTO sessions").
WithArgs(sqlmock.AnyArg(), accountID, sqlmock.AnyArg(), sqlmock.AnyArg()).
WillReturnError(sql.ErrConnDone)
mock.ExpectQuery("SELECT \\* FROM sessions WHERE account_id = \\$1 ORDER BY created_at DESC LIMIT 1").
WithArgs(accountID).
WillReturnError(sql.ErrNoRows)

_, err = store.CreateSession(accountID)
_, err = store.RefreshSession(accountID)
if err == nil {
t.Errorf("expected error, got nil")
}
Expand Down Expand Up @@ -216,3 +216,105 @@ func TestIsExpired(t *testing.T) {
})
}
}
func TestRefreshSession_Success(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()

sqlxDB := sqlx.NewDb(db, "sqlmock")
store := NewSessionStore(sqlxDB)

accountID := 1
sessionID := "test-session-id"
createdAt := time.Now().Add(-1 * time.Hour)
expiresAt := createdAt.Add(12 * time.Hour)

rows := sqlmock.NewRows([]string{"id", "account_id", "created_at", "expires_at"}).
AddRow(sessionID, accountID, createdAt, expiresAt)
mock.ExpectQuery("SELECT \\* FROM sessions WHERE account_id = \\$1 ORDER BY created_at DESC LIMIT 1").
WithArgs(accountID).
WillReturnRows(rows)

mock.ExpectExec("UPDATE sessions SET expires_at = \\? WHERE id = \\?").
WithArgs(sqlmock.AnyArg(), sessionID).
WillReturnResult(sqlmock.NewResult(1, 1))

session, err := store.RefreshSession(accountID)
if err != nil {
t.Errorf("expected no error, got %v", err)
}

if session.AccountID != accountID {
t.Errorf("expected account ID %d, got %d", accountID, session.AccountID)
}

if session.ID != sessionID {
t.Errorf("expected session ID %s, got %s", sessionID, session.ID)
}

if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}

func TestRefreshSession_NotFound(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()

sqlxDB := sqlx.NewDb(db, "sqlmock")
store := NewSessionStore(sqlxDB)

accountID := 1
mock.ExpectQuery("SELECT \\* FROM sessions WHERE account_id = \\$1 ORDER BY created_at DESC LIMIT 1").
WithArgs(accountID).
WillReturnError(sql.ErrNoRows)

_, err = store.RefreshSession(accountID)
if err == nil {
t.Errorf("expected error, got nil")
}

if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}

func TestRefreshSession_Error(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()

sqlxDB := sqlx.NewDb(db, "sqlmock")
store := NewSessionStore(sqlxDB)

accountID := 1
sessionID := "test-session-id"
createdAt := time.Now().Add(-1 * time.Hour)
expiresAt := createdAt.Add(12 * time.Hour)

rows := sqlmock.NewRows([]string{"id", "account_id", "created_at", "expires_at"}).
AddRow(sessionID, accountID, createdAt, expiresAt)
mock.ExpectQuery("SELECT \\* FROM sessions WHERE account_id = \\$1 ORDER BY created_at DESC LIMIT 1").
WithArgs(accountID).
WillReturnRows(rows)

mock.ExpectExec("UPDATE sessions SET expires_at = \\? WHERE id = \\?").
WithArgs(sqlmock.AnyArg(), sessionID).
WillReturnError(sql.ErrConnDone)

_, err = store.RefreshSession(accountID)
if err == nil {
t.Errorf("expected error, got nil")
}

if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
Loading