add extractors for userid and token

This commit is contained in:
Pavel 2024-05-20 17:29:45 +03:00
parent 15087a0f99
commit e7db450e8c
7 changed files with 111 additions and 88 deletions

@ -4,21 +4,21 @@ JWT_AUDIENCE="pena"
JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHgnvr7O2tiApjJfid1orFnIGm69\n80fZp+Lpbjo+NC/0whMFga2Biw5b1G2Q/B2u0tpO1Fs/E8z7Lv1nYfr5jx2S8x6B\ndA4TS2kB9Kf0wn0+7wSlyikHoKhbtzwXHZl17GsyEi6wHnsqNBSauyIWhpha8i+Y\n+3GyaOY536H47qyXAgMBAAE=\n-----END PUBLIC KEY-----" JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHgnvr7O2tiApjJfid1orFnIGm69\n80fZp+Lpbjo+NC/0whMFga2Biw5b1G2Q/B2u0tpO1Fs/E8z7Lv1nYfr5jx2S8x6B\ndA4TS2kB9Kf0wn0+7wSlyikHoKhbtzwXHZl17GsyEi6wHnsqNBSauyIWhpha8i+Y\n+3GyaOY536H47qyXAgMBAAE=\n-----END PUBLIC KEY-----"
HTTP_HOST=0.0.0.0 HTTP_HOST=0.0.0.0
HTTP_PORT=8003 HTTP_PORT=8082
GRPC_HOST=0.0.0.0 GRPC_HOST=0.0.0.0
GRPC_PORT=9000 GRPC_PORT=9000
GRPC_DOMEN=customer-service:9000 GRPC_DOMEN=customer-service:9000
MONGO_HOST=localhost MONGO_HOST=localhost
MONGO_PORT=27024 MONGO_PORT=27020
MONGO_USER=test MONGO_USER=test
MONGO_PASSWORD=test MONGO_PASSWORD=test
MONGO_DB_NAME=admin MONGO_DB_NAME=admin
MONGO_AUTH=admin MONGO_AUTH=admin
KAFKA_BROKERS=localhost:9092 KAFKA_BROKERS=localhost:9092
KAFKA_TOPIC_TARIFF=tariffs KAFKA_TOPIC_TARIFF=test-topic
AUTH_MICROSERVICE_USER_URL=http://localhost:8000/user AUTH_MICROSERVICE_USER_URL=http://localhost:8000/user
HUBADMIN_MICROSERVICE_TARIFF_URL=http://localhost:8001/tariff HUBADMIN_MICROSERVICE_TARIFF_URL=http://localhost:8001/tariff
@ -27,9 +27,11 @@ DISCOUNT_MICROSERVICE_GRPC_HOST=localhost:9040
PAYMENT_MICROSERVICE_GRPC_HOST=treasurer-service:9085 PAYMENT_MICROSERVICE_GRPC_HOST=treasurer-service:9085
VERIFICATION_MICROSERVICE_USER_URL=http://10.8.0.8:7035/verification VERIFICATION_MICROSERVICE_USER_URL=http://10.8.0.8:7035/verification
TEMPLATEGEN_MICROSERVICE_URL=10.6.0.17 TEMPLATEGEN_MICROSERVICE_URL=10.6.0.17
CODEWORD_MICROSERVICE_GRPC_HOST = http://localhost:8000/user
API_URL=https://api.smtp.bz/v1/smtp/send API_URL=https://api.smtp.bz/v1/smtp/send
MAIL_SENDER=noreply@mailing.pena.digital MAIL_SENDER=noreply@mailing.pena.digital
MAIL_API_KEY=P0YsjUB137upXrr1NiJefHmXVKW1hmBWlpev MAIL_API_KEY=P0YsjUB137upXrr1NiJefHmXVKW1hmBWlpev
MAIL_AUTH_USERNAME=kotilion.95@gmail.com MAIL_AUTH_USERNAME=kotilion.95@gmail.com
MAIL_AUTH_PASSWORD=vWwbCSg4bf0p MAIL_AUTH_PASSWORD=vWwbCSg4bf0p
MAIL_ADDRESS = mail@mail.com

2
go.mod

@ -19,7 +19,7 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20240221002015-b0ce06bbee7c google.golang.org/genproto/googleapis/api v0.0.0-20240221002015-b0ce06bbee7c
google.golang.org/grpc v1.62.0 google.golang.org/grpc v1.62.0
google.golang.org/protobuf v1.32.0 google.golang.org/protobuf v1.32.0
penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240220080149-ae9c991d3ece penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240223054633-6cb3d5ce45b6
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240412164014-6ce70d76fedc penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240412164014-6ce70d76fedc
) )

4
go.sum

@ -264,7 +264,7 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240220080149-ae9c991d3ece h1:CsjgNNqssfa05B7iDNMyK2wWR7SZ/kglLTMAVrhGLtY= penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240223054633-6cb3d5ce45b6 h1:oV+/HNX+JPoQ3/GUx08hio7d45WpY0AMGrFs7j70QlA=
penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240220080149-ae9c991d3ece/go.mod h1:lTmpjry+8evVkXWbEC+WMOELcFkRD1lFMc7J09mOndM= penahub.gitlab.yandexcloud.net/backend/penahub_common v0.0.0-20240223054633-6cb3d5ce45b6/go.mod h1:lTmpjry+8evVkXWbEC+WMOELcFkRD1lFMc7J09mOndM=
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240412164014-6ce70d76fedc h1:B9X8pOrqWPGbWZNXSJEUk/8GWeBDGQmMKgQ0F+PSliQ= penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240412164014-6ce70d76fedc h1:B9X8pOrqWPGbWZNXSJEUk/8GWeBDGQmMKgQ0F+PSliQ=
penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240412164014-6ce70d76fedc/go.mod h1:/DcyAjBh41IbomuDu5QzhL9flZW6lWO3ZAEbUXKobk0= penahub.gitlab.yandexcloud.net/backend/quiz/common.git v0.0.0-20240412164014-6ce70d76fedc/go.mod h1:/DcyAjBh41IbomuDu5QzhL9flZW6lWO3ZAEbUXKobk0=

@ -110,6 +110,16 @@ func (api *API2) noauth(ctx *fiber.Ctx) error {
return api.error(ctx, fiber.StatusUnauthorized, "failed to get jwt payload") return api.error(ctx, fiber.StatusUnauthorized, "failed to get jwt payload")
} }
func (api *API2) extractUserID(ctx *fiber.Ctx) (string, bool) {
id, ok := ctx.Context().UserValue(models.AuthJWTDecodedUserIDKey).(string)
return id, ok
}
func (api *API2) extractToken(ctx *fiber.Ctx) (string, bool) {
token, ok := ctx.Context().UserValue(models.AuthJWTDecodedAccessTokenKey).(string)
return token, ok
}
// Health // Health
func (api *API2) GetHealth(ctx *fiber.Ctx) error { func (api *API2) GetHealth(ctx *fiber.Ctx) error {
@ -119,8 +129,8 @@ func (api *API2) GetHealth(ctx *fiber.Ctx) error {
// Account // Account
func (api *API2) DeleteAccount(ctx *fiber.Ctx) error { func (api *API2) DeleteAccount(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -133,8 +143,8 @@ func (api *API2) DeleteAccount(ctx *fiber.Ctx) error {
} }
func (api *API2) ChangeAccount(ctx *fiber.Ctx) error { func (api *API2) ChangeAccount(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -156,6 +166,7 @@ func (api *API2) SetAccountVerificationStatus(ctx *fiber.Ctx) error {
if userID == "" { if userID == "" {
return api.error(ctx, fiber.StatusBadRequest, "invalid format for parameter userId") return api.error(ctx, fiber.StatusBadRequest, "invalid format for parameter userId")
} }
var request models.SetAccountStatus var request models.SetAccountStatus
if err := ctx.BodyParser(&request); err != nil { if err := ctx.BodyParser(&request); err != nil {
return api.error(ctx, fiber.StatusBadRequest, "failed to bind json", err) return api.error(ctx, fiber.StatusBadRequest, "failed to bind json", err)
@ -171,8 +182,8 @@ func (api *API2) SetAccountVerificationStatus(ctx *fiber.Ctx) error {
} }
func (api *API2) GetAccount(ctx *fiber.Ctx) error { func (api *API2) GetAccount(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -185,8 +196,8 @@ func (api *API2) GetAccount(ctx *fiber.Ctx) error {
} }
func (api *API2) AddAccount(ctx *fiber.Ctx) error { func (api *API2) AddAccount(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -295,8 +306,8 @@ func (api *API2) PaginationAccounts(ctx *fiber.Ctx) error {
// Cart // Cart
func (api *API2) RemoveFromCart(ctx *fiber.Ctx) error { func (api *API2) RemoveFromCart(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -314,13 +325,13 @@ func (api *API2) RemoveFromCart(ctx *fiber.Ctx) error {
} }
func (api *API2) Add2cart(ctx *fiber.Ctx) error { func (api *API2) Add2cart(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
token := ctx.Get(models.AuthJWTDecodedAccessTokenKey) token, ok := api.extractToken(ctx)
if token == "" { if !ok || token == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -347,13 +358,13 @@ func (api *API2) Add2cart(ctx *fiber.Ctx) error {
} }
func (api *API2) PayCart(ctx *fiber.Ctx) error { func (api *API2) PayCart(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
accessToken := ctx.Get(models.AuthJWTDecodedAccessTokenKey) accessToken, ok := api.extractToken(ctx)
if accessToken == "" { if !ok || accessToken == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -573,7 +584,11 @@ func (api *API2) GetHistory(ctx *fiber.Ctx) error {
if accountID != "" { if accountID != "" {
userID = accountID userID = accountID
} else { } else {
userID = ctx.Get(models.AuthJWTDecodedUserIDKey) id, ok := api.extractUserID(ctx)
if !ok || id == "" {
return api.noauth(ctx)
}
} }
limit, err := strconv.ParseInt(limitStr, 10, 64) limit, err := strconv.ParseInt(limitStr, 10, 64)
@ -623,8 +638,8 @@ func (api *API2) GetHistory(ctx *fiber.Ctx) error {
// Wallet // Wallet
func (api *API2) RequestMoney(ctx *fiber.Ctx) error { func (api *API2) RequestMoney(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -650,8 +665,8 @@ func (api *API2) RequestMoney(ctx *fiber.Ctx) error {
} }
func (api *API2) ChangeCurrency(ctx *fiber.Ctx) error { func (api *API2) ChangeCurrency(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -723,8 +738,8 @@ func (api *API2) CalculateLTV(ctx *fiber.Ctx) error {
} }
func (api *API2) GetRecentTariffs(ctx *fiber.Ctx) error { func (api *API2) GetRecentTariffs(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }
@ -860,8 +875,8 @@ func (api *API2) SendReport(ctx *fiber.Ctx) error {
} }
func (api *API2) PostWalletRspay(ctx *fiber.Ctx) error { func (api *API2) PostWalletRspay(ctx *fiber.Ctx) error {
userID := ctx.Get(models.AuthJWTDecodedUserIDKey) userID, ok := api.extractUserID(ctx)
if userID == "" { if !ok || userID == "" {
return api.noauth(ctx) return api.noauth(ctx)
} }

@ -10,13 +10,19 @@ import (
"testing" "testing"
) )
func TestGetAccount(t *testing.T) { func TestPostWalletRspay(t *testing.T) {
jwtUtil := helpers.InitializeJWT() jwtUtil := helpers.InitializeJWT()
t.Run("rspay", func(t *testing.T) { t.Run("rspay", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
req := struct {
Money float32
}{
Money: 100,
}
assert.NotPanics(t, func() { assert.NotPanics(t, func() {
token, tokenErr := jwtUtil.Create("6597babdd1ba7e2dbd32d7e3") token, tokenErr := jwtUtil.Create("6597babdd1ba7e2dbd32d7e3")
if isNoError := assert.NoError(t, tokenErr); !isNoError { if isNoError := assert.NoError(t, tokenErr); !isNoError {
@ -26,6 +32,7 @@ func TestGetAccount(t *testing.T) {
response, err := client.Post[interface{}, models.ResponseErrorHTTP](ctx, &client.RequestSettings{ response, err := client.Post[interface{}, models.ResponseErrorHTTP](ctx, &client.RequestSettings{
URL: "http://localhost:8082/wallet/rspay", URL: "http://localhost:8082/wallet/rspay",
Headers: map[string]string{"Authorization": fmt.Sprintf("Bearer %s", token)}, Headers: map[string]string{"Authorization": fmt.Sprintf("Bearer %s", token)},
Body: req,
}) })
if isNoError := assert.NoError(t, err); !isNoError { if isNoError := assert.NoError(t, err); !isNoError {
return return

@ -7,17 +7,24 @@ import (
"net/http" "net/http"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models" "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
"penahub.gitlab.yandexcloud.net/pena-services/customer/pkg/client" "penahub.gitlab.yandexcloud.net/pena-services/customer/pkg/client"
"penahub.gitlab.yandexcloud.net/pena-services/customer/tests/helpers"
"testing" "testing"
) )
func TestCurrencies(t *testing.T) { func TestCurrencies(t *testing.T) {
jwtUtil := helpers.InitializeJWT()
t.Run("Получение текущих доступных курсов", func(t *testing.T) { t.Run("Получение текущих доступных курсов", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
assert.NotPanics(t, func() { assert.NotPanics(t, func() {
token, tokenErr := jwtUtil.Create("6597babdd1ba7e2dbd32d7e3")
if isNoError := assert.NoError(t, tokenErr); !isNoError {
return
}
responseGetCurrencies, errCurrencies := client.Get[[]models.CurrencyList, models.ResponseErrorHTTP](ctx, &client.RequestSettings{ responseGetCurrencies, errCurrencies := client.Get[[]models.CurrencyList, models.ResponseErrorHTTP](ctx, &client.RequestSettings{
URL: "http://localhost:8082/currencies", URL: "http://localhost:8082/currencies",
Headers: map[string]string{"Authorization": fmt.Sprintf("Bearer %s", token)},
}) })
if isNoError := assert.NoError(t, errCurrencies); !isNoError { if isNoError := assert.NoError(t, errCurrencies); !isNoError {
return return

@ -2,65 +2,57 @@ package integration
import ( import (
"context" "context"
"github.com/gofiber/fiber/v2"
"github.com/pioz/faker" "github.com/pioz/faker"
"go.uber.org/zap"
"log"
"net/http"
"net/http/httptest"
"penahub.gitlab.yandexcloud.net/backend/penahub_common/mongo"
http2 "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/controller/http"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/repository" "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/interface/repository"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models" "penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
"strconv" "strconv"
"testing"
"time" "time"
) )
func TestLogostat(t *testing.T) { //func TestLogostat(t *testing.T) {
logger, err := zap.NewProduction(zap.AddStacktrace(zap.DPanicLevel)) // logger, err := zap.NewProduction(zap.AddStacktrace(zap.DPanicLevel))
if err != nil { // if err != nil {
log.Fatalf("failed to init zap logger: %v", err) // log.Fatalf("failed to init zap logger: %v", err)
} // }
ctx := context.Background() // ctx := context.Background()
mongoDB, err := mongo.Connect(ctx, &mongo.ConnectDeps{ // mongoDB, err := mongo.Connect(ctx, &mongo.ConnectDeps{
Configuration: &mongo.Configuration{ // Configuration: &mongo.Configuration{
Host: "localhost", // Host: "localhost",
Port: "27020", // Port: "27020",
User: "test", // User: "test",
Password: "test", // Password: "test",
Auth: "admin", // Auth: "admin",
DatabaseName: "admin", // DatabaseName: "admin",
}, // },
Timeout: 10 * time.Second, // Timeout: 10 * time.Second,
}) // })
//
repoAc := repository.NewAccountRepository2(logger, mongoDB.Collection("accounts")) // repoAc := repository.NewAccountRepository2(logger, mongoDB.Collection("accounts"))
repoHi := repository.NewHistoryRepository2(logger, mongoDB.Collection("histories")) // repoHi := repository.NewHistoryRepository2(logger, mongoDB.Collection("histories"))
InsertToDB(ctx, repoAc, repoHi) // InsertToDB(ctx, repoAc, repoHi)
//
api := http2.NewAPI2(logger, mongoDB, nil, nil, nil, nil) // api := http2.NewAPI2(logger, mongoDB, nil, nil, nil, nil)
//
app := fiber.New() // app := fiber.New()
req := httptest.NewRequest(http.MethodGet, "/", nil) // req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Content-Type", "application/json") // req.Header.Set("Content-Type", "application/json")
//
requestBody := struct { // requestBody := struct {
From int // From int
Limit int // Limit int
Page int // Page int
To int // To int
}{ // }{
From: 1713087258, // From: 1713087258,
Limit: 10, // Limit: 10,
Page: 1, // Page: 1,
To: 1713260058, // To: 1713260058,
} // }
//
req = req.WithContext(context.WithValue(req.Context(), "requestBody", requestBody)) // req = req.WithContext(context.WithValue(req.Context(), "requestBody", requestBody))
resp := httptest.NewRecorder() // resp := httptest.NewRecorder()
//
} //}
func InsertToDB(ctx context.Context, acc repository.AccountRepository, history repository.HistoryRepository) { func InsertToDB(ctx context.Context, acc repository.AccountRepository, history repository.HistoryRepository) {
partner1 := "partner1" partner1 := "partner1"