def post_user(self, doc, **kw): """ Creates new user with tags, the owner of the tags is assigned to the user document format: <user name="user"> <tag name="password" value="12345"/> <tag name="email" value="*****@*****.**"/> <tag name="display_name" value="user"/> </user> """ userxml = etree.fromstring(doc) required_tags = ['user_name', 'password', 'email', 'display_name'] tags = {} if userxml.tag == 'user': user_name = userxml.attrib['name'] if user_name: tags['user_name'] = user_name for t in userxml.xpath('tag'): tags[t.get('name')] = t.get('value') #if (t.attrib['name']=='password') or (t.attrib['name']=='email'): if t.get('name') in REMOVE_TAGS: t.getparent().remove(t) #removes email and password if t.attrib['name'] == 'email': userxml.attrib['value'] = t.attrib[ 'value'] #set it as value of the user if all(k in tags for k in required_tags): log.debug("ADMIN: Adding user: %s", str(user_name)) u = User(user_name=tags['user_name'], password=tags['password'], email_address=tags['email'], display_name=tags['display_name']) DBSession.add(u) self._update_groups(u, tags.get('groups', '').split(',')) try: transaction.commit() except IntegrityError: abort( 405, 'Another user already has this user name or email address' ) #r = BQUser.query.filter(BQUser.resource_name == tags['user_name']).first() r = data_service.query(resource_type='user', name=tags['user_name'], wpublic=1) if len(r) > 0: admin = get_username() #get admin user set_current_user( tags['user_name'] ) #change document as user so that all changes are owned by the new user r = data_service.update_resource( '/data_service/%s' % r[0].attrib.get('resource_uniq'), new_resource=userxml) set_current_user(admin) #set back to admin user return self.get_user( '%s' % r.attrib.get('resource_uniq'), **kw) else: abort(400) abort(400)
def credentials(self, **kw): response = etree.Element('resource', type='credentials') username = identity.get_username() if username: etree.SubElement(response, 'tag', name='user', value=username) #OLD way of sending credential #if cred[1]: # etree.SubElement(response,'tag', name='pass', value=cred[1]) # etree.SubElement(response,'tag', # name="basic-authorization", # value=base64.encodestring("%s:%s" % cred)) #tg.response.content_type = "text/xml" return etree.tostring(response)
def setbasicauth(self, username, passwd, **kw): log.debug("Set basic auth %s", kw) if not identity.is_admin() and username != identity.get_username(): return "<error msg='failed: not allowed to change password of others' />" user = tg.request.identity.get('user') log.debug("Got user %s", user) if user and user.user_name == username: # sanity check user = DBSession.merge(user) user.password = passwd log.info("Setting new basicauth password for %s", username) #transaction.commit() return "<success/>" log.error("Could not set basicauth password for %s", username) return "<error msg='Failed to set password'/>"
def stats(self, **kw): log.info('stats %s' % kw) wpublic = kw.pop('wpublic', 0) anonymous = identity.anonymous() def usage_resource(): log.info("CALL EXPENSIVE") all_count = data_service.count("image", wpublic=wpublic, images2d=True, parent=False) image_count = data_service.count("image", wpublic=wpublic, permcheck=not anonymous) #images2d = data_service.count("image", wpublic=wpublic, images2d=True) tag_count = data_service.count("tag", wpublic=wpublic, permcheck=not anonymous, parent=False) gob_count = data_service.count("gobject", wpublic=wpublic, permcheck=not anonymous, parent=False) resource = etree.Element('resource', uri='/usage/stats') etree.SubElement(resource, 'tag', name='number_images', value=str(all_count)) etree.SubElement(resource, 'tag', name='number_images_user', value=str(image_count)) #etree.SubElement(resource, 'tag', name='number_images_planes', value=str(images2d)) etree.SubElement(resource, 'tag', name='number_tags', value=str(tag_count)) etree.SubElement(resource, 'tag', name='number_gobs', value=str(gob_count)) return etree.tostring(resource) usage_cache = cache.get_cache("usage") resource = usage_cache.get_value(key=identity.get_username(), createfunc=usage_resource, expiretime=3600) return resource
def _begin_mex_session(self): """Begin a mex associated with the visit to record changes""" # #log.debug('begin_session '+ str(tgidentity.current.visit_link )) #log.debug ( str(tgidentity.current.visit_link.users)) mex = module_service.begin_internal_mex() mex_uri = mex.get('uri') mex_uniq = mex.get('resource_uniq') session['mex_uniq'] = mex_uniq session['mex_uri'] = mex_uri session['mex_auth'] = "%s:%s" % (identity.get_username(), mex_uniq) log.info("MEX Session %s ( %s ) ", mex_uri, mex_uniq) #v = Visit.lookup_visit (tgidentity.current.visit_link.visit_key) #v.mexid = mexid #session.flush() return mex
def analysis_monthly(self, **kw): log.info('uploads %s' % kw) def fetch_counts(): return self.get_counts_month('mex', 13) usage_cache = cache.get_cache("analysis_monthly") counts, days = usage_cache.get_value(key=identity.get_username(), createfunc=fetch_counts, expiretime=3600) #counts, days = self.get_counts_month('mex', 13) resource = etree.Element('resource', uri='/usage/analysis_monthly') etree.SubElement(resource, 'tag', name='counts', value=','.join(counts)) etree.SubElement(resource, 'tag', name='days', value=','.join(days)) return etree.tostring(resource)
def uploads(self, **kw): log.info('uploads %s' % kw) def fetch_counts(): return self.get_counts('image', 31) usage_cache = cache.get_cache("uploads") counts, days = usage_cache.get_value(key=identity.get_username(), createfunc=fetch_counts, expiretime=600) resource = etree.Element('resource', uri='/usage/uploads') etree.SubElement(resource, 'tag', name='counts', value=','.join(counts)) etree.SubElement(resource, 'tag', name='days', value=','.join(days)) return etree.tostring(resource)
def savefile(self, **kw): log.info("savefile request " + str(tg.request)) username = get_username() # check the user identity here and return 401 if fails if anonymous(): response.status_int = 401 log.debug('Access denied') return 'Access denied' # if requested test for uploaded hashes_str = kw.pop('hashes', None) if hashes_str != None: all_hashes = [fhash.strip() for fhash in hashes_str.split(',')] #for fhash in hashes_str.split(','): # all_hashes.append( fhash ) #found_hashes = blob_service.files_exist(all_hashes) TODO found_hashes = [] found_html = ",".join([str(h) for h in found_hashes]) return "Found: " + found_html # here user is authenticated - upload if not 'upload' in kw: response.status_int = 501 return "No file to be uploaded..." upload = kw['upload'] uploadroot = config.get('bisque.image_service.upload_dir', data_path('uploads')) upload_dir = uploadroot + '/' + str(username) _mkdir(upload_dir) if not upload.filename: return 'No file sent...' #patch for no copy file uploads - check for regular file or file like object uploadpath = upload_dir + '/' + upload.filename #KGK: note upload.file.name is not available for some uploads (attached files) #abs_path_src = os.path.abspath(upload.file.name) #if os.path.isfile(abs_path_src): # shutil.move(abs_path_src, uploadpath) #else: with open(uploadpath, 'wb') as trg: shutil.copyfileobj(upload.file, trg) return 'Upload done for: ' + upload.filename
def local_dispatch(self, fullurl, body=None): path, params = urlparse.urlsplit(fullurl)[2:4] userId = identity.get_username() try: id = int(path.split('/')[-1]) except ValueError: id = None request = "%s?%s" % (path, params) data_token = self.server.srv.process(request, id, userId) if data_token.isHttpError(): log.debug('Response Code: ' + str(data_token.httpResponseCode)) raise RequestError(data_token.httpResponseCode) #second check if the output is TEXT/HTML/XML if data_token.isText(): return data_token.data if data_token.isFile(): fpath = data_token.data.split('/') fname = fpath[len(fpath) - 1] if data_token.hasFileName(): fname = data_token.outFileName print "has ", fname #Content-Disposition: attachment; filename=genome.jpeg; #if data_token.isImage(): # disposition = 'filename="%s"'%(fname) #else: # disposition = 'attachment; filename="%s"'%(fname) #cherrypy.response.headers["Content-Disposition"] = disposition # this header is cleared when the streaming is used #cherrypy.response.headers["Content-Length"] = 10*1024*1024 ofs = RenamableFile(data_token.data, 'rb') ofs.name = fname return ofs log.debug('Returning file: ' + str(fname))
def put_user(self, uniq, doc, **kw): """ update user @param: uniq - resource uniq for the user @param: doc - document in the format shown below document format: <user name="user" resource_uniq="00-1235218954"> <tag name="password" value="12345"/> or <tag name="password" value="******"/> <tag name="email" value="*****@*****.**"/> <tag name="display_name" value="user"/> </user> """ userxml = etree.fromstring(doc) required_tags = ['user_name', 'password', 'email', 'display_name'] tags = {} if userxml.tag == 'user': user_name = userxml.attrib.get('name') if user_name: #tags['user_name'] = user_name for t in userxml.xpath('tag'): tags[t.get('name')] = t.get('value') #if t.attrib['name'] == 'password' or t.attrib['name']=='email': if t.get('name') in REMOVE_TAGS: t.getparent().remove(t) #removes email and password if t.attrib['name'] == 'email': userxml.attrib['value'] = t.attrib.get( 'value') #set it as value of the user if all(k in tags for k in required_tags ): #checks to see if all required tags are present #update tg_user #tg_user = DBSession.query(User).filter(User.user_name == tags.get('user_name')).first() #tg_user = User.by_user_name(tags.get('user_name')) tg_user = User.by_user_name(user_name) if not tg_user: log.debug( 'No user was found with name of %s. Please check core tables?', user_name) abort(404) #reset values on tg user tg_user.email_address = tags.get("email", tg_user.email_address) if tags['password'] and tags['password'].count('*') != len( tags['password'] ): #no password and ***.. not allowed passwords tg_user.password = tags.get( "password", tg_user.password ) #just set it as itself if nothing is provided #else: # tags.pop("password", None) #remove the invalid password tg_user.display_name = tags.get("display_name", tg_user.display_name) self._update_groups(tg_user, tags.get('groups', '').split(',')) if tags.get('user_name') != user_name: tg_user.user_name = tags.get('user_name') userxml.set('name', tags['user_name']) #del tags['user_name'] log.debug("ADMIN: Updated user: %s", str(user_name)) transaction.commit() ### ALL loaded variables are detached #userxml.attrib['resource_uniq'] = r.attrib['resource_uniq'] #reset BQUser admin = get_username() #get admin user set_current_user( tags['user_name'] ) #change document as user so that all changes are owned by the new user r = data_service.update_resource(resource=userxml, new_resource=userxml, replace=True) log.debug("Sent XML %s", etree.tostring(userxml)) set_current_user(admin) #set back to admin user #DBSession.flush() return self.get_user(r.attrib['resource_uniq'], **kw) abort(400)
def notify(self, **kw): ''' DN upload request using HTTP uploads this function is only created temporaly to provide backward compatibility for DN provide http uploads, where directory is not specified by DN but is known by the server and thus should be ignored here ''' username = get_username() #log.debug( 'notify - username: '******'notify needs credentialed user') abort(401) log.debug('notify - args: ' + str(kw)) bixfiles = kw.pop('bixfiles', []) imagefiles = kw.pop('imagefiles', []) upload_dir = kw.pop('uploaddir', None) if (upload_dir == None): uploadroot = config.get('bisque.image_service.upload_dir', data_path('uploads')) upload_dir = os.path.join(uploadroot, username) #upload_dir = uploadroot+'/'+ str(identity.current.user_name) remove_uploads = config.get('bisque.image_service.remove_uploads', False) #identity.set_current_identity(ident) importer = BIXImporter(upload_dir) images = [] for bix in bixfiles.split(':'): if bix != None and bix != '': try: name, uri = importer.process_bix(bix) except Exception: name = '%s [error importing]' % (bix) uri = '#' if name != '' and uri != '': images.append((name, uri)) if remove_uploads: try: os.unlink(os.path.join(upload_dir, bix)) os.unlink(os.path.join(upload_dir, name)) except Exception: log.debug( 'Error removing temp BIX and/or Image files') imageshtml = "<table>" imageshtml += "".join([ '<tr><td><a href="%s">%s</a></td></tr>' % (self.imagelink(u), n) for n, u in images ]) imageshtml += '</table>' if len(bixfiles) < len(imagefiles): inputimages = imagefiles.split(':') for n, u in images: inputimages.remove(n) if remove_uploads: for name in inputimages: os.unlink(os.path.join(upload_dir, name)) imageshtml += '<h2>Uploaded but not included as images %d (no meta-data file):</h2>' % ( len(inputimages)) imageshtml += "<table>".join( ['<tr><td>%s</td></tr>' % (n) for n in inputimages]) imageshtml += '</table>' return '<h2>Uploaded %d images:</h2>' % (len(images)) + imageshtml