block-accounting/backend/internal/interface/rest/presenters/auth.go

104 lines
2.6 KiB
Go
Raw Normal View History

2024-05-24 17:44:24 +00:00
package presenters
import (
2024-05-26 00:30:35 +00:00
"context"
2024-05-24 17:44:24 +00:00
"encoding/json"
"fmt"
"time"
"github.com/emochka2007/block-accounting/internal/interface/rest/domain"
"github.com/emochka2007/block-accounting/internal/pkg/models"
"github.com/emochka2007/block-accounting/internal/usecase/interactors/jwt"
2024-05-26 00:30:35 +00:00
"github.com/google/uuid"
2024-05-24 17:44:24 +00:00
)
type AuthPresenter interface {
ResponseJoin(user *models.User) ([]byte, error)
ResponseLogin(user *models.User) ([]byte, error)
ResponseRefresh(tokens jwt.AccessToken) ([]byte, error)
2024-05-26 00:30:35 +00:00
ResponseNewInvite(
ctx context.Context,
organizationID uuid.UUID,
link string,
) ([]byte, error)
2024-05-24 17:44:24 +00:00
}
type authPresenter struct {
jwtInteractor jwt.JWTInteractor
}
func NewAuthPresenter(
jwtInteractor jwt.JWTInteractor,
) AuthPresenter {
return &authPresenter{
jwtInteractor: jwtInteractor,
}
}
func (p *authPresenter) ResponseJoin(user *models.User) ([]byte, error) {
2024-05-24 23:58:05 +00:00
tokens, err := p.jwtInteractor.NewToken(user, 24*time.Hour, "")
2024-05-24 17:44:24 +00:00
if err != nil {
return nil, fmt.Errorf("error create access token. %w", err)
}
out, err := json.Marshal(domain.LoginResponse{
Token: tokens.Token,
RefreshToken: tokens.RefreshToken,
ExpiredAt: tokens.ExpiredAt.UnixMilli(),
RTExpiredAt: tokens.RTExpiredAt.UnixMilli(),
})
if err != nil {
return nil, fmt.Errorf("error marshal join response. %w", err)
}
return out, nil
}
func (p *authPresenter) ResponseLogin(user *models.User) ([]byte, error) {
2024-05-24 23:58:05 +00:00
tokens, err := p.jwtInteractor.NewToken(user, 24*time.Hour, "")
2024-05-24 17:44:24 +00:00
if err != nil {
return nil, fmt.Errorf("error create access token. %w", err)
}
out, err := json.Marshal(domain.LoginResponse{
Token: tokens.Token,
RefreshToken: tokens.RefreshToken,
ExpiredAt: tokens.ExpiredAt.UnixMilli(),
RTExpiredAt: tokens.RTExpiredAt.UnixMilli(),
})
if err != nil {
return nil, fmt.Errorf("error marshal login response. %w", err)
}
return out, nil
}
func (p *authPresenter) ResponseRefresh(tokens jwt.AccessToken) ([]byte, error) {
out, err := json.Marshal(domain.LoginResponse{
Token: tokens.Token,
RefreshToken: tokens.RefreshToken,
ExpiredAt: tokens.ExpiredAt.UnixMilli(),
RTExpiredAt: tokens.RTExpiredAt.UnixMilli(),
})
if err != nil {
return nil, fmt.Errorf("error marshal refresh response. %w", err)
}
return out, nil
}
2024-05-26 00:30:35 +00:00
func (p *authPresenter) ResponseNewInvite(
ctx context.Context,
organizationID uuid.UUID,
link string,
) ([]byte, error) {
out, err := json.Marshal(map[string]string{
"link": "/" + organizationID.String() + "/invite/" + link,
})
if err != nil {
return nil, fmt.Errorf("error marshal refresh response. %w", err)
}
return out, nil
}