homebox/backend/internal/repo/repo_tokens.go

76 lines
1.9 KiB
Go
Raw Normal View History

2022-08-30 02:30:36 +00:00
package repo
import (
"context"
"time"
"github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/authtokens"
"github.com/hay-kot/homebox/backend/internal/types"
2022-08-30 02:30:36 +00:00
)
type TokenRepository struct {
2022-08-30 02:30:36 +00:00
db *ent.Client
}
// GetUserFromToken get's a user from a token
func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (*ent.User, error) {
2022-08-31 00:40:39 +00:00
user, err := r.db.AuthTokens.Query().
2022-08-30 02:30:36 +00:00
Where(authtokens.Token(token)).
Where(authtokens.ExpiresAtGTE(time.Now())).
WithUser().
2022-08-31 00:40:39 +00:00
QueryUser().
WithGroup().
2022-08-30 02:30:36 +00:00
Only(ctx)
if err != nil {
2022-08-30 18:05:11 +00:00
return nil, err
2022-08-30 02:30:36 +00:00
}
2022-08-31 00:40:39 +00:00
return user, nil
2022-08-30 02:30:36 +00:00
}
// Creates a token for a user
func (r *TokenRepository) CreateToken(ctx context.Context, createToken types.UserAuthTokenCreate) (types.UserAuthToken, error) {
2022-08-30 02:30:36 +00:00
tokenOut := types.UserAuthToken{}
dbToken, err := r.db.AuthTokens.Create().
SetToken(createToken.TokenHash).
SetUserID(createToken.UserID).
SetExpiresAt(createToken.ExpiresAt).
Save(ctx)
if err != nil {
return tokenOut, err
}
tokenOut.TokenHash = dbToken.Token
tokenOut.UserID = createToken.UserID
tokenOut.CreatedAt = dbToken.CreatedAt
tokenOut.ExpiresAt = dbToken.ExpiresAt
return tokenOut, nil
}
// DeleteToken remove a single token from the database - equivalent to revoke or logout
func (r *TokenRepository) DeleteToken(ctx context.Context, token []byte) error {
2022-08-30 02:30:36 +00:00
_, err := r.db.AuthTokens.Delete().Where(authtokens.Token(token)).Exec(ctx)
return err
}
// PurgeExpiredTokens removes all expired tokens from the database
func (r *TokenRepository) PurgeExpiredTokens(ctx context.Context) (int, error) {
2022-08-30 02:30:36 +00:00
tokensDeleted, err := r.db.AuthTokens.Delete().Where(authtokens.ExpiresAtLTE(time.Now())).Exec(ctx)
if err != nil {
return 0, err
}
return tokensDeleted, nil
}
func (r *TokenRepository) DeleteAll(ctx context.Context) (int, error) {
2022-08-30 02:30:36 +00:00
amount, err := r.db.AuthTokens.Delete().Exec(ctx)
return amount, err
}