Skip to content

Commit

Permalink
add dependency injection
Browse files Browse the repository at this point in the history
  • Loading branch information
GenesisBlock3301 committed Dec 12, 2023
1 parent 21a475b commit cd78302
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 26 deletions.
18 changes: 14 additions & 4 deletions backend/controllers/role_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,34 @@ import (
"net/http"
)

func CreateRoleController(ctx *gin.Context) {
type RoleController struct {
RoleService services.RoleService
}

func NewRoleController(RoleService services.RoleService) *RoleController {
return &RoleController{
RoleService: RoleService,
}
}

func (u *RoleController) CreateRoleController(ctx *gin.Context) {
var roleInput serializers.Role
if err := ctx.ShouldBindJSON(&roleInput); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
_, err := services.CreateRoleService(&roleInput)
_, err := u.RoleService.CreateRoleService(&roleInput)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
return
}
ctx.JSON(200, gin.H{"message": "Successfully role created!"})
}

func GetALLRoleController(ctx *gin.Context) {
func (u *RoleController) GetALLRoleController(ctx *gin.Context) {
limit := ctx.Query("limit")
offset := ctx.Query("offset")
roleCount, roles := services.GetAllRolesService(limit, offset)
roleCount, roles := u.RoleService.GetAllRolesService(limit, offset)
ctx.JSON(200, gin.H{
"totalRole": roleCount,
"roles": roles,
Expand Down
28 changes: 19 additions & 9 deletions backend/controllers/user_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ import (
"time"
)

type UserController struct {
UserService services.UserService
}

func NewUserController(service services.UserService) *UserController {
return &UserController{
UserService: service,
}
}

// CreateUserController UserRegistration controllers
// @Summary Register User.
// @Schemes http https
Expand All @@ -24,7 +34,7 @@ import (
// @Success 200 {string} successfully login
// @failure 400 {string} string "error"
// @Router /create [post]
func CreateUserController(ctx *gin.Context) {
func (u *UserController) CreateUserController(ctx *gin.Context) {
var userInput serializers.RegisterSerializer
// Validate UserInput
if err := ctx.ShouldBindJSON(&userInput); err != nil {
Expand All @@ -38,7 +48,7 @@ func CreateUserController(ctx *gin.Context) {
ctx.JSON(http.StatusBadRequest, gin.H{"errors": isErrors})
return
}
_, err = services.CreateUserService(userInput)
_, err = u.UserService.CreateUserService(userInput)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
return
Expand All @@ -57,13 +67,13 @@ func CreateUserController(ctx *gin.Context) {
// @Success 200 {string} successfully login.
// @failure 400 {string} string "error"
// @Router /login [post]
func LoginController(ctx *gin.Context) {
func (u *UserController) LoginController(ctx *gin.Context) {
var user serializers.User
if err := ctx.ShouldBindJSON(&user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
isValidCredential, userID, inActiveUser := services.VerifyCredentialService(user.Email, user.Password)
isValidCredential, userID, inActiveUser := u.UserService.VerifyCredentialService(user.Email, user.Password)
if inActiveUser {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Inactive user try to active your account first."})
return
Expand Down Expand Up @@ -92,7 +102,7 @@ func LoginController(ctx *gin.Context) {
// @Produce json
// @Success 200 {string} get user successfully.
// @Router / [get]
func GetCurrentUserController(ctx *gin.Context) {
func (u *UserController) GetCurrentUserController(ctx *gin.Context) {
userId, err := services.ExtractTokenID(ctx)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
Expand Down Expand Up @@ -121,11 +131,11 @@ func GetCurrentUserController(ctx *gin.Context) {
// @Produce json
// @Success 200 {string} successfully verify email.
// @Router /email-verify/ [get]
func VerifyEmailController(ctx *gin.Context) {
func (u *UserController) VerifyEmailController(ctx *gin.Context) {
token := ctx.Query("token")

// Extract email and verify
err := services.VerifyEmailService(token)
err := u.UserService.VerifyEmailService(token)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error"})
return
Expand All @@ -144,7 +154,7 @@ func VerifyEmailController(ctx *gin.Context) {
// @Produce json
// @Success 200 {string} successfully generate OTP
// @Router /generate-otp/ [get]
func GenerateOTP(ctx *gin.Context) {
func (u *UserController) GenerateOTP(ctx *gin.Context) {
var UserLogin serializers.LoginSerializer
// Validate UserInput
if err := ctx.ShouldBindJSON(&UserLogin); err != nil {
Expand Down Expand Up @@ -177,7 +187,7 @@ func GenerateOTP(ctx *gin.Context) {
// @Produce json
// @Success 200 {string} sent verify init.
// @Router /verify-otp/ [get]
func VerifyOTP(ctx *gin.Context) {
func (u *UserController) VerifyOTP(ctx *gin.Context) {
var otp serializers.VerifyOTPSerializer
// Validate OTP Input.
if err := ctx.ShouldBindJSON(&otp); err != nil {
Expand Down
7 changes: 5 additions & 2 deletions backend/routes/roles_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package routes

import (
"github.com/GenesisBlock3301/role_based_access_boilerplate_go/backend/controllers"
"github.com/GenesisBlock3301/role_based_access_boilerplate_go/backend/services"
"github.com/gin-gonic/gin"
)

func RoleRouter(roleRouter *gin.RouterGroup) {
roleRouter.POST("/create", controllers.CreateRoleController)
roleRouter.GET("/list", controllers.GetALLRoleController)
roleService := &services.RoleService{}
roleController := controllers.NewRoleController(*roleService)
roleRouter.POST("/create", roleController.CreateRoleController)
roleRouter.GET("/list", roleController.GetALLRoleController)
}
15 changes: 9 additions & 6 deletions backend/routes/user_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ package routes
import (
"github.com/GenesisBlock3301/role_based_access_boilerplate_go/backend/controllers"
"github.com/GenesisBlock3301/role_based_access_boilerplate_go/backend/middlewares"
"github.com/GenesisBlock3301/role_based_access_boilerplate_go/backend/services"
"github.com/gin-gonic/gin"
)

func UserRouter(userRouter *gin.RouterGroup) {
userRouter.GET("/", middlewares.JWTAuthMiddleware(), controllers.GetCurrentUserController)
userRouter.POST("/create/", controllers.CreateUserController)
userRouter.GET("/email-verify/", controllers.VerifyEmailController)
userRouter.POST("/login", controllers.LoginController)
userRouter.GET("/generate-otp/", controllers.GenerateOTP)
userRouter.POST("/verify-otp/", controllers.VerifyOTP)
userService := &services.UserService{}
userController := controllers.NewUserController(*userService)
userRouter.GET("/", middlewares.JWTAuthMiddleware(), userController.GetCurrentUserController)
userRouter.POST("/create/", userController.CreateUserController)
userRouter.GET("/email-verify/", userController.VerifyEmailController)
userRouter.POST("/login", userController.LoginController)
userRouter.GET("/generate-otp/", userController.GenerateOTP)
userRouter.POST("/verify-otp/", userController.VerifyOTP)
}
6 changes: 4 additions & 2 deletions backend/services/role_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ type IRoleService interface {
GetAllRolesService(limit string, offset string) (int64, []serializers.RoleResponse)
}

type RoleService struct{}

// CreateRoleService for creating Service
func CreateRoleService(role *serializers.Role) (bool, error) {
func (r *RoleService) CreateRoleService(role *serializers.Role) (bool, error) {
err := db.DB.Table(schemas.Roles).Where("role_name = ?", role.RoleName).First(&role).Error
if err == nil {
return false, errors.New("role already exits")
Expand All @@ -28,7 +30,7 @@ func CreateRoleService(role *serializers.Role) (bool, error) {
}

// GetAllRolesService GetAllRoles service
func GetAllRolesService(limit string, offset string) (int64, []serializers.RoleResponse) {
func (r *RoleService) GetAllRolesService(limit string, offset string) (int64, []serializers.RoleResponse) {
var count int64

if err := db.DB.Table("role_based_access.roles").Count(&count).Error; err != nil {
Expand Down
6 changes: 3 additions & 3 deletions backend/services/user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type IUserServiceInterface interface {

type UserService struct{}

func CreateUserService(user serializers.RegisterSerializer) (bool, error) {
func (u *UserService) CreateUserService(user serializers.RegisterSerializer) (bool, error) {
err := db.DB.Table(schemas.Users).Where("email = ?", user.Email).First(&user).Error
if err == nil {
return false, errors.New("user already exits")
Expand All @@ -33,7 +33,7 @@ func CreateUserService(user serializers.RegisterSerializer) (bool, error) {
return true, nil
}

func VerifyCredentialService(email string, password string) (bool, uint, bool) {
func (u *UserService) VerifyCredentialService(email string, password string) (bool, uint, bool) {
user, err := utils.FindByEmail(email)
if user.IsActive == 0 {
return false, 0, true
Expand All @@ -44,7 +44,7 @@ func VerifyCredentialService(email string, password string) (bool, uint, bool) {
return utils.ComparePassword([]byte(user.Password), []byte(password)), user.ID, false
}

func VerifyEmailService(token string) error {
func (u *UserService) VerifyEmailService(token string) error {
parseToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return []byte(configurations.EmailTokenSecret), nil
})
Expand Down

0 comments on commit cd78302

Please sign in to comment.