Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# GoAsali Framework

## About GoAsali
<a href="https://flutter.dev/">
<h1 align="center">
<img alt="Flutter" src="https://github.com/abolfazlalz/GoAsali/assets/73333017/45aebfce-cd3f-47df-a229-7fe4230ede86">
</h1>
</a>

GoAsali is a Web Application framework whose purpose is to create Web Applications with a specific structure.

Expand All @@ -12,4 +15,4 @@ Coming soon ... ⌛️🫠

Thank you for considering contributing to the GoAsali template.

You can by cloning the project and make a pull request to starting contributing.
You can by cloning the project and make a pull request to starting contributing.
44 changes: 25 additions & 19 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,42 +1,48 @@
module github.com/abolfazlalz/goasali

go 1.18
go 1.20

require (
github.com/caarlos0/env/v8 v8.0.0
github.com/gin-gonic/gin v1.7.7
github.com/go-playground/validator/v10 v10.13.0
github.com/gin-gonic/gin v1.9.0
github.com/go-playground/validator/v10 v10.11.2
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/joho/godotenv v1.5.1
github.com/nicksnyder/go-i18n/v2 v2.2.1
golang.org/x/crypto v0.8.0
golang.org/x/text v0.9.0
gorm.io/driver/mysql v1.5.0
gorm.io/driver/sqlite v1.5.0
gorm.io/gorm v1.25.0
github.com/redis/go-redis/v9 v9.0.5
golang.org/x/crypto v0.11.0
golang.org/x/text v0.11.0
gorm.io/driver/mysql v1.5.1
gorm.io/driver/sqlite v1.5.2
gorm.io/gorm v1.25.2
)

require (
github.com/bytedance/sonic v1.9.2 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
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-sql-driver/mysql v1.7.0 // indirect
github.com/golang-jwt/jwt/v5 v5.0.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.18 // indirect
github.com/mattn/go-sqlite3 v1.14.16 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-sqlite3 v1.14.17 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/redis/go-redis/v9 v9.0.4 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/sys v0.7.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
golang.org/x/arch v0.4.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/sys v0.10.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
120 changes: 58 additions & 62 deletions go.sum

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions http/users.http
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,21 @@ Content-Type: application/json
Accept-Language: fa

{
"username": "abolfazlalz1",
"username": "abolfazlalz",
"password": "helloworld"
}

### User info request
GET http://localhost:9000/auth
Content-Type: application/json
Accept-Language: fa
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFib2xmYXpsYWx6IiwiZXhwIjoxNjg2MTE5MzgwfQ.3UHg_e8BFcxfoW0CGWA7FCL6JIg_dQ98quXw8aF26xw

### List of users
GET http://localhost:9000/admin/users
Content-Type: application/json
Accept-Language: fa
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFib2xmYXpsYWx6IiwiZXhwIjoxNjg0ODQ3NTEwfQ.kR9NQiEukHUUgMtNrbblNQkWVpmqwX30r8R-7oexyrw
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFib2xmYXpsYWx6IiwiZXhwIjoxNjg0MTU0MTc0fQ.z4f8mWwZQ90_EsR28TXLFSix6dHh5lFe7QCiurPIyAE

### Refresh token
Expand All @@ -34,4 +41,4 @@ Accept-Language: fa

{
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFib2xmYXpsYWx6MSIsImV4cCI6MTY4NzA3NzI3MX0.ojQn8JhSNmpq4htOf9Bbc2Rg_ObxFldsvQYdKrj8OpE"
}
}
34 changes: 34 additions & 0 deletions internal/users/controllers/admin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package controllers

import (
"fmt"
"github.com/abolfazlalz/goasali/internal/users/db/models"
"github.com/abolfazlalz/goasali/internal/users/services"
"github.com/abolfazlalz/goasali/pkg/cache"
"github.com/abolfazlalz/goasali/pkg/http/controllers"
"github.com/gin-gonic/gin"
"github.com/nicksnyder/go-i18n/v2/i18n"
"gorm.io/gorm"
)

type AdminController struct {
*controllers.Controllers
service *services.AdminService
}

func NewAdmin(db *gorm.DB, bundle *i18n.Bundle, cache cache.Cache) *AdminController {
return &AdminController{
service: services.NewAdmin(db, cache),
Controllers: controllers.New(bundle, cache),
}
}

func (ctrl AdminController) List(c *gin.Context) {
users := &[]models.User{}
if err := ctrl.service.UsersList(users); err != nil {
ctrl.HandleHttp(c, ctrl.ErrorMessage(err.Error()))
}

fmt.Println(users)
c.JSON(200, users)
}
22 changes: 11 additions & 11 deletions internal/users/controllers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ type AuthController struct {
authService services.AuthServiceI
}

func NewAuthController(db *gorm.DB, bundle *i18n.Bundle, cache cache.Cache) IAuthController {
ctrl := controllers.NewController(bundle, cache)
func NewAuth(db *gorm.DB, bundle *i18n.Bundle, cache cache.Cache) IAuthController {
ctrl := controllers.New(bundle, cache)
return &AuthController{
Controllers: ctrl,
authService: services.NewAuthServiceLogs(services.NewAuthService(db, cache)),
Expand All @@ -47,15 +47,15 @@ func (ac *AuthController) Login(c *gin.Context) {
token, err := ac.authService.Login(user, body.Username, body.Password)
if err != nil {
if err == services.UserUnauthorizedError {
ac.HttpError.HandleHttp(c, ac.HttpCode(400), ac.I18nErrorMessageConfig(c, "authorization.unauthorized"))
ac.HttpError.HandleHttp(c, ac.HttpCode(400), ac.I18nErrorMessageConfig("authorization.unauthorized"))
return
}
ac.HttpError.HandleHttp(c, ac.HttpCode(500), ac.I18nErrorMessageConfig(c, "errors.internal_server"))
ac.HttpError.HandleHttp(c, ac.HttpCode(500), ac.I18nErrorMessageConfig("errors.internal_server"))
return
}

c.JSON(200, gin.H{
"user": user,
"service": user,
"access_token": token.AccessToken,
"refresh_token": token.RefreshToken,
"status": true,
Expand All @@ -71,7 +71,7 @@ func (ac *AuthController) CreateAccount(c *gin.Context) {
}

if body.Password != body.ConfirmPassword {
ac.HttpError.HandleHttp(c, ac.I18nErrorMessageConfig(c, "validation.password_same"))
ac.HttpError.HandleHttp(c, ac.I18nErrorMessageConfig("validation.password_same"))
return
}

Expand All @@ -85,13 +85,13 @@ func (ac *AuthController) CreateAccount(c *gin.Context) {
token, err := ac.authService.CreateAccount(&user)

if err != nil {
log.Printf("Error during create new user: %v", err)
ac.HttpError.HandleHttp(c, ac.HttpCode(500), ac.I18nErrorMessageConfig(c, "errors.internal_server"))
log.Printf("Error during create new service: %v", err)
ac.HttpError.HandleHttp(c, ac.HttpCode(500), ac.I18nErrorMessageConfig("errors.internal_server"))
return
}

c.JSON(201, gin.H{
"user": user,
"service": user,
"access_token": token.AccessToken,
"refresh_token": token.RefreshToken,
"status": true,
Expand All @@ -118,9 +118,9 @@ func (ac *AuthController) RefreshToken(c *gin.Context) {
}

func (ac *AuthController) Info(c *gin.Context) {
user, err := c.Get("user")
user, err := c.Get("service")
if !err {
ac.HttpError.HandleHttp(c, ac.HttpError.I18nErrorMessageConfig(c, "authorization.status_forbidden"), ac.HttpError.HttpCode(http.StatusForbidden))
ac.HttpError.HandleHttp(c, ac.HttpError.I18nErrorMessageConfig("authorization.status_forbidden"), ac.HttpError.HttpCode(http.StatusForbidden))
return
}
c.JSON(http.StatusOK, user)
Expand Down
2 changes: 1 addition & 1 deletion internal/users/controllers/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type LoginUser struct {
}

type RegisterUser struct {
Username string `binding:"required,unique=users"`
Username string `binding:"required,unique=service"`
Password string `binding:"required"`
ConfirmPassword string `binding:"required" json:"confirm_password"`
FirstName string `binding:"required" json:"first_name"`
Expand Down
18 changes: 6 additions & 12 deletions internal/users/db/models/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,14 @@ import (

type Role struct {
gorm.Model
Name string
RoleId uint
Role *Role `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
Name string
RoleId uint
Role *Role `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
Permissions []*Permission `gorm:"many2many:role_permissions;"`
}

type Permission struct {
gorm.Model
Name string `json:"name" gorm:"unique"`
}

type RolePermission struct {
gorm.Model
RoleId uint
PermissionId uint
Role Role
Permission Permission
Name string `json:"name" gorm:"unique"`
Roles []*Role `gorm:"many2many:role_permissions;"`
}
48 changes: 48 additions & 0 deletions internal/users/db/repository/roles.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package repository

import (
"errors"
"github.com/abolfazlalz/goasali/internal/users/db/models"
"github.com/abolfazlalz/goasali/pkg/cache"
"github.com/abolfazlalz/goasali/pkg/repositories"
"gorm.io/gorm"
)

var (
RoleNotFound = errors.New("role not found ")
)

type Role struct {
*repositories.Repository[models.Role]
}

func NewRoleRepository(db *gorm.DB, cache cache.Cache) *Role {
return &Role{
Repository: repositories.NewRepositoryInstance[models.Role](db, cache),
}
}

func (r *Role) AssignPermissions(roleId uint, permissions ...models.Permission) error {
var role *models.Role
r.Db.First(role, "id=?", roleId)
if role == nil {
return RoleNotFound
}
if err := r.Db.Where("id=?", roleId).Association("Permission").Append(permissions); err != nil {
return err
}
return nil
}

func (r *Role) CreatePermission(permission *models.Permission) error {
re := r.Db.Where("name=?", permission.Name).FirstOrCreate(permission)
return re.Error
}

func (r *Role) DeletePermissionById(id ...uint) error {
if len(id) < 1 {
return errors.New("one id for delete a permission required")
}
r.Db.Delete(id)
return nil
}
41 changes: 38 additions & 3 deletions internal/users/middlewares/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,50 @@ import (
"github.com/abolfazlalz/goasali/internal/users/db/models"
"github.com/abolfazlalz/goasali/internal/users/db/repository"
"github.com/abolfazlalz/goasali/internal/users/utils/tokens"
"github.com/abolfazlalz/goasali/pkg/cache"
"github.com/abolfazlalz/goasali/pkg/errors"
routes "github.com/abolfazlalz/goasali/pkg/http/routers"
"github.com/gin-gonic/gin"
"log"
"net/http"
"strings"
"time"
)

func IsAuthMiddlewareCache(c *gin.Context) {
context := routes.NewContext(c)
hErr := errors.NewByContext(c)

cacheMng := context.Cache

bearToken := c.GetHeader("Authorization")

token := strings.Split(bearToken, " ")[1]
key := fmt.Sprintf("jwt_key_%s", bearToken)

var user *models.User
if err := cacheMng.Get(key, user); err != nil {
panic(err)
}
if user == nil {
userJwt := tokens.NewUserJwt(token, context.DB, cacheMng)
if err := userJwt.User(user); err != nil {
panic(err)
}
if err := cacheMng.Set(cache.Item{Key: key, Value: user, TTL: 60 * time.Second}); err != nil {
panic(err)
}
}

if user != nil {
c.Set("service", &user)
c.Next()
return
}

hErr.HandleHttp(c, hErr.I18nErrorMessageConfig("authorization.access_denied"))
}

func IsAuthMiddleware(c *gin.Context) {
prefix := log.Prefix()

Expand Down Expand Up @@ -40,7 +76,7 @@ func IsAuthMiddleware(c *gin.Context) {
log.Printf("Error in check middleware auth: %v", err)
if verr, ok := err.(errors.I18nMessageError); ok {
errors.NewByContext(c).I18nErrorMessage(c, verr.I18nId)
httpErr.HandleHttp(c, httpErr.HttpCode(http.StatusUnauthorized), httpErr.I18nErrorMessageConfig(c, verr.I18nId))
httpErr.HandleHttp(c, httpErr.HttpCode(http.StatusUnauthorized), httpErr.I18nErrorMessageConfig(verr.I18nId))
return
}

Expand All @@ -55,7 +91,6 @@ func IsAuthMiddleware(c *gin.Context) {
return
}

c.Set("user", &user)

c.Set("service", &user)
c.Next()
}
Loading