Ejemplo n.º 1
0
def register_new_user(request):

    login = ''
    password = ''
    _ = request.translate
    dbsession = request.db
    try:
        login = request.params['username']
        password = request.params['password']
        email = request.params['email']
        vorname = request.params['vorname'] 
        nachname = request.params['nachname']
        
        if not login or not password or not email or not vorname or not nachname:
            raise WrongUserRegistrationData('Missing user registration information.')
        
        if 'form.submitted' in request.params:
            # check if there is already a user with the same login registered in the database
            if not Users.by_username(login, dbsession):
                # register new user in the databse
                newUser = Users(login=login, password=password, email=email, vorname=vorname, nachname=nachname)
                dbsession.add(newUser)
    
                # define response header
                #userName = newUser.vorname+' '+newUser.nachname
                headers = remember(request, login)
                # get target url and route to it
                target_url = request.route_url('home_login',_query={'georef':'on'})
                transaction.commit()
                return HTTPFound(location = target_url, headers = headers)
        
    except WrongUserRegistrationData:
        raise 
    except:
        raise InternalAuthentificationError('Internal server error while trying to register user. Please try again or contact the page administrator.')
Ejemplo n.º 2
0
def change_pw(request):
    login = ''
    old_password = ''
    new_password = ''
    _ = request.translate
    dbsession = request.db
    
    try:
        # parse query parameter 
        login = checkIsUser(request)
        old_password = request.params['old_password']
        new_password = request.params['new_password']    
        if not login or not old_password or not new_password:
            raise MissingQueryParameterError('Some post parameters are missing.')
        
        # get user and check is the correct password
        if 'form.submitted' in request.params:
            # get actual user
            login = checkIsUser(request)
            user = Users.by_username(login, dbsession)
            if user and user.validate_password(old_password):
                # change password
                user._set_password(new_password)
                
                # define response header
                # get target url and route to it
                target_url = request.route_url('home_login')
                return HTTPFound(location = target_url)   
            else:
                raise WrongPasswordError('Password for the user %s is not valid, please try again')        
    except WrongPasswordError, MissingQueryParameterError:
        raise 
Ejemplo n.º 3
0
def register_new_user(request):

    login = ''
    password = ''
    _ = request.translate
    dbsession = request.db
    try:
        login = request.params['username']
        password = request.params['password']
        email = request.params['email']
        vorname = request.params['vorname'] 
        nachname = request.params['nachname']
        
        if not login or not password or not email or not vorname or not nachname:
            raise WrongUserRegistrationData('Missing user registration information.')
        
        if 'form.submitted' in request.params:
            # check if there is already a user with the same login registered in the database
            if not Users.by_username(login, dbsession):
                # register new user in the databse
                newUser = Users(login=login, password=password, email=email, vorname=vorname, nachname=nachname)
                dbsession.add(newUser)
    
                # define response header
                #userName = newUser.vorname+' '+newUser.nachname
                headers = remember(request, login)
                # get target url and route to it
                target_url = request.route_url('home_login',_query={'georef':'on'})
                transaction.commit()
                return HTTPFound(location = target_url, headers = headers)
        
    except WrongUserRegistrationData:
        raise 
    except:
        raise InternalAuthentificationError('Internal server error while trying to register user. Please try again or contact the page administrator.')
Ejemplo n.º 4
0
def georeference_profile_page(request):
    log.info('Request - Get georeference profile page.')
    dbsession = request.db
    userid = checkIsUser(request)
    user = Users.by_username(userid, dbsession)
    try:
        log.debug('Query georeference profile information from database for user %s'%userid)
        query_georefprocess = georeference_profile_query%userid
                    
        resultSet = dbsession.execute(query_georefprocess)
        
        log.debug('Create response list')
        georef_profile = []
        for record in resultSet:              
            georef_profile.append({'georef_id':record['georef_id'], 'mtb_id':record['mtbid'], 
                    'clip_params': record['clip_params'], 'time': record['time'], 'transformed': record['isttransformiert'],
                    'isvalide': record['isvalide'], 'titel': record['titel'], 'key': record['key'],
                    'time_georef':record['time_georef'],'boundingbox':record['box'][4:-1].replace(' ',','),'type':record['type'],
                    'published':record['published']})
             
        log.debug('Response: %s'%georef_profile) 
        
        return {'georef_profile':georef_profile, 'points':user.bonuspunkte}
    except Exception as e:
        log.error('Error while trying to request georeference history information');
        log.error(e)
        return {}
Ejemplo n.º 5
0
def getUploadProfilePage(request):
    log.debug('Request - Get Upload profile page.')
    dbsession = request.db
    username = checkIsUser(request)
    user = Users.by_username(username, dbsession)
    userid = user.id
    
    try:
        log.debug('Query Upload profile information from database for user %s'%userid)
        query_uploadprofile = upload_profile_query%userid
        
        resultSet = dbsession.execute(query_uploadprofile)
        
        log.debug('Create response list')
        
        upload_profile = []
        for record in resultSet:
            upload_profile.append({'upload_id':record['upload_id'], 'upload_mapid':record['upload_mapid'], 
                    'time': record['time'], 'licence': record['licence'], 'title': record['title'],
                    'upload_time':record['upload_time'], 'imagepath':record['imagepath'], 'thumbnail': record['thumbnail']})  
                   
        log.debug('Response: %s'%upload_profile)   
            
        return {'upload_profile':upload_profile}
        
    except Exception as e:
        log.error('Error while trying to request upload history information');
        log.error(e)
        return {}             
        return {}
Ejemplo n.º 6
0
def login(request):

    login = ''
    password = ''
    _ = request.translate
    dbsession = request.db

    try:
        login = request.params['username']
        password = request.params['password']
        user = Users.by_username(login, dbsession)
        if not password or not user:
            raise WrongLoginDataError(
                'The login data for user %s seems not to be valide, please try again.'
            )

        if 'form.submitted' in request.params:
            if user and user.validate_password(password):
                # define response header
                #userName = user.vorname+' '+user.nachname
                headers = remember(request, login)
                # get target url and route to it
                target_url = request.route_url('home_login',
                                               _query={'georef': 'on'})
                return HTTPFound(location=target_url, headers=headers)
            else:
                raise WrongPasswordError(
                    'Password for the user %s is not valid, please try again.')
    except WrongPasswordError, WrongLoginDataError:
        raise
Ejemplo n.º 7
0
def resetGeorefParameters(request):
    try:
        log.info('Receive a reset georeference parameter requests.')
        login = checkIsUser(request)
        dbsession = request.db
        messtischblatt_id = request.params['mtbid']
        georeference_process = Georeferenzierungsprozess.by_messtischblattid(messtischblatt_id, dbsession)
        referenz = georeference_process.clipparameter
        fehlerbeschreibung = 'Zuruecksetzen von Georeferenzierungsparameter für GeorefId=%s'%georeference_process.id
        if login and messtischblatt_id and referenz and fehlerbeschreibung and Users.by_username(login, dbsession):
            log.debug('Save reset process in table fehlermeldungen ...')
            newFehlermeldung = Fehlermeldung(objektid = messtischblatt_id, referenz = referenz, nutzerid = login,
                        fehlerbeschreibung = fehlerbeschreibung, timestamp = getTimestampAsPGStr())
            dbsession.add(newFehlermeldung)
            
            log.debug('Remove georeference process ...')
            dbsession.delete(georeference_process)
            
            log.debug('Remove refmtblayer ...')
            try:
                refmtblayer = RefMtbLayer.by_id(MTB_LAYER_ID, messtischblatt_id, dbsession)
                dbsession.delete(refmtblayer)
            except:
                log.debug('No entry for refmtblayer found ...')
                pass
            
            log.debug('Update messtischblatt db ...')
            messtischblatt = Messtischblatt.by_id(messtischblatt_id, dbsession) 
            messtischblatt.isttransformiert = False
            
            return json.dumps({'status':'confirmed'}, ensure_ascii=False, encoding='utf-8')
    except DBAPIError:
        log.error('Problems while trying to remove georeference parameter from the database ...')
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
Ejemplo n.º 8
0
def georeference_profile_page(request):
    log.info('Request - Get georeference profile page.')
    dbsession = request.db
    userid = checkIsUser(request)
    user = Users.by_username(userid, dbsession)
    try:
        log.debug('Query georeference profile information from database for user %s'%userid)
        queryData = request.db.query(Georeferenzierungsprozess, Metadata, Map).join(Metadata, Georeferenzierungsprozess.mapid == Metadata.mapid)\
            .join(Map, Georeferenzierungsprozess.mapid == Map.id)\
            .filter(Georeferenzierungsprozess.nutzerid == userid)\
            .order_by(desc(Georeferenzierungsprozess.id))

        log.debug('Create response list')
        georef_profile = []
        for record in queryData:
            georef = record[0]
            metadata = record[1]
            mapObj = record[2]
            boundingbox = Map.getBox2d(georef.mapid, dbsession, 900913)
            georef_profile.append({'georef_id':georef.id, 'mapid':georef.mapid, 
                    'clip_params': georef.georefparams, 'time': metadata.timepublish, 'transformed': georef.processed,
                    'isvalide': georef.adminvalidation, 'titel': metadata.title, 'key': mapObj.apsdateiname,
                    'time_georef':georef.timestamp,'boundingbox':boundingbox[4:-1].replace(' ',','),'type':georef.type,
                    'published':georef.processed})
             
        log.debug('Response: %s'%georef_profile) 
        
        return {'georef_profile':georef_profile, 'points':user.bonuspunkte}
    except Exception as e:
        log.error('Error while trying to request georeference history information');
        log.error(e)
        log.error(traceback.format_exc())
        raise HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
Ejemplo n.º 9
0
def login(request):
    
    login = ''
    password = ''
    _ = request.translate
    dbsession = request.db
    
    try:
        login = request.params['username']
        password = request.params['password']
        user = Users.by_username(login, dbsession)
        if not password or not user:
            raise WrongLoginDataError('The login data for user %s seems not to be valide, please try again.')   
        
        if 'form.submitted' in request.params:
            if user and user.validate_password(password):
                # define response header
                #userName = user.vorname+' '+user.nachname
                headers = remember(request, login)
                # get target url and route to it
                target_url = request.route_url('home_login')
                return HTTPFound(location = target_url, headers = headers)   
            else:
                raise WrongPasswordError('Password for the user %s is not valid, please try again.')  
    except WrongPasswordError, WrongLoginDataError:
        raise 
Ejemplo n.º 10
0
def checkIsUser(request):
    userid = unauthenticated_userid(request)
    log.info('Checked userid is %s'%userid)
    if Users.by_username(userid, request.db):
        # this should return None if the user doesn't exist
        return userid
    else:
        return False
 def createTestUser(cls):
     newUser = Users(login=login,
                     password=password,
                     email=email,
                     vorname=vorname,
                     nachname=nachname)
     cls.dbsession.add(newUser)
     cls.user = newUser
Ejemplo n.º 12
0
def checkIsUser(request):
    userid = unauthenticated_userid(request)
    log.info('Checked userid is %s' % userid)
    if Users.by_username(userid, request.db):
        # this should return None if the user doesn't exist
        return userid
    else:
        return False
Ejemplo n.º 13
0
def georeference_profile_page(request):
    log.info('Request - Get georeference profile page.')
    dbsession = request.db
    userid = checkIsUser(request)
    user = Users.by_username(userid, dbsession)
    try:
        log.debug(
            'Query georeference profile information from database for user %s'
            % userid)
        queryData = request.db.query(Georeferenzierungsprozess, Metadata, Map).join(Metadata, Georeferenzierungsprozess.mapid == Metadata.mapid)\
            .join(Map, Georeferenzierungsprozess.mapid == Map.id)\
            .filter(Georeferenzierungsprozess.nutzerid == userid)\
            .order_by(desc(Georeferenzierungsprozess.id))

        log.debug('Create response list')
        georef_profile = []
        for record in queryData:
            georef = record[0]
            metadata = record[1]
            mapObj = record[2]
            boundingbox = Map.getBox2d(georef.mapid, dbsession, 900913)
            georef_profile.append({
                'georef_id':
                georef.id,
                'mapid':
                georef.mapid,
                'clip_params':
                georef.georefparams,
                'time':
                metadata.timepublish,
                'transformed':
                georef.processed,
                'isvalide':
                georef.adminvalidation,
                'titel':
                metadata.title,
                'key':
                mapObj.apsdateiname,
                'time_georef':
                georef.timestamp,
                'boundingbox':
                boundingbox[4:-1].replace(' ', ','),
                'type':
                georef.type,
                'published':
                georef.processed
            })

        log.debug('Response: %s' % georef_profile)

        return {'georef_profile': georef_profile, 'points': user.bonuspunkte}
    except Exception as e:
        log.error(
            'Error while trying to request georeference history information')
        log.error(e)
        log.error(traceback.format_exc())
        raise HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
Ejemplo n.º 14
0
def georeference_profile_page(request):
    log.info('Request - Get georeference profile page.')
    dbsession = request.db
    userid = checkIsUser(request)
    user = Users.by_username(userid, dbsession)
    try:
        log.debug(
            'Query georeference profile information from database for user %s'
            % userid)
        query_georefprocess = georeference_profile_query % userid

        resultSet = dbsession.execute(query_georefprocess)

        log.debug('Create response list')
        georef_profile = []
        for record in resultSet:
            georef_profile.append({
                'georef_id':
                record['georef_id'],
                'mtb_id':
                record['mtbid'],
                'clip_params':
                record['clip_params'],
                'time':
                record['time'],
                'transformed':
                record['isttransformiert'],
                'isvalide':
                record['isvalide'],
                'titel':
                record['titel'],
                'key':
                record['key'],
                'time_georef':
                record['time_georef'],
                'boundingbox':
                record['box'][4:-1].replace(' ', ','),
                'type':
                record['type'],
                'published':
                record['published']
            })

        log.debug('Response: %s' % georef_profile)

        return {'georef_profile': georef_profile, 'points': user.bonuspunkte}
    except Exception as e:
        log.error(
            'Error while trying to request georeference history information')
        log.error(e)
        return {}
Ejemplo n.º 15
0
def reset_pw(request):
    dbsession = request.db
    try:
        login = request.params['username']
        email = request.params['email']

        if not login or not email:
            raise MissingQueryParameterError(
                'Missing information for reset password process.')

        if 'form.submitted' in request.params:
            user = Users.by_username(login, dbsession)
            if user and user.email == email:
                # register ticket in database
                newTicket = Fehlermeldung(fehlerbeschreibung="Passwort reset",
                                          timestamp=getTimestampAsPGStr(),
                                          referenz="users",
                                          nutzerid=user.login,
                                          objektid=user.id)
                dbsession.add(newTicket)

                # reset password
                newPassword = generateRandomString(10)
                user._set_password(newPassword)

                # send new password
                reset_msg = password_reset_msg.format(
                    user=str(user.login), new_password=str(newPassword))
                response = sendMailCommandLine(
                    user.email, 'Your password has been changed!', reset_msg)
                if not response:
                    raise InternalAuthentificationError(
                        'Internal server error while trying to send you your new password. Please try again or contact the page administrator.'
                    )

                # create response
                target_url = request.route_url('auth',
                                               action='page_reset_success')
                transaction.commit()
                return HTTPFound(location=target_url)
            else:
                raise InternalAuthentificationError(
                    'Internal server error while trying to change password. Please try again or contact the page administrator.'
                )

        else:
            raise MissingQueryParameterError('Missing form validation.')

    except MissingQueryParameterError, InternalAuthentificationError:
        raise
Ejemplo n.º 16
0
def getWelcomePage(request):  
    log.info('Call view get_welcome_page.')
    try:
        dbsession = request.db
        # get occurrence of georeferenced messtischblaetter
        occurrenceGeorefMtbs = int(getCountOfGeorefMesstischblaetter(dbsession))
        possibleMtbs = int(getCountOfPublishedMesstischblaetter(dbsession))
        georefRelation = int((float(occurrenceGeorefMtbs) / float(possibleMtbs)) * 100) 
        # get paginator for user ranking list
        paginator = Users.get_paginator(request, dbsession)
        return {'paginator':paginator,'occurrence_mtbs':occurrenceGeorefMtbs, 'possible_mtbs': possibleMtbs, 'georef_rel': georefRelation}
    except Exception:
        log.debug('Error while creating paginator for user georeference ranking')
        log.debug(Exception)
        return {}
Ejemplo n.º 17
0
def getWelcomePage(request):  
    log.info('Call view get_welcome_page.')
    try:
        dbsession = request.db
        # get occurrence of georeferenced messtischblaetter
        occurrenceGeorefMtbs = Map.getCountIsGeoref(dbsession)
        possibleMtbs = Map.getCountIsActive(dbsession)
        georefRelation = int((float(occurrenceGeorefMtbs) / float(possibleMtbs)) * 100) 
        # get paginator for user ranking list
        paginator = Users.get_paginator(request, dbsession)
        return {'paginator':paginator,'occurrence_mtbs':occurrenceGeorefMtbs, 'possible_mtbs': possibleMtbs, 'georef_rel': georefRelation}
    except Exception:
        log.error('Error while creating paginator for user georeference ranking')
        log.error(Exception)
        log.error(traceback.format_exc())
        raise HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
Ejemplo n.º 18
0
def resetGeorefParameters(request):
    try:
        log.info('Receive a reset georeference parameter requests.')
        login = checkIsUser(request)
        dbsession = request.db
        messtischblatt_id = request.params['mtbid']
        georeference_process = Georeferenzierungsprozess.by_messtischblattid(
            messtischblatt_id, dbsession)
        referenz = georeference_process.clipparameter
        fehlerbeschreibung = 'Zuruecksetzen von Georeferenzierungsparameter für GeorefId=%s' % georeference_process.id
        if login and messtischblatt_id and referenz and fehlerbeschreibung and Users.by_username(
                login, dbsession):
            log.debug('Save reset process in table fehlermeldungen ...')
            newFehlermeldung = Fehlermeldung(
                objektid=messtischblatt_id,
                referenz=referenz,
                nutzerid=login,
                fehlerbeschreibung=fehlerbeschreibung,
                timestamp=getTimestampAsPGStr())
            dbsession.add(newFehlermeldung)

            log.debug('Remove georeference process ...')
            dbsession.delete(georeference_process)

            log.debug('Remove refmtblayer ...')
            try:
                refmtblayer = RefMtbLayer.by_id(MTB_LAYER_ID,
                                                messtischblatt_id, dbsession)
                dbsession.delete(refmtblayer)
            except:
                log.debug('No entry for refmtblayer found ...')
                pass

            log.debug('Update messtischblatt db ...')
            messtischblatt = Messtischblatt.by_id(messtischblatt_id, dbsession)
            messtischblatt.isttransformiert = False

            return json.dumps({'status': 'confirmed'},
                              ensure_ascii=False,
                              encoding='utf-8')
    except DBAPIError:
        log.error(
            'Problems while trying to remove georeference parameter from the database ...'
        )
        return Response(conn_err_msg,
                        content_type='text/plain',
                        status_int=500)
Ejemplo n.º 19
0
def report_error(request):
    try:
        log.debug('Report error is called')
        dbsession = request.db
            
        # parse parameter
        login = checkIsUser(request)
        objektid = request.params['id']
        referenz = request.params['reference']
        fehlerbeschreibung = request.params['message']
        if login and objektid and referenz and fehlerbeschreibung:
            # check if valide user
            if Users.by_username(login, dbsession):
                newFehlermeldung = Fehlermeldung(objektid = objektid, referenz = referenz, nutzerid = login,
                                                 fehlerbeschreibung = fehlerbeschreibung, timestamp = getTimestampAsPGStr())
                dbsession.add(newFehlermeldung)
                log.debug('Report error is registered in database')
                return json.dumps({'status':'confirmed'}, ensure_ascii=False, encoding='utf-8')
    except DBAPIError:
        log.error('Problems while trying to register report error in database')
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
Ejemplo n.º 20
0
def getUploadProfilePage(request):
    log.debug('Request - Get Upload profile page.')
    dbsession = request.db
    username = checkIsUser(request)
    user = Users.by_username(username, dbsession)
    userid = user.id

    try:
        log.debug(
            'Query Upload profile information from database for user %s' %
            userid)
        query_uploadprofile = upload_profile_query % userid

        resultSet = dbsession.execute(query_uploadprofile)

        log.debug('Create response list')

        upload_profile = []
        for record in resultSet:
            upload_profile.append({
                'upload_id': record['upload_id'],
                'upload_mapid': record['upload_mapid'],
                'time': record['time'],
                'licence': record['licence'],
                'title': record['title'],
                'upload_time': record['upload_time'],
                'imagepath': record['imagepath'],
                'thumbnail': record['thumbnail']
            })

        log.debug('Response: %s' % upload_profile)

        return {'upload_profile': upload_profile}

    except Exception as e:
        log.error('Error while trying to request upload history information')
        log.error(e)
        return {}
        return {}
Ejemplo n.º 21
0
def reset_pw(request):
    dbsession = request.db
    try:
        login = request.params['username']
        email = request.params['email']
        
        if not login or not email:
            raise MissingQueryParameterError('Missing information for reset password process.')
    
        if 'form.submitted' in request.params:
            user = Users.by_username(login, dbsession)
            if user and user.email == email:
                # register ticket in database
                newTicket = Fehlermeldung(fehlerbeschreibung="Passwort reset", timestamp=getTimestampAsPGStr(), referenz="users", nutzerid=user.login, objektid=user.id);
                dbsession.add(newTicket);
                
                # reset password 
                newPassword = generateRandomString(10) 
                user._set_password(newPassword)
                
                # send new password
                reset_msg = password_reset_msg.format(user = str(user.login), new_password = str(newPassword))
                response = sendMailCommandLine(user.email, 'Your password has been changed!', reset_msg)
                if not response:
                    raise InternalAuthentificationError('Internal server error while trying to send you your new password. Please try again or contact the page administrator.')
                
                # create response
                target_url = request.route_url('auth', action='page_reset_success')
                transaction.commit()
                return HTTPFound(location = target_url)   
            else:
                raise InternalAuthentificationError('Internal server error while trying to change password. Please try again or contact the page administrator.')
            
        else:
            raise MissingQueryParameterError('Missing form validation.')

    except MissingQueryParameterError, InternalAuthentificationError:
        raise
Ejemplo n.º 22
0
def getWelcomePage(request):
    log.info('Call view get_welcome_page.')
    try:
        dbsession = request.db
        # get occurrence of georeferenced messtischblaetter
        occurrenceGeorefMtbs = Map.getCountIsGeoref(dbsession)
        possibleMtbs = Map.getCountIsActive(dbsession)
        georefRelation = int(
            (float(occurrenceGeorefMtbs) / float(possibleMtbs)) * 100)
        # get paginator for user ranking list
        paginator = Users.get_paginator(request, dbsession)
        return {
            'paginator': paginator,
            'occurrence_mtbs': occurrenceGeorefMtbs,
            'possible_mtbs': possibleMtbs,
            'georef_rel': georefRelation
        }
    except Exception:
        log.error(
            'Error while creating paginator for user georeference ranking')
        log.error(Exception)
        log.error(traceback.format_exc())
        raise HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
Ejemplo n.º 23
0
def getWelcomePage(request):
    log.info('Call view get_welcome_page.')
    try:
        dbsession = request.db
        # get occurrence of georeferenced messtischblaetter
        occurrenceGeorefMtbs = int(
            getCountOfGeorefMesstischblaetter(dbsession))
        possibleMtbs = int(getCountOfPublishedMesstischblaetter(dbsession))
        georefRelation = int(
            (float(occurrenceGeorefMtbs) / float(possibleMtbs)) * 100)
        # get paginator for user ranking list
        paginator = Users.get_paginator(request, dbsession)
        return {
            'paginator': paginator,
            'occurrence_mtbs': occurrenceGeorefMtbs,
            'possible_mtbs': possibleMtbs,
            'georef_rel': georefRelation
        }
    except Exception:
        log.debug(
            'Error while creating paginator for user georeference ranking')
        log.debug(Exception)
        return {}
Ejemplo n.º 24
0
def georeferenceConfirm(request):
    log.info('Receive request for processing georeference validation result')

    try:
        userid = checkIsUser(request)
        user = Users.by_username(userid, request.db)
        request_data = None
        if request.method == 'POST':
            request_data = request.json_body

        if request_data:
            validateId(request_data['id'])
            log.debug('Request data is valide: %s' % request_data)

        log.debug(
            'Check if there is already a registered georeference process for this messtischblatt ...'
        )
        messtischblatt = Messtischblatt.by_id(request_data['id'], request.db)
        isAlreadyGeorefProcess = Georeferenzierungsprozess.by_messtischblattid(
            messtischblatt.id, request.db)
        if isAlreadyGeorefProcess is not None:
            response = {
                'text':
                'There is already a registered georeference process for this messtischblatt. Please move forward to the update process.',
                'georeferenceid': isAlreadyGeorefProcess.id
            }
            return json.dumps(response, ensure_ascii=False, encoding='utf-8')

        # actual only support this option if target srs is EPSG:4314
        log.debug('Start saving georeference process in the database ...')
        epsg_code = int(
            str(request_data['georeference']['target']).split(':')[1])
        if request_data['georeference'][
                'source'] == 'pixel' and epsg_code == 4314:
            log.debug('Create georeference process record ...')
            timestamp = getTimestampAsPGStr()
            georeference_parameter = str(
                convertUnicodeDictToUtf(request_data['georeference']))
            georefProcess = Georeferenzierungsprozess(
                messtischblattid=messtischblatt.id,
                nutzerid=userid,
                clipparameter=georeference_parameter,
                timestamp=timestamp,
                isvalide=True,
                type='new',
                refzoomify=True,
                publish=False,
                processed=False)
            request.db.add(georefProcess)
            request.db.flush()

            log.debug('Creating passpoints ...')
            #             gcps = request_data['georeference']['gcps']
            #             passpoints = []
            #             for i in range(0,len(gcps)):
            #                 unrefPoint = [gcps[i]['source'][0],gcps[i]['source'][1]]
            #                 refPoint = 'POINT(%s %s)'%(gcps[i]['target'][0], gcps[i]['target'][1])
            #                 passpoint = Passpoint(objectid = messtischblatt.id, userid = user.id, unrefpoint = unrefPoint,
            #                                       refpoint = refPoint, deprecated = False, timestamp = timestamp, georeferenceprocessid =  georefProcess.id)
            #                 request.db.add(passpoint)
            #                 passpoints.append(passpoints)

            log.debug('Create response ...')
            ##gcps = getJsonDictPasspointsForMapObject(messtischblatt.id, request.db)
            response = {
                'text':
                'Georeference result saved. It will soon be ready for use.',
                'georeferenceid': georefProcess.id,
                'points': 20,
                'gcps': request_data['georeference'],
                'type': 'confirm'
            }
            return json.dumps(response, ensure_ascii=False, encoding='utf-8')
        else:
            raise GeoreferenceParameterError(
                'Wrong or missing service parameter')

    except GeoreferenceParameterError as e:
        message = 'Wrong or missing service parameter - %s' % e.value
        log.error(message)
        return HTTPBadRequest(message)
    except Exception as e:
        message = 'Problems while computing validation result - %s' % e
        log.error(message)
        return HTTPInternalServerError(message)
Ejemplo n.º 25
0
def georeferenceConfirm(request):
    log.info('Receive request for processing georeference validation result')
    
    try:
        userid = checkIsUser(request)
        user = Users.by_username(userid, request.db)
        request_data = None
        if request.method == 'POST':
            request_data = request.json_body
            
        if request_data:
            validateId(request_data['id'])
            log.debug('Request data is valide: %s'%request_data)
            
        log.debug('Check if there is already a registered georeference process for this messtischblatt ...')
        messtischblatt = Messtischblatt.by_id(request_data['id'], request.db)
        isAlreadyGeorefProcess = Georeferenzierungsprozess.by_messtischblattid(messtischblatt.id, request.db)
        if isAlreadyGeorefProcess is not None:
            response = {'text':'There is already a registered georeference process for this messtischblatt. Please move forward to the update process.','georeferenceid':isAlreadyGeorefProcess.id}
            return json.dumps(response, ensure_ascii=False, encoding='utf-8')        
        
        # actual only support this option if target srs is EPSG:4314
        log.debug('Start saving georeference process in the database ...')
        epsg_code = int(str(request_data['georeference']['target']).split(':')[1])
        if request_data['georeference']['source'] == 'pixel' and epsg_code == 4314:
            log.debug('Create georeference process record ...')
            timestamp = getTimestampAsPGStr()
            georeference_parameter = str(convertUnicodeDictToUtf(request_data['georeference']))
            georefProcess = Georeferenzierungsprozess(messtischblattid = messtischblatt.id, nutzerid = userid, 
                clipparameter = georeference_parameter, timestamp = timestamp, isvalide = True, type = 'new', refzoomify = True, publish = False, processed = False)
            request.db.add(georefProcess)
            request.db.flush()
            
            log.debug('Creating passpoints ...')
#             gcps = request_data['georeference']['gcps']
#             passpoints = []
#             for i in range(0,len(gcps)):
#                 unrefPoint = [gcps[i]['source'][0],gcps[i]['source'][1]]
#                 refPoint = 'POINT(%s %s)'%(gcps[i]['target'][0], gcps[i]['target'][1])
#                 passpoint = Passpoint(objectid = messtischblatt.id, userid = user.id, unrefpoint = unrefPoint,
#                                       refpoint = refPoint, deprecated = False, timestamp = timestamp, georeferenceprocessid =  georefProcess.id)
#                 request.db.add(passpoint)
#                 passpoints.append(passpoints)
                
            log.debug('Create response ...')  
            ##gcps = getJsonDictPasspointsForMapObject(messtischblatt.id, request.db)
            response = {'text':'Georeference result saved. It will soon be ready for use.','georeferenceid':georefProcess.id, 'points':20,
                         'gcps':request_data['georeference'] ,'type':'confirm'}
            return json.dumps(response, ensure_ascii=False, encoding='utf-8') 
        else:
            raise GeoreferenceParameterError('Wrong or missing service parameter')
        
        
    except GeoreferenceParameterError as e:
        message = 'Wrong or missing service parameter - %s'%e.value
        log.error(message)
        return HTTPBadRequest(message) 
    except Exception as e:
        message = 'Problems while computing validation result - %s'%e
        log.error(message)
        return HTTPInternalServerError(message)
Ejemplo n.º 26
0
def groupfinder(userid, request):
    user = Users.by_username(userid, request.db)
    if user:
        return ['g:%s' % g for g in str(user.groups).split(',')]
Ejemplo n.º 27
0
 def getUser(self, dbsession):
     user = Users.by_username(login, dbsession)
     return user    
 def getUser(self, dbsession):
     user = Users.by_username(login, dbsession)
     return user
Ejemplo n.º 29
0
def store_image(request):
    try:
        log.debug('Receive a upload request.')
        username = checkIsUser(request)
        user = Users.by_username(username, request.db)

        # check if need metadata is send
        log.debug('Check if mandatory metadata is send ...')
        params = request.params
        if not 'title' in params or not 'titleshort' in params or \
                not 'imagelicence' in params or not 'imageowner' in params:
            raise MissingQueryParameterError('Missing query parameter ...')
        
        # register upload process in database
        log.debug('Register upload process to database ...')
        uploadObj = Uploads(userid = user.id, time = getTimestampAsPGStr(), params = '%s'%request.params)
        request.db.add(uploadObj)
        
        log.debug('Create and add mapObj ...')
        mapObj = Map(istaktiv = False, isttransformiert = False, maptype = 'A', hasgeorefparams = 0)
        request.db.add(mapObj)
        request.db.flush()
        
        # check if image allowed extensions
        # ``filename`` contains the name of the file in string format.
        log.debug('Create filename for persistent saving ...')
        filename = request.POST['file'].filename
        if not allowed_file(filename):
            raise WrongParameterException('Format of the image is not supported through the upload API.')
            
        
        # ``input_file`` contains the actual file data which needs to be
        # stored somewhere.
        inputFile = request.POST['file'].file
    
        # Note that we are generating our own filename instead of trusting
        # the incoming filename since that might result in insecure paths.
        # Please note that in a real application you would not use /tmp,
        # and if you write to an untrusted location you will need to do
        # some extra work to prevent symlink attacks.    
        newFilename = '%s.%s' % ('df_dk_%s'%mapObj.id, filename.rsplit('.', 1)[1])
        filePath = os.path.join(UPLOAD_DIR, newFilename)
    
        # save file to disk
        log.debug('Save file to datastore ...')
        saveFile(inputFile, filePath)
        
        # process thumbnails
        log.debug('Create thumbnails ...')
        thumbSmall = createSmallThumbnail(filePath, UPLOAD_THUMBS_SMALL_DIR)
        thumbMid = createMidThumbnail(filePath, UPLOAD_THUMBS_MID_DIR)   
        log.debug('Create zoomify tiles')    
        zoomifyTiles = processZoomifyTiles(filePath, UPLOAD_ZOOMIFY_DIR, log)
        
        # parse boundinbBox
        pgBoundingBoxStr = parseBoundingBoxFromRequest(request.params)
            
        # add geometry to map object and update other attributes
        # work around --> should be replaced through adding the geomtry on initial adding
        log.debug('Update mapObj and create metadataObj ...')
        mapObj.apsdateiname = newFilename
        mapObj.originalimage = filePath
        Map.updateGeometry(mapObj.id, pgBoundingBoxStr, request.db)        
        request.db.flush()
        
        # parse and create metadataObj
        if 'title' in request.params:
            title = request.params['title']
        if 'titleshort' in request.params:
            titleshort = request.params['titleshort']    
        if 'serientitle' in request.params:
            serientitle = request.params['serientitle'] 
        if 'description' in request.params:
            description = request.params['description']  
        if 'timepublish' in request.params:
            timepublish = request.params['timepublish']                         
        if 'imagelicence' in request.params:
            imagelicence = request.params['imagelicence']
        if 'scale' in request.params:
            scale = request.params['scale']
        if 'imageowner' in request.params:
            imageowner = request.params['imageowner']
           
        # create metadata obj 
        # the creating of the paths are right now quite verbose
        imagezoomify = UPLOAD_SERVICE_URL_ZOOMIFY + os.path.basename(filePath).split('.')[0] + '/ImageProperties.xml' 
        thumbssmall = UPLOAD_SERVICE_URL_THUMBS_SMALL + os.path.basename(thumbSmall)
        thumbsmid = UPLOAD_SERVICE_URL_THUMBS_MID + os.path.basename(thumbMid)
        metadataObj = Metadata(mapid = mapObj.id, title = title, titleshort = titleshort, 
                serientitle = serientitle, description = description, timepublish = "%s-01-01 00:00:00"%(timepublish), 
                imagelicence = imagelicence, imageowner = imageowner, scale = scale,
                imagezoomify = imagezoomify,
                thumbssmall = thumbssmall,
                thumbsmid = thumbsmid)
        request.db.add(metadataObj)
        
        # update uploadObj and create response
        uploadObj.mapid = mapObj.id
        
        log.debug('Create response ...')
        target_url = request.route_url('upload-profile')
        return HTTPFound(location = target_url)  
    
    # Exception handling     
    except NotFoundException as e:
        log.exception(e)
        ERR_MSG = GENERAL_ERROR_MESSAGE + "We're sorry, but something went wrong. Please be sure that your file respects the upload conditions."
        return HTTPBadRequest(ERR_MSG)
    except DBAPIError as e:
        log.error('Database error within a upload process')
        log.exception(e)
        return HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
    except MissingQueryParameterError or WrongParameterException as e:
        log.exception(e)
        raise HTTPBadRequest(GENERAL_ERROR_MESSAGE)
    except Exception as e:
        log.exception(e)
        raise HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
Ejemplo n.º 30
0
def store_image(request):
    try:
        log.debug('Receive a upload request.')
        username = checkIsUser(request)
        user = Users.by_username(username, request.db)

        # check if need metadata is send
        log.debug('Check if mandatory metadata is send ...')
        params = request.params
        if not 'title' in params or not 'titleshort' in params or \
                not 'imagelicence' in params or not 'imageowner' in params:
            raise MissingQueryParameterError('Missing query parameter ...')

        # register upload process in database
        log.debug('Register upload process to database ...')
        uploadObj = Uploads(userid=user.id,
                            time=getTimestampAsPGStr(),
                            params='%s' % request.params)
        request.db.add(uploadObj)

        log.debug('Create and add mapObj ...')
        mapObj = Map(istaktiv=False,
                     isttransformiert=False,
                     maptype='A',
                     hasgeorefparams=0)
        request.db.add(mapObj)
        request.db.flush()

        # check if image allowed extensions
        # ``filename`` contains the name of the file in string format.
        log.debug('Create filename for persistent saving ...')
        filename = request.POST['file'].filename
        if not allowed_file(filename):
            raise WrongParameterException(
                'Format of the image is not supported through the upload API.')

        # ``input_file`` contains the actual file data which needs to be
        # stored somewhere.
        inputFile = request.POST['file'].file

        # Note that we are generating our own filename instead of trusting
        # the incoming filename since that might result in insecure paths.
        # Please note that in a real application you would not use /tmp,
        # and if you write to an untrusted location you will need to do
        # some extra work to prevent symlink attacks.
        newFilename = '%s.%s' % ('df_dk_%s' % mapObj.id, filename.rsplit(
            '.', 1)[1])
        filePath = os.path.join(UPLOAD_DIR, newFilename)

        # save file to disk
        log.debug('Save file to datastore ...')
        saveFile(inputFile, filePath)

        # process thumbnails
        log.debug('Create thumbnails ...')
        thumbSmall = createSmallThumbnail(filePath, UPLOAD_THUMBS_SMALL_DIR)
        thumbMid = createMidThumbnail(filePath, UPLOAD_THUMBS_MID_DIR)
        log.debug('Create zoomify tiles')
        zoomifyTiles = processZoomifyTiles(filePath, UPLOAD_ZOOMIFY_DIR, log)

        # parse boundinbBox
        pgBoundingBoxStr = parseBoundingBoxFromRequest(request.params)

        # add geometry to map object and update other attributes
        # work around --> should be replaced through adding the geomtry on initial adding
        log.debug('Update mapObj and create metadataObj ...')
        mapObj.apsdateiname = newFilename
        mapObj.originalimage = filePath
        Map.updateGeometry(mapObj.id, pgBoundingBoxStr, request.db)
        request.db.flush()

        # parse and create metadataObj
        if 'title' in request.params:
            title = request.params['title']
        if 'titleshort' in request.params:
            titleshort = request.params['titleshort']
        if 'serientitle' in request.params:
            serientitle = request.params['serientitle']
        if 'description' in request.params:
            description = request.params['description']
        if 'timepublish' in request.params:
            timepublish = request.params['timepublish']
        if 'imagelicence' in request.params:
            imagelicence = request.params['imagelicence']
        if 'scale' in request.params:
            scale = request.params['scale']
        if 'imageowner' in request.params:
            imageowner = request.params['imageowner']

        # create metadata obj
        # the creating of the paths are right now quite verbose
        imagezoomify = UPLOAD_SERVICE_URL_ZOOMIFY + os.path.basename(
            filePath).split('.')[0] + '/ImageProperties.xml'
        thumbssmall = UPLOAD_SERVICE_URL_THUMBS_SMALL + os.path.basename(
            thumbSmall)
        thumbsmid = UPLOAD_SERVICE_URL_THUMBS_MID + os.path.basename(thumbMid)
        metadataObj = Metadata(mapid=mapObj.id,
                               title=title,
                               titleshort=titleshort,
                               serientitle=serientitle,
                               description=description,
                               timepublish="%s-01-01 00:00:00" % (timepublish),
                               imagelicence=imagelicence,
                               imageowner=imageowner,
                               scale=scale,
                               imagezoomify=imagezoomify,
                               thumbssmall=thumbssmall,
                               thumbsmid=thumbsmid)
        request.db.add(metadataObj)

        # update uploadObj and create response
        uploadObj.mapid = mapObj.id

        log.debug('Create response ...')
        target_url = request.route_url('upload-profile')
        return HTTPFound(location=target_url)

    # Exception handling
    except NotFoundException as e:
        log.exception(e)
        ERR_MSG = GENERAL_ERROR_MESSAGE + "We're sorry, but something went wrong. Please be sure that your file respects the upload conditions."
        return HTTPBadRequest(ERR_MSG)
    except DBAPIError as e:
        log.error('Database error within a upload process')
        log.exception(e)
        return HTTPInternalServerError(GENERAL_ERROR_MESSAGE)
    except MissingQueryParameterError or WrongParameterException as e:
        log.exception(e)
        raise HTTPBadRequest(GENERAL_ERROR_MESSAGE)
    except Exception as e:
        log.exception(e)
        raise HTTPInternalServerError(GENERAL_ERROR_MESSAGE)