genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
hs_monolith/runtime/auth.go

90 lines
2.2 KiB
Go
Raw Normal View History

2017-05-03 08:02:29 +02:00
// Package with supporting functionality to run the microservice
package runtime
import (
"fmt"
"net/http"
"time"
"github.com/genofire/hs_master-kss-monolith/lib/log"
"sync"
)
2017-05-03 08:02:29 +02:00
// URL to the microservice which manages permissions
var PermissionURL string
2017-05-03 08:02:29 +02:00
// Type of permission
type Permission int
2017-05-03 08:02:29 +02:00
// Some permissions (the real permissions need to come from the permission microservice)
const (
2017-05-03 08:02:29 +02:00
// permission to add goods to the stock
// e.g. if a good is received and now available to sell
PermissionCreateGood = 1
2017-05-03 08:02:29 +02:00
// permission to delete goods from the stock
2017-05-15 10:22:24 +02:00
// e.g. if a good becomes fouled and has to be removed
PermissionDeleteGood = 2
)
2017-05-03 08:02:29 +02:00
// Struct that holds the information for a permission cache
type permissionMicroServiceCache struct {
LastCheck time.Time
session string
permissions map[Permission]boolMicroServiceCache
sync.Mutex
}
2017-05-03 08:02:29 +02:00
// Function to check, if a user has a permission
func (c *permissionMicroServiceCache) HasPermission(p Permission) (bool, error) {
c.LastCheck = time.Now()
c.Lock()
defer c.Unlock()
if cache, ok := c.permissions[p]; ok {
before := time.Now().Add(-CacheConfig.After.Duration)
if before.After(cache.LastCheck) {
return cache.Value, nil
}
}
url := fmt.Sprintf(PermissionURL, c.session, p)
log.Log.WithField("url", url).Info("has permission?")
2017-04-29 18:26:36 +02:00
res, err := http.Get(url)
2017-04-29 18:26:36 +02:00
value := false
if err == nil {
value = (res.StatusCode == http.StatusOK)
}
c.permissions[p] = boolMicroServiceCache{
LastCheck: c.LastCheck,
2017-04-29 18:26:36 +02:00
Value: value,
}
return c.permissions[p].Value, err
}
2017-05-03 08:02:29 +02:00
// Cache for permissions
var permissionCache map[string]*permissionMicroServiceCache
var permissionMutex sync.Mutex
2017-05-15 10:22:24 +02:00
2017-05-03 08:02:29 +02:00
// Function to initialize the permission cache
func init() {
permissionCache = make(map[string]*permissionMicroServiceCache)
}
2017-05-03 08:02:29 +02:00
// Function to check, if the current session has any permissions
2017-04-28 12:05:58 +02:00
func HasPermission(session string, p int) (bool, error) {
permissionMutex.Lock()
defer permissionMutex.Unlock()
_, ok := permissionCache[session]
if !ok {
permissionCache[session] = &permissionMicroServiceCache{
LastCheck: time.Now(),
session: session,
permissions: make(map[Permission]boolMicroServiceCache),
}
}
2017-04-28 12:05:58 +02:00
return permissionCache[session].HasPermission(Permission(p))
}