2022-09-28 09:01:17 +02:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/photoprism/photoprism/internal/acl"
|
|
|
|
"github.com/photoprism/photoprism/internal/entity"
|
|
|
|
"github.com/photoprism/photoprism/internal/event"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Auth checks if the user has permission to access the specified resource and returns the session if so.
|
|
|
|
func Auth(c *gin.Context, resource acl.Resource, grant acl.Permission) *entity.Session {
|
|
|
|
return AuthAny(c, resource, acl.Permissions{grant})
|
|
|
|
}
|
|
|
|
|
|
|
|
// AuthAny checks if at least one permission allows access and returns the session in this case.
|
2022-09-30 00:42:19 +02:00
|
|
|
func AuthAny(c *gin.Context, resource acl.Resource, grants acl.Permissions) (s *entity.Session) {
|
|
|
|
// Get client IP address and session ID, if any.
|
|
|
|
ip := ClientIP(c)
|
2022-09-28 09:01:17 +02:00
|
|
|
sessId := SessionID(c)
|
|
|
|
|
2022-09-30 00:42:19 +02:00
|
|
|
// Find client session.
|
|
|
|
if s = Session(sessId); s == nil {
|
|
|
|
event.AuditWarn([]string{ip, "unauthenticated", "%s %s as unknown user", "denied"}, grants.String(), string(resource))
|
2022-09-28 09:01:17 +02:00
|
|
|
return entity.SessionStatusUnauthorized()
|
2022-09-30 00:42:19 +02:00
|
|
|
} else {
|
|
|
|
s.SetClientIP(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check authorization.
|
|
|
|
if s.User() == nil {
|
|
|
|
event.AuditWarn([]string{ip, "session %s", "%s %s as unknown user", "denied"}, s.RefID, grants.String(), string(resource))
|
2022-09-28 09:01:17 +02:00
|
|
|
return entity.SessionStatusUnauthorized()
|
|
|
|
} else if acl.Resources.DenyAll(resource, s.User().AclRole(), grants) {
|
2022-09-30 00:42:19 +02:00
|
|
|
event.AuditErr([]string{ip, "session %s", "%s %s as %s", "denied"}, s.RefID, grants.String(), string(resource), s.User().AclRole().String())
|
2022-09-28 09:01:17 +02:00
|
|
|
return entity.SessionStatusForbidden()
|
|
|
|
} else {
|
2022-09-30 00:42:19 +02:00
|
|
|
event.AuditInfo([]string{ip, "session %s", "%s %s as %s", "granted"}, s.RefID, grants.String(), string(resource), s.User().AclRole().String())
|
2022-09-28 09:01:17 +02:00
|
|
|
return s
|
|
|
|
}
|
|
|
|
}
|