add base goffee

This commit is contained in:
JACS 2026-05-01 11:56:07 -05:00
parent c95e8a9245
commit ac2cfa9fe1
108 changed files with 64018 additions and 0 deletions

436
utils/authority.go Normal file
View file

@ -0,0 +1,436 @@
// Copyright (c) 2025 Zeni Kim <zenik@smarteching.com>
// Use of this source code is governed by MIT-style
// license that can be found in the LICENSE file.
package utils
import (
"errors"
"fmt"
"git.smarteching.com/goffee/core"
"git.smarteching.com/jacs/goffeetabler/models"
"gorm.io/gorm"
)
type Authority struct{}
var auth *Authority
var (
ErrPermissionInUse = errors.New("cannot delete assigned permission")
ErrPermissionNotFound = errors.New("permission not found")
ErrRoleInUse = errors.New("cannot delete assigned role")
ErrRoleNotFound = errors.New("role not found")
)
// Add a new role to the database
func (a *Authority) CreateRole(c *core.Context, r models.Role) error {
roleSlug := r.Slug
var dbRole models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&dbRole)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
// create
createRes := c.GetGorm().Create(&r)
if createRes.Error != nil {
return createRes.Error
}
return nil
}
return res.Error
}
return errors.New(fmt.Sprintf("role '%v' already exists", roleSlug))
}
// Add a new permission to the database
func (a *Authority) CreatePermission(c *core.Context, p models.Permission) error {
permSlug := p.Slug
var dbPerm models.Permission
res := c.GetGorm().Where("slug = ?", permSlug).First(&dbPerm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
// create
createRes := c.GetGorm().Create(&p)
if createRes.Error != nil {
return createRes.Error
}
return nil
}
return res.Error
}
return errors.New(fmt.Sprintf("permission '%v' already exists", permSlug))
}
// Assigns a group of permissions to a given role
func (a *Authority) AssignPermissionsToRole(c *core.Context, roleSlug string, permSlugs []string) error {
var role models.Role
rRes := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if rRes.Error != nil {
if errors.Is(rRes.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return rRes.Error
}
var perms []models.Permission
for _, permSlug := range permSlugs {
var perm models.Permission
pRes := c.GetGorm().Where("slug = ?", permSlug).First(&perm)
if pRes.Error != nil {
if errors.Is(pRes.Error, gorm.ErrRecordNotFound) {
return ErrPermissionNotFound
}
return pRes.Error
}
perms = append(perms, perm)
}
tx := c.GetGorm().Begin()
for _, perm := range perms {
var rolePerm models.RolePermission
res := c.GetGorm().Where("role_id = ?", role.ID).Where("permission_id =?", perm.ID).First(&rolePerm)
if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {
cRes := tx.Create(&models.RolePermission{RoleID: role.ID, PermissionID: perm.ID})
if cRes.Error != nil {
tx.Rollback()
return cRes.Error
}
}
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
tx.Rollback()
return res.Error
}
if rolePerm != (models.RolePermission{}) {
tx.Rollback()
return errors.New(fmt.Sprintf("permission '%v' is aleady assigned to the role '%v'", perm.Name, role.Name))
}
rolePerm = models.RolePermission{}
}
return tx.Commit().Error
}
// Assigns a role to a given user
func (a *Authority) AssignRoleToUser(c *core.Context, userID uint, roleSlug string) error {
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return res.Error
}
var userRole models.UserRole
res = c.GetGorm().Where("user_id = ?", userID).Where("role_id = ?", role.ID).First(&userRole)
if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {
c.GetGorm().Create(&models.UserRole{UserID: userID, RoleID: role.ID})
return nil
}
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
return res.Error
}
return errors.New(fmt.Sprintf("this role '%v' is aleady assigned to the user", roleSlug))
}
// Checks if a role is assigned to a user
func (a *Authority) CheckUserRole(c *core.Context, userID uint, roleSlug string) (bool, error) {
// find the role
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrRoleNotFound
}
return false, res.Error
}
// check if the role is a assigned
var userRole models.UserRole
res = c.GetGorm().Where("user_id = ?", userID).Where("role_id = ?", role.ID).First(&userRole)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
return false, res.Error
}
return true, nil
}
// Checks if a permission is assigned to a user
func (a *Authority) CheckUserPermission(c *core.Context, userID uint, permSlug string) (bool, error) {
// the user role
var userRoles []models.UserRole
res := c.GetGorm().Where("user_id = ?", userID).Find(&userRoles)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
return false, res.Error
}
//prepare an array of role ids
var roleIDs []interface{}
for _, r := range userRoles {
roleIDs = append(roleIDs, r.RoleID)
}
// find the permission
var perm models.Permission
res = c.GetGorm().Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrPermissionNotFound
}
return false, res.Error
}
// find the role permission
var rolePermission models.RolePermission
res = c.GetGorm().Where("role_id IN (?)", roleIDs).Where("permission_id = ?", perm.ID).First(&rolePermission)
if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, res.Error
}
return true, nil
}
// Checks if a permission is assigned to a role
func (a *Authority) CheckRolePermission(c *core.Context, roleSlug string, permSlug string) (bool, error) {
// find the role
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrRoleNotFound
}
return false, res.Error
}
// find the permission
var perm models.Permission
res = c.GetGorm().Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrPermissionNotFound
}
return false, res.Error
}
// find the rolePermission
var rolePermission models.RolePermission
res = c.GetGorm().Where("role_id = ?", role.ID).Where("permission_id = ?", perm.ID).First(&rolePermission)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
return false, res.Error
}
return true, nil
}
// Revokes a roles's permission
func (a *Authority) RevokeRolePermission(c *core.Context, roleSlug string, permSlug string) error {
// find the role
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return res.Error
}
// find the permission
var perm models.Permission
res = c.GetGorm().Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrPermissionNotFound
}
return res.Error
}
// revoke the permission
rRes := c.GetGorm().Where("role_id = ?", role.ID).Where("permission_id = ?", perm.ID).Delete(models.RolePermission{})
if rRes.Error != nil {
return rRes.Error
}
return nil
}
// Revokes a user's role
func (a *Authority) RevokeUserRole(c *core.Context, userID uint, roleSlug string) error {
// find the role
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return res.Error
}
// revoke the role
rRes := c.GetGorm().Where("user_id = ?", userID).Where("role_id = ?", role.ID).Delete(models.UserRole{})
if rRes.Error != nil {
return rRes.Error
}
return nil
}
// Revokes all user's role
func (a *Authority) RevokeAllUserRole(c *core.Context, userID uint) error {
// revoke the role
rRes := c.GetGorm().Where("user_id = ?", userID).Delete(models.UserRole{})
if rRes.Error != nil {
return rRes.Error
}
return nil
}
// Returns all stored roles
func (a *Authority) GetAllRoles(c *core.Context) ([]models.Role, error) {
var roles []models.Role
res := c.GetGorm().Find(&roles)
if res.Error != nil {
return nil, res.Error
}
return roles, nil
}
// Returns all user assigned roles
func (a *Authority) GetUserRoles(c *core.Context, userID uint) ([]models.Role, error) {
var userRoles []models.UserRole
res := c.GetGorm().Where("user_id = ?", userID).Find(&userRoles)
if res.Error != nil {
return nil, res.Error
}
var roleIDs []interface{}
for _, r := range userRoles {
roleIDs = append(roleIDs, r.RoleID)
}
var roles []models.Role
res = c.GetGorm().Where("id IN (?)", roleIDs).Find(&roles)
if res.Error != nil {
return nil, res.Error
}
return roles, nil
}
// Returns all role assigned permissions
func (a *Authority) GetRolePermissions(c *core.Context, roleSlug string) ([]models.Permission, error) {
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).Find(&role)
if res.Error != nil {
return nil, res.Error
}
var rolePerms []models.RolePermission
res = c.GetGorm().Where("role_id = ?", role.ID).Find(&rolePerms)
if res.Error != nil {
return nil, res.Error
}
var permIDs []interface{}
for _, rolePerm := range rolePerms {
permIDs = append(permIDs, rolePerm.PermissionID)
}
var perms []models.Permission
res = c.GetGorm().Where("id IN (?)", permIDs).Find(&perms)
if res.Error != nil {
return nil, res.Error
}
return perms, nil
}
// Returns all stored permissions
func (a *Authority) GetAllPermissions(c *core.Context) ([]models.Permission, error) {
var perms []models.Permission
res := c.GetGorm().Find(&perms)
if res.Error != nil {
return nil, res.Error
}
return perms, nil
}
// Deletes a given role even if it's has assigned permissions
func (a *Authority) DeleteRole(c *core.Context, roleSlug string) error {
// find the role
var role models.Role
res := c.GetGorm().Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
return res.Error
}
// check if the role is assigned to a user
var ca int64
res = c.GetGorm().Model(models.UserRole{}).Where("role_id = ?", role.ID).Count(&ca)
if res.Error != nil {
return res.Error
}
if ca != 0 {
// role is assigned
return ErrRoleInUse
}
tx := c.GetGorm().Begin()
// revoke the assignment of permissions before deleting the role
dRes := tx.Where("role_id = ?", role.ID).Delete(models.RolePermission{})
if dRes.Error != nil {
tx.Rollback()
return dRes.Error
}
// delete the role
dRes = c.GetGorm().Where("slug = ?", roleSlug).Delete(models.Role{})
if dRes.Error != nil {
tx.Rollback()
return dRes.Error
}
return tx.Commit().Error
}
// Deletes a given permission
func (a *Authority) DeletePermission(c *core.Context, permSlug string) error {
// find the permission
var perm models.Permission
res := c.GetGorm().Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
return res.Error
}
// check if the permission is assigned to a role
var rolePermission models.RolePermission
res = c.GetGorm().Where("permission_id = ?", perm.ID).First(&rolePermission)
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
return res.Error
}
if res.Error == nil {
return ErrPermissionInUse
}
// delete the permission
dRes := c.GetGorm().Where("slug = ?", permSlug).Delete(models.Permission{})
if dRes.Error != nil {
return dRes.Error
}
return nil
}

84
utils/helpers.go Normal file
View file

@ -0,0 +1,84 @@
// Copyright 2023 Harran Ali <harran.m@gmail.com>. All rights reserved.
// Copyright (c) 2024 Zeni Kim <zenik@smarteching.com>
// Use of this source code is governed by MIT-style
// license that can be found in the LICENSE file.
package utils
import (
"crypto/md5"
"fmt"
"log"
"time"
"git.smarteching.com/goffee/core"
"git.smarteching.com/jacs/goffeetabler/models"
)
func CreateSeedData() {
db := core.ResolveGorm()
var hashing = new(core.Hashing)
var role models.Role
// seed user
password := "goffee"
name := "admin"
fullname := "Goffee administrator"
email := "change@me.com"
passwordHashed, _ := hashing.HashPassword(password)
user := models.User{
Name: name,
Fullname: fullname,
Email: email,
Password: passwordHashed,
}
result := db.Create(&user)
if result.Error != nil {
log.Fatal("Can't create seed user in database")
}
// seed roles
roles := []models.Role{
{Name: "Administrator", Slug: "admin"},
{Name: "Authenticated", Slug: "authenticated"},
}
for _, role := range roles {
result = db.Create(&role)
if result.Error != nil {
log.Fatal("Can't create seed role in database")
}
}
// seed permission
permission := models.Permission{Name: "Users administration", Slug: "admin-users"}
result = db.Create(&permission)
if result.Error != nil {
log.Fatal("Can't create seed permission in database")
}
result = db.Where("slug = ?", "admin").First(&role)
if result.Error != nil {
log.Fatal("Can't find user admin in database")
}
result = db.Create(&models.RolePermission{RoleID: role.ID, PermissionID: permission.ID})
if result.Error != nil {
log.Fatal("Can't register permission role in database")
}
result = db.Create(&models.UserRole{UserID: user.ID, RoleID: role.ID})
if result.Error != nil {
log.Fatal("Can't assign role administrator to user in database")
}
}
// generate a hashed string to be used as key for caching auth jwt token
func CreateAuthTokenHashedCacheKey(userID uint, userAgent string) string {
cacheKey := fmt.Sprintf("userid:_%v_useragent:_%v_jwt_token", userID, userAgent)
hashedCacheKey := fmt.Sprintf("%v", fmt.Sprintf("%x", md5.Sum([]byte(cacheKey))))
return hashedCacheKey
}
func FormatUnix(value int64) string {
return time.Unix(value, 0).Format("2006-01-02 15:04:05")
}

170
utils/session.go Normal file
View file

@ -0,0 +1,170 @@
// Copyright (c) 2024 Zeni Kim <zenik@smarteching.com>
// Use of this source code is governed by MIT-style
// license that can be found in the LICENSE file.
package utils
import (
"errors"
"fmt"
"sync"
"time"
"encoding/json"
"git.smarteching.com/goffee/core"
"git.smarteching.com/jacs/goffeetabler/models"
"gorm.io/gorm"
)
type SessionUser struct {
mu sync.RWMutex
context *core.Context
userID uint
hashedSessionKey string
authenticated bool
sessionStart time.Time
values map[string]interface{}
}
// start the struct
func (s *SessionUser) Init(c *core.Context) bool {
// check session cookie
pass := true
token := ""
s.context = c
payload := make(map[string]interface{})
// get cookie
usercookie, err := c.GetCookie()
if err != nil {
}
token = usercookie.Token
if token == "" {
pass = false
} else {
payload, err = c.GetJWT().DecodeToken(token)
if err != nil {
pass = false
} else {
userID := uint(c.CastToInt(payload["userID"]))
userAgent := c.GetUserAgent()
// get data from redis
hashedCacheKey := CreateAuthTokenHashedCacheKey(userID, userAgent)
cachedToken, err := c.GetCache().Get(hashedCacheKey)
if err != nil {
pass = false
} else if cachedToken != token {
pass = false
} else {
var user models.User
res := c.GetGorm().Where("id = ?", userID).First(&user)
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
pass = false
}
// if have session start the struct
if pass {
userAgent := c.GetUserAgent()
sessionKey := fmt.Sprintf("sess_%v", userAgent)
s.hashedSessionKey = CreateAuthTokenHashedCacheKey(userID, sessionKey)
s.values = make(map[string]interface{})
s.authenticated = true
s.userID = userID
value, _ := c.GetCache().Get(s.hashedSessionKey)
if len(value) > 0 {
_ = json.Unmarshal([]byte(value), &s.values)
}
return true
} else {
s.hashedSessionKey = ""
s.authenticated = false
s.userID = 0
return false
}
}
}
}
return false
}
func (s *SessionUser) Set(key string, value interface{}) error {
s.mu.Lock()
s.values[key] = value
s.mu.Unlock()
return s.Save()
}
func (s *SessionUser) Get(key string) (interface{}, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
val, ok := s.values[key]
return val, ok
}
func (s *SessionUser) Delete(key string) interface{} {
s.mu.RLock()
v, ok := s.values[key]
s.mu.RUnlock()
if ok {
s.mu.Lock()
delete(s.values, key)
s.mu.Unlock()
}
s.Save()
return v
}
func (s *SessionUser) Flush() error {
s.mu.Lock()
s.context.GetCache().Delete(s.hashedSessionKey)
s.mu.Unlock()
return nil
}
func (s *SessionUser) Save() error {
var value string
s.mu.RLock()
if len(s.values) > 0 {
buf, err := json.Marshal(&s.values)
if err != nil {
s.mu.RUnlock()
return err
}
value = string(buf)
}
if len(value) > 0 {
s.context.GetCache().Set(s.hashedSessionKey, value)
} else {
s.context.GetCache().Delete(s.hashedSessionKey)
}
s.mu.RUnlock()
return nil
}
func (s *SessionUser) GetUserID() uint {
return s.userID
}