Beispiel #1
0
def addSuperUser(userInfo={}):
    if not all(
        userInfo,
        'username' in userInfo,
        userInfo['username']
    ):
        userInfo = getUserInfoFromPrompt()
    xml = read_file('admin.xml')
    xml = xml.replace('%USERNAME%', userInfo.pop('username'))
    for k, v in userInfo.iteritems():
        placeholder = "%{0}%".format(k)
        if v and len(v):
            xml = xml.replace(placeholder, '\n  <{0}>{1}</{0}>'.format(k, v))
        else:
            xml = xml.replace(placeholder, '')
    doc = StringDocument(xml)
    rec = xmlp.process_document(session, doc)
    id = rec.process_xpath(session, '/config/@id')[0]
    rec.id = id
    superAuthStore.store_record(session, rec)
    superAuthStore.commit_storing(session)
    # Confirm user stored
    try:
        user = superAuthStore.fetch_object(session, id)
    except c3errors.ObjectDoesNotExistException:
        raise DatabaseOperationError(
            'User not successfully created. Please try again.'
        )
    print 'OK: Username and passwords set for this user'
    return 0
 def show_adminMenu(self, values=None, message=''):
     page = read_file('adminmenu.html')
     if values is None:
         values = {'%USERNAME%' :  '',
                   '%FULLNAME%' : '',
                   '%EMAIL%' : '',
                   '%TELEPHONE%' : '',
                   '%USER%' :'',
                   '%SUPERUSER%' : 'checked="checked"'
                   }
     page = page.replace('%MESSAGE%', message)
     page = page.replace('%INSTSELECT%', self.create_select())
     page = page.replace('%INSTUSERLIST%', self.list_usersByInst())
     page = page.replace('%INSTSELECTOPTIONS%', self.get_institutions())
     page = page.replace('%DOCSTORESELECT%', self.get_docStoreSelect())
     page = multiReplace(page, values)
     return page
 def delete_user(self, form):
     global userStore, rebuild
     userid = form.get('user', None)
     cancel = form.get('cancel', None)
     confirm = form.get('confirm', None)
     passwd = form.get('passwd', None)
     if (confirm == 'true'):
         output = [
             '<div id="single"><h3 class="bar">Delete User Confirmation.'
             '</h3>',
             read_file('deleteuser.html').replace('%USERID%', userid),
             '</div>'
         ]
         return ''.join(output)
     elif (cancel == 'Cancel'):
         return self.show_adminMenu(
             None,
             '<p class="error">Delete cancelled at your request.</p>'
         )
     else:
         if (passwd and session.user.check_password(session, passwd)):
             try:
                 userStore.delete_record(session, userid)
             except:
                 return self.show_adminMenu(
                     None,
                     '<p class="error">Unable to delete user {0} - '
                     'user does not exist.</p>'.format(userid)
                 )
             else:
                 rebuild = True
                 return self.show_adminMenu(
                     None,
                     '<p class="ok">User {0} Deleted.</p>'.format(userid)
                 )
         else:
             return self.show_adminMenu(
                 None,
                 '<p class="error">Unable to delete user {0} - '
                 'incorrect password.</p>'
                 ''.format(userid)
             )
 def handle(self, req):
     form = FieldStorage(req, True)
     tmpl = unicode(read_file(self.baseTemplatePath))
     title = ' :: '.join(self.htmlTitle)
     navbar = ' '.join(self.htmlNav)
     replaceAll = {
         "%TITLE%": title,
         "%NAVBAR%": navbar,
         "%USERNAME%": session.user.username,
         "%REALNAME%": session.user.realName
     }
     tmpl = multiReplace(tmpl, replaceAll)
     path = req.uri[1:]
     path = path[path.rfind('/') + 1:]
     content = None
     operation = form.get('operation', None)
     if path.endswith('.js'):
         self.send_response(read_file(abspath('../js/{0}'.format(path))),
                            req,
                            content_type='text/javascript',
                            code=200
                            )
         return apache.OK
     elif path == 'users.html':
         if (operation):
             if (operation == 'findcontacts'):
                 content = self.get_contactDetails(form)
                 self.send_xml(content, req)
                 return
             else:
                 if (operation == 'adduser'):
                     content = self.add_user(form)
                 elif (operation == 'addinstitution'):
                     content = self.add_inst(form)
                 elif (operation == 'editinstitution'):
                     content = self.edit_inst(form)
                 elif (operation == 'deleteinst'):
                     content = self.delete_inst(form)
                 elif (operation == 'deleteuser'):
                     content = self.delete_user(form)
                 elif operation in ['edit', 'edituser']:
                     content = self.edit_user(form)
                 else:
                     content = self.show_adminMenu()
         else:
             content = self.show_adminMenu()
     elif path == 'admin':
         # redirect to make sure later relative links work correctly
         redirect(req, 'admin/',
                  permanent=False, # TODO: make me True
                  text=("To prevent URL collisions caused by internal "
                        "relative, this service must be accessed at "
                        "admin/"
                        )
                  )
         return
     else:
         content = self.show_adminMenu()
     content = tmpl.replace('%CONTENT%', content)
     # send the display
     self.send_html(content, req)
    def delete_inst(self, form):
        global instStore, rebuild
        instid = form.get('inst', None)
        cancel = form.get('cancel', None)
        confirm = form.get('confirm', None)
        passwd = form.get('passwd', None)
        #check again to see that this inst has no users.
        sqlQ = ("SELECT hubAuthStore FROM hubAuthStore_linkauthinst WHERE "
                "institutionid=%s"
                )
        result = userStore._query(sqlQ, (instid,))
        if len(result):
            return self.show_adminMenu(
                None,
                '<p class="error">Unable to delete institution - '
                'there are still {0} users in this institution which must be '
                'deleted first.</p>'.format(len(result))
            )

        if (confirm == 'true'):
            sqlQ = ("SELECT editingstore FROM editingstore_linkrecinst WHERE "
                    "institutionid=%s"
                    )
            result = userStore._query(sqlQ, (instid,))
            if len(result):
                fileinfo = ('<b>This institution still has draft files '
                            'linked to it - if you delete this institution '
                            'the draft files linked to it will also be '
                            'deleted</b>'
                            )
                output = ['<div id="single"><h3 class="bar">Delete '
                          'Institution Confirmation.</h3>',
                          multiReplace(read_file('deleteinst.html'),
                                       dict(['%INSTID%', instid,
                                             '%%%FILEINFO%%%', fileinfo
                                             ])
                          ),
                          '</div>'
                          ]
            else:
                output = ['<div id="single">',
                          '<h3 class="bar">',
                          'Delete Institution Confirmation.',
                          '</h3>',
                          multiReplace(read_file('deleteinst.html'),
                                       dict([('%INSTID%', instid),
                                             ('%%%FILEINFO%%%', '')
                                             ])
                                       ),
                          '</div>'
                          ]
            return ''.join(output)
        elif (cancel == 'Cancel'):
            return self.show_adminMenu()
        else:
            if (passwd and session.user.check_password(session, passwd)):
                try:
                    instStore.delete_record(session, instid)
                except:
                    return self.show_adminMenu(
                        None,
                        '<p class="error">Unable to delete institution - '
                        'user does not exist.</p>'
                    )
                else:
                    sqlQ = ("SELECT editingstore FROM "
                            "editingstore_linkrecinst WHERE institutionid=%s"
                            )
                    result = userStore._query(sqlQ, (instid,))
                    for r in result:
                        recid = r['editingstore']
                        try:
                            editStore.delete_record(session, recid)
                        except:
                            pass
                    rebuild = True
                    return self.show_adminMenu()
            else :
                return self.show_adminMenu(
                    None,
                    '<p class="error">Unable to delete institution - '
                    'incorrect password.</p>'
                )
 def show_userEdit(self, values, message=''):
     page = read_file('users.html')
     values['%message%'] = message
     return multiReplace(page, values)
Beispiel #7
0
def cache_html():
    fullTxr = db.get_object(session, 'htmlFullTxr')
    fullSplitTxr = db.get_object(session, 'htmlFullSplitTxr')
    idList = recordStore.fetch_idList(session)
    total = len(idList)
    print "Caching HTML for %d records..." % (total)
    for rec in recordStore:
        recid = rec.id
        print rec.id.ljust(50),
        # FIXME: rec.size is always 0
        # small record assumed to be < 100kb ...
#        if (rec.size * 6 < (100 * 1024)):
#            print '[Build at access time - record is really small (approx %d kb)]' % (rec.size*6)
#            continue
        paramDict = {
                'RECID': recid,
                'TOC_CACHE_URL': toc_cache_url,
                '%REP_NAME%':repository_name, 
                '%REP_LINK%':repository_link,
                '%REP_LOGO%':repository_logo, 
                '%TITLE%': 'Display in Full',
                '%NAVBAR%': '',
                'SCRIPT':script
        }
    
        path = '%s/%s-1.shtml' % (cache_path, recid)
        rec = recordStore.fetch_record(session, recid)
        
        tmpl = read_file(templatePath)
        anchorPageHash = {}
        if (len(rec.get_xml(session)) < maximum_page_size * 1024):
            # Oh good. Nice and short record - do it the easy way
            doc = fullTxr.process_record(session, rec)
            # open, read, delete tocfile NOW to avoid overwriting screwups
            try:
                tocfile = read_file(os.path.join(toc_cache_path, 'foo.bar'))
                os.remove(os.path.join(toc_cache_path, 'foo.bar'))
                tocfile = tocfile.replace('RECID', recid)
            except:
                pass
                    
            doc = doc.get_raw(session)
            try: doc = doc.encode('utf-8', 'latin-1')
            except: pass # hope for the best!
            page = tmpl.replace('%CONTENT%', doc)
            for k, v in paramDict.iteritems():
                page = page.replace(k, v)
                
            write_file(path, page)
            print '\t[OK]'
        else:
            # Long record - have to do splitting, link resolving etc.
            doc = fullSplitTxr.process_record(session, rec)
            # open, read, and delete tocfile NOW to avoid overwriting screwups
            try:
                tocfile = read_file(os.path.join(toc_cache_path, 'foo.bar'))
                os.remove(os.path.join(toc_cache_path, 'foo.bar'))
                tocfile = tocfile.replace('RECID', recid)
            except:
                pass
                    
            doc = doc.get_raw(session)
            try: doc = doc.encode('utf-8', 'latin-1')
            except: pass # hope for the best!
            # before we split need to find all internal anchors
            anchor_re = re.compile('<a .*?name="(.*?)".*?>')
            anchors = anchor_re.findall(doc)
            pseudopages = doc.split('<p style="page-break-before: always"/>')
            pages = []
            while pseudopages:
                page = '<div id="padder"><div id="rightcol" class="ead"><div class="pagenav">%PAGENAV%</div>'
                while (len(page) < maximum_page_size * 1024):
                    page = page + pseudopages.pop(0)
                    if not pseudopages:
                        break
                        
                # append: pagenav, end rightcol div, end padder div, left div (containing toc)
                page = page + '<div class="pagenav">%PAGENAV%</div>\n</div>\n</div>\n<div id="leftcol" class="toc"><!--#include virtual="/ead/tocs/RECID.inc"--></div>'
                pages.append(page)
                
            start = 0
            for a in anchors:
                for x in range(start, len(pages)):
                    if (pages[x].find('name="%s"' % a) > -1):
                        anchorPageHash[a] = x + 1
                        start = x                                       # next anchor must be on this page or later
                        
            for x in range(len(pages)):
                doc = pages[x]
                # now we know how many real pages there are, generate some page navigation links
                pagenav = ['<div class="backlinks">']
                if (x > 0):
                    pagenav.extend(['<a href="%s/%s-1.shtml" title="First page" onclick="setCookie(\'%s-tocstate\', stateToString(\'someId\'))"><img src="/images/fback.gif" alt="First"/></a>' % (cache_url, recid, recid),
                                    '<a href="%s/%s-%d.shtml" title="Previous page" onclick="setCookie(\'%s-tocstate\', stateToString(\'someId\'))"><img src="/images/back.gif" alt="Previous"/></a>' % (cache_url, recid, x, recid)])
                pagenav.extend(['</div>', '<div class="forwardlinks">'])
                if (x < len(pages)-1):
                    pagenav.extend(['<a href="%s/%s-%d.shtml" title="Next page" onclick="setCookie(\'%s-tocstate\', stateToString(\'someId\'))"><img src="/images/forward.gif" alt="Next"/></a>' % (cache_url, recid, x+2, recid),
                                    '<a href="%s/%s-%d.shtml" title="Final page" onclick="setCookie(\'%s-tocstate\', stateToString(\'someId\'))"><img src="/images/fforward.gif" alt="Final"/></a>' % (cache_url, recid, len(pages), recid)
                                  ])
                pagenav.append('</div><div class="numnav">')
                for y in range(len(pages)):
                    if (y == x):
                        pagenav.append('<strong>%d</strong>' % (y+1))
                    else:
                        pagenav.append('<a href="%s/%s-%d.shtml" title="Page %d" onclick="setCookie(\'%s-tocstate\', stateToString(\'someId\'))">%d</a>' % (cache_url, recid, y+1, y+1, recid, y+1))
                pagenav.append('</div>')

                # now stick the page together and send it back
                pagex = tmpl.replace('%CONTENT%', doc)
                pagex = pagex.replace('%PAGENAV%', '\n'.join(pagenav))

                #resolve internal ref links
                for k, v in anchorPageHash.iteritems():
                    pagex = pagex.replace('PAGE#%s"' % k, '%s/RECID-%d.shtml#%s"' % (cache_url, v, k))

                # any remaining links were not anchored - encoders fault :( - hope they're on page 1
                pagex = pagex.replace('PAGE#', '%s/RECID-1.shtml#' % cache_url)
                        
                for k, v in paramDict.iteritems():
                    pagex = pagex.replace(k, v)
                            
                write_file('%s/%s-%d.shtml' % (cache_path, recid, x+1), pagex)
            print '\t[OK - %d pages]' % len(pages)
            
        try:
            if anchorPageHash:
                for k, v in anchorPageHash.iteritems():
                    tocfile = tocfile.replace('PAGE#%s"' % k, '%s/%s-%d.shtml#%s"' % (cache_url, recid, v, k))

                # any remaining links were not anchored - encoders fault :( - hope they're on page 1
                tocfile = tocfile.replace('PAGE#', '%s/%s-1.shtml#' % (cache_url, recid))
            else:
                # must all be on 1 page
                tocfile = tocfile.replace('PAGE#', '%s/%s-1.shtml#' % (cache_url, recid))

            write_file(os.path.join(toc_cache_path, recid +'.inc'), tocfile)
            os.chmod(os.path.join(toc_cach_path, recid + '.inc'), 0755)
                    
        except:
            pass
Beispiel #8
0
def inputError(msg):
    lgr.log_error(session, msg)
    sys.exit()


if ('-adduser' in sys.argv):
    un = raw_input('Please enter a username: '******'You must enter a username for this user.')
    pw = getpass.getpass('Please enter a password for this user: '******'You must enter a password for this user.')
    pw2 = getpass.getpass('Please re-enter the password to confirm: ')
    if pw != pw2: inputError('The two passwords submitted did not match. Please try again.')
    rn = raw_input('Real name of this user (not mandatory): ')
    addy = raw_input('Email address for this user (not mandatory): ')
    xml = read_file('admin.xml').replace('%USERNAME%', un)
    for k,v in {'%password%': crypt(pw, pw[:2]), '%realName%': rn, '%email%': addy}.iteritems():
        if v and len(v):
            xml = xml.replace(k, '\n  <%s>%s</%s>' % (k[1:-1],v,k[1:-1]))
        else:
            xml = xml.replace(k, '')
    doc = StringDocument(xml)
    rec = xmlp.process_document(session, doc)
    id = rec.process_xpath(session, '/config/@id')[0]
    rec.id = id
    authStore.store_record(session, rec)
    authStore.commit_storing(session)
    try:
        user = authStore.fetch_object(session, id)
    except c3errors.FileDoesNotExistException:
        print 'ERROR: User not successfully created. Please try again.'