Saving token to DB

This commit is contained in:
2024-08-13 22:00:07 +02:00
parent 6b7ce5b719
commit e7f6983a22
4 changed files with 57 additions and 3 deletions

View File

@ -1,6 +1,7 @@
package models
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base32"
@ -40,3 +41,25 @@ func GenerateToken(userID int, ttl time.Duration, scope string) (*Token, error)
token.Hash = hash[:]
return token, nil
}
func (m *DBModel) InsertToken(t *Token, u User) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
stmt := `INSERT INTO tokens
(user_id, name, email, token_hash, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)`
_, err := m.DB.ExecContext(ctx, stmt,
u.ID,
u.LastName,
u.Email,
t.Hash,
time.Now(),
time.Now(),
)
if err != nil {
return err
}
return nil
}