113 lines
2.5 KiB
Go
113 lines
2.5 KiB
Go
package repositories
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.jamestombleson.com/jtom38/go-cook/internal/domain"
|
|
"github.com/huandu/go-sqlbuilder"
|
|
)
|
|
|
|
const (
|
|
refreshTokenTableName = "RefreshTokens"
|
|
)
|
|
|
|
type RefreshTokenTable interface {
|
|
Create(username string, token string) (int64, error)
|
|
GetByUsername(name string) (domain.RefreshTokenEntity, error)
|
|
DeleteById(id int64) (int64, error)
|
|
}
|
|
|
|
type RefreshTokenRepository struct {
|
|
connection *sql.DB
|
|
}
|
|
|
|
func NewRefreshTokenRepository(conn *sql.DB) RefreshTokenRepository {
|
|
return RefreshTokenRepository{
|
|
connection: conn,
|
|
}
|
|
}
|
|
|
|
func (rt RefreshTokenRepository) Create(username string, token string) (int64, error) {
|
|
dt := time.Now()
|
|
builder := sqlbuilder.NewInsertBuilder()
|
|
builder.InsertInto(refreshTokenTableName)
|
|
builder.Cols("Username", "Token", "CreatedAt", "LastUpdated")
|
|
builder.Values(username, token, dt, dt)
|
|
query, args := builder.Build()
|
|
|
|
_, err := rt.connection.Exec(query, args...)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return 1, nil
|
|
}
|
|
|
|
func (rt RefreshTokenRepository) GetByUsername(name string) (domain.RefreshTokenEntity, error) {
|
|
builder := sqlbuilder.NewSelectBuilder()
|
|
builder.Select("*").From(refreshTokenTableName).Where(
|
|
builder.E("Username", name),
|
|
)
|
|
|
|
query, args := builder.Build()
|
|
rows, err := rt.connection.Query(query, args...)
|
|
if err != nil {
|
|
return domain.RefreshTokenEntity{}, err
|
|
}
|
|
|
|
data := rt.processRows(rows)
|
|
if len(data) == 0 {
|
|
return domain.RefreshTokenEntity{}, errors.New("no token found for user")
|
|
}
|
|
|
|
return data[0], nil
|
|
}
|
|
|
|
func (rt RefreshTokenRepository) DeleteById(id int64) (int64, error) {
|
|
builder := sqlbuilder.NewDeleteBuilder()
|
|
builder.DeleteFrom(refreshTokenTableName)
|
|
builder.Where(
|
|
builder.EQ("Id", id),
|
|
)
|
|
|
|
query, args := builder.Build()
|
|
rows, err := rt.connection.Exec(query, args...)
|
|
if err != nil {
|
|
return -1, err
|
|
}
|
|
|
|
return rows.RowsAffected()
|
|
}
|
|
|
|
func (rd RefreshTokenRepository) processRows(rows *sql.Rows) []domain.RefreshTokenEntity {
|
|
items := []domain.RefreshTokenEntity{}
|
|
|
|
for rows.Next() {
|
|
var id int64
|
|
var username string
|
|
var token string
|
|
var createdAt time.Time
|
|
var lastUpdated time.Time
|
|
|
|
err := rows.Scan(&id, &username, &token, &createdAt, &lastUpdated)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
|
|
items = append(items, domain.RefreshTokenEntity{
|
|
Id: id,
|
|
Username: username,
|
|
Token: token,
|
|
CreatedAt: createdAt,
|
|
LastUpdated: lastUpdated,
|
|
})
|
|
}
|
|
|
|
return items
|
|
}
|
|
|
|
//func (rt RefreshTokenRepository) Delete()
|