Skip to content

Commit

Permalink
⚡️ Added LogOut service
Browse files Browse the repository at this point in the history
  • Loading branch information
lhbelfanti committed Jan 14, 2025
1 parent 8ce9540 commit 207ea5e
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/api/auth/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ var (
FailedToSelectUserByUsername = errors.New("failed to execute select user by username")
FailedToLoginDueWrongPassword = errors.New("failed to login due wrong password")
FailedToCreateUserSession = errors.New("failed to create user session")
FailedToDeleteUserSession = errors.New("failed to delete user session")
)

const (
Expand Down
25 changes: 25 additions & 0 deletions cmd/api/auth/logout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package auth

import (
"context"

"ahbcc/cmd/api/user/session"
"ahbcc/internal/log"
)

// LogOut Logs the user out. It deletes the current user session associated to that user by the token
type LogOut func(ctx context.Context, token string) error

// MakeLogOut creates a new LogOut
func MakeLogOut(deleteUserSession session.Delete) LogOut {
return func(ctx context.Context, token string) error {

err := deleteUserSession(ctx, token)
if err != nil {
log.Error(ctx, err.Error())
return FailedToDeleteUserSession
}

return nil
}
}
33 changes: 33 additions & 0 deletions cmd/api/auth/logout_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package auth_test

import (
"context"
"errors"
"testing"

"github.com/stretchr/testify/assert"

"ahbcc/cmd/api/auth"
"ahbcc/cmd/api/user/session"
)

func TestLogOut_success(t *testing.T) {
mockDeleteUserSession := session.MockDelete(nil)

logOut := auth.MakeLogOut(mockDeleteUserSession)

got := logOut(context.Background(), "token")

assert.Nil(t, got)
}

func TestLogOut_failsWhenDeleteSessionThrowsError(t *testing.T) {
mockDeleteUserSession := session.MockDelete(errors.New("failed to delete session"))

logOut := auth.MakeLogOut(mockDeleteUserSession)

want := auth.FailedToDeleteUserSession
got := logOut(context.Background(), "token")

assert.Equal(t, want, got)
}
7 changes: 7 additions & 0 deletions cmd/api/user/session/mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ func MockCreateToken(token string, expiresAt time.Time, err error) CreateToken {
}
}

// MockDelete mocks a Delete function
func MockDelete(err error) Delete {
return func(ctx context.Context, token string) error {
return err
}
}

// MockUserSessionDAO mocks a session DAO
func MockUserSessionDAO() DAO {
return DAO{
Expand Down

0 comments on commit 207ea5e

Please sign in to comment.