from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.security import Authenticated, Everyone

from app.models.user import UserModel


class CustomAuthenticationPolicy(AuthTktAuthenticationPolicy):
    def authenticated_userid(self, request):
        user = request.user

        if user:
            userid = user.id
            return userid

    def effective_principals(self, request):
        principals = [Everyone]
        user = request.user

        if user:
            principal = Authenticated
            userid = user.id
            group = user.group
            group_ = '{}:{}'.format('group', group)
            ACE = (principal, userid, group_)
            [principals.append(ep) for ep in ACE]

        return principals


def get_user(request):
    userid = request.unauthenticated_userid

    if userid:
        query = request.dbsession.query(UserModel)
        user = query.filter_by(id=userid).first()
        return user
