MSP-1538 implement session api
This commit is contained in:
1 parent
45810b4ec8
commit
4d1c17f9ae
4 files changed
+230
No files matched your search
@@ -0,0 +1,52 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type SessionService interface {
|
||||
All(ctx context.Context, limit int, offset int) (*domain.SessionResponse, error)
|
||||
Revoke(ctx context.Context, id int) error
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
service SessionService
|
||||
}
|
||||
|
||||
func NewSession(service SessionService) Session {
|
||||
return Session{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.PageRequest
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/all [POST]
|
||||
func (c Session) All(ctx context.Context, req domain.PageRequest) (*domain.SessionResponse, error) {
|
||||
return c.service.All(ctx, req.Limit, req.Offset)
|
||||
}
|
||||
|
||||
// Revoke
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/revoke [POST]
|
||||
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
||||
return c.service.Revoke(ctx, req.Id)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Id int
|
||||
UserId int
|
||||
Status string
|
||||
ExpiredAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
TotalCount int
|
||||
Items []Session
|
||||
}
|
||||
|
||||
type SessionRequest struct {
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type RevokeRequest struct {
|
||||
Id int `valid:"required"`
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
@@ -22,6 +24,8 @@ func NewToken(db db.DB) Token {
|
||||
}
|
||||
|
||||
func (r Token) Save(ctx context.Context, token entity.Token) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.Save")
|
||||
|
||||
q := `
|
||||
INSERT INTO tokens
|
||||
(token, user_id, status, expired_at, created_at, updated_at)
|
||||
@@ -36,6 +40,8 @@ func (r Token) Save(ctx context.Context, token entity.Token) error {
|
||||
}
|
||||
|
||||
func (r Token) GetEntity(ctx context.Context, token string) (*entity.Token, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.GetEntity")
|
||||
|
||||
result := entity.Token{}
|
||||
q := `
|
||||
SELECT token, user_id, status, expired_at, created_at, updated_at
|
||||
@@ -54,6 +60,8 @@ func (r Token) GetEntity(ctx context.Context, token string) (*entity.Token, erro
|
||||
}
|
||||
|
||||
func (r Token) RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.RevokeByUserId")
|
||||
|
||||
q := `
|
||||
UPDATE tokens
|
||||
SET status = $1, updated_at = $2
|
||||
@@ -66,3 +74,88 @@ func (r Token) RevokeByUserId(ctx context.Context, userId int64, updatedAt time.
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Token) All(ctx context.Context, limit int, offset int) ([]entity.Token, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.All")
|
||||
|
||||
query, args, err := query.New().
|
||||
Select("*").
|
||||
From("tokens").
|
||||
OrderBy("created_at DESC").
|
||||
Offset(uint64(offset)).
|
||||
Limit(uint64(limit)).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
tokens := make([]entity.Token, 0)
|
||||
err = r.db.Select(ctx, &tokens, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select query %s", query)
|
||||
}
|
||||
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func (r Token) UpdateStatus(ctx context.Context, id int, status string) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.UpdateStatus")
|
||||
|
||||
q := `
|
||||
UPDATE tokens SET status = $1, updated_at = $2 where id = $3;
|
||||
`
|
||||
_, err := r.db.Exec(ctx, q, status, time.Now().UTC(), id)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update token status")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Token) Count(ctx context.Context) (int64, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.Count")
|
||||
|
||||
count := int64(0)
|
||||
err := r.db.SelectRow(ctx, &count, "select count(*) from tokens")
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "select count")
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r Token) UpdateStatusByUserId(ctx context.Context, userId int, status string) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.UpdateStatusByUserId")
|
||||
|
||||
q := `
|
||||
UPDATE tokens SET status = $1, updated_at = $2 where user_id = $3;
|
||||
`
|
||||
_, err := r.db.Exec(ctx, q, status, time.Now().UTC(), userId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update token status")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Token) LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers")
|
||||
|
||||
query := `
|
||||
select t.user_id, max(t.created_at) as created_at from tokens t
|
||||
join users u on t.user_id = u.id
|
||||
where u.blocked = false
|
||||
group by t.user_id
|
||||
`
|
||||
tokens := make([]entity.Token, 0)
|
||||
err := r.db.Select(ctx, &tokens, query)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select query: %s", query)
|
||||
}
|
||||
|
||||
result := make(map[int64]time.Time, 0)
|
||||
for _, token := range tokens {
|
||||
result[token.UserId] = token.CreatedAt
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
@@ -15,6 +16,9 @@ type TokenRep interface {
|
||||
Save(ctx context.Context, token entity.Token) error
|
||||
GetEntity(ctx context.Context, token string) (*entity.Token, error)
|
||||
RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error
|
||||
All(ctx context.Context, limit int, offset int) ([]entity.Token, error)
|
||||
Count(ctx context.Context) (int64, error)
|
||||
UpdateStatus(ctx context.Context, id int, status string) error
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
@@ -78,3 +82,57 @@ func (s Token) RevokeAllByUserId(ctx context.Context, userId int64) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Token) All(ctx context.Context, limit int, offset int) (*domain.SessionResponse, error) {
|
||||
group, ctx := errgroup.WithContext(ctx)
|
||||
var tokens []entity.Token
|
||||
var total int64
|
||||
var err error
|
||||
group.Go(func() error {
|
||||
tokens, err = s.tokenRep.All(ctx, limit, offset)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get all tokens")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
group.Go(func() error {
|
||||
total, err = s.tokenRep.Count(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "count all tokens")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
err = group.Wait()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "wait workers")
|
||||
}
|
||||
|
||||
items := make([]domain.Session, 0)
|
||||
for _, token := range tokens {
|
||||
status := token.Status
|
||||
if time.Now().UTC().After(token.ExpiredAt) {
|
||||
status = entity.TokenStatusExpired
|
||||
}
|
||||
items = append(items, domain.Session{
|
||||
Id: token.Id,
|
||||
UserId: int(token.UserId),
|
||||
Status: status,
|
||||
ExpiredAt: token.ExpiredAt,
|
||||
CreatedAt: token.CreatedAt,
|
||||
})
|
||||
}
|
||||
result := domain.SessionResponse{
|
||||
TotalCount: int(total),
|
||||
Items: items,
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (s Token) Revoke(ctx context.Context, id int) error {
|
||||
err := s.tokenRep.UpdateStatus(ctx, id, entity.TokenStatusRevoked)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "token update status")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user