1
0
mirror of https://github.com/dkmstr/openuds.git synced 2025-01-10 01:17:59 +03:00

Removed "util" ticket and adapted several 1.8 db model stuff (UnsavedForeignKey)

This commit is contained in:
Adolfo Gómez García 2015-04-27 05:17:25 +02:00
parent f411eec5f4
commit f39d780a88
12 changed files with 86 additions and 120 deletions

View File

@ -33,11 +33,8 @@
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
from django.template import loader, Context
from uds.core.util import OsDetector
from uds.core.util.Ticket import Ticket
from uds.core.auths.auth import webPassword
from uds.core import Module
from uds.core.transports import protocols
@ -165,10 +162,7 @@ class Transport(Module):
'''
return '''
from __future__ import unicode_literals
# pylint: disable=import-error, no-name-in-module, too-many-format-args, undefined-variable, invalid-sequence-index
from PyQt4 import QtCore, QtGui
QtGui.QMessageBox.critical(parent, 'Not supported', 'The transport {transport.name} is not supported on your platform.', QtGui.QMessageBox.Ok)
'''.format(service=userService, transport=transport)

View File

@ -1,80 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Virtual Cable S.L.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of Virtual Cable S.L. nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
.. moduleauthor:: Adolfo Gómez, dkmaster at dkmon dot com
'''
from __future__ import unicode_literals
from uds.core.util.Cache import Cache
from uds.core.managers import cryptoManager
TICKET_OWNER = 'e6242ba4-62fa-11e4-b7ec-10feed05884b'
class Ticket(object):
'''
Manages tickets & ticketing save/loading
Right now, uses cache as backend
'''
def __init__(self, key=None, data=None):
self.uuidGenerator = lambda: (cryptoManager().uuid() + cryptoManager().uuid()).replace('-', '')
self.cache = Cache(TICKET_OWNER)
self.data = data
self.key = key
if key is not None:
self.load()
else:
self.key = self.uuidGenerator()
def save(self, data=None, validity=Cache.DEFAULT_VALIDITY):
'''
Stores data inside ticket, and make data persistent (store in db)
'''
if data is not None:
self.data = data
self.cache.put(self.key, self.data, validity)
return self.key
def load(self):
'''
Load data (if still valid) for a ticket
'''
self.data = self.cache.get(self.key, None)
return self.data
def delete(self):
'''
Removes a ticket from storage (db)
'''
self.cache.remove(self.key)
def __unicode__(self):
return "Ticket: {}, {}".format(self.key, self.data)

View File

@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import uds.models.Util
class Migration(migrations.Migration):
dependencies = [
('uds', '0015_ticketstore'),
]
operations = [
migrations.AlterField(
model_name='deployedservice',
name='image',
field=models.ForeignKey(related_name='deployedServices', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='uds.Image', null=True),
),
migrations.AlterField(
model_name='group',
name='manager',
field=uds.models.Util.UnsavedForeignKey(related_name='groups', to='uds.Authenticator'),
),
migrations.AlterField(
model_name='user',
name='manager',
field=uds.models.Util.UnsavedForeignKey(related_name='users', to='uds.Authenticator'),
),
]

View File

@ -33,8 +33,6 @@
from __future__ import unicode_literals
__updated__ = '2015-03-02'
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.db.models import signals
@ -45,11 +43,11 @@ from uds.models.ManagedObjectModel import ManagedObjectModel
from uds.models.Util import NEVER
import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
@python_2_unicode_compatible
class Authenticator(ManagedObjectModel):
@ -58,6 +56,7 @@ class Authenticator(ManagedObjectModel):
Sample authenticators are LDAP, Active Directory, SAML, ...
'''
# pylint: disable=model-missing-unicode
priority = models.IntegerField(default=0, db_index=True)
small_name = models.CharField(max_length=32, default='', db_index=True)

View File

@ -33,8 +33,6 @@
from __future__ import unicode_literals
__updated__ = '2014-09-16'
from django.db import models
from django.db.models import signals
from django.utils.encoding import python_2_unicode_compatible
@ -46,11 +44,14 @@ from uds.models.UUIDModel import UUIDModel
from uds.models.Authenticator import Authenticator
from uds.models.User import User
from uds.models.Util import UnsavedForeignKey
import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
@python_2_unicode_compatible
class Group(UUIDModel):
@ -58,7 +59,7 @@ class Group(UUIDModel):
This class represents a group, associated with one authenticator
'''
# pylint: disable=model-missing-unicode
manager = models.ForeignKey(Authenticator, on_delete=models.CASCADE, related_name='groups')
manager = UnsavedForeignKey(Authenticator, on_delete=models.CASCADE, related_name='groups')
name = models.CharField(max_length=128, db_index=True)
state = models.CharField(max_length=1, default=State.ACTIVE, db_index=True)
comments = models.CharField(max_length=256, default='')

View File

@ -31,8 +31,6 @@
from __future__ import unicode_literals
__updated__ = '2015-03-23'
from django.db import models
from uds.models.UUIDModel import UUIDModel
@ -46,6 +44,8 @@ import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
class TicketStore(UUIDModel):
'''
@ -62,6 +62,9 @@ class TicketStore(UUIDModel):
data = models.BinaryField() # Associated ticket data
validator = models.BinaryField(null=True, blank=True, default=None) # Associated validator for this ticket
class InvalidTicket(Exception):
pass
class Meta:
'''
Meta class to declare the name of the table at database
@ -105,7 +108,7 @@ class TicketStore(UUIDModel):
now = getSqlDatetime()
if t.stamp + validity < now:
raise Exception('Not valid anymore')
raise TicketStore.InvalidTicket('Not valid anymore')
data = pickle.loads(t.data)
@ -114,7 +117,7 @@ class TicketStore(UUIDModel):
validator = pickle.loads(t.validator)
if validator(data) is False:
raise Exception('Validation failed')
raise TicketStore.InvalidTicket('Validation failed')
if invalidate is True:
t.stamp = now - validity - datetime.timedelta(seconds=1)
@ -122,7 +125,7 @@ class TicketStore(UUIDModel):
return data
except TicketStore.DoesNotExist:
raise Exception('Does not exists')
raise TicketStore.InvalidTicket('Does not exists')
@staticmethod
def revalidate(uuid, validity=None):

View File

@ -33,13 +33,12 @@
from __future__ import unicode_literals
__updated__ = '2014-10-30'
from django.db import models
from django.db.models import signals
from django.utils.encoding import python_2_unicode_compatible
from uds.models.Authenticator import Authenticator
from uds.models.Util import UnsavedForeignKey
from uds.models.Util import NEVER
from uds.models.Util import getSqlDatetime
from uds.core.util import log
@ -49,6 +48,8 @@ import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
@python_2_unicode_compatible
class User(UUIDModel):
@ -56,7 +57,7 @@ class User(UUIDModel):
This class represents a single user, associated with one authenticator
'''
# pylint: disable=model-missing-unicode, maybe-no-member
manager = models.ForeignKey(Authenticator, on_delete=models.CASCADE, related_name='users')
manager = UnsavedForeignKey(Authenticator, on_delete=models.CASCADE, related_name='users')
name = models.CharField(max_length=128, db_index=True)
real_name = models.CharField(max_length=128)
comments = models.CharField(max_length=256)

View File

@ -33,21 +33,33 @@
from __future__ import unicode_literals
__updated__ = '2015-03-02'
from datetime import datetime
from django.db import models
from django.db import connection
from time import mktime
import logging
__updated__ = '2015-04-27'
logger = logging.getLogger(__name__)
NEVER = datetime(1972, 7, 1)
NEVER_UNIX = int(mktime(NEVER.timetuple()))
class UnsavedForeignKey(models.ForeignKey):
'''
From 1.8 of django, we need to point to "saved" objects.
If dont, will raise an InvalidValue exception.
We need to trick in some cases, because for example, root user is not in DB
'''
# Allows pointing to an unsaved object
allow_unsaved_instance_assignment = True
def getSqlDatetime(unix=False):
'''
Returns the current date/time of the database server.

View File

@ -30,8 +30,6 @@
'''
from __future__ import unicode_literals
__updated__ = '2015-04-26'
from django.utils.translation import ugettext as _
from django.http import HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.views.decorators.csrf import csrf_exempt
@ -41,7 +39,7 @@ from django.shortcuts import render_to_response
from django.template import RequestContext
from uds.core.auths.auth import webLogin, webLogout, authenticateViaCallback, authLogLogin, getUDSCookie
from uds.models import Authenticator, DeployedService, Transport
from uds.models import Authenticator, DeployedService
from uds.core.util import html
from uds.core.util import OsDetector
from uds.core.util.State import State
@ -50,7 +48,7 @@ from uds.core.ui import theme
from uds.models import TicketStore
from uds.core.auths.Exceptions import InvalidUserException
from uds.core.services.Exceptions import InvalidServiceException, ServiceInMaintenanceMode
from uds.core.services.Exceptions import InvalidServiceException
import uds.web.errors as errors
from uds.web.views.service import getService
@ -60,6 +58,9 @@ import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
@csrf_exempt
def authCallback(request, authName):
'''
@ -141,9 +142,9 @@ def ticketAuth(request, ticketId):
'''
Used to authenticate an user via a ticket
'''
data = TicketStore.get(ticketId)
try:
data = TicketStore.get(ticketId)
try:
# Extract ticket.data from ticket.data storage, and remove it if success
username = data['username']
@ -184,10 +185,14 @@ def ticketAuth(request, ticketId):
request.user = usr # Temporarily store this user as "authenticated" user, next requests will be done using session
logger.debug("Service & transport: {}, {}".format(servicePool, transport))
for v in DeployedService.objects.all():
logger.debug("{} {}".format(v.uuid, v.name))
# Check if servicePool is part of the ticket
if servicePool is not None:
# If service pool is in there, also is transport
res = getService(request, servicePool, transport)
res = getService(request, 'F' + servicePool, transport)
if res is None:
return render_to_response(theme.template('service_not_ready.html'), context_instance=RequestContext(request))
@ -211,13 +216,15 @@ def ticketAuth(request, ticketId):
# Now ensure uds cookie is at response
getUDSCookie(request, response, True)
return response
except TicketStore.InvalidTicket:
logger.error('Ticket is invalid: {} requested from {}'.format(ticketId, request.ip))
return errors.exceptionView(request, InvalidUserException())
except Authenticator.DoesNotExist:
logger.error('Ticket has an non existing authenticator')
return errors.error(request, InvalidUserException())
return errors.exceptionView(request, InvalidUserException())
except DeployedService.DoesNotExist:
logger.error('Ticket has an invalid Service Pool')
return errors.error(request, InvalidServiceException())
return errors.exceptionView(request, InvalidServiceException())
except Exception as e:
logger.exception('Exception')
return errors.exceptionView(request, e)

View File

@ -30,9 +30,6 @@
'''
from __future__ import unicode_literals
__updated__ = '2015-03-26'
from django.http import HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
@ -45,6 +42,8 @@ import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
@webLoginRequired(admin=True)
def download(request, idDownload):

View File

@ -30,8 +30,6 @@
'''
from __future__ import unicode_literals
__updated__ = '2015-04-24'
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.core.urlresolvers import reverse
@ -51,6 +49,8 @@ import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
def about(request):
'''

View File

@ -30,8 +30,6 @@
'''
from __future__ import unicode_literals
__updated__ = '2015-03-27'
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
@ -49,6 +47,7 @@ import uds.web.errors as errors
import logging
logger = logging.getLogger(__name__)
__updated__ = '2015-04-27'
def login(request, tag=None):