fixes for action token

This commit is contained in:
Sergey Chubaryan 2024-09-05 03:48:17 +03:00
parent 25ba361486
commit 7c1a98ed75
4 changed files with 32 additions and 12 deletions

9
sql/03_action_token.sql Normal file
View File

@ -0,0 +1,9 @@
create table if not exists action_tokens (
id int generated always as identity,
user_id int,
value text
target int,
expiration timestamp,
primary key(id)
);

View File

@ -1,5 +1,7 @@
package models package models
import "time"
type ActionTokenTarget int type ActionTokenTarget int
const ( const (
@ -8,8 +10,9 @@ const (
) )
type ActionTokenDTO struct { type ActionTokenDTO struct {
Id string Id string
UserId string UserId string
Value string Value string
Target ActionTokenTarget Target ActionTokenTarget
Expiration time.Time
} }

View File

@ -4,6 +4,7 @@ import (
"backend/src/core/models" "backend/src/core/models"
"backend/src/integrations" "backend/src/integrations"
"context" "context"
"database/sql"
) )
type ActionTokenRepo interface { type ActionTokenRepo interface {
@ -24,10 +25,10 @@ type actionTokenRepo struct {
func (a *actionTokenRepo) CreateActionToken(ctx context.Context, dto models.ActionTokenDTO) (*models.ActionTokenDTO, error) { func (a *actionTokenRepo) CreateActionToken(ctx context.Context, dto models.ActionTokenDTO) (*models.ActionTokenDTO, error) {
query := ` query := `
insert into insert into
action_tokens (user_id, value, target) action_tokens (user_id, value, target, expiration)
values ($1, $2, $3) values ($1, $2, $3, $4)
returning id;` returning id;`
row := a.db.QueryRowContext(ctx, query, dto.UserId, dto.Value, dto.Target) row := a.db.QueryRowContext(ctx, query, dto.UserId, dto.Value, dto.Target, dto.Expiration)
id := "" id := ""
if err := row.Scan(&id); err != nil { if err := row.Scan(&id); err != nil {
@ -46,12 +47,18 @@ func (a *actionTokenRepo) PopActionToken(ctx context.Context, userId, value stri
query := ` query := `
delete delete
from action_tokens from action_tokens
where user_id=$1 and value=$2 and target=$3 where
user_id=$1 and value=$2 and target=$3
and CURRENT_TIMESTAMP < expiration
returning id;` returning id;`
row := a.db.QueryRowContext(ctx, query, userId, value, target) row := a.db.QueryRowContext(ctx, query, userId, value, target)
id := "" id := ""
if err := row.Scan(&id); err != nil { err := row.Scan(&id)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err return nil, err
} }

View File

@ -122,9 +122,10 @@ func (u *userService) HelpPasswordForgot(ctx context.Context, userId string) err
actionToken, err := u.deps.ActionTokenRepo.CreateActionToken( actionToken, err := u.deps.ActionTokenRepo.CreateActionToken(
ctx, ctx,
models.ActionTokenDTO{ models.ActionTokenDTO{
UserId: user.Id, UserId: user.Id,
Value: uuid.New().String(), Value: uuid.New().String(),
Target: models.ActionTokenTargetForgotPassword, Target: models.ActionTokenTargetForgotPassword,
Expiration: time.Now().Add(1 * time.Hour),
}, },
) )
if err != nil { if err != nil {