Beispiel #1
0
    def get_permissions(request):
        if not asbool(settings.get("enable_user_authentication", False)):
            return []
        if not request.user:
            return []

        from gengine.app.model import DBSession, t_auth_tokens, t_auth_users, t_auth_roles, t_auth_roles_permissions, t_auth_users_roles
        from sqlalchemy.sql import select
        j = t_auth_users_roles.join(t_auth_roles).join(t_auth_roles_permissions)
        q = select([t_auth_roles_permissions.c.name],from_obj=j).where(t_auth_users_roles.c.auth_user_id==request.user.id)
        rows = DBSession.execute(q).fetchall()
        return [r["name"] for r in rows]
Beispiel #2
0
def admin_tenant(environ, start_response):
    from gengine.app.admin import adminapp

    def admin_app(environ, start_response):
        #return HTTPSProxied(DebuggedApplication(adminapp.wsgi_app, True))(environ, start_response)
        return HTTPSProxied(adminapp.wsgi_app)(environ, start_response)

    def request_auth(environ, start_response):
        resp = Response()
        resp.status_code = 401
        resp.www_authenticate = 'Basic realm="%s"' % (
            "Gamification Engine Admin", )
        return resp(environ, start_response)

    if not asbool(get_settings().get("enable_user_authentication", False)):
        return admin_app(environ, start_response)

    req = Request(environ)

    def _get_basicauth_credentials(request):
        authorization = request.headers.get("authorization", "")
        try:
            authmeth, auth = authorization.split(' ', 1)
        except ValueError:  # not enough values to unpack
            return None
        if authmeth.lower() == 'basic':
            try:
                auth = base64.b64decode(auth.strip()).decode("UTF-8")
            except binascii.Error:  # can't decode
                return None
            try:
                login, password = auth.split(':', 1)
            except ValueError:  # not enough values to unpack
                return None
            return {'login': login, 'password': password}
        return None

    user = None
    cred = _get_basicauth_credentials(req)
    token = req.cookies.get("token", None)
    if token:
        tokenObj = DBSession.query(AuthToken).filter(
            AuthToken.token == token).first()
        user = None
        if tokenObj and tokenObj.valid_until < datetime.datetime.utcnow():
            tokenObj.extend()
        if tokenObj:
            user = tokenObj.user

    if not user:
        if cred:
            user = DBSession.query(AuthUser).filter_by(
                email=cred["login"]).first()
        if not user or not user.verify_password(cred["password"]):
            return request_auth(environ, start_response)

    if user:
        j = t_auth_users_roles.join(t_auth_roles).join(
            t_auth_roles_permissions)
        q = select(
            [t_auth_roles_permissions.c.name],
            from_obj=j).where(t_auth_users_roles.c.auth_user_id == user.id)
        permissions = [r["name"] for r in DBSession.execute(q).fetchall()]
        if not perm_global_access_admin_ui in permissions:
            return request_auth(environ, start_response)
        else:
            token_s = user.get_or_create_token().token

            def start_response_with_headers(status, headers, exc_info=None):

                cookie = SimpleCookie()
                cookie['X-Auth-Token'] = token_s
                cookie['X-Auth-Token']['path'] = get_settings().get(
                    "urlprefix", "").rstrip("/") + "/"

                headers.append(
                    ('Set-Cookie', cookie['X-Auth-Token'].OutputString()), )

                return start_response(status, headers, exc_info)

            return admin_app(environ, start_response_with_headers)