def addUser(self, user):
     if user.externalId() is None:
         user.setExternalId(uniqueId(user))
     self._store.addObject(user)
     if self._saveNewUsers:
         self._store.saveChanges()
     UserManager.addUser(self, user)
Example #2
0
    def testUniqueId(self):
        past = set()

        def checkId(i):
            self.assertIsInstance(i, str, type(i))
            self.assertEqual(len(i), 32)
            for c in i:
                self.assertTrue(c in '0123456789abcdef')
            self.assertFalse(i in past)
            past.add(i)

        for n in range(10):
            checkId(uniqueId())
            checkId(uniqueId(None))
            checkId(uniqueId(n))
            checkId(uniqueId(forObject=checkId))
Example #3
0
 def addUser(self, user):
     if user.externalId() is None:
         user.setExternalId(uniqueId(user))
     self._store.addObject(user)
     if self._saveNewUsers:
         self._store.saveChanges()
     UserManager.addUser(self, user)
Example #4
0
    def __init__(self, trans, identifier=None):
        self._lastAccessTime = self._creationTime = time()
        self._isExpired = self._dirty = False
        self._numTrans = 0
        self._values = {}
        app = trans.application()
        self._timeout = app.sessionTimeout(trans)
        self._prefix = app.sessionPrefix(trans)
        self._sessionName = app.sessionName(trans)

        if identifier:
            if re.search(r'[^\w\.\-]', identifier) is not None:
                raise SessionError("Illegal characters in session identifier")
            if len(identifier) > 80:
                raise SessionError("Session identifier too long")
            self._identifier = identifier
        else:
            attempts = 0
            while attempts < 10000:
                self._identifier = self._prefix + (
                    '{:02d}{:02d}{:02d}{:02d}{:02d}{:02d}').format(
                        *localtime()[:6]) + '-' + uniqueId(self)
                if not app.hasSession(self._identifier):
                    break
                attempts += 1
            else:
                raise SessionError(
                    "Can't create valid session id"
                    f" after {attempts} attempts.")

        if app.setting('Debug')['Sessions']:
            print('>> [session] Created session, timeout =', self._timeout,
                  'id =', self._identifier, 'self =', self)
Example #5
0
    def __init__(self, trans):
        Object.__init__(self)
        self._lastAccessTime = self._creationTime = time()
        self._isExpired = 0
        self._numTrans = 0
        self._values = {}
        self._timeout = trans.application().setting('SessionTimeout') * 60
        sessionPrefix = trans.application().setting('SessionPrefix', None)
        if sessionPrefix == 'hostname':
            self._prefix = _hostname + '-'
        elif sessionPrefix is None:
            self._prefix = ''
        else:
            self._prefix = sessionPrefix + '-'

        attempts = 0
        while attempts < 10000:
            self._identifier = self._prefix + string.join(
                map(lambda x: '%02d' % x,
                    localtime(time())[:6]), '') + '-' + uniqueId(self)
            if not trans.application().hasSession(self._identifier):
                break
            attempts = attempts + 1
        else:
            raise SessionError, "Can't create valid session id after %d attempts." % attempts
        if trans.application().setting('Debug')['Sessions']:
            print '>> [session] Created session, timeout=%s, id=%s, self=%s' % (
                self._timeout, self._identifier, self)
Example #6
0
    def __init__(self, trans, identifier=None):
        self._lastAccessTime = self._creationTime = time()
        self._isExpired = self._dirty = False
        self._numTrans = 0
        self._values = {}
        app = trans.application()
        self._timeout = app.sessionTimeout(trans)
        self._prefix = app.sessionPrefix(trans)
        self._sessionName = app.sessionName(trans)

        if identifier:
            if re.search(r'[^\w\.\-]', identifier) is not None:
                raise SessionError("Illegal characters in session identifier")
            if len(identifier) > 80:
                raise SessionError("Session identifier too long")
            self._identifier = identifier
        else:
            attempts = 0
            while attempts < 10000:
                self._identifier = self._prefix + ''.join(
                    map(lambda x: '%02d' % x,
                        localtime()[:6])) + '-' + uniqueId(self)
                if not app.hasSession(self._identifier):
                    break
                attempts += 1
            else:
                raise SessionError(
                    "Can't create valid session id after %d attempts." %
                    attempts)

        if app.setting('Debug')['Sessions']:
            print('>> [session] Created session, '
                  'timeout = %s, id = %s, self = %s' %
                  (self._timeout, self._identifier, self))
Example #7
0
    def __init__(self, trans, identifier=None):
        self._lastAccessTime = self._creationTime = time()
        self._isExpired = self._dirty = False
        self._numTrans = 0
        self._values = {}
        app = trans.application()
        self._timeout = app.sessionTimeout(trans)
        self._prefix = app.sessionPrefix(trans)
        self._sessionName = app.sessionName(trans)

        if identifier:
            if re.search(r'[^\w\.\-]', identifier) is not None:
                raise SessionError("Illegal characters in session identifier")
            if len(identifier) > 80:
                raise SessionError("Session identifier too long")
            self._identifier = identifier
        else:
            attempts = 0
            while attempts < 10000:
                self._identifier = self._prefix + ''.join(
                    map(lambda x: '%02d' % x,
                        localtime()[:6])) + '-' + uniqueId(self)
                if not app.hasSession(self._identifier):
                    break
                attempts += 1
            else:
                raise SessionError(
                    "Can't create valid session id after %d attempts." % attempts)

        if app.setting('Debug')['Sessions']:
            print ('>> [session] Created session, '
                'timeout = %s, id = %s, self = %s'
                % (self._timeout, self._identifier, self))
Example #8
0
    def writeCenter(self):
        if self.getUser() and not self.request().hasField("extra"):
            self.writeln('<div align="center"><b>Du er allerede innlogget.')
            return
        self.writeln(
            '<p align="center"><table border="0" cellpadding="20" cellspacing="20" width="300">'
        )

        # Create a "unique" login id and put it in the form as well as in the session.
        # Login will only be allowed if they match.
        loginid = uniqueId(self)
        self.session().setValue('loginid', loginid)

        action = self.request().field('action', '')
        if action:
            action = 'action="%s"' % action
        else:
            action = 'action="Index"'

        self.writeln('<tr><td><form method="post" name="loginform" %s>' %
                     action)
        self.write(
            '<table border="0" cellpadding="3" cellspacing="0" class="shade">')
        extra = self.request().field('extra', None)
        if not extra and self.request().isSessionExpired(
        ) and not self.request().hasField('logout'):
            extra = 'Du har automatisk blitt logget ut p.g.a. inaktivitet.'
        if extra:
            self.write(
                '<tr><td align="left" class="error" colspan="2">%s</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>'
                % self.htmlEncode(extra))
        self.writeln('''
                <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr>
                <td align="right">Brukernavn</td>
                <td><input type="TEXT" name="username"></td>
                </tr>
                <tr>
                <td align="right">Passord</td>
                <td><input type="PASSWORD" name="password"></td>
                </tr>
                <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="login" value="Login"></td>
                </tr>
                <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr><td><input type="hidden" name="loginid" value="%s">&nbsp;</td><td>&nbsp;</td></tr>
             </table>
            </form>
           </td>
           ''' % loginid)
        self.writeln('</td></tr></table>')
Example #9
0
 def externalId(self):
     if self._externalId is None:
         from time import localtime, time
         attempts = 0
         while attempts < 10000:
             self._externalId = uniqueId(self)
             # @@ 2001-02-17 ce: check that manager doesn't already have this
             # if mgr.userForExternalId(self._externalId, None) is None:
             #	break
             break
             attempts += 1
         else:
             raise Exception, "Can't create valid external id after %i attempts." % attempts
     return self._externalId
Example #10
0
	def writeContent(self):

		# Any messages to display ? 		

		extra = self.request().field('extra', None)
		
		if not extra and self.request().isSessionExpired() and not self.request().hasField('logout'):
			extra = 'You have been automatically logged out due to inactivity.'
		
		if extra:
			LapWeb.messageBox(self, self.htmlEncode(extra))
			self.writeln("<br>")
			self.writeln("<br>")

		# Create unique loginid			
		
		loginid = uniqueId(self)
		self.session().setValue('loginid', loginid)

		action = self.request().field('action', '')
		
		print "LoginPage " + action

		# Create login form		

		print "Creating login form"
		form = LapWeb.Form(self, "loginform", action, "Login")

#		form.addFile("Proxy file", "proxy")
		form.addText("Username", "name")
		form.addPassword("Password", "password")
		form.addHidden("", "loginid", loginid)
		form.setAction(action)
		form.setSubmitButton("login", "Login")

		# Forward any passed in values to the user's intended page after successful login,
		# except for the special values used by the login mechanism itself
		
		for name, value in self.request().fields().items():
			if name not in 'login loginid proxy extra logout name password'.split():
				if isinstance(value, types.ListType):
					for valueStr in value:
						form.addHidden("", name, valueStr)
				else:
					form.addHidden("", name, value)

		print "Rendering login form"

		form.render()
Example #11
0
    def writeContent(self):
        self.writeln(
            '<div style="margin-left:auto;margin-right:auto;width:20em">'
            '<p>&nbsp;</p>')
        request = self.request()
        extra = request.field('extra', None)
        if not extra and request.isSessionExpired(
        ) and not request.hasField('logout'):
            extra = 'You have been automatically logged out due to inactivity.'
        if extra:
            self.writeln('<p style="color:#333399">%s</p>' %
                         self.htmlEncode(extra))
        if self.session().hasValue('loginid'):
            loginid = self.session().value('loginid')
        else:
            # Create a "unique" login id and put it in the form as well as in the session.
            # Login will only be allowed if they match.
            loginid = uniqueId(self)
            self.session().setValue('loginid', loginid)

        action = request.field('action', '')
        if action:
            action = ' action="%s"' % action
        self.writeln('''<p>Please log in</p>
                                <form method="post" name="loginform"%s>
                                <table cellpadding="4" cellspacing="4"
                                style="background-color:#CCCCEE;border:1px solid #3333CC;width:20em">
                                <tr><td align="right"><label for="username">Username:</label></td>
                                <td><input type="text" name="username" value=""></td></tr>
                                <tr><td align="right"><label for="password">Password:</label></td>
                                <td><input type="password" name="password" value=""></td></tr>
                                <tr><td colspan="2" align="right"><input type="submit" name="login" value="Login"></td></tr>
                                </table>
                                <input type="hidden" name="loginid" value="%s">'''
                     % (action, loginid))
        # Forward any passed in values to the user's intended page after successful login,
        # except for the special values used by the login mechanism itself
        for name, value in request.fields().items():
            if name not in ('login', 'loginid', 'username', 'password',
                            'extra', 'logout'):
                if type(value) != type([]):
                    value = [value]
                for v in value:
                    self.writeln(
                        '''<input type="hidden" name="%s" value="%s">''' %
                        (self.htmlEncode(name), self.htmlEncode(v)))
        self.writeln('</form>\n<p>&nbsp;</p></div>')
Example #12
0
    def writeContent(self):
        self.writeln(
            '<div style="margin-left:auto;margin-right:auto;width:20em">'
            '<p>&nbsp;</p>')
        request = self.request()
        extra = request.field('extra', None)
        if (not extra and request.isSessionExpired()
                and not request.hasField('logout')):
            extra = 'You have been automatically logged out due to inactivity.'
        if extra:
            self.writeln(
                f'<p style="color:#339">{self.htmlEncode(extra)}</p>')
        if self.session().hasValue('loginId'):
            loginId = self.session().value('loginId')
        else:
            # Create a "unique" login id and put it in the form as well as
            # in the session. Login will only be allowed if they match.
            loginId = uniqueId(self)
            self.session().setValue('loginId', loginId)
        action = request.field('action', '')
        if action:
            action = f' action="{action}"'
        self.writeln(f'''<p>Please log in to view the example.
The username and password is <kbd>alice</kbd> or <kbd>bob</kbd>.</p>
<form method="post" id="loginForm"{action}>
<table style="background-color:#cce;border:1px solid #33c;width:20em">
<tr><td style="text-align:right"><label for="username">Username:</label></td>
<td><input type="text" id="username" name="username" value="admin"></td></tr>
<tr><td style="text-align:right"><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password" value=""></td></tr>
<tr><td colspan="2" style="text-align:right">
<input type="submit" name="login" value="Login"></td></tr>
</table>
<input type="hidden" name="loginId" value="{loginId}">''')
        # Forward any passed in values to the user's intended page
        # after successful login, except for the special values
        # used by the login mechanism itself:
        enc = self.htmlEncode
        for name, value in request.fields().items():
            if name not in ('login', 'logout', 'loginId',
                            'username', 'password', 'extra'):
                if not isinstance(value, list):
                    value = [value]
                for v in value:
                    self.writeln('<input type="hidden"'
                                 f' name="{enc(name)}" value="{enc(v)}">')
        self.writeln('</form>\n<p>&nbsp;</p></div>')
Example #13
0
    def writeCenter(self):
        if self.getUser() and not self.request().hasField("extra"):
            self.writeln('<div align="center"><b>Du er allerede innlogget.')
            return
        self.writeln('<p align="center"><table border="0" cellpadding="20" cellspacing="20" width="300">')

        # Create a "unique" login id and put it in the form as well as in the session.
        # Login will only be allowed if they match.
        loginid = uniqueId(self)
        self.session().setValue('loginid', loginid)

        action = self.request().field('action', '')
        if action:
            action = 'action="%s"' % action
        else:
            action = 'action="Index"'


        self.writeln('<tr><td><form method="post" name="loginform" %s>' % action)
        self.write('<table border="0" cellpadding="3" cellspacing="0" class="shade">')
        extra = self.request().field('extra', None)
        if not extra and self.request().isSessionExpired() and not self.request().hasField('logout'):
            extra = 'Du har automatisk blitt logget ut p.g.a. inaktivitet.'
        if extra:
            self.write('<tr><td align="left" class="error" colspan="2">%s</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>' % self.htmlEncode(extra))
        self.writeln('''
                <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr>
                <td align="right">Brukernavn</td>
                <td><input type="TEXT" name="username"></td>
                </tr>
                <tr>
                <td align="right">Passord</td>
                <td><input type="PASSWORD" name="password"></td>
                </tr>
                <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="login" value="Login"></td>
                </tr>
                <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr><td><input type="hidden" name="loginid" value="%s">&nbsp;</td><td>&nbsp;</td></tr>
             </table>
            </form>
           </td>
           ''' % loginid)
        self.writeln('</td></tr></table>')
Example #14
0
    def writeContent(self):
        self.writeln('<div style="margin-left:auto;margin-right:auto;width:20em">'
            '<p>&nbsp;</p>')
        request = self.request()
        extra = request.field('extra', None)
        if not extra and request.isSessionExpired() and not request.hasField('logout'):
            extra = 'You have been automatically logged out due to inactivity.'
        if extra:
            self.writeln('<p style="color:#333399">%s</p>' % self.htmlEncode(extra))
        if self.session().hasValue('loginid'):
            loginid = self.session().value('loginid')
        else:
            # Create a "unique" login id and put it in the form as well as in the session.
            # Login will only be allowed if they match.
            loginid = uniqueId(self)
            self.session().setValue('loginid', loginid)
        action = request.field('action', '')
        if action:
            action = ' action="%s"' % action
        self.writeln('''<p>Please log in to view the example.
The username and password is <tt>alice</tt> or <tt>bob</tt>.</p>
<form method="post" name="loginform"%s>
<table cellpadding="4" cellspacing="4"
style="background-color:#CCCCEE;border:1px solid #3333CC;width:20em">
<tr><td align="right"><label for="username">Username:</label></td>
<td><input type="text" id="username" name="username" value="admin"></td></tr>
<tr><td align="right"><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password" value=""></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="login" value="Login"></td></tr>
</table>
<input type="hidden" name="loginid" value="%s">''' % (action, loginid))
        # Forward any passed in values to the user's intended page after successful login,
        # except for the special values used by the login mechanism itself
        for name, value in request.fields().items():
            if name not in ('login', 'loginid', 'username', 'password', 'extra', 'logout'):
                if not isinstance(value, list):
                    value = [value]
                for v in value:
                    self.writeln('''<input type="hidden" name="%s" value="%s">'''
                        % (self.htmlEncode(name), self.htmlEncode(v)))
        self.writeln('</form>\n<p>&nbsp;</p></div>')
Example #15
0
    def externalId(self):
        if self._externalId is None:
            from time import localtime, time

            self._externalId = uniqueId(self)
        return self._externalId
Example #16
0
 def externalId(self):
     if self._externalId is None:
         self._externalId = uniqueId(self)
     return self._externalId
	def writeContent(self):
		self.write('''
<center>
	<table border="0" cellpadding="0" cellspacing="0" bgcolor="#ffffff" width="300">
''')

		extra = self.request().field('extra', None)
		if not extra and self.request().isSessionExpired() and not self.request().hasField('logout'):
			extra = 'You have been automatically logged out due to inactivity.'
		if extra:
			self.write('<tr><td align="left">%s</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>' % self.htmlEncode(extra))
		
		# Create a "unique" login id and put it in the form as well as in the session.
		# Login will only be allowed if they match.
		loginid = uniqueId(self)
		self.session().setValue('loginid', loginid)

		action = self.request().field('action', '')
		if action:
			action = 'action="%s"' % action

		self.write('''
		<tr>
			<td align="left">Please log in (use Alice or Bob as the username and password):</td>
		</tr>
		<tr>
			<td>
				<form method="post" name="loginform" %s>
					<table border="0" width="100%%" cellpadding="3" cellspacing="0" bgcolor="#cecece" align="left">
						<tr><td>&nbsp;</td><td>&nbsp;</td></tr>
						<tr>
							<td align="right">Username</td>
							<td><input type="TEXT" name="username"></td>
						</tr>
						<tr>
							<td align="right">Password</td>
							<td><input type="PASSWORD" name="password"></td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td><input type="submit" name="login" value="Login"></td>
						</tr>
						<tr><td>&nbsp;</td><td>&nbsp;</td></tr>
					</table>
					<input type="hidden" name="loginid" value="%s">''' % (action, loginid))

		# Forward any passed in values to the user's intended page after successful login,
		# except for the special values used by the login mechanism itself
		for name, value in self.request().fields().items():
			if name not in 'login loginid username password extra logout'.split():
				if isinstance(value, types.ListType):
					for valueStr in value:
						self.write('''<input type="hidden" name="%s" value="%s">'''
								   % (self.htmlEncode(name), self.htmlEncode(valueStr)))
				else:
					self.write('''<input type="hidden" name="%s" value="%s">'''
							   % (self.htmlEncode(name), self.htmlEncode(value)))
		self.write('''
				</form>
			</td>
		</tr>
	</table>
</center>
''')
Example #18
0
 def writeContent(self, trans=None):
   #
   # read in database
   #
   globalSetVars = self._globalSetVars
   store = globalSetVars['store']
   priceObjects = store.fetchObjectsOfClass(priceStore)
   prices = {}
   for x in priceObjects:
     a = x.allAttrs(0)
     prices[a['BKZ']] = a
   taid = self.getSite() + DateTime.now().strftime("%Y%m%d%H%M%S") + uniqueId(self)[:4]
   if tableStore != '':
     date = DateTime.DateTimeFrom(self.transaction.request().field('date',''))
     notice = self.transaction.request().field('notice','')
     bookdate = DateTime.DateTimeFrom(self.transaction.request().field('bookdate',''))
     #
     # read all objects from database
     #
     storeObjects = store.fetchObjectsOfClass(tableStore,'WHERE ID like "%%0"')
     for entry in storeObjects:
       attrs = entry.allAttrs(0)
       for y in range(Anzahl_Beitragsarten):
         #
         # Aufnahmegebuehr kalkulieren
         #
         if (attrs['Beitragsart'+str(y+1)] != '') \
             and (attrs['BeitragsartErhebungAb'+str(y+1)] == attrs['Eintrittsdatum']) \
             and not (attrs['BeitragsartFreiAb'+str(y+1)] and (attrs['BeitragsartFreiAb'+str(y+1)] <= attrs['Eintrittsdatum'])) \
             and (attrs['BeitragsartErhebungAb'+str(y+1)] < date):
           price = prices['11' + attrs['Beitragsart'+str(y+1)][2:]]
           if attrs['BeitragsartErhebungAb'+str(y+1)] >= price['Ab']:
             price_haben = price['AbHaben']
             price_soll = price['AbSoll']
           else:
             price_haben = price['Haben']
             price_soll = price['Soll']
           transfer = Transfers()
           transfer.setTAID(taid)
           transfer.setTransferID(attrs['ID'] + "_" + price['BKZ'])
           transfer.setWho(attrs['Nachname'] + ', ' + attrs['Vorname'])
           transfer.setImportWho(attrs['Nachname'] + ', ' + attrs['Vorname'])
           transfer.setBeschreibung(price['Beschreibung'])
           transfer.setImportBeschreibung(price['Beschreibung'])
           transfer.setHaben(price_haben)
           transfer.setSoll(price_soll)
           if attrs['ID'] < price['Konto']:
             transfer.setKonto1(price['Konto'])
             transfer.setKonto2(attrs['ID'])
           else:
             transfer.setKonto1(attrs['ID'])
             transfer.setKonto2(price['Konto'])
           transfer.setChangedBy(self.transaction.session().value('authenticated_user',''))
           transfer.setChangedAt(DateTime.now())
           if bookdate:
             transfer.setJahr(bookdate.year)
             transfer.setDatum(bookdate)
           else:
             transfer.setJahr(DateTime.now().year)
             transfer.setDatum(DateTime.now())
           transfer.setBKZ(price['BKZ'])
           transfer.setChangedOn(self.getSite())
           #
           # store transfer in database
           #
           store.addObject(transfer)
           #
         #
         # Beitrag kalkulieren
         #
         if attrs['Beitragsart'+str(y+1)] \
             and not ((attrs['BeitragsartFreiAb'+str(y+1)] == attrs['BeitragsartErhebungAb'+str(y+1)]) \
               and attrs['BeitragsartFreiAb'+str(y+1)] \
               and attrs['BeitragsartErhebungAb'+str(y+1)]) \
             and (attrs['BeitragsartAb'+str(y+1)] < date) \
             and (attrs['BeitragsartErhebungAb'+str(y+1)] \
               and (attrs['BeitragsartErhebungAb'+str(y+1)] < date)) \
             and (not attrs['BeitragsartFreiAb'+str(y+1)] \
               or (attrs['BeitragsartFreiAb'+str(y+1)] >= attrs['BeitragsartErhebungAb'+str(y+1)])) \
             and (not attrs['Austrittsdatum'] \
               or (attrs['Austrittsdatum'] >= attrs['BeitragsartErhebungAb'+str(y+1)])):
           price = prices[attrs['Beitragsart'+str(y+1)]]
           price_soll,price_haben,bkz,beschreibung = fee(attrs['Beitragsart'+str(y+1)],attrs['Eintrittsdatum'],attrs['BeitragsartAb'+str(y+1)],attrs['BeitragsartFreiAb'+str(y+1)],attrs['BeitragsartErhebungAb'+str(y+1)],date,price,notice)
           transfer = Transfers()
           transfer.setTAID(taid)
           transfer.setTransferID(attrs['ID'] + "_" + price['BKZ'])
           transfer.setWho(attrs['Nachname'] + ', ' + attrs['Vorname'])
           transfer.setImportWho(attrs['Nachname'] + ', ' + attrs['Vorname'])
           transfer.setBeschreibung(beschreibung)
           transfer.setImportBeschreibung(beschreibung)
           transfer.setHaben(price_haben)
           transfer.setSoll(price_soll)
           if attrs['ID'] < price['Konto']:
             transfer.setKonto1(price['Konto'])
             transfer.setKonto2(attrs['ID'])
           else:
             transfer.setKonto1(attrs['ID'])
             transfer.setKonto2(price['Konto'])
           transfer.setChangedBy(self.transaction.session().value('authenticated_user',''))
           transfer.setChangedAt(DateTime.now())
           if bookdate:
             transfer.setJahr(bookdate.year)
             transfer.setDatum(bookdate)
           else:
             transfer.setJahr(DateTime.now().year)
             transfer.setDatum(DateTime.now())
           transfer.setBKZ(bkz)
           transfer.setChangedOn(self.getSite())
           #
           # store transfer in database
           #
           store.addObject(transfer)
           if attrs['BeitragsartFreiAb'+str(y+1)] and (date >= attrs['BeitragsartFreiAb'+str(y+1)]):
             entry.setValueForKey('BeitragsartErhebungAb'+str(y+1), attrs['BeitragsartFreiAb'+str(y+1)])
           else:
             entry.setValueForKey('BeitragsartErhebungAb'+str(y+1), date)
     #
     # save changes
     #
     try:
       store.saveChanges()
     except OperationalError,x:
       store.discardEverything()
       errorCode,errorText = x
       #
       # back to error page
       #
       self.transaction.response().sendRedirect('Error?problem=Daten+konnten+nicht+gespeichert+werden!&reason=' + urlEncode(str(errorText)))
     except Warning,x:
       pass
Example #19
0
 def externalId(self):
     if self._externalId is None:
         self._externalId = uniqueId(self)
     return self._externalId
Example #20
0
 def writeContent(self, trans=None):
   #
   # get the year for which the new saldos have to be calculated
   #
   try:
     year = int(self.transaction.request().field('date','')[-4:])
   except ValueError:
     self.transaction.response().sendRedirect('Administration')
   else:
     bemerkung = self.transaction.request().field('bemerkung','')
     notice = self.transaction.request().field('notice','')
     globalSetVars = self._globalSetVars
     store = globalSetVars['store']
     #
     # BKZs einlesen
     #
     priceObjects = store.fetchObjectsOfClass(priceStore)
     prices = {}
     for x in priceObjects:
       a = x.allAttrs(0)
       prices[a['BKZ']] = a
     konto = prices['EL']['Konto']
     #
     # calculate new saldos from given year
     #
     transfers = store.fetchObjectsOfClass(self.storeName,'WHERE Jahr="%s" ORDER BY Datum' % str(year))
     saldos = {}
     for transfer in transfers:
       x = transfer.allAttrs(0)
       if saldos.has_key(x['Konto1']):
         saldo = saldos[x['Konto1']]
       else:
         saldo = 0.0
       if x['Haben'] != 0.0:
         saldo = saldo + x['Haben']
       if x['Soll'] != 0.0:
         saldo = saldo - x['Soll']
       if saldo != 0.0:
         saldos[x['Konto1']] = saldo
       elif saldos.has_key(x['Konto1']):
         del saldos[x['Konto1']]
       if (x['Konto1'] != x['Konto2']):
         if saldos.has_key(x['Konto2']):
           saldo = saldos[x['Konto2']]
         else:
           saldo = 0.0
         if x['Haben'] != 0.0:
           saldo = saldo - x['Haben']
         if x['Soll'] != 0.0:
           saldo = saldo + x['Soll']
         if saldo != 0.0:
           saldos[x['Konto2']] = saldo
         elif saldos.has_key(x['Konto2']):
           del saldos[x['Konto2']]
     #
     # book Lastschriften
     #
     taid = self.getSite() + DateTime.now().strftime("%Y%m%d%H%M%S") + uniqueId(self)[:4]
     for x in saldos.keys():
       if (x[:2] in self.accountStores.keys()) and (x[-1:] == '0') and (saldos[x] < 0.1):
         #
         # create transfer objectonly for Zahlungsart == "Lastschrift"
         #
         member = store.fetchObjectsOfClass(self.accountStores[x[:2]],'WHERE ID="%s"' % x)[0].allAttrs(0)
         if member['Zahlungsart'] == 'Lastschrift':
           transfer = Transfers()
           transfer.setTAID(taid)
           transfer.setImportWho(member['Nachname'] + ', ' + member['Vorname'])
           if notice:
             transfer.setImportBeschreibung(bemerkung + "(%s)" % notice)
             transfer.setBeschreibung(bemerkung + "(%s)" % notice)
           else:
             transfer.setImportBeschreibung(bemerkung)
             transfer.setBeschreibung(bemerkung)
           transfer.setWho(member['Nachname'] + ', ' + member['Vorname'])
           transfer.setBKZ('EL')
           transfer.setTransferID(x + "_EL")
           transfer.setHaben(saldos[x] * -1.0)
           transfer.setSoll(0.0)
           if x < konto:
             transfer.setKonto1(x)
             transfer.setKonto2(konto)
           else:
             transfer.setKonto1(konto)
             transfer.setKonto2(x)
           transfer.setChangedBy(self.transaction.session().value('authenticated_user',''))
           transfer.setChangedAt(DateTime.now())
           transfer.setJahr(year)
           transfer.setDatum(DateTime.now())
           transfer.setChangedOn(self.getSite())
           store.addObject(transfer)
     for x in self.accountStores.keys():
       storeObjects = store.fetchObjectsOfClass('IDs','WHERE %s = "%s"' % ('Tablename',self.accountStores[x]))
       if (len(storeObjects) == 1):
         id = storeObjects[0]
         id.setLastschriften(taid)
     store.saveChanges()
     self.transaction.response().sendRedirect('Administration')
Example #21
0
    def loginUser(self, name, password):

        # Check out proxy from MyProxy

        UID = uniqueId()

        filename = "/tmp/lap_%s" % (UID)

        myproxy = pyMyProxy.MyProxyStore()
        # 		print name, password, filename
        myproxy.proxyGetDelegation(name, password, proxyfile=filename)

        os.chmod(filename, stat.S_IRUSR)

        tempFile = file(filename, "r")

        proxyContent = tempFile.readlines()

        tempFile.close()

        proxy = pyARC.Proxy(filename)
        DNString = proxy.getDN()
        timeLeft = proxy.getTimeleft()

        os.remove(filename)

        # Check to make sure that the proxy has not expired

        if timeLeft > 0:

            # Create a user (and directory)

            user = Lap.User(DNString)
            # user.createDir()

            # Transfer proxy to user directory

            # proxyFile = file("./%s/lap_proxy" % user.getDir(), "w")
            proxyFile = file(user.getProxy(), "w")

            for line in proxyContent:
                proxyFile.write(line)

            proxyFile.close()
            proxyContent = []

            # Make sure it is not world-readable

            # os.chown(user.getProxy(), 0, 0)
            # 			os.chmod(user.getProxy(), stat.S_IRUSR)
            os.chmod(user.getProxy(), 0600)

            # Ok, user is authenticated

            self.session().setValue("authenticated_user", DNString)

            return 1

        else:
            print "proxy has expired"
            self.session().setValue("authenticated_user", None)
            return 0
Example #22
0
    def writeContent(self):
        self.write('''
<center>
	<table border="0" cellpadding="0" cellspacing="0" bgcolor="#ffffff" width="300">
''')

        extra = self.request().field('extra', None)
        if not extra and self.request().isSessionExpired(
        ) and not self.request().hasField('logout'):
            extra = 'You have been automatically logged out due to inactivity.'
        if extra:
            self.write(
                '<tr><td align="left">%s</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>'
                % self.htmlEncode(extra))

        # Create a "unique" login id and put it in the form as well as in the session.
        # Login will only be allowed if they match.
        loginid = uniqueId(self)
        self.session().setValue('loginid', loginid)

        action = self.request().field('action', '')
        if action:
            action = 'action="%s"' % action

        self.write('''
		<tr>
			<td align="left">Please log in (use Alice or Bob as the username and password):</td>
		</tr>
		<tr>
			<td>
				<form method="post" name="loginform" %s>
					<table border="0" width="100%%" cellpadding="3" cellspacing="0" bgcolor="#cecece" align="left">
						<tr><td>&nbsp;</td><td>&nbsp;</td></tr>
						<tr>
							<td align="right">Username</td>
							<td><input type="TEXT" name="username"></td>
						</tr>
						<tr>
							<td align="right">Password</td>
							<td><input type="PASSWORD" name="password"></td>
						</tr>
						<tr>
							<td>&nbsp;</td>
							<td><input type="submit" name="login" value="Login"></td>
						</tr>
						<tr><td>&nbsp;</td><td>&nbsp;</td></tr>
					</table>
					<input type="hidden" name="loginid" value="%s">''' % (action, loginid))

        # Forward any passed in values to the user's intended page after successful login,
        # except for the special values used by the login mechanism itself
        for name, value in self.request().fields().items():
            if name not in 'login loginid username password extra logout'.split(
            ):
                if isinstance(value, types.ListType):
                    for valueStr in value:
                        self.write(
                            '''<input type="hidden" name="%s" value="%s">''' %
                            (self.htmlEncode(name), self.htmlEncode(valueStr)))
                else:
                    self.write(
                        '''<input type="hidden" name="%s" value="%s">''' %
                        (self.htmlEncode(name), self.htmlEncode(value)))
        self.write('''
				</form>
			</td>
		</tr>
	</table>
</center>
''')