コード例 #1
0
ファイル: login.py プロジェクト: kloavis/portcullis
def user_login(request):

    error = ''

    if request.method == 'POST':
        json_data = json.loads(request.POST['json_data'])

        user = authenticate(username=json_data["username"], password=json_data["password"])
        if user is not None:
            if user.is_active:
                login(request, user)

                greeting_page = loader.get_template('greeting.html')
                greeting_c = RequestContext(request, {})

                data = {
                    'greeting': greeting_page.render(greeting_c),
                }

                return cors_http_response_json(data)
            else:
                error = "This account is disabled"
        else:
            error = "Invalid username and/or password"

    return cors_http_response_json({'error': error})
コード例 #2
0
ファイル: get_data.py プロジェクト: kloavis/portcullis
def render_graph(request):
    '''
    Takes a single datastream id and a time frame and generates json for the data.
    '''
    jsonData = request.REQUEST.get('json_data', None)
    if jsonData is None:
        return cors_http_response_json({'error': "Unrecognized data."})

    return cors_http_response_json(get_stream_data(json.loads(jsonData), request.user))
コード例 #3
0
ファイル: get_data.py プロジェクト: kloavis/portcullis
def get_data_by_ds_column(request):
    '''
    ' This view will take a column name/value and a time range (in epoch secs),
    ' and return a json response containing all the matching sensor data points.
    '
    ' returns - HttpResponse containing jsondata {'echo of query', 'streams': [[<ds_id>, <value>, <timestamp>]] }
    '''
    # TODO: Check perms, etc.
    import time
    beg_time = time.time()
    jsonData = request.REQUEST.get('jsonData', None)
    if jsonData is None:
        return cors_http_response_json({'errors': 'Error: No jsonData received.'})

    try:
        jsonData = json.loads(jsonData)
    except Exception as e:
        return cors_http_response_json({'errors': 'Error: Invalid JSON: ' + str(e)})

    try:
        column = jsonData['column']
        value = jsonData['value']
        time_start = jsonData['start']
        time_end = jsonData['end']
    except KeyError as e:
        return cors_http_response_json({'errors': 'Error: KeyError: ' + str(e)})

    # Scrub column, so it is safe to use in query
    ds_columns = [x.get_attname_column()[1] for x in DataStream._meta.fields]

    if column not in ds_columns:
        return cors_http_response_json({'errors': 'Error: Column Name %s not in DataStream table.' % column})

    kwargs = {
        'timestamp__gte':                   time_start,
        'timestamp__lte':                   time_end,
        'datastream__'+column+'__contains': value
    }

    data_points = list(SensorReading.objects.select_related().filter(**kwargs).values_list('datastream', 'value', 'timestamp'))

    elapsed_time = time.time() - beg_time
    print 'Took: %f seconds before JSON' % elapsed_time
    # Echo back query, and send data
    data = {
        'column':  column,
        'value':   value,
        'start':   time_start,
        'end':     time_end,
        'streams': data_points,
        'time':    elapsed_time
        }

    resp = HttpResponse(json.dumps(data, cls=DecimalEncoder), mimetype='application/json')
    resp['Access-Control-Allow-Origin'] = '*'
    return resp
コード例 #4
0
ファイル: login.py プロジェクト: kloavis/portcullis
def password_form(request):
    '''
    ' This view will render the change password request form.
    '''

    portcullisUser = check_access(request)

    if isinstance(portcullisUser, HttpResponse):
        return cors_http_response_json({'errors': portcullisUser.content})
    if not isinstance(portcullisUser, AuthUser):
        return cors_http_response_json({'errors': 'User must be logged in to change password.'})

    t = loader.get_template('passwordForm.html')
    c = RequestContext(request, {'user': portcullisUser})
    return cors_http_response_json({'html': t.render(c)})
コード例 #5
0
ファイル: get_data.py プロジェクト: kloavis/portcullis
def shared_graph(request, token, id):
    '''
    This function will use a key to send the jsonData for a shared graph.
    '''
    try:
        # Get the key from the token
        key = Key.objects.get(key = token)

        # Get the graph from the id.
        graph = SavedDSGraph.objects.get(id = id)
    except ObjectDoesNotExist:
        return cors_http_response_json({'error': 'Graph %s/%s/ does not exist' % (token, str(id))})
    
    params = {
        'start':         graph.start,
        'end':           graph.end,
        'reduction':     graph.reduction_type,
        'granularity':   graph.granularity,
        'datastream_id': graph.datastream.id,
        'zoom_start':    graph.zoom_start,
        'zoom_end':      graph.zoom_end
        }
    
    return cors_http_response_json(get_stream_data(params, key, request.user))
コード例 #6
0
ファイル: login.py プロジェクト: kloavis/portcullis
def change_password(request):
    '''
    ' This view will allow a user to change their password.
    '
    ' POST arguments:
    '   jsonData - JSON data containing:
    '              oldPassword - string containing user's current password.
    '              newPassword - string containing password to change to.
    '''

    portcullisUser = check_access(request)

    if isinstance(portcullisUser, HttpResponse):
        return cors_http_response_json({'errors': portcullisUser.content})
    if not isinstance(portcullisUser, AuthUser):
        return cors_http_response_json({'errors': 'Please log in before changing your password.'})

    jsonData = request.REQUEST.get('jsonData', None)

    try:
        jsonData = json.loads(jsonData)
    except Exception as e:
        return cors_http_response_json({'errors': 'JSON Exception: %s: %s' % (type(e), e.message)})

    try:
        oldPassword = jsonData['oldPassword']
        newPassword = jsonData['newPassword']
    except KeyError as e:
        return cors_http_response_json({'errors': 'KeyError: %s' % e.message})

    # Make sure old password is valid
    user = authenticate(username=portcullisUser.get_username(), password=oldPassword)
    if user is None or user != portcullisUser:
        return cors_http_response_json({'errors': 'Authentication Error: Username and password are not correct'})
    elif not user.is_active:
        error = 'Authentication Error: User is not active.  You must be active to change password.'
        return cors_http_response_json({'errors': error})

    # Change the password
    portcullisUser.set_password(newPassword)
    portcullisUser.save()
    return cors_http_response_json({'success': 'Password successfully changed!'})
コード例 #7
0
ファイル: create_shared.py プロジェクト: kloavis/portcullis
def create_saved_view(request):
    '''
    ' Create a savedView and return the token or link for that shared view.
    '''

    portcullisUser = check_access(request)

    if isinstance(portcullisUser, HttpResponse):
        transaction.rollback()
        return cors_http_response_json({'errors': portcullisUser.content})

    if request.user.is_anonymous():
        transaction.rollback()
        return cors_http_response_json({'errors': "Must be logged in to create saved view"})

    if 'jsonData' not in request.POST:
        transaction.rollback()
        return cors_http_response_json({'errors': "Unrecongnized data"})

    try:
        jsonData = json.loads(request.POST['jsonData'])
    except Exception as e:
        transaction.rollback()
        return cors_http_response_json({'errors': 'Ivalid json: %s' % e.message})

    expires = timezone.now() + timedelta(days=7)
    key = Key.objects.generateKey(portcullisUser, 'Saved view', expires, 20)

    # Create a SavedView object and graphs, and save data.
    savedView = SavedView.objects.create(key = key)

    try:
        start = jsonData['start']
        end = jsonData['end']
        gran = jsonData['granularity']
    except Exception as e:
        transaction.rollback()
        return cors_http_response_json({'errors': 'Error getting json data: %s: %s:' % (type(e), e.message)})

    for graphData in jsonData['graphs']:
        try:
            ds = DataStream.objects.get(id = graphData['ds_id'])
        except DataStream.DoesNotExist:
            transaction.rollback()
            return cors_http_response_json({'errors': 'Datastream does not exist.'})
        except Exception as e:
            transaction.rollback()
            return cors_http_response_json({'errors': 'Unknown error occurred: %s: %s' % (type(e), e.message)})
                               
        # Make sure not to add the key if not the owner.
        if key not in ds.can_read.all() and portcullisUser == ds.owner and not ds.is_public:
            ds.can_read.add(key)
                               
        try:
            reduction = graphData['reduction']
            zoom_start = graphData['zoom_start']
            zoom_end = graphData['zoom_end']
        except Exception as e:
            transaction.rollback()
            return cors_http_response_json({'errors': 'Error getting json data for datastream %d: %s' % (ds.id, e.message)})
        
        graph = SavedDSGraph(datastream = ds, start = start, end = end,
                             reduction_type = reduction, granularity = gran,
                             zoom_start = zoom_start, zoom_end = zoom_end)
        try:
            graph.save()
            savedView.widget.add(graph)
        except Exception as e:
            transaction.rollback()
            return cors_http_response_json({'errors': 'Error saving graph: %s' % e.message})
        
    link = reverse('portcullis-saved-view', args = ['saved_view', key.key])
    transaction.commit()
    return cors_http_response_json({'html':'<a href="%s">%s</a>' % (link, link)})
コード例 #8
0
ファイル: create_ds.py プロジェクト: kloavis/portcullis
def create_datastreams(request):
    '''
    ' Creates DataStreams with an array of data from json and with the owner of the specified token.
    '
    ' The json required format is the following: TBD
    '
    ' Returns: HttpResponse with Json containing a list with the new DataStream's ids and a dictionary of errors
    '''
    timingMark = time.time()
    #TODO: for now screw permissions, but later, put them in!!
    
    errors = []

    try:
        json_data = json.loads(request.POST.get("jsonData"))
    except Exception as e:
        #transaction.rollback()
        errors.append({ 'error': "Missing jsonData from request.", 'exception': str(e) })
        return cors_http_response_json(errors)
    
    if 'key' in json_data:
        try:
            key = Key.objects.get(key=json_data['key'])
        except Key.DoesNotExist as e:
            #transaction.rollback()
            errors.append({'error': 'Key not in Database: ' + str(json_data['key']), 'exception': str(e)})
            return cors_http_response_json(errors)
    else:
        #transaction.rollback()
        errors.append({'error': 'No Key received.', 'exception': None})
        return cors_http_response_json(errors)

    owner = key.owner

    if 'datastreams' not in json_data:
        #transaction.rollback()
        errors.append({ 'error': 'No datastream data received', 'exception': None })
        return cors_http_response_json(errors)

    if not isinstance(json_data['datastreams'], list):
        #transaction.rollback()
        errors.append({'error': 'Datastream object not a list.', 'exception': None})
        return cors_http_response_json(errors)

    return_ids = {}
    for data in json_data['datastreams']:
             
        try:
            ds_name = data['name']
        except Exception as e:
            error = "Exception getting DataStream name %s." % type(e) 
            errors.append({"error": error, "exception": str(e)})
            continue
        
        try:
            ds = create_ds(owner, data) 

            #If not a ds then an error
            if not isinstance(ds, DataStream):
                errors.append(ds)
                continue

        except (IntegrityError, ValidationError) as e:
            try:
                ds = DataStream.objects.get(name=ds_name, owner=owner)
            except DataStream.DoesNotExist:
                error = 'Unexpected error getting datastream!  Datastream does not exist, but could not create.'
                errors.append({'error': error, 'exception': str(e)})
                continue

        return_ids[ds_name] = ds.pk
        ds.can_read.add(key)
        ds.can_post.add(key)

    #transaction.commit()
    elapsedTime = time.time() - timingMark
    return cors_http_response_json({'ids': return_ids, "errors": errors, "time": elapsedTime})