2021-07-21 23:04:00 +00:00
|
|
|
package memory
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-02-01 18:38:08 +00:00
|
|
|
"errors"
|
2021-10-05 06:54:36 +00:00
|
|
|
"path"
|
2021-07-21 23:04:00 +00:00
|
|
|
"sync"
|
2021-10-17 22:51:10 +00:00
|
|
|
|
2022-03-13 10:58:34 +00:00
|
|
|
"source.toby3d.me/toby3d/auth/internal/domain"
|
|
|
|
"source.toby3d.me/toby3d/auth/internal/token"
|
2021-07-21 23:04:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type memoryTokenRepository struct {
|
2021-10-13 21:53:31 +00:00
|
|
|
store *sync.Map
|
2021-07-21 23:04:00 +00:00
|
|
|
}
|
|
|
|
|
2021-10-13 21:53:31 +00:00
|
|
|
const DefaultPathPrefix string = "tokens"
|
2021-10-05 06:54:36 +00:00
|
|
|
|
2021-10-13 21:53:31 +00:00
|
|
|
func NewMemoryTokenRepository(store *sync.Map) token.Repository {
|
2021-07-21 23:04:00 +00:00
|
|
|
return &memoryTokenRepository{
|
2021-10-13 21:53:31 +00:00
|
|
|
store: store,
|
2021-07-21 23:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-29 20:35:39 +00:00
|
|
|
func (repo *memoryTokenRepository) Create(ctx context.Context, accessToken *domain.Token) error {
|
2021-10-17 22:51:10 +00:00
|
|
|
t, err := repo.Get(ctx, accessToken.AccessToken)
|
2022-02-01 18:38:08 +00:00
|
|
|
if err != nil && !errors.Is(err, token.ErrNotExist) {
|
2021-10-17 22:51:10 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-09-20 15:45:54 +00:00
|
|
|
|
2021-10-17 22:51:10 +00:00
|
|
|
if t != nil {
|
2021-10-17 23:12:00 +00:00
|
|
|
return token.ErrExist
|
2021-09-20 15:45:54 +00:00
|
|
|
}
|
|
|
|
|
2021-10-17 22:51:10 +00:00
|
|
|
repo.store.Store(path.Join(DefaultPathPrefix, accessToken.AccessToken), accessToken)
|
2021-09-20 15:45:54 +00:00
|
|
|
|
2021-09-22 21:32:40 +00:00
|
|
|
return nil
|
|
|
|
}
|
2021-07-21 23:04:00 +00:00
|
|
|
|
2021-10-13 21:53:31 +00:00
|
|
|
func (repo *memoryTokenRepository) Get(ctx context.Context, accessToken string) (*domain.Token, error) {
|
2021-10-17 22:51:10 +00:00
|
|
|
t, ok := repo.store.Load(path.Join(DefaultPathPrefix, accessToken))
|
|
|
|
if !ok {
|
|
|
|
return nil, token.ErrNotExist
|
|
|
|
}
|
|
|
|
|
|
|
|
result, ok := t.(*domain.Token)
|
2021-10-13 21:53:31 +00:00
|
|
|
if !ok {
|
2021-10-17 22:51:10 +00:00
|
|
|
return nil, token.ErrNotExist
|
2021-10-13 21:53:31 +00:00
|
|
|
}
|
2021-09-20 15:45:54 +00:00
|
|
|
|
2021-10-17 22:51:10 +00:00
|
|
|
return result, nil
|
2021-07-21 23:04:00 +00:00
|
|
|
}
|