From 167d6b9774df6c0714df2dc2aa7e1b36e1b264ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=5B=20Taha=2E=20Dostifam=E2=80=8D=20=5D?= Date: Sun, 26 May 2024 01:20:15 +0330 Subject: [PATCH] refactor hiher layers done and auth controller almost done execpt reset-password service --- Makefile | 20 +- app/controller/auth_controller.go | 153 ++++++++++++++++ app/controller/user_controller.go | 108 ----------- app/dto/dto.go | 62 ------- app/dto/user_dto.go | 10 - app/middleware/authenticated.go | 29 ++- app/middleware/error_handler.go | 2 +- app/presenters/auth_presenter.go | 11 ++ app/presenters/chat_presenters.go | 82 ++++----- app/presenters/error_presenters.go | 54 ++++++ app/presenters/message_presenters.go | 8 +- app/presenters/public_presenters.go | 41 ----- app/presenters/user_presenter.go | 30 ++- app/router/auth_routes.go | 23 +++ app/router/user_routes.go | 26 --- app/router/ws_routes.go | 25 ++- app/validator/auth.go | 19 ++ app/validator/validate.go | 46 +++++ cmd/server/server.go | 172 +++++++++++------- config/config_test.go | 4 +- docker-compose.yml | 8 +- go.mod | 37 ++-- go.sum | 75 +++----- integration.Dockerfile | 9 - internal/model/auth_model.go | 16 +- internal/repository/auth_repository.go | 46 +++++ internal/service/auth/auth_errors.go | 32 ++-- internal/service/auth/auth_service.go | 79 ++++++-- internal/service/auth/auth_validations.go | 2 +- internal/service/user/user_service.go | 2 +- pkg/auth_manager/auth_manager.go | 4 +- pkg/email/email.go | 32 +--- pkg/email/email_test.go | 33 ---- scripts/build.sh | 3 - scripts/docker_compose_build.sh | 3 - scripts/integration_test.sh | 3 - scripts/run_devel.sh | 3 - scripts/run_prod.sh | 6 - socket/handlers/chats_handler.go | 38 ++-- socket/handlers/handler.go | 44 +++-- socket/handlers/messages_handler.go | 5 +- .../repository/user_repository_test.go | 2 +- .../integration/service/auth_service_test.go | 7 +- utils/bearer/bearer.go | 50 ----- utils/bearer/bearer_test.go | 16 -- utils/hash/hash.go | 34 ++-- utils/hash/hash_test.go | 5 +- utils/random/random_test.go | 4 +- utils/structs/set_value_by_tag_test.go | 6 +- 49 files changed, 758 insertions(+), 771 deletions(-) create mode 100644 app/controller/auth_controller.go delete mode 100644 app/controller/user_controller.go delete mode 100644 app/dto/dto.go delete mode 100644 app/dto/user_dto.go create mode 100644 app/presenters/auth_presenter.go create mode 100644 app/presenters/error_presenters.go delete mode 100644 app/presenters/public_presenters.go create mode 100644 app/router/auth_routes.go delete mode 100644 app/router/user_routes.go create mode 100644 app/validator/auth.go create mode 100644 app/validator/validate.go delete mode 100644 integration.Dockerfile delete mode 100755 scripts/build.sh delete mode 100755 scripts/docker_compose_build.sh delete mode 100755 scripts/integration_test.sh delete mode 100755 scripts/run_devel.sh delete mode 100755 scripts/run_prod.sh delete mode 100644 utils/bearer/bearer.go delete mode 100644 utils/bearer/bearer_test.go diff --git a/Makefile b/Makefile index 5f54c71..c812ca3 100644 --- a/Makefile +++ b/Makefile @@ -1,14 +1,12 @@ -PACKAGES=$(shell go list ./... | grep -v 'tests') - -# Install tools are needed for development (golangci-lint, gofumpt) +# Install development tools (golangci-lint, gofumpt) devtools: @echo "Installing devtools" go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.57.1 go install mvdan.cc/gofumpt@latest -# GoLang Unit-Test +# Tests test: - go test ./... -covermode=atomic + go test ./... # Format fmt: @@ -18,3 +16,15 @@ fmt: # Linter check: golangci-lint run --build-tags "${BUILD_TAG}" --timeout=20m0s + +# Run on development +dev: + go run cmd/server/server.go + +# Build for production +build: + export GIN_MODE=release + export ENV=production + go mod tidy + go clean -cache + go build -o ./build/server cmd/server/server.go diff --git a/app/controller/auth_controller.go b/app/controller/auth_controller.go new file mode 100644 index 0000000..5c208a0 --- /dev/null +++ b/app/controller/auth_controller.go @@ -0,0 +1,153 @@ +package controller + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/kavkaco/Kavka-Core/app/presenters" + validator "github.com/kavkaco/Kavka-Core/app/validator" + auth "github.com/kavkaco/Kavka-Core/internal/service/auth" + chat "github.com/kavkaco/Kavka-Core/internal/service/chat" + "github.com/kavkaco/Kavka-Core/pkg/email" + "go.uber.org/zap" +) + +type AuthController struct { + ctx context.Context + logger *zap.Logger + authService auth.AuthService + chatService chat.ChatService + emailService email.EmailOtp +} + +func NewAuthController(ctx context.Context, logger *zap.Logger, authService auth.AuthService, chatService chat.ChatService, emailService email.EmailOtp) *AuthController { + return &AuthController{ctx, logger, authService, chatService, emailService} +} + +func (ctrl *AuthController) HandleLogin(c *gin.Context) { + if body := validator.ValidateBody[validator.AuthLoginRequest](c); body != nil { + user, accessToken, refreshToken, err := ctrl.authService.Login(ctrl.ctx, body.Email, body.Password) + if err != nil { + presenters.ErrorResponse(c, err) + return + } + + userChats, err := ctrl.chatService.GetUserChats(ctrl.ctx, user.UserID) + if err != nil { + presenters.ErrorResponse(c, err) + return + } + + c.Header(presenters.RefreshTokenHeaderName, refreshToken) + c.Header(presenters.AccessTokenHeaderName, accessToken) + + c.JSON(http.StatusOK, presenters.UserResponse(c, user, userChats)) + } +} + +func (ctrl *AuthController) HandleRegister(c *gin.Context) { + if body := validator.ValidateBody[validator.AuthRegisterRequest](c); body != nil { + _, verifyEmailToken, err := ctrl.authService.Register(ctrl.ctx, body.Name, body.LastName, body.Username, body.Email, body.Password) + if err != nil { + presenters.ErrorResponse(c, err) + return + } + + // FIXME + fmt.Println(verifyEmailToken) + + c.JSON(http.StatusOK, presenters.CodeMessageDto{ + Code: 200, + Message: "account registered successfully", + }) + } +} + +func (ctrl *AuthController) HandleRefreshToken(c *gin.Context) { + refreshToken := c.GetHeader(presenters.RefreshTokenHeaderName) + accessToken := c.GetHeader(presenters.AccessTokenHeaderName) + + newAccessToken, err := ctrl.authService.RefreshToken(ctrl.ctx, refreshToken, accessToken) + if errors.Is(err, auth.ErrAccessDenied) { + presenters.AccessDenied(c) + return + } else if err != nil { + presenters.ErrorResponse(c, err) + return + } + + c.Header(presenters.AccessTokenHeaderName, newAccessToken) + + c.JSON(http.StatusOK, presenters.CodeMessageDto{ + Code: 200, + Message: "access token refreshed", + }) +} + +func (ctrl *AuthController) HandleAuthenticate(c *gin.Context) { + accessToken := c.GetHeader(presenters.AccessTokenHeaderName) + + // get the user info + user, err := ctrl.authService.Authenticate(ctrl.ctx, accessToken) + if err != nil { + presenters.AccessDenied(c) + return + } + + // gathering user chats + userChats, err := ctrl.chatService.GetUserChats(ctrl.ctx, user.UserID) + if err != nil { + presenters.InternalServerErrorResponse(c) + return + } + + err = presenters.UserResponse(c, user, userChats) + if err != nil { + presenters.InternalServerErrorResponse(c) + } +} + +func (ctrl *AuthController) HandleVerifyEmail(c *gin.Context) { + redirectTo := c.Query("redirect_to") + verifyEmailToken := c.Param("token") + + if verifyEmailToken == "" { + presenters.BadRequestResponse(c) + return + } + + err := ctrl.authService.VerifyEmail(ctrl.ctx, verifyEmailToken) + if err != nil { + presenters.ErrorResponse(c, err) + return + } + + if redirectTo != "" { + c.Redirect(http.StatusPermanentRedirect, redirectTo) + return + } + + c.JSON(http.StatusOK, presenters.CodeMessageDto{ + Code: 200, + Message: "email verified", + }) +} + +func (ctrl *AuthController) HandleChangePassword(c *gin.Context) { + accessToken := c.GetHeader(presenters.AccessTokenHeaderName) + if body := validator.ValidateBody[validator.ChangePasswordRequest](c); body != nil { + err := ctrl.authService.ChangePassword(ctrl.ctx, accessToken, body.OldPassword, body.NewPassword) + if err != nil { + presenters.ErrorResponse(c, err) + return + } + + c.JSON(http.StatusOK, presenters.CodeMessageDto{ + Code: 200, + Message: "password changed", + }) + } +} diff --git a/app/controller/user_controller.go b/app/controller/user_controller.go deleted file mode 100644 index 0d33fd4..0000000 --- a/app/controller/user_controller.go +++ /dev/null @@ -1,108 +0,0 @@ -package controller - -import ( - "context" - "fmt" - "net/http" - - "github.com/gin-gonic/gin" - dto "github.com/kavkaco/Kavka-Core/app/dto" - "github.com/kavkaco/Kavka-Core/app/presenters" - "github.com/kavkaco/Kavka-Core/internal/service" - "github.com/kavkaco/Kavka-Core/utils/bearer" - "go.uber.org/zap" -) - -type UserController struct { - logger *zap.Logger - userService service.UserService - chatService service.ChatService -} - -func NewUserController(logger *zap.Logger, userService service.UserService, chatService service.ChatService) *UserController { - return &UserController{logger, userService, chatService} -} - -func (ctrl *UserController) HandleLogin(ginCtx *gin.Context) { - body := dto.Validate[dto.UserLoginDto](ginCtx) - phone := body.Phone - - err := ctrl.userService.Login(phone) - if err != nil { - presenters.ResponseError(ginCtx, err) - return - } - - ginCtx.JSON(http.StatusOK, presenters.SimpleMessageDto{ - Code: 200, - Message: "OTP Code Sent", - }) -} - -func (ctrl *UserController) HandleVerifyOTP(ginCtx *gin.Context) { - body := dto.Validate[dto.UserVerifyOTPDto](ginCtx) - - tokens, err := ctrl.userService.VerifyOTP(body.Phone, body.OTP) - if err != nil { - presenters.ResponseError(ginCtx, err) - return - } - - ginCtx.Header("refresh", tokens) - ginCtx.Header("authorization", fmt.Sprintf("Bearer %s", tokens.AccessToken)) - - ginCtx.JSON(http.StatusOK, presenters.SimpleMessageDto{ - Code: 200, - Message: "Logged in successfully", - }) -} - -func (ctrl *UserController) HandleRefreshToken(ginCtx *gin.Context) { - refreshToken, bearerRfOk := bearer.RefreshToken(ginCtx) - - if bearerRfOk { - accessToken, bearerAtOk := bearer.AccessToken(ginCtx) - - if bearerAtOk { - newAccessToken, refErr := ctrl.userService.RefreshToken(refreshToken, accessToken) - if refErr != nil { - presenters.ResponseError(ginCtx, refErr) - return - } - - ginCtx.Header("refresh", newAccessToken) - ginCtx.Header("authorization", fmt.Sprintf("Bearer %s", refreshToken)) - - ginCtx.JSON(http.StatusOK, presenters.SimpleMessageDto{ - Code: 200, - Message: "Tokens refreshed successfully", - }) - } - } -} - -func (ctrl *UserController) HandleAuthenticate(ginCtx *gin.Context) { - ctx := context.TODO() - accessToken, bearerOk := bearer.AccessToken(ginCtx) - - if bearerOk { - // get the user info - userInfo, err := ctrl.userService.Authenticate(accessToken) - if err != nil { - presenters.AccessDenied(ginCtx) - return - } - - // gathering user chats - userChats, err := ctrl.chatService.GetUserChats(ctx, userInfo.StaticID) - if err != nil { - presenters.ResponseInternalServerError(ginCtx) - return - } - - err = presenters.ResponseUserInfo(ginCtx, userInfo, userChats) - if err != nil { - presenters.ResponseInternalServerError(ginCtx) - } - } -} diff --git a/app/dto/dto.go b/app/dto/dto.go deleted file mode 100644 index 2a3cfb7..0000000 --- a/app/dto/dto.go +++ /dev/null @@ -1,62 +0,0 @@ -package dto - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/go-playground/validator" - "github.com/kavkaco/Kavka-Core/app/presenters" -) - -type validationErrorResponse struct { - Success bool `json:"success"` - Errors []errorResponse `json:"errors"` -} - -type errorResponse struct { - Error bool - FailedField string - Tag string - Value interface{} -} - -var validate = validator.New() - -func Validate[Dto interface{}](ctx *gin.Context) *Dto { - var validationErrors []errorResponse - - body := new(Dto) - - bindErr := ctx.Bind(&body) - - if bindErr != nil { - presenters.ResponseBadRequest(ctx) //nolint - return nil - } - - errs := validate.Struct(body) - - if errs != nil { - for _, err := range errs.(validator.ValidationErrors) { //nolint - var elem errorResponse - - elem.FailedField = err.Field() - elem.Tag = err.Tag() - elem.Value = err.Value() - elem.Error = true - - validationErrors = append(validationErrors, elem) - } - } - - if len(validationErrors) > 0 { - ctx.JSON(http.StatusBadRequest, validationErrorResponse{ - Success: false, - Errors: validationErrors, - }) - - return nil - } - - return body -} diff --git a/app/dto/user_dto.go b/app/dto/user_dto.go deleted file mode 100644 index 64f2404..0000000 --- a/app/dto/user_dto.go +++ /dev/null @@ -1,10 +0,0 @@ -package dto - -type UserLoginDto struct { - Phone string `json:"phone" validate:"required"` -} - -type UserVerifyOTPDto struct { - Phone string `json:"phone" validate:"required"` - OTP int `json:"otp" validate:"required"` -} diff --git a/app/middleware/authenticated.go b/app/middleware/authenticated.go index c34cba9..c0ba250 100644 --- a/app/middleware/authenticated.go +++ b/app/middleware/authenticated.go @@ -1,27 +1,26 @@ package middleware import ( + "context" + "github.com/gin-gonic/gin" "github.com/kavkaco/Kavka-Core/app/presenters" - "github.com/kavkaco/Kavka-Core/internal/service" - "github.com/kavkaco/Kavka-Core/utils/bearer" + "github.com/kavkaco/Kavka-Core/internal/service/auth" ) -func AuthenticatedMiddleware(userService service.UserService) func(ctx *gin.Context) { - return func(ctx *gin.Context) { - accessToken, bearerOk := bearer.AccessToken(ctx) +func AuthenticatedMiddleware(ctx context.Context, authService auth.AuthService) func(ctx *gin.Context) { + return func(ginCtx *gin.Context) { + accessToken := ginCtx.GetHeader(presenters.AccessTokenHeaderName) - if bearerOk { - userInfo, err := userService.Authenticate(accessToken) - if err != nil { - presenters.AccessDenied(ctx) - return - } + user, err := authService.Authenticate(ctx, accessToken) + if err != nil { + presenters.AccessDenied(ginCtx) + return + } - ctx.Set("user_static_id", userInfo.StaticID.Hex()) + ginCtx.Set("userID", user.UserID) - // Process request - ctx.Next() - } + // Process request + ginCtx.Next() } } diff --git a/app/middleware/error_handler.go b/app/middleware/error_handler.go index fa29207..e277b1c 100644 --- a/app/middleware/error_handler.go +++ b/app/middleware/error_handler.go @@ -6,5 +6,5 @@ import ( ) func ErrorHandler(ctx *gin.Context, err error) { - presenters.ResponseError(ctx, err) + presenters.ErrorResponse(ctx, err) } diff --git a/app/presenters/auth_presenter.go b/app/presenters/auth_presenter.go new file mode 100644 index 0000000..e0935ae --- /dev/null +++ b/app/presenters/auth_presenter.go @@ -0,0 +1,11 @@ +package presenters + +const ( + RefreshTokenHeaderName = "X-Refresh-Token" + AccessTokenHeaderName = "X-Access-Token" +) + +type AuthRegisterRequest struct { + Code int `json:"code"` + Message string `json:"message"` +} diff --git a/app/presenters/chat_presenters.go b/app/presenters/chat_presenters.go index 716a839..028885a 100644 --- a/app/presenters/chat_presenters.go +++ b/app/presenters/chat_presenters.go @@ -1,10 +1,9 @@ package presenters import ( - "errors" + "log" - "github.com/kavkaco/Kavka-Core/internal/model/chat" - "github.com/kavkaco/Kavka-Core/internal/model/user" + "github.com/kavkaco/Kavka-Core/internal/model" "github.com/kavkaco/Kavka-Core/utils" "go.mongodb.org/mongo-driver/bson/primitive" ) @@ -24,51 +23,36 @@ type HttpDirectChatDetail struct { LastName string `json:"lastName"` } -func UnmarshalFetchedUsers(fetchedUsers primitive.A) ([]user.User, error) { - users := []user.User{} - - for _, v := range fetchedUsers { - currentUser, err := utils.TypeConverter[user.User](v) - if err != nil { - return nil, err - } - - users = append(users, *currentUser) - } - - return users, nil -} - -func ChatAsJSON(obj chat.ChatC, userStaticID primitive.ObjectID) (interface{}, error) { +func ChatAsJSON(chat model.Chat, userID model.UserID) (interface{}, error) { // Determine the specific ChatDetail type based on chatType var httpChatDetail interface{} - switch obj.ChatType { - case chat.TypeDirect: - chatDetailLocal, err := utils.TypeConverter[map[string]interface{}](obj.ChatDetail) - if err != nil { - return nil, err - } + switch chat.ChatType { + case model.TypeDirect: + log.Fatal("Not implemented yet") + // chatDetailLocal, err := utils.TypeConverter[map[string]interface{}](chat.ChatDetail) + // if err != nil { + // return nil, err + // } - fetchedUsers, err := UnmarshalFetchedUsers((*chatDetailLocal)["fetchedUsers"].(primitive.A)) - if err != nil { - return nil, err - } + // fetchedUsers, err := UnmarshalFetchedUsers((*chatDetailLocal)["fetchedUsers"].(primitive.A)) + // if err != nil { + // return nil, err + // } - if len(fetchedUsers) != 2 { - return nil, errors.New("invalid length of fetched users") - } + // if len(fetchedUsers) != 2 { + // return nil, errors.New("invalid length of fetched users") + // } - // FIXME - // target := chat.DetectTarget(fetchedUsers, userStaticID) + // recipientUserID := model.DetectRecipient(fetchedUsers, userID) // httpChatDetail = HttpDirectChatDetail{ - // UserID: target.StaticID, - // Name: target.Name, + // UserID: recipientUserID, + // Name: fetchedUsers, // LastName: target.LastName, // } - case chat.TypeChannel: - chatDetailLocal, err := utils.TypeConverter[chat.ChannelChatDetail](obj.ChatDetail) + case model.TypeChannel: + chatDetailLocal, err := utils.TypeConverter[model.ChannelChatDetail](chat.ChatDetail) if err != nil { return nil, err } @@ -77,8 +61,8 @@ func ChatAsJSON(obj chat.ChatC, userStaticID primitive.ObjectID) (interface{}, e Title: chatDetailLocal.Title, Username: chatDetailLocal.Username, } - case chat.TypeGroup: - chatDetailLocal, err := utils.TypeConverter[chat.GroupChatDetail](obj.ChatDetail) + case model.TypeGroup: + chatDetailLocal, err := utils.TypeConverter[model.GroupChatDetail](chat.ChatDetail) if err != nil { return nil, err } @@ -89,16 +73,16 @@ func ChatAsJSON(obj chat.ChatC, userStaticID primitive.ObjectID) (interface{}, e } } - obj.ChatDetail = httpChatDetail + chat.ChatDetail = httpChatDetail - for i, msg := range obj.Messages { - messageJson, err := MessageAsJSON(*msg) - if err != nil { - return nil, err - } + // for i, msg := range chat.Messages { + // messageJson, err := MessageAsJSON(*msg) + // if err != nil { + // return nil, err + // } - obj.Messages[i] = messageJson - } + // chat.Messages[i] = messageJson + // } - return obj, nil + return chat, nil } diff --git a/app/presenters/error_presenters.go b/app/presenters/error_presenters.go new file mode 100644 index 0000000..0f3afa2 --- /dev/null +++ b/app/presenters/error_presenters.go @@ -0,0 +1,54 @@ +package presenters + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +type ErrorDetail struct { + Error bool + FailedField string + Tag string + Value interface{} +} + +type CodeMessageErrorDto struct { + Code int `json:"code"` + Message string `json:"message"` + Errors []ErrorDetail `json:"errors"` +} + +type CodeMessageDto struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func BadRequestResponse(ctx *gin.Context) error { + code := http.StatusBadRequest + + ctx.JSON(http.StatusBadRequest, CodeMessageDto{ + Code: code, + Message: "bad request", + }) + + return nil +} + +func ErrorResponse(ctx *gin.Context, err error) { + code := http.StatusNotImplemented + + ctx.JSON(code, CodeMessageDto{ + Code: code, + Message: err.Error(), + }) +} + +func InternalServerErrorResponse(ctx *gin.Context) { + code := http.StatusInternalServerError + + ctx.JSON(code, CodeMessageDto{ + Code: code, + Message: "internal server error", + }) +} diff --git a/app/presenters/message_presenters.go b/app/presenters/message_presenters.go index 5fa35be..e7c15c2 100644 --- a/app/presenters/message_presenters.go +++ b/app/presenters/message_presenters.go @@ -1,16 +1,16 @@ package presenters import ( - "github.com/kavkaco/Kavka-Core/internal/model/message" + "github.com/kavkaco/Kavka-Core/internal/model" "github.com/kavkaco/Kavka-Core/utils" ) -func MessageAsJSON(obj message.Message) (*message.Message, error) { +func MessageAsJSON(obj model.Message) (*model.Message, error) { var messageContent interface{} switch obj.Type { - case message.TypeTextMessage: - localMessageContent, err := utils.TypeConverter[message.TextMessage](obj.Content) + case model.TypeTextMessage: + localMessageContent, err := utils.TypeConverter[model.TextMessage](obj.Content) if err != nil { return nil, err } diff --git a/app/presenters/public_presenters.go b/app/presenters/public_presenters.go deleted file mode 100644 index 6c06db2..0000000 --- a/app/presenters/public_presenters.go +++ /dev/null @@ -1,41 +0,0 @@ -package presenters - -import ( - "net/http" - - "github.com/gin-gonic/gin" -) - -type SimpleMessageDto struct { - Code int `json:"code"` - Message string `json:"message"` -} - -func ResponseBadRequest(ctx *gin.Context) error { - code := http.StatusBadRequest - - ctx.JSON(http.StatusBadRequest, SimpleMessageDto{ - Code: code, - Message: "Bad Request", - }) - - return nil -} - -func ResponseError(ctx *gin.Context, err error) { - code := http.StatusInternalServerError - - ctx.JSON(code, SimpleMessageDto{ - Code: code, - Message: err.Error(), - }) -} - -func ResponseInternalServerError(ctx *gin.Context) { - code := http.StatusInternalServerError - - ctx.JSON(code, SimpleMessageDto{ - Code: code, - Message: "Internal Server Error", - }) -} diff --git a/app/presenters/user_presenter.go b/app/presenters/user_presenter.go index 97028f0..b114601 100644 --- a/app/presenters/user_presenter.go +++ b/app/presenters/user_presenter.go @@ -4,48 +4,44 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/kavkaco/Kavka-Core/internal/model/chat" - "github.com/kavkaco/Kavka-Core/internal/model/user" + "github.com/kavkaco/Kavka-Core/internal/model" ) -// the data and information that would be send to user after authentication. -// the messages of chats must not be sent - -type UserInfoDto struct { +type UserDto struct { Message string `json:"message"` Code int `json:"code"` - UserInfo *user.User `json:"user"` - UserChats []chat.ChatC `json:"chats"` + User *model.User `json:"user"` + UserChats []model.Chat `json:"chats"` } func AccessDenied(ctx *gin.Context) { code := http.StatusForbidden - ctx.JSON(code, SimpleMessageDto{ + ctx.JSON(code, CodeMessageDto{ Code: code, - Message: "Forbidden", + Message: "forbidden", }) } -func ResponseUserInfo(ctx *gin.Context, userInfo *user.User, userChats []chat.ChatC) error { +func UserResponse(ctx *gin.Context, user *model.User, userChats []model.Chat) error { // Marshal all of the chats into json using by ChatAsJson function - marshaledChatsJson := []chat.ChatC{} + marshaledChatsJson := []model.Chat{} for _, v := range userChats { - chatJson, err := ChatAsJSON(v, userInfo.StaticID) + chatJson, err := ChatAsJSON(v, user.UserID) if err != nil { return err } - marshaledChatsJson = append(marshaledChatsJson, chatJson.(chat.ChatC)) + marshaledChatsJson = append(marshaledChatsJson, chatJson.(model.Chat)) } // Response JSON - ctx.JSON(http.StatusOK, UserInfoDto{ - Message: "Success", + ctx.JSON(http.StatusOK, UserDto{ + Message: "user found", Code: 200, - UserInfo: userInfo, + User: user, UserChats: marshaledChatsJson, }) diff --git a/app/router/auth_routes.go b/app/router/auth_routes.go new file mode 100644 index 0000000..9ad460a --- /dev/null +++ b/app/router/auth_routes.go @@ -0,0 +1,23 @@ +package router + +import ( + "context" + + "github.com/gin-gonic/gin" + "github.com/kavkaco/Kavka-Core/app/controller" + auth "github.com/kavkaco/Kavka-Core/internal/service/auth" + chat "github.com/kavkaco/Kavka-Core/internal/service/chat" + "github.com/kavkaco/Kavka-Core/pkg/email" + "go.uber.org/zap" +) + +func NewAuthRouter(ctx context.Context, logger *zap.Logger, router *gin.RouterGroup, authService auth.AuthService, chatService chat.ChatService, emailService email.EmailOtp) { + ctrl := controller.NewAuthController(ctx, logger, authService, chatService, emailService) + + router.POST("/login", ctrl.HandleLogin) + router.POST("/register", ctrl.HandleRegister) + router.POST("/refresh_token", ctrl.HandleRefreshToken) + router.POST("/authenticate", ctrl.HandleAuthenticate) + router.GET("/verify_email/:token", ctrl.HandleVerifyEmail) + router.POST("/change_password", ctrl.HandleChangePassword) +} diff --git a/app/router/user_routes.go b/app/router/user_routes.go deleted file mode 100644 index 8ef71c3..0000000 --- a/app/router/user_routes.go +++ /dev/null @@ -1,26 +0,0 @@ -package router - -import ( - "github.com/gin-gonic/gin" - "github.com/kavkaco/Kavka-Core/app/controller" - "github.com/kavkaco/Kavka-Core/internal/service" - "go.uber.org/zap" -) - -type UserRouter struct { - userService service.UserService - chatService service.ChatService - ctrl *controller.UserController - router *gin.RouterGroup -} - -func NewUserRouter(logger *zap.Logger, router *gin.RouterGroup, userService service.UserService, chatService service.ChatService) *UserRouter { - ctrl := controller.NewUserController(logger, userService, chatService) - - router.POST("/login", ctrl.HandleLogin) - router.POST("/verify_otp", ctrl.HandleVerifyOTP) - router.POST("/refresh_token", ctrl.HandleRefreshToken) - router.POST("/authenticate", ctrl.HandleAuthenticate) - - return &UserRouter{userService, chatService, ctrl, router} -} diff --git a/app/router/ws_routes.go b/app/router/ws_routes.go index c20c5ce..2803a7e 100644 --- a/app/router/ws_routes.go +++ b/app/router/ws_routes.go @@ -1,41 +1,38 @@ package router import ( + "context" + "github.com/gin-gonic/gin" "github.com/kavkaco/Kavka-Core/app/presenters" + "github.com/kavkaco/Kavka-Core/internal/model" "github.com/kavkaco/Kavka-Core/socket" "github.com/kavkaco/Kavka-Core/socket/handlers" - "go.mongodb.org/mongo-driver/bson/primitive" "go.uber.org/zap" ) -func WebsocketRoute(logger *zap.Logger, websocketAdapter socket.SocketAdapter, handlerServices handlers.HandlerServices) func(ctx *gin.Context) { +func WebsocketRoute(ctx context.Context, logger *zap.Logger, websocketAdapter socket.SocketAdapter, handlerServices handlers.HandlerServices) func(ctx *gin.Context) { return func(ctx *gin.Context) { // Get UserStaticID form AuthenticatedMiddleware and cast to primitive.ObjectId! - userStaticIDAny, getOk := ctx.Get("user_static_id") + userIDAny, getOk := ctx.Get("user_static_id") + if getOk { - userStaticIDStr, castOk := userStaticIDAny.(string) + userID, castOk := userIDAny.(model.UserID) if !castOk { logger.Error("Unable to cast any to string") ctx.Next() return } - userStaticID, err := primitive.ObjectIDFromHex(userStaticIDStr) - if err != nil { - logger.Error("Unable to cast string to ObjectId") - ctx.Next() - } - // Call handle from WebsocketAdapter and pass the conn to the handler - err = websocketAdapter.Handle(ctx, func(conn interface{}) { - handlerErr := handlers.NewSocketHandler(logger, websocketAdapter, conn, &handlerServices, userStaticID) + err := websocketAdapter.Handle(ctx, func(conn interface{}) { + handlerErr := handlers.NewSocketHandler(ctx, logger, websocketAdapter, conn, &handlerServices, userID) if handlerErr != nil { - logger.Error("Unable to create SocketHandler instance: " + err.Error()) + logger.Error("Unable to create socket handler instance") } }) if err != nil { - presenters.ResponseInternalServerError(ctx) + presenters.InternalServerErrorResponse(ctx) } } else { logger.Error("Unable to read user_static_id from gin.Context") diff --git a/app/validator/auth.go b/app/validator/auth.go new file mode 100644 index 0000000..0f519fd --- /dev/null +++ b/app/validator/auth.go @@ -0,0 +1,19 @@ +package dto + +type AuthLoginRequest struct { + Email string `json:"email" binding:"required"` + Password string `json:"password" binding:"required"` +} + +type AuthRegisterRequest struct { + Name string `json:"name" binding:"required"` + LastName string `json:"lastName" binding:"required"` + Username string `json:"username" binding:"required"` + Email string `json:"email" binding:"required"` + Password string `json:"password" binding:"required"` +} + +type ChangePasswordRequest struct { + OldPassword string `json:"oldPassword" binding:"required"` + NewPassword string `json:"newPassword" binding:"required"` +} diff --git a/app/validator/validate.go b/app/validator/validate.go new file mode 100644 index 0000000..3678bef --- /dev/null +++ b/app/validator/validate.go @@ -0,0 +1,46 @@ +package dto + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" + "github.com/kavkaco/Kavka-Core/app/presenters" +) + +var validate = validator.New(validator.WithRequiredStructEnabled()) + +func ValidateBody[Dto interface{}](ctx *gin.Context) *Dto { + var details []presenters.ErrorDetail + + json := new(Dto) + + if err := ctx.ShouldBindJSON(&json); err != nil { + presenters.BadRequestResponse(ctx) //nolint + return nil + } + + if errs := validate.Struct(json); errs != nil { + for _, err := range errs.(validator.ValidationErrors) { //nolint + var ed presenters.ErrorDetail + + ed.FailedField = err.Field() + ed.Tag = err.Tag() + ed.Value = err.Value() + ed.Error = true + + details = append(details, ed) + } + } + + if len(details) > 0 { + ctx.JSON(http.StatusBadRequest, presenters.CodeMessageErrorDto{ + Code: http.StatusBadRequest, + Errors: details, + }) + + return nil + } + + return json +} diff --git a/cmd/server/server.go b/cmd/server/server.go index 1fa091c..e1f9a70 100644 --- a/cmd/server/server.go +++ b/cmd/server/server.go @@ -1,74 +1,106 @@ package main +import ( + "context" + + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/kavkaco/Kavka-Core/app/middleware" + "github.com/kavkaco/Kavka-Core/app/router" + "github.com/kavkaco/Kavka-Core/config" + "github.com/kavkaco/Kavka-Core/database" + "github.com/kavkaco/Kavka-Core/internal/repository" + "github.com/kavkaco/Kavka-Core/internal/service/auth" + "github.com/kavkaco/Kavka-Core/internal/service/chat" + "github.com/kavkaco/Kavka-Core/internal/service/message" + user "github.com/kavkaco/Kavka-Core/internal/service/user" + "github.com/kavkaco/Kavka-Core/logs" + "github.com/kavkaco/Kavka-Core/pkg/auth_manager" + "github.com/kavkaco/Kavka-Core/pkg/email" + "github.com/kavkaco/Kavka-Core/socket/adapters" + "github.com/kavkaco/Kavka-Core/socket/handlers" + "github.com/kavkaco/Kavka-Core/utils/hash" +) + func main() { - // // Init Zap Logger - // logger := logs.InitZapLogger() - - // // Define paths - // TemplatesPath := config.ProjectRootPath + "/app/views/mail/" - - // // Load Configs - // configs := config.Read() - - // // Init MongoDB - // mongoDB, mongoErr := database.GetMongoDBInstance( - // database.NewMongoDBConnectionString( - // configs.Mongo.Host, - // configs.Mongo.Port, - // configs.Mongo.Username, - // configs.Mongo.Password, - // ), - // configs.Mongo.DBName, - // ) - // if mongoErr != nil { - // panic(mongoErr) - // } - - // // Init RedisDB - // redisClient := database.GetRedisDBInstance(configs.Redis) - - // // Init WebServer - // ginEngine := gin.New() - // api := ginEngine.Group("/api/v1") - - // // Cors - // api.Use(cors.New(cors.Config{ - // AllowOrigins: []string{configs.App.Server.CORS.AllowOrigins}, - // AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Refresh", "Authorization"}, - // ExposeHeaders: []string{"Refresh", "Authorization"}, - // AllowCredentials: true, - // })) - - // // Initializing various services and repositories used in the application - // session := session.NewSession(logger, redisClient, configs.App.Auth) - // smsService := sms_service.NewSmsService(logger, &configs.SMS, TemplatesPath) - - // userRepo := userRepository.NewRepository(logger, mongoDB) - // userService := service.NewUserService(logger, userRepo, session, smsService) - - // chatRepo := chatRepository.NewRepository(logger, mongoDB) - // chatService := service.NewChatService(logger, chatRepo, userRepo) - - // messageRepo := messageRepository.NewRepository(logger, mongoDB) - // messageService := service.NewMessageService(logger, messageRepo, chatRepo) - - // // Init routes - // router.NewUserRouter(logger, api.Group("/users"), userService, chatService) - - // // Init websocket server - // websocketAdapter := adapters.NewWebsocketAdapter(logger) - - // handlerServices := handlers.HandlerServices{ - // UserService: userService, - // ChatService: chatService, - // MsgService: messageService, - // } - - // api.GET("/ws", middleware.AuthenticatedMiddleware(userService), router.WebsocketRoute(logger, websocketAdapter, handlerServices)) - - // // Everything almost done! - // err := ginEngine.Run(configs.App.HTTP.Address) - // if err != nil { - // panic(err) - // } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // Init Zap Logger + logger := logs.InitZapLogger() + + // Define paths + TemplatesPath := config.ProjectRootPath + "/app/views/mail/" + + // Load Configs + configs := config.Read() + + // Init MongoDB + mongoDB, mongoErr := database.GetMongoDBInstance( + database.NewMongoDBConnectionString( + configs.Mongo.Host, + configs.Mongo.Port, + configs.Mongo.Username, + configs.Mongo.Password, + ), + configs.Mongo.DBName, + ) + if mongoErr != nil { + panic(mongoErr) + } + + // Init RedisDB + redisClient := database.GetRedisDBInstance(configs.Redis) + + // Init WebServer + ginEngine := gin.New() + api := ginEngine.Group("/api/v1") + + // Cors + api.Use(cors.New(cors.Config{ + AllowOrigins: []string{configs.App.Server.CORS.AllowOrigins}, + AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Refresh", "Authorization"}, + ExposeHeaders: []string{"Refresh", "Authorization"}, + AllowCredentials: true, + })) + + authManager := auth_manager.NewAuthManager(redisClient, auth_manager.AuthManagerOpts{ + PrivateKey: configs.App.Auth.SECRET, + }) + + hashManager := hash.NewHashManager(hash.DefaultHashParams) + + emailService := email.NewEmailService(logger, &configs.Email, TemplatesPath) + + userRepo := repository.NewUserRepository(mongoDB) + userService := user.NewUserService(userRepo) + + authRepo := repository.NewAuthRepository(mongoDB) + authService := auth.NewAuthService(authRepo, userRepo, authManager, hashManager) + + chatRepo := repository.NewChatRepository(mongoDB) + chatService := chat.NewChatService(chatRepo, userRepo) + + messageRepo := repository.NewMessageRepository(mongoDB) + messageService := message.NewMessageService(messageRepo, chatRepo) + + // Init routes + router.NewAuthRouter(ctx, logger, api.Group("/auth"), authService, chatService, *emailService) + + // Init websocket server + websocketAdapter := adapters.NewWebsocketAdapter(logger) + + handlerServices := handlers.HandlerServices{ + UserService: userService, + ChatService: chatService, + MessageService: messageService, + } + + api.GET("/ws", middleware.AuthenticatedMiddleware(ctx, authService), router.WebsocketRoute(ctx, logger, websocketAdapter, handlerServices)) + + // Everything almost done! + err := ginEngine.Run(configs.App.HTTP.Address) + if err != nil { + panic(err) + } } diff --git a/config/config_test.go b/config/config_test.go index eda7ee0..5565cb6 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -3,7 +3,7 @@ package config import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConfigsDirPath(t *testing.T) { @@ -14,7 +14,7 @@ func TestConfigsDirPath(t *testing.T) { func TestRead(t *testing.T) { configs := Read() - assert.NotEmpty(t, configs) + require.NotEmpty(t, configs) t.Log(configs) } diff --git a/docker-compose.yml b/docker-compose.yml index 456ddbc..0feaecf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -43,13 +43,9 @@ services: image: "golang:latest" ports: - "8000:8000" - integration_test: - container_name: "kavka_integration_test" - build: - context: ./ - dockerfile: integration.Dockerfile - + networks: default: + external: true driver: "host" name: kavka_default_network diff --git a/go.mod b/go.mod index 4b7d455..6594f82 100644 --- a/go.mod +++ b/go.mod @@ -3,15 +3,16 @@ module github.com/kavkaco/Kavka-Core go 1.21 require ( + github.com/bozaro/golorem v0.0.0-20170501165920-50e5b610280b github.com/gin-gonic/gin v1.9.1 + github.com/go-playground/validator/v10 v10.20.0 github.com/golang-jwt/jwt/v4 v4.4.2 - github.com/google/uuid v1.6.0 github.com/minio/minio-go/v7 v7.0.69 github.com/ory/dockertest/v3 v3.10.0 - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.9.0 go.mongodb.org/mongo-driver v1.12.1 go.uber.org/zap v1.27.0 - gopkg.in/go-playground/assert.v1 v1.2.1 + golang.org/x/crypto v0.23.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -20,11 +21,11 @@ require ( github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect - github.com/bozaro/golorem v0.0.0-20170501165920-50e5b610280b // indirect - github.com/bytedance/sonic v1.10.0 // indirect + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect - github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect - github.com/chenzhuoyu/iasm v0.9.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect github.com/containerd/continuity v0.4.3 // indirect github.com/docker/cli v26.1.3+incompatible // indirect github.com/docker/docker v26.1.3+incompatible // indirect @@ -35,16 +36,15 @@ require ( github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/cpuid/v2 v2.2.6 // indirect - github.com/kr/pretty v0.3.0 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/leodido/go-urn v1.4.0 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/minio/md5-simd v1.1.2 // indirect github.com/minio/sha256-simd v1.0.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -55,24 +55,20 @@ require ( github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0 // indirect github.com/opencontainers/runc v1.1.12 // indirect - github.com/pelletier/go-toml/v2 v2.1.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.1 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/rogpeppe/go-internal v1.8.0 // indirect github.com/rs/xid v1.5.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/ugorji/go/codec v1.2.11 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/arch v0.5.0 // indirect - golang.org/x/crypto v0.23.0 // indirect + golang.org/x/arch v0.7.0 // indirect golang.org/x/net v0.25.0 // indirect - google.golang.org/protobuf v1.31.0 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + google.golang.org/protobuf v1.34.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/loremipsum.v1 v1.1.2 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) @@ -80,7 +76,7 @@ require ( github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/go-playground/validator v9.31.0+incompatible + github.com/gin-contrib/cors v1.7.2 github.com/go-redis/redis/v8 v8.11.5 github.com/golang/snappy v0.0.1 // indirect github.com/gorilla/websocket v1.5.0 @@ -91,7 +87,6 @@ require ( github.com/xdg-go/scram v1.1.2 // indirect github.com/xdg-go/stringprep v1.0.4 // indirect github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect - go.uber.org/mock v0.4.0 golang.org/x/sync v0.7.0 // indirect golang.org/x/sys v0.20.0 // indirect golang.org/x/text v0.15.0 // indirect diff --git a/go.sum b/go.sum index cccc7c7..01e6bba 100644 --- a/go.sum +++ b/go.sum @@ -8,23 +8,20 @@ github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEV github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= github.com/bozaro/golorem v0.0.0-20170501165920-50e5b610280b h1:D3YtkBLwtjFPegR4lwiwoCiV+f7bOq/MDh6Xi+nEq3Q= github.com/bozaro/golorem v0.0.0-20170501165920-50e5b610280b/go.mod h1:gqvWc1EBvN2S3BBwczsP6n4MFQzpHRffNXxK2pebPPA= -github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= -github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= -github.com/bytedance/sonic v1.10.0 h1:qtNZduETEIWJVIyDl01BeNxur2rW9OwTQ/yBqFRkKEk= -github.com/bytedance/sonic v1.10.0/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= -github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= -github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= -github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= -github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo= -github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= github.com/containerd/continuity v0.4.3 h1:6HVkalIp+2u1ZLH1J/pYX2oBVXlJZvh1X1A7bEZ9Su8= github.com/containerd/continuity v0.4.3/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -44,10 +41,10 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= -github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw= +github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= @@ -58,10 +55,6 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator v9.31.0+incompatible h1:UA72EPEogEnq76ehGdEDp4Mit+3FDh548oRqwVgNsHA= -github.com/go-playground/validator v9.31.0+incompatible/go.mod h1:yrEkQXlcI+PugkyDjY2bRrL/UBU4f3rvrgkN3V8JEig= -github.com/go-playground/validator/v10 v10.15.3 h1:S+sSpunYjNPDuXkWbK+x+bA7iXiW296KG4dL3X7xUZo= -github.com/go-playground/validator/v10 v10.15.3/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= @@ -74,11 +67,9 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs= github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -97,25 +88,19 @@ github.com/klauspost/compress v1.17.6 h1:60eq2E/jlfwQXtvZEeBUYADs+BwKBWURIY+Gj2e github.com/klauspost/compress v1.17.6/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= -github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= -github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2 h1:hRGSmZu7j271trc9sneMrpOW7GN5ngLm8YUZIPzf394= github.com/lib/pq v0.0.0-20180327071824-d34b9ff171c2/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= github.com/minio/minio-go/v7 v7.0.69 h1:l8AnsQFyY1xiwa/DaQskY4NXSLA2yrGsW5iD9nRPVS0= @@ -149,14 +134,12 @@ github.com/opencontainers/runc v1.1.12 h1:BOIssBaW1La0/qbNZHXOOa71dZfZEQOzW7dqQf github.com/opencontainers/runc v1.1.12/go.mod h1:S+lQwSfncpBha7XTy/5lBwWgm5+y5Ma/O44Ekby9FK8= github.com/ory/dockertest/v3 v3.10.0 h1:4K3z2VMe8Woe++invjaTB7VRyQXQy5UY+loujO4aNE4= github.com/ory/dockertest/v3 v3.10.0/go.mod h1:nr57ZbRWMqfsdGdFNLHz5jjNdDb7VVFnzAeW1n5N1Lg= -github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= -github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg= +github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= @@ -166,18 +149,19 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= -github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= -github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= @@ -200,15 +184,13 @@ go.mongodb.org/mongo-driver v1.12.1 h1:nLkghSU8fQNaK7oUmDhQFsnrtcoNy7Z6LVFKsEecq go.mongodb.org/mongo-driver v1.12.1/go.mod h1:/rGBTebI3XYboVmgz+Wv3Bcbl3aD0QF9zl6kDDw18rQ= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= -go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y= -golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc= +golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -267,20 +249,13 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.34.0 h1:Qo/qEd2RZPCf2nKuorzksSknv0d3ERwp1vFG38gSmH4= +google.golang.org/protobuf v1.34.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM= -gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/loremipsum.v1 v1.1.2 h1:12APklfJKuGszqZsrArW5QoQh03/W+qyCCjvnDuS6Tw= -gopkg.in/loremipsum.v1 v1.1.2/go.mod h1:TuRvzFuzuejXj+odBU6Tubp/EPUyGb9wmSvHenyP2Ts= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= diff --git a/integration.Dockerfile b/integration.Dockerfile deleted file mode 100644 index c8e2f2e..0000000 --- a/integration.Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM golang:1.22-alpine - -WORKDIR /server - -COPY . . - -RUN chmod +x ./scripts/integration_test.sh - -CMD ["./scripts/integration_test.sh"] diff --git a/internal/model/auth_model.go b/internal/model/auth_model.go index eb7920b..1f02bd9 100644 --- a/internal/model/auth_model.go +++ b/internal/model/auth_model.go @@ -1,17 +1,13 @@ package model -import ( - "time" -) - type Auth struct { - UserID UserID `bson:"user_id" json:"user_id"` - PasswordHash string `bson:"password_hash"` - FailedLoginAttempts int `bson:"failed_login_attempts" json:"failed_login_attempts"` - AccountLockedUntil *time.Duration `bson:"account_locked_until" json:"accountLockedUntil"` - EmailVerified bool `bson:"email_verified" json:"emailVerified"` + UserID UserID `bson:"user_id" json:"user_id"` + PasswordHash string `bson:"password_hash"` + FailedLoginAttempts int `bson:"failed_login_attempts" json:"failed_login_attempts"` + AccountLockedUntil int64 `bson:"account_locked_until" json:"accountLockedUntil"` + EmailVerified bool `bson:"email_verified" json:"emailVerified"` } func NewAuth(userID UserID, passwordHash string) *Auth { - return &Auth{UserID: userID, PasswordHash: passwordHash, FailedLoginAttempts: 0, AccountLockedUntil: nil, EmailVerified: false} + return &Auth{UserID: userID, PasswordHash: passwordHash, FailedLoginAttempts: 0, AccountLockedUntil: 0, EmailVerified: false} } diff --git a/internal/repository/auth_repository.go b/internal/repository/auth_repository.go index 3a92813..cdb7792 100644 --- a/internal/repository/auth_repository.go +++ b/internal/repository/auth_repository.go @@ -3,6 +3,8 @@ package repository import ( "context" "errors" + "fmt" + "time" "github.com/kavkaco/Kavka-Core/database" "github.com/kavkaco/Kavka-Core/internal/model" @@ -18,6 +20,9 @@ type AuthRepository interface { ChangePassword(ctx context.Context, userID model.UserID, passwordHash string) error VerifyEmail(ctx context.Context, userID model.UserID) error IncrementFailedLoginAttempts(ctx context.Context, userID model.UserID) error + ClearFailedLoginAttempts(ctx context.Context, userID model.UserID) error + LockAccount(ctx context.Context, userID model.UserID, lockDuration time.Duration) error + UnlockAccount(ctx context.Context, userID model.UserID) error } type authRepository struct { @@ -40,6 +45,47 @@ func (a *authRepository) IncrementFailedLoginAttempts(ctx context.Context, userI return nil } +func (a *authRepository) ClearFailedLoginAttempts(ctx context.Context, userID model.UserID) error { + fmt.Println("fuck you mother fucker") + + filter := bson.M{"user_id": userID} + update := bson.M{"$set": bson.M{"failed_login_attempts": 0}} + + _, err := a.authCollection.UpdateOne(ctx, filter, update) + if err != nil { + return err + } + + return nil +} + +func (a *authRepository) LockAccount(ctx context.Context, userID model.UserID, lockDuration time.Duration) error { + now := time.Now() + now = now.Add(lockDuration) + + filter := bson.M{"user_id": userID} + update := bson.M{"$set": bson.M{"account_locked_until": now.Unix()}} + + _, err := a.authCollection.UpdateOne(ctx, filter, update) + if err != nil { + return err + } + + return nil +} + +func (a *authRepository) UnlockAccount(ctx context.Context, userID model.UserID) error { + filter := bson.M{"user_id": userID} + update := bson.M{"$set": bson.M{"account_locked_until": 0}} + + _, err := a.authCollection.UpdateOne(ctx, filter, update) + if err != nil { + return err + } + + return nil +} + func (a *authRepository) VerifyEmail(ctx context.Context, userID model.UserID) error { filter := bson.M{"user_id": userID} update := bson.M{"$set": bson.M{"email_verified": true}} diff --git a/internal/service/auth/auth_errors.go b/internal/service/auth/auth_errors.go index cd20a61..979e935 100644 --- a/internal/service/auth/auth_errors.go +++ b/internal/service/auth/auth_errors.go @@ -5,19 +5,21 @@ import "errors" var ( ErrInvalidValidation = errors.New("failed to validate arguments") - ErrInvalidPassword = errors.New("invalid password") - ErrInvalidOtpCode = errors.New("invalid otp code") - ErrUserNotFound = errors.New("user not found") - ErrInvalidEmailOrPassword = errors.New("invalid email or password") - ErrAccessDenied = errors.New("access denied") - ErrEmailNotVerified = errors.New("email not verified") - ErrAccountLocked = errors.New("account locked") - ErrVerifyEmail = errors.New("failed verify email") - ErrGenerateToken = errors.New("failed to generate token") - ErrHashingPassword = errors.New("failed to hash password") - ErrCreateAuthStore = errors.New("failed to to create auth store") - ErrCreateUser = errors.New("failed to to create user") - ErrCreateEmailToken = errors.New("failed to create email token") - ErrDestroyToken = errors.New("failed to destroy token") - ErrChangePassword = errors.New("failed to change password") + ErrInvalidPassword = errors.New("invalid password") + ErrInvalidOtpCode = errors.New("invalid otp code") + ErrUserNotFound = errors.New("user not found") + ErrInvalidEmailOrPassword = errors.New("invalid email or password") + ErrAccessDenied = errors.New("access denied") + ErrEmailNotVerified = errors.New("email not verified") + ErrAccountLocked = errors.New("account locked") + ErrVerifyEmail = errors.New("failed verify email") + ErrGenerateToken = errors.New("failed to generate token") + ErrHashingPassword = errors.New("failed to hash password") + ErrCreateAuthStore = errors.New("failed to to create auth store") + ErrCreateUser = errors.New("failed to to create user") + ErrCreateEmailToken = errors.New("failed to create email token") + ErrDestroyToken = errors.New("failed to destroy token") + ErrChangePassword = errors.New("failed to change password") + ErrClearFailedLoginAttempts = errors.New("failed to clear failed login attempts") + ErrUnlockAccount = errors.New("failed to unlock account") ) diff --git a/internal/service/auth/auth_service.go b/internal/service/auth/auth_service.go index 992d8e2..f9fd2dc 100644 --- a/internal/service/auth/auth_service.go +++ b/internal/service/auth/auth_service.go @@ -2,6 +2,7 @@ package auth import ( "context" + "errors" "fmt" "strings" "time" @@ -13,19 +14,22 @@ import ( "github.com/kavkaco/Kavka-Core/utils/hash" ) -const ResetPasswordTokenExpr = time.Minute * 10 -const VerifyEmailTokenExpr = time.Minute * 5 -const MaximumFailedLoginAttempts = 5 -const AccessTokenExpr = time.Hour * 24 * 2 // 2 days -const RefreshTokenExpr = time.Hour * 24 * 14 // 2 weeks +const ( + ResetPasswordTokenExpr = time.Minute * 10 // 10 minutes + VerifyEmailTokenExpr = time.Minute * 5 // 5 minutes + AccessTokenExpr = time.Hour * 24 * 2 // 2 days + RefreshTokenExpr = time.Hour * 24 * 14 // 2 weeks + LockAccountDuration = time.Second * 5 + MaximumFailedLoginAttempts = 5 +) type AuthService interface { Login(ctx context.Context, email string, password string) (_ *model.User, act string, rft string, _ error) Register(ctx context.Context, name string, lastName string, username string, email string, password string) (user *model.User, verifyEmailToken string, err error) - VerifyEmail(ctx context.Context, email string) error - SendResetPasswordVerification(ctx context.Context, email string) (token string, timeout time.Duration, err error) + VerifyEmail(ctx context.Context, verifyEmailToken string) error + SendResetPasswordVerification(ctx context.Context, email string) (token string, timeout time.Duration, _ error) SubmitResetPassword(ctx context.Context, token string, newPassword string) error - ChangePassword(ctx context.Context, userID model.UserID, oldPassword string, newPassword string) error + ChangePassword(ctx context.Context, accessToken string, oldPassword string, newPassword string) error Authenticate(ctx context.Context, accessToken string) (*model.User, error) RefreshToken(ctx context.Context, refreshToken string, accessToken string) (string, error) } @@ -51,7 +55,9 @@ func (a *AuthManager) Register(ctx context.Context, name string, lastName string userModel := model.NewUser(name, lastName, email, username) savedUser, err := a.userRepo.Create(ctx, userModel) - if err != nil { + if errors.Is(err, repository.ErrEmailAlreadyTaken) { + return nil, "", repository.ErrEmailAlreadyTaken + } else if err != nil { return nil, "", ErrCreateUser } @@ -117,6 +123,8 @@ func (a *AuthManager) VerifyEmail(ctx context.Context, verifyEmailToken string) return ErrVerifyEmail } + a.authManager.Destroy(ctx, verifyEmailToken) + return nil } @@ -140,8 +148,35 @@ func (a *AuthManager) Login(ctx context.Context, email string, password string) return nil, "", "", ErrEmailNotVerified } - if auth.FailedLoginAttempts >= MaximumFailedLoginAttempts { - return nil, "", "", fmt.Errorf("%w until: %v", ErrAccountLocked, auth.AccountLockedUntil.String()) + // Check the expiration of account locked time + if auth.AccountLockedUntil != 0 { + now := time.Now() + lockTime := time.Unix(auth.AccountLockedUntil, 0) + + // End of account lock! + if now.After(lockTime) { + err := a.authRepo.UnlockAccount(ctx, auth.UserID) + if err != nil { + return nil, "", "", ErrUnlockAccount + } + + err = a.authRepo.ClearFailedLoginAttempts(ctx, auth.UserID) + if err != nil { + return nil, "", "", ErrClearFailedLoginAttempts + } + + auth.AccountLockedUntil = 0 + } + } + + // Account is still locked + if auth.AccountLockedUntil != 0 { + lockTime := time.Unix(auth.AccountLockedUntil, 0) + return nil, "", "", fmt.Errorf("%w until %v", ErrAccountLocked, lockTime) + } + + if auth.FailedLoginAttempts+1 == MaximumFailedLoginAttempts { + a.authRepo.LockAccount(ctx, auth.UserID, LockAccountDuration) } validPassword := a.hashManager.CheckPasswordHash(password, auth.PasswordHash) @@ -166,18 +201,23 @@ func (a *AuthManager) Login(ctx context.Context, email string, password string) return nil, "", "", ErrGenerateToken } + err = a.authRepo.ClearFailedLoginAttempts(ctx, auth.UserID) + if err != nil { + return nil, "", "", ErrClearFailedLoginAttempts + } + return user, accessToken, refreshToken, nil } -func (a *AuthManager) ChangePassword(ctx context.Context, email string, oldPassword string, newPassword string) error { - err := a.validator.Struct(ChangePasswordValidation{email, oldPassword, newPassword}) +func (a *AuthManager) ChangePassword(ctx context.Context, accessToken string, oldPassword string, newPassword string) error { + err := a.validator.Struct(ChangePasswordValidation{accessToken, oldPassword, newPassword}) if err != nil { return fmt.Errorf("%w: %v", ErrInvalidValidation, err) } - user, err := a.userRepo.FindByEmail(ctx, email) + user, err := a.Authenticate(ctx, accessToken) if err != nil { - return ErrUserNotFound + return err } auth, err := a.authRepo.GetUserAuth(ctx, user.UserID) @@ -210,12 +250,17 @@ func (a *AuthManager) RefreshToken(ctx context.Context, refreshToken string, acc return "", fmt.Errorf("%w: %v", ErrInvalidValidation, err) } - // Let's check that refresh token not be invalid or expired + // Let's check that tokens not be invalid or expired rftClaims, err := a.authManager.DecodeToken(ctx, refreshToken, auth_manager.RefreshToken) if err != nil { return "", ErrAccessDenied } + _, err = a.authManager.DecodeToken(ctx, accessToken, auth_manager.AccessToken) + if err != nil { + return "", ErrAccessDenied + } + // Find auth with user_id _, err = a.authRepo.GetUserAuth(ctx, rftClaims.UserID) if err != nil { @@ -259,7 +304,7 @@ func (a *AuthManager) SendResetPasswordVerification(ctx context.Context, email s } if auth.FailedLoginAttempts >= MaximumFailedLoginAttempts { - return "", 0, fmt.Errorf("%w until: %v", ErrAccountLocked, auth.AccountLockedUntil.String()) + return "", 0, fmt.Errorf("%w until: %v", ErrAccountLocked, auth.AccountLockedUntil) } resetPasswordToken, err := a.authManager.GenerateToken(ctx, auth_manager.ResetPassword, auth_manager.NewTokenClaims(auth.UserID, auth_manager.ResetPassword), ResetPasswordTokenExpr) diff --git a/internal/service/auth/auth_validations.go b/internal/service/auth/auth_validations.go index a043655..f21c4f3 100644 --- a/internal/service/auth/auth_validations.go +++ b/internal/service/auth/auth_validations.go @@ -22,7 +22,7 @@ type LoginValidation struct { } type ChangePasswordValidation struct { - Email string `validate:"required"` + AccessToken string `validate:"required"` OldPassword string `validate:"required"` NewPassword string `validate:"required"` } diff --git a/internal/service/user/user_service.go b/internal/service/user/user_service.go index 8f4da72..c3d182f 100644 --- a/internal/service/user/user_service.go +++ b/internal/service/user/user_service.go @@ -15,7 +15,7 @@ type UserManager struct { userRepo repository.UserRepository } -func NewMessageService(userRepo repository.UserRepository) UserService { +func NewUserService(userRepo repository.UserRepository) UserService { return &UserManager{userRepo} } diff --git a/pkg/auth_manager/auth_manager.go b/pkg/auth_manager/auth_manager.go index 4b5ac2e..d734a08 100644 --- a/pkg/auth_manager/auth_manager.go +++ b/pkg/auth_manager/auth_manager.go @@ -40,9 +40,7 @@ type AuthManager interface { } type AuthManagerOpts struct { - RefreshTokenExpiration time.Duration - AccessTokenExpiration time.Duration - PrivateKey string + PrivateKey string } // Used as jwt claims diff --git a/pkg/email/email.go b/pkg/email/email.go index 129e244..bb4401a 100644 --- a/pkg/email/email.go +++ b/pkg/email/email.go @@ -1,11 +1,7 @@ package email import ( - "bytes" "fmt" - "os" - "strings" - "text/template" "github.com/kavkaco/Kavka-Core/config" "go.uber.org/zap" @@ -14,41 +10,25 @@ import ( const TEMPLATE_FORMAT = "txt" type EmailOtp struct { - logger *zap.Logger - config *config.Email - templatesPath string + Logger *zap.Logger + Config *config.Email + TemplatesPath string } func NewEmailService(logger *zap.Logger, configs *config.Email, templatesPath string) *EmailOtp { return &EmailOtp{logger, configs, templatesPath} } -func (s *EmailOtp) SendEmail(body string, receivers []string) error { +func (s *EmailOtp) SendEmail(template string, receivers []string, args interface{}) error { if config.CurrentEnv == config.Development { fmt.Println("------ Email Sent ------") - fmt.Printf("%s\n", strings.TrimSpace(body)) + fmt.Println(args) fmt.Println("-----------------------") } return nil } -// Parses and returns the template. func (s *EmailOtp) Template(name string, args interface{}) (string, error) { - filename := fmt.Sprintf("%s/%s.%s", s.templatesPath, name, TEMPLATE_FORMAT) - - fileData, readErr := os.ReadFile(filename) - if readErr != nil { - return "", readErr - } - - renderedFile := new(bytes.Buffer) - - t := template.Must(template.New(name).Parse(string(fileData))) - err := t.Execute(renderedFile, args) - if err != nil { - return "", err - } - - return renderedFile.String(), nil + panic("not implemented") } diff --git a/pkg/email/email_test.go b/pkg/email/email_test.go index ce26fff..8774a6e 100644 --- a/pkg/email/email_test.go +++ b/pkg/email/email_test.go @@ -1,34 +1 @@ package email - -import ( - "os" - "testing" - - "github.com/kavkaco/Kavka-Core/config" - "github.com/stretchr/testify/assert" - "go.uber.org/zap" -) - -func TestSendEmail(t *testing.T) { - logger, _ := zap.NewDevelopment() - defer logger.Sync() // nolint - - // Get wd - wd, _ := os.Getwd() - templatesPath := wd + "/../../app/views/email/" - - // Load configs - config := config.Read() - - receivers := []string{"+989368392346"} - - emailService := NewEmailService(logger, &config.Email, templatesPath) - - template, templateErr := emailService.Template("code_sent", struct{ Code int }{ - Code: 123456, - }) - assert.NoError(t, templateErr) - - err := emailService.SendEmail(template, receivers) - assert.NoError(t, err) -} diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100755 index bc1d3ec..0000000 --- a/scripts/build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -go build -o ./build/server cmd/server/server.go diff --git a/scripts/docker_compose_build.sh b/scripts/docker_compose_build.sh deleted file mode 100755 index 1759af8..0000000 --- a/scripts/docker_compose_build.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -sudo docker-compose up -d --build \ No newline at end of file diff --git a/scripts/integration_test.sh b/scripts/integration_test.sh deleted file mode 100755 index 2f911f9..0000000 --- a/scripts/integration_test.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -go test -v ./tests/integration/* \ No newline at end of file diff --git a/scripts/run_devel.sh b/scripts/run_devel.sh deleted file mode 100755 index 21c0b5e..0000000 --- a/scripts/run_devel.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -go run cmd/server/server.go diff --git a/scripts/run_prod.sh b/scripts/run_prod.sh deleted file mode 100755 index 0dd23e7..0000000 --- a/scripts/run_prod.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash - -go mod tidy - -./scripts/build.sh -./build/server diff --git a/socket/handlers/chats_handler.go b/socket/handlers/chats_handler.go index 3c516c0..795b90d 100644 --- a/socket/handlers/chats_handler.go +++ b/socket/handlers/chats_handler.go @@ -23,39 +23,41 @@ func NewChatsHandler(args HandlerArgs) (ok bool, err error) { return false, nil } +// FIXME func CreateDirect(event string, args HandlerArgs) (bool, error) { - staticID := args.Message.Data["static_id"] + panic("not implemented") - staticID, err := primitive.ObjectIDFromHex(staticID.(string)) - if err != nil { - return false, err - } + // userID := args.Message.Data["user_id"] - _, err = args.Services.ChatService.CreateDirect(args.UserStaticID, staticID.(primitive.ObjectID)) - if err != nil { - return false, err - } + // userID, err := primitive.ObjectIDFromHex(userID.(string)) + // if err != nil { + // return false, err + // } - // FIXME - // err = args.conn.WriteJSON(presenters.ChatAsJSON(event, chat)) + // _, err = args.Services.ChatService.CreateDirect(args.Ctx, args.UserID, userID) + // if err != nil { + // return false, err + // } - return true, nil + // // err = args.conn.WriteJSON(presenters.ChatAsJSON(event, chat)) + + // return true, nil } func GetChat(event string, args HandlerArgs) (bool, error) { - staticID := args.Message.Data["static_id"] + chatID := args.Message.Data["static_id"] - staticID, err := primitive.ObjectIDFromHex(staticID.(string)) + chatID, err := primitive.ObjectIDFromHex(chatID.(string)) if err != nil { return false, err } - foundChat, err := args.Services.ChatService.GetChat(staticID.(primitive.ObjectID)) + foundChat, err := args.Services.ChatService.GetChat(args.Ctx, chatID.(primitive.ObjectID)) if err != nil { return false, err } - chatJson, err := presenters.ChatAsJSON(*foundChat, args.UserStaticID) + chatJson, err := presenters.ChatAsJSON(*foundChat, args.UserID) if err != nil { return false, err } @@ -78,7 +80,7 @@ func CreateGroup(event string, args HandlerArgs) (bool, error) { description := args.Message.Data["description"] if title != nil && username != nil && description != nil { - _, err := args.Services.ChatService.CreateGroup(args.UserStaticID, title.(string), username.(string), description.(string)) + _, err := args.Services.ChatService.CreateGroup(args.Ctx, args.UserID, title.(string), username.(string), description.(string)) if err != nil { return false, err } @@ -98,7 +100,7 @@ func CreateChannel(event string, args HandlerArgs) (bool, error) { description := args.Message.Data["description"] if title != nil && username != nil && description != nil { - _, err := args.Services.ChatService.CreateChannel(args.UserStaticID, title.(string), username.(string), description.(string)) + _, err := args.Services.ChatService.CreateChannel(args.Ctx, args.UserID, title.(string), username.(string), description.(string)) if err != nil { return false, err } diff --git a/socket/handlers/handler.go b/socket/handlers/handler.go index 4705f3e..9d33d02 100644 --- a/socket/handlers/handler.go +++ b/socket/handlers/handler.go @@ -1,11 +1,13 @@ package handlers import ( - "github.com/kavkaco/Kavka-Core/internal/model/chat" - "github.com/kavkaco/Kavka-Core/internal/model/message" - "github.com/kavkaco/Kavka-Core/internal/model/user" + "context" + + "github.com/kavkaco/Kavka-Core/internal/model" + chat "github.com/kavkaco/Kavka-Core/internal/service/chat" + message "github.com/kavkaco/Kavka-Core/internal/service/message" + user "github.com/kavkaco/Kavka-Core/internal/service/user" "github.com/kavkaco/Kavka-Core/socket" - "go.mongodb.org/mongo-driver/bson/primitive" "go.uber.org/zap" ) @@ -15,30 +17,32 @@ var HandlersList = []func(args HandlerArgs) (ok bool, err error){ } type HandlerServices struct { - UserService user.Service - ChatService chat.Service - MsgService message.Service + UserService user.UserService + ChatService chat.ChatService + MessageService message.MessageService } type HandlerArgs struct { - Logger *zap.Logger - Adapter socket.SocketAdapter - UserStaticID primitive.ObjectID - Message socket.IncomingSocketMessage - Services *HandlerServices - Conn interface{} + Ctx context.Context + Logger *zap.Logger + Adapter socket.SocketAdapter + UserID model.UserID + Message socket.IncomingSocketMessage + Services *HandlerServices + Conn interface{} } -func NewSocketHandler(logger *zap.Logger, adapter socket.SocketAdapter, conn interface{}, services *HandlerServices, userStaticID primitive.ObjectID) error { +func NewSocketHandler(ctx context.Context, logger *zap.Logger, adapter socket.SocketAdapter, conn interface{}, services *HandlerServices, userID model.UserID) error { err := adapter.HandleMessages(conn, func(msg socket.IncomingSocketMessage) { // Define HandlerArgs handlerArgs := HandlerArgs{ - Conn: conn, - Logger: logger, - Adapter: adapter, - Message: msg, - Services: services, - UserStaticID: userStaticID, + Ctx: ctx, + Conn: conn, + Logger: logger, + Adapter: adapter, + Message: msg, + Services: services, + UserID: userID, } // Add Handlers Of HandlersList diff --git a/socket/handlers/messages_handler.go b/socket/handlers/messages_handler.go index 0ec1493..3e4b549 100644 --- a/socket/handlers/messages_handler.go +++ b/socket/handlers/messages_handler.go @@ -1,6 +1,7 @@ package handlers import ( + "github.com/kavkaco/Kavka-Core/internal/model" "go.mongodb.org/mongo-driver/bson/primitive" ) @@ -26,7 +27,7 @@ func InsertTextMessage(_ string, args HandlerArgs) (bool, error) { return false, err } - _, err = args.Services.MsgService.InsertTextMessage(chatID.(primitive.ObjectID), args.UserStaticID, messageContent.(string)) + _, err = args.Services.MessageService.InsertTextMessage(args.Ctx, chatID.(primitive.ObjectID), args.UserID, messageContent.(string)) if err != nil { return false, err } @@ -48,7 +49,7 @@ func DeleteMessage(_ string, args HandlerArgs) (bool, error) { return false, err } - err = args.Services.MsgService.DeleteMessage(chatID.(primitive.ObjectID), messageID.(primitive.ObjectID)) + err = args.Services.MessageService.DeleteMessage(args.Ctx, chatID.(model.ChatID), args.UserID, messageID.(model.MessageID)) if err != nil { return false, err } diff --git a/tests/integration/repository/user_repository_test.go b/tests/integration/repository/user_repository_test.go index 3d7ffa4..f72d18e 100644 --- a/tests/integration/repository/user_repository_test.go +++ b/tests/integration/repository/user_repository_test.go @@ -27,7 +27,7 @@ func (s *UserTestSuite) SetupSuite() { func (s *UserTestSuite) TestA_Create() { ctx := context.TODO() - var chatsListIDs = []model.ChatID{ + chatsListIDs := []model.ChatID{ primitive.NewObjectID(), primitive.NewObjectID(), primitive.NewObjectID(), diff --git a/tests/integration/service/auth_service_test.go b/tests/integration/service/auth_service_test.go index 430daad..9b0f52e 100644 --- a/tests/integration/service/auth_service_test.go +++ b/tests/integration/service/auth_service_test.go @@ -3,7 +3,6 @@ package service import ( "context" "testing" - "time" lorem "github.com/bozaro/golorem" "github.com/kavkaco/Kavka-Core/internal/repository" @@ -32,9 +31,7 @@ func (s *AuthTestSuite) SetupSuite() { authRepo := repository.NewAuthRepository(db) userRepo := repository.NewUserRepository(db) authManager := auth_manager.NewAuthManager(redisClient, auth_manager.AuthManagerOpts{ - RefreshTokenExpiration: time.Second * 10, - AccessTokenExpiration: time.Second * 3, - PrivateKey: "private-key", + PrivateKey: "private-key", }) hashManager := hash.NewHashManager(hash.DefaultHashParams) s.service = service.NewAuthService(authRepo, userRepo, authManager, hashManager) @@ -90,7 +87,7 @@ func (s *AuthTestSuite) TestD_ChangePassword() { newPassword := "password-changed" - err := s.service.ChangePassword(ctx, s.email, s.password, newPassword) + err := s.service.ChangePassword(ctx, s.accessToken, s.password, newPassword) require.NoError(s.T(), err) // Login again with new password to be sure that's changed! diff --git a/utils/bearer/bearer.go b/utils/bearer/bearer.go deleted file mode 100644 index 7d9a15e..0000000 --- a/utils/bearer/bearer.go +++ /dev/null @@ -1,50 +0,0 @@ -package bearer - -import ( - "strings" - - "github.com/gin-gonic/gin" - "github.com/kavkaco/Kavka-Core/app/presenters" -) - -func extractTokenFromHeader(authHeader string) string { - token := strings.Split(authHeader, "Bearer ") - return token[1] -} - -func AccessToken(ctx *gin.Context) (string, bool) { - bearerHeader := ctx.GetHeader("Authorization") - - if len(bearerHeader) == 0 { - err := presenters.ResponseBadRequest(ctx) - if err != nil { - return "", false - } - return "", false - } - - accessToken := extractTokenFromHeader(bearerHeader) - if len(accessToken) == 0 { - err := presenters.ResponseBadRequest(ctx) - if err != nil { - return "", false - } - return "", false - } - - return accessToken, true -} - -func RefreshToken(ctx *gin.Context) (string, bool) { - refreshToken := ctx.GetHeader("refresh") - - if len(refreshToken) == 0 { - err := presenters.ResponseBadRequest(ctx) - if err != nil { - return "", false - } - return "", false - } - - return refreshToken, true -} diff --git a/utils/bearer/bearer_test.go b/utils/bearer/bearer_test.go deleted file mode 100644 index 0ca2deb..0000000 --- a/utils/bearer/bearer_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package bearer - -import ( - "testing" - - "gopkg.in/go-playground/assert.v1" -) - -func TestExtractFromHeader(t *testing.T) { - sampleToken := "Hello_World" - authorizationToken := "Bearer " + sampleToken - - token := extractTokenFromHeader(authorizationToken) - - assert.Equal(t, token, sampleToken) -} diff --git a/utils/hash/hash.go b/utils/hash/hash.go index c83e671..c756109 100644 --- a/utils/hash/hash.go +++ b/utils/hash/hash.go @@ -17,19 +17,19 @@ var ( ) type HashParams struct { - memory uint32 - iterations uint32 - parallelism uint8 - saltLength uint32 - keyLength uint32 + Memory uint32 + Iterations uint32 + Parallelism uint8 + SaltLength uint32 + KeyLength uint32 } var DefaultHashParams = &HashParams{ - memory: 64 * 1024, - iterations: 10, - parallelism: 2, - saltLength: 16, - keyLength: 32, + Memory: 8 * 1024, + Iterations: 3, + Parallelism: 4, + SaltLength: 16, + KeyLength: 32, } type HashManager struct { @@ -41,17 +41,17 @@ func NewHashManager(params *HashParams) *HashManager { } func (h *HashManager) HashPassword(password string) (hashedPassword string, err error) { - salt, err := h.generateRandomBytes(h.params.saltLength) + salt, err := h.generateRandomBytes(h.params.SaltLength) if err != nil { return "", err } - hash := argon2.IDKey([]byte(password), salt, h.params.iterations, h.params.memory, h.params.parallelism, h.params.keyLength) + hash := argon2.IDKey([]byte(password), salt, h.params.Iterations, h.params.Memory, h.params.Parallelism, h.params.KeyLength) b64Salt := base64.RawStdEncoding.EncodeToString(salt) b64Hash := base64.RawStdEncoding.EncodeToString(hash) - hashedPassword = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, h.params.memory, h.params.iterations, h.params.parallelism, b64Salt, b64Hash) + hashedPassword = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, h.params.Memory, h.params.Iterations, h.params.Parallelism, b64Salt, b64Hash) return hashedPassword, nil } @@ -64,7 +64,7 @@ func (h *HashManager) CheckPasswordHash(password, hashedPassword string) bool { return false } - otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength) + otherHash := argon2.IDKey([]byte(password), salt, p.Iterations, p.Memory, p.Parallelism, p.KeyLength) return subtle.ConstantTimeCompare(hash, otherHash) == 1 } @@ -95,7 +95,7 @@ func (h *HashManager) decodeHash(encodedHash string) (params *HashParams, salt, } p := &HashParams{} - _, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism) + _, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Iterations, &p.Parallelism) if err != nil { return nil, nil, nil, err } @@ -104,13 +104,13 @@ func (h *HashManager) decodeHash(encodedHash string) (params *HashParams, salt, if err != nil { return nil, nil, nil, err } - p.saltLength = uint32(len(salt)) + p.SaltLength = uint32(len(salt)) hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[5]) if err != nil { return nil, nil, nil, err } - p.keyLength = uint32(len(hash)) + p.KeyLength = uint32(len(hash)) return p, salt, hash, nil } diff --git a/utils/hash/hash_test.go b/utils/hash/hash_test.go index 8fb788f..f502540 100644 --- a/utils/hash/hash_test.go +++ b/utils/hash/hash_test.go @@ -3,7 +3,6 @@ package hash import ( "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -19,8 +18,8 @@ func TestHashManager(t *testing.T) { t.Log(hashedPassword) valid := hashManager.CheckPasswordHash(plainPassword, hashedPassword) - assert.True(t, valid) + require.True(t, valid) valid = hashManager.CheckPasswordHash("invalid-plain-password", hashedPassword) - assert.False(t, valid) + require.False(t, valid) } diff --git a/utils/random/random_test.go b/utils/random/random_test.go index c220f87..70b884a 100644 --- a/utils/random/random_test.go +++ b/utils/random/random_test.go @@ -3,12 +3,12 @@ package random import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGenerateOTP(t *testing.T) { otp := GenerateOTP() - assert.NotZero(t, otp) + require.NotZero(t, otp) t.Log(otp) } diff --git a/utils/structs/set_value_by_tag_test.go b/utils/structs/set_value_by_tag_test.go index 850fe43..14f3391 100644 --- a/utils/structs/set_value_by_tag_test.go +++ b/utils/structs/set_value_by_tag_test.go @@ -3,7 +3,7 @@ package structs import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type Sample struct { @@ -18,8 +18,8 @@ func Test_SetFieldByBSON(t *testing.T) { for _, sample := range samples { err := SetFieldByBSON(sample, "age", newAge) - assert.NoError(t, err) + require.NoError(t, err) } - assert.Equal(t, samples[0].Age, newAge) + require.Equal(t, samples[0].Age, newAge) }