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

77 lines
1.9 KiB
Go
Raw Normal View History

package runtime
import (
"fmt"
"net/http"
"time"
"github.com/genofire/hs_master-kss-monolith/lib/log"
)
2017-04-28 10:27:36 +02:00
// url to the microservice which manage the permissions
var PermissionURL string
2017-04-28 10:27:36 +02:00
// type of permission
type Permission int
2017-04-28 10:27:36 +02:00
// some permission (see Permission)
const (
2017-04-28 10:27:36 +02:00
// has the user the permission to create need goods of a product
// e.g. if a good received and now availablity to sell
PermissionCreateGood = 1
2017-04-28 10:27:36 +02:00
// has the user the permission to delete need goods of a product
// e.g. if a good become rancid and has to remove from stock
PermissionDeleteGood = 2
)
type permissionMicroServiceCache struct {
LastCheck time.Time
session string
permissions map[Permission]boolMicroServiceCache
}
func (c *permissionMicroServiceCache) HasPermission(p Permission) (bool, error) {
c.LastCheck = time.Now()
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
}
var permissionCache map[string]*permissionMicroServiceCache
func init() {
permissionCache = make(map[string]*permissionMicroServiceCache)
}
2017-04-28 10:27:36 +02:00
// check if the client with the session string has a permissions (see Permission)
2017-04-28 12:05:58 +02:00
func HasPermission(session string, p int) (bool, error) {
_, 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))
}