2022-09-12 22:47:27 +00:00
|
|
|
package repo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2022-09-24 19:33:38 +00:00
|
|
|
"github.com/hay-kot/homebox/backend/ent"
|
|
|
|
"github.com/hay-kot/homebox/backend/ent/documenttoken"
|
2022-09-12 22:47:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// DocumentTokensRepository is a repository for Document entity
|
|
|
|
type DocumentTokensRepository struct {
|
|
|
|
db *ent.Client
|
|
|
|
}
|
|
|
|
|
2022-09-27 23:52:13 +00:00
|
|
|
type (
|
|
|
|
DocumentToken struct {
|
|
|
|
ID uuid.UUID `json:"-"`
|
|
|
|
TokenHash []byte `json:"tokenHash"`
|
|
|
|
ExpiresAt time.Time `json:"expiresAt"`
|
|
|
|
DocumentID uuid.UUID `json:"documentId"`
|
|
|
|
}
|
|
|
|
|
|
|
|
DocumentTokenCreate struct {
|
|
|
|
TokenHash []byte `json:"tokenHash"`
|
|
|
|
DocumentID uuid.UUID `json:"documentId"`
|
|
|
|
ExpiresAt time.Time `json:"expiresAt"`
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
mapDocumentTokenErr = mapTErrFunc(mapDocumentToken)
|
|
|
|
)
|
|
|
|
|
|
|
|
func mapDocumentToken(e *ent.DocumentToken) DocumentToken {
|
|
|
|
return DocumentToken{
|
|
|
|
ID: e.ID,
|
|
|
|
TokenHash: e.Token,
|
|
|
|
ExpiresAt: e.ExpiresAt,
|
|
|
|
DocumentID: e.Edges.Document.ID,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *DocumentTokensRepository) Create(ctx context.Context, data DocumentTokenCreate) (DocumentToken, error) {
|
2022-09-12 22:47:27 +00:00
|
|
|
result, err := r.db.DocumentToken.Create().
|
|
|
|
SetDocumentID(data.DocumentID).
|
|
|
|
SetToken(data.TokenHash).
|
|
|
|
SetExpiresAt(data.ExpiresAt).
|
|
|
|
Save(ctx)
|
|
|
|
|
|
|
|
if err != nil {
|
2022-09-27 23:52:13 +00:00
|
|
|
return DocumentToken{}, err
|
2022-09-12 22:47:27 +00:00
|
|
|
}
|
|
|
|
|
2022-09-27 23:52:13 +00:00
|
|
|
return mapDocumentTokenErr(r.db.DocumentToken.Query().
|
2022-09-12 22:47:27 +00:00
|
|
|
Where(documenttoken.ID(result.ID)).
|
|
|
|
WithDocument().
|
2022-09-27 23:52:13 +00:00
|
|
|
Only(ctx))
|
2022-09-12 22:47:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *DocumentTokensRepository) PurgeExpiredTokens(ctx context.Context) (int, error) {
|
|
|
|
return r.db.DocumentToken.Delete().Where(documenttoken.ExpiresAtLT(time.Now())).Exec(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *DocumentTokensRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
|
|
|
return r.db.DocumentToken.DeleteOneID(id).Exec(ctx)
|
|
|
|
}
|