Beispiel #1
0
    def update(self, code=None, state=None, **args):
        ''' Either code or error is defined here if this is in response to Authorization '''
        super(V2TokenView, self).update(**args)
        oauth = self.context.__parent__.__parent__
        self.context.__parent__.__parent__.error_msg = None

        if self.error is None:
            if code is not None:
                token = self.context.__parent__
                if token.state == state:
                    self.context.code = code
                    data = urlencode(self.context.parms)
                    print "----------------------------------------------------"
                    print "url=[%s]; data=[%s]" % (self.context.uri, data)
                    req = Request(self.context.uri)
                    req.add_header(
                        'User-Agent',
                        'Python urlib2 (grok.zopefoundation.org, Python 2.7)')
                    req.add_header('Content-Type',
                                   'application/x-www-form-urlencoded')
                    req.add_header('Accept', 'application/json')
                    req.add_data(data)
                    try:
                        res = urlopen(req).read()  # should be doing a post
                        self.context.info = json.loads(res)
                        try:
                            # Update session information with auth info
                            session = ISession(self.request)['OAuth2']
                            session['info'] = self.context.info

                            service = self.context.__parent__.service
                            principal = component.queryAdapter(self.context,
                                                               IOAuthPrincipal,
                                                               name=service)
                            session[
                                'principal'] = principal if principal else None
                            # If we get here, we can notify subscribers.
                            grok.notify(
                                OAuthenticatedEvent(session['principal']))
                            self.redirect(self.url(grok.getApplication()))
                        except Exception as e:
                            print "Problem in adapter for service: {}".format(
                                str(e))
                            self.error = str(e)
                    except HTTPError as e:
                        print "Error while exchanging tokens: {}".format(
                            str(e))
                        self.error = str(e)
                else:
                    self.error = 'State Mismatch'
            else:
                self.error = 'Invalid code'
        if type(self.error) is str and len(self.error):
            print "-------------------------------------------------"
            print "Error [%s] in token exchange" % self.error

        oauth.error_msg = self._render_template()
        self.redirect(self.url(grok.getApplication()))
Beispiel #2
0
    def up(self):
        self.app.version = (0,8,1)
        setup = zope.component.getUtility(grokcore.site.interfaces.IUtilityInstaller)
        setup(grok.getApplication(),
              TKTCookieCredentialsPlugin(),
              ICredentialsPlugin,
              name='mod_auth_tkt',
        )
        setup(grok.getApplication(),
              TKTAuthenticatorPlugin(),
              IAuthenticatorPlugin,
              name='tkt-auth',
        )

        return 'TKTCookieCredentials and TKTAuthenticator utilities installed.'
Beispiel #3
0
    def __call__(self, *args, **kw):
        self.now = util.clock()

        # We are calling this here because the first setupLocale() call in
        # zope.publisher.http.HTTPRequest does not include application and
        # therefore we can't actually determine what locales are available.
        self.request.setupLocale()

        self.request.response.setHeader(
            "Content-Type",
            self.contentType
            )

        try:
            application = grok.getApplication()
        except:
            application = None

        if application is not None and application.sendCachingHeaders:
            self._sendCachingHeaders()
        else:
            self._sendDisableCachingHeaders()


        return super(MobileView, self).__call__(*args, **kw)
Beispiel #4
0
Datei: user.py Projekt: bcgsc/gum
 def form_fields(self):
     # this is a property because class attributes are computed
     # before components which provide schema extensions are registered
     form_fields = core_user_fields()
     # munge roomNumber and street into officeLocation
     form_fields = form_fields.omit('roomNumber','street','dn')
     form_fields += FormFields(IUser['officeLocation'])
     # __name__ should not be edited after an account has been created!
     # (although sometimes a typo is made in account creation, so perhaps
     #  a special form or UI to handle this use-case maybe? say if the 
     #  account is less than 5 minutes old ...)
     form_fields['__name__'].for_display = True
     
     extra_fields = FormFields(*additional_user_fields())
     # XXX we lie about IUserSchemaExtensions being IUser objects to
     # get around FormFields behaviour of adapter = interface(context)
     # a better fix might be refacter the IUser interfaces in some
     # manner ...
     for f in extra_fields: f.interface = IUser
     form_fields += extra_fields
     
     # limit fields which users without the Admin role can edit
     # erm, this mess could be pushed into a custom IPrincipalRoleMap implementation
     is_admin = False
     uname = self.request.principal.id.split('.')[-1]
     app = grok.getApplication()
     if uname in app['groups'][app.ldap_admin_group].uids:
         is_admin = True
     
     for f in form_fields:
         admin_only = getattr(f.field, 'ldap_admin_only', False)
         if not is_admin and admin_only:
             f.for_display = True
     
     return form_fields
    def __new__(self, token):
        app = grok.getApplication()
        users = IOAuthPrincipalSource(app)

        url = u"https://discordapp.com/api/users/@me"
        print "User token info found: %s" % token.info
        req = Request(url)
        
        req.add_header('User-Agent',  'Python urlib2 (grok.zopefoundation.org, Python 2.7)')
        req.add_header("Content-Type", "application/json")
        req.add_header("Authorization", "{} {}".format(token.info['token_type'],
                                                       token.info['access_token']))
        res = urlopen(req).read()
        if res: res = json.loads(res)
        if res is None:
            return None
        else:
            print "Personal info returned: %s" % res
            uid = u"Discord.{}".format(res['id'])
            found = users.find(id=uid)
            if len(found)==0:
                user = users.new(id=uid)
            else:
                user = list(found)[0]

            user.authInfo = token.info
            user.title = unicode(res['username'])
            user.description = user.title
            user.domain = u'Discord'
            user.login = user.disco_id = unicode(res['id'])
            user.secret = unicode(token.info['access_token'])
            return user
Beispiel #6
0
 def __call__(self):
     request = self.request
     if (not IUnauthenticatedPrincipal.providedBy(request.principal)
         and 'gum.Login' in request):
         request.response.redirect( self.url(grok.getApplication()) )
     else:
         return self.template.render(self)
Beispiel #7
0
 def all_users(self):
     "All users info"
     out = []
     users = grok.getApplication()['users']
     for user in users.values():
         out.append(self._marshall_user_info(user))
     return out
    def __new__(self, token):
        app = grok.getApplication()
        users = IOAuthPrincipalSource(app)
        uri = "https://api.twitter.com/1.1/account/verify_credentials.json"

        req = Request(url)
        req.add_header('User-Agent',  'Python urlib2 (grok.zopefoundation.org, Python 2.7)')
        req.add_header("Content-Type", "application/json")
        req.add_header("Authorization", "{} {}".format(token.info['token_type'],
                                                       token.info['access_token']))
        res = urlopen(req).read()
        if res: res = json.loads(res)
        if res is None:
            return None
        else:
            print "result=%s" % res
            uid = u"Twitter.{}".format(res['id'])

            found = users.find(id=uid)
            if len(found)==0:
                user = users.new(id=uid)
            else:
                user = list(found)[0]

            user.authInfo = token.info
            user.domain = u'Twitter'
            user.login = uid
            user.secret = token.info['access_token']
            return user
    def __new__(self, token):
        app = grok.getApplication()
        users = IOAuthPrincipalSource(app)

        url = u"https://graph.facebook.com/me"
        print "User token info found: %s" % token.info
        req = Request(url)
        
        req.add_header('User-Agent',  'Python urlib2 (grok.zopefoundation.org, Python 2.7)')
        req.add_header("Content-Type", "application/json")
        req.add_header("Authorization", "{} {}".format(token.info['token_type'],
                                                       token.info['access_token']))
        req.add_data(urlencode(dict(access_token=token.info['access_token'],
                                    fields='id,name,first_name,last_name')))
        res = urlopen(req).read()
        if res: res = json.loads(res)
        if res is None:
            return None
        else:
            print "Personal info returned: %s" % res
            uid = u"Facebook.{}".format(res['id'])
            found = users.find(id=uid)
            if len(found)==0:
                user = users.new(id=uid)
            else:
                user = list(found)[0]

            user.authInfo = token.info
            user.title = unicode(res['name'])
            user.description = u'{} {}'.format(res['first_name'], res['last_name'])
            user.domain = u'Facebook'
            user.login = unicode(res['id'])
            user.secret = unicode(token.info['access_token'])
            return user
Beispiel #10
0
    def __new__(self, token):
        app = grok.getApplication()
        users = IOAuthPrincipalSource(app)

        url = u"https://www.googleapis.com/userinfo/v2/me"
        req = Request(url)
        req.add_header('User-Agent',  'Python urlib2 (grok.zopefoundation.org, Python 2.7)')
        req.add_header("Content-Type", "application/json")
        req.add_header("Authorization", "{} {}".format(token.info['token_type'],
                                                       token.info['access_token']))
        res = urlopen(req).read()
        if res: res = json.loads(res)
        if res is None:
            return None
        else:
            uid = u"Google.{}".format(res['id'])
            found = users.find(id=uid)
            if len(found)==0:
                user = users.new(id=uid)
            else:
                user = list(found)[0]

            user.authInfo = token.info
            user.title = unicode(res['name'])
            user.description = u'{} {}'.format(res['given_name'], res['family_name'])
            user.domain = u'Google'
            user.login = unicode(res['id'])
            user.secret = unicode(token.info['access_token'])
            return user
Beispiel #11
0
 def all_users(self):
     "All users info"
     out = []
     users = grok.getApplication()['users']
     for user in users.values():
         out.append(self._marshall_user_info(user))
     return out
Beispiel #12
0
 def generate_token(site=None, **args):
     if site is None:
         site = grok.getApplication()
     sm = site.getSiteManager()
     auth_name = grok.name.bind().get(TokenAuthenticator)
     plugin = sm[auth_name]
     token = plugin.make_token(**args)
     return token
Beispiel #13
0
 def is_admin(self):
     # TO-DO: supporting Organization editing, could be removed in a
     # future UI clean-up
     grant_info = IGrantInfo(grok.getApplication())
     for role in grant_info.getRolesForPrincipal(self.request.principal.id):
         if role[0] == u'gum.Admin':
             return True
     return False
 def generate_url(self, request, as_thumbnail):
     app = grok.getApplication()
     params = '?id=' + self.p2_id
     if as_thumbnail:
         params += '&thumbnail'
     url = grok.url(request, app, '@@media')
     url += params
     return url
Beispiel #15
0
 def is_admin(self):
     # TO-DO: supporting Organization editing, could be removed in a
     # future UI clean-up
     grant_info = IGrantInfo( grok.getApplication() )
     for role in grant_info.getRolesForPrincipal(self.request.principal.id):
         if role[0] == u'gum.Admin':
             return True
     return False
Beispiel #16
0
 def traverse(self, name):
     group = self.context[name]
     principal_id = self.request.principal.id
     uid = principal_id.split('.')[-1]
     
     # grant permissions if user belongs to group
     ppm = IPrincipalPermissionManager(grok.getApplication())     
     if uid in group.uids:
         ppm.grantPermissionToPrincipal(u'gum.EditGroup', principal_id)
     
     # grant permissions if the user is Admin
     grant_info = IGrantInfo(grok.getApplication())
     for role, perm in grant_info.getRolesForPrincipal(principal_id):
         if role == u'gum.Admin' and perm == Allow:
             ppm.grantPermissionToPrincipal(u'gum.EditGroup', principal_id)
     
     return group
Beispiel #17
0
 def update(self):
     content = self.context.get(self.request.locale.id.language, None)
     if content is None:
         language = grok.getApplication().defaultLanguage
         if language not in self.context:
             self.context[language] = LocationContainer()
         content = self.context[language]
     self.locations = content.values()
Beispiel #18
0
def principal_homefolder(principal):
    principal = IMasterUser(principal)
    application = grok.getApplication()
    manager = IHomeFolderManager(application)
    hf = manager.get(principal.id)
    if not hf:
        hf = manager.create(principal.id)
    return hf
Beispiel #19
0
def update_principal_info_from_ldap(event):
    "Update the principal with information from LDAP"
    principal = event.principal
    app = grok.getApplication()
    __name__ = principal.id.split('.')[-1]
    user = app['users'][__name__]
    principal.title = user.cn
    principal.__name__ = __name__
Beispiel #20
0
def update_principal_info_from_ldap(event):
    "Update the principal with information from LDAP"
    principal = event.principal
    app = grok.getApplication()
    __name__ = principal.id.split('.')[-1]
    user = app['users'][__name__]
    principal.title = user.cn
    principal.__name__ = __name__
Beispiel #21
0
 def __call__(self, _context):
     terms = []
     app = grok.getApplication()
     authors = app['authors']
     for author in authors.values():
         title = author.mkTitle()
         token = author.key()
         terms.append(SimpleVocabulary.createTerm(author, token, title))
     return SimpleVocabulary(terms)
Beispiel #22
0
    def up(self):
        self.app.version = (0, 8, 1)
        setup = zope.component.getUtility(
            grokcore.site.interfaces.IUtilityInstaller)
        setup(
            grok.getApplication(),
            TKTCookieCredentialsPlugin(),
            ICredentialsPlugin,
            name='mod_auth_tkt',
        )
        setup(
            grok.getApplication(),
            TKTAuthenticatorPlugin(),
            IAuthenticatorPlugin,
            name='tkt-auth',
        )

        return 'TKTCookieCredentials and TKTAuthenticator utilities installed.'
Beispiel #23
0
 def nav(self):
     app = grok.getApplication()
     return ( (app),
              (app['users']),
              (app['groups']),
              (app['orgs']),
              (app['transcripts']),
              (app['smart']),
              (app['extensions']),
             )
Beispiel #24
0
 def save(self):
     "Store information in LDAP"
     app = grok.getApplication()
     dbc = app.ldap_connection()
     
     if not self.exists_in_ldap:
         dbc.add(self.dn, self.ldap_entry)
         self.exists_in_ldap = True
     else:
         dbc.modify(self.dn, self.ldap_entry)
Beispiel #25
0
 def load(self):
     "Fetch Group data from LDAP"
     app = grok.getApplication()
     dbc = app.ldap_connection()
     results = dbc.search( app.ldap_group_search_base,
                           scope='one',
                           filter="(&(objectclass=groupOfUniqueNames)(cn=%s))" % self.cn )
     if not results:
         return None
     else:
         return results[0][1] 
Beispiel #26
0
 def values(self):
     app = grok.getApplication()
     dbc = app.ldap_connection()
     results = dbc.search( app.ldap_group_search_base,
                          scope='one',
                          filter="(&(objectclass=groupOfUniqueNames))" )
     groups = []
     for x in results:
         groups.append( self.create_group_from_ldap_results( x[1] ) )
     
     return groups
Beispiel #27
0
 def do_login(self, **data):
     login = Login()
     self.applyData(login, **data)
     principals = IOAuthPrincipalSource(grok.getApplication())
     account = principals.find(login=login.login, domain=principals.domain)
     if account:  # check password, and authenticate if match
         from zope.password.password import SSHAPasswordManager
         mgr = SSHAPasswordManager()
         if mgr.checkPassword(account.secret, login.secret):
             session = ISession(self.request)['OAuth2']
             session['principal'] = account  # Found the principal
Beispiel #28
0
 def update(self):
     app = grok.getApplication()
     if 'oauth2Applications' in app.keys():
         self.oauth = app['oauth2Applications']
     else:
         self.oauth = app['oauth2Applications'] = OAuth2Applications()
     if 'oauth2editing' in self.request:
         try:
             self.oauth.editmode = int(self.request['oauth2editing'])
         except:
             pass
Beispiel #29
0
def ldap_added_subscriber(obj, event):
    trst = Transcript()
    app = grok.getApplication()
    dbc = app.ldap_connection()
    trst.dn = obj.dn
    trst.before = u''
    trst.after = unicode(obj.ldap_entry)
    trst.observation_datetime = datetime.now()
    trst.principal_id = obj.principal_id
    namechooser = INameChooser( app['transcripts'] )
    name = namechooser.chooseName('ldap_add', trst)
    app['transcripts'][name] = trst
Beispiel #30
0
 def ldap_entry(self):
     "Representation of the object as an LDAP Entry"
     app = grok.getApplication()
     uniqueMembers = []
     for uid in self.uids:
         uniqueMembers.append( u'uid=%s,%s' % (uid, app.ldap_user_search_base))
     entry = { 'objectClass': ['top', 'groupOfUniqueNames'],
               'cn': [ unicode(self.cn), ],
               'uniqueMember': uniqueMembers, }
     if self.description:
         entry['description'] = [ unicode(self.description), ]
     return entry
Beispiel #31
0
 def user(self):
     app = grok.getApplication()
     try:
         uid = self.principal_id.split('.')[-1:][0]
         user = app['users'][ uid ]
     except KeyError:
         # non-ldap user, or user account was deleted
         class UnknownUser(object):
             def __init__(self, name):
                 self.uid = name
                 self.cn = name
         user = UnknownUser(uid)
     return user
Beispiel #32
0
    def groups(self):
        search_term = ldap.filter.escape_filter_chars(
            self.request.form.get('search_term', None))
        if not search_term or len(search_term) < 3:
            return {}

        groups = grok.getApplication()['groups']
        results = []

        for group in groups.search('cn', search_term, False):
            results.append(group)

        return results[:15]
Beispiel #33
0
    def update(self):
        gid = self.request.form.get('gid', None)
        group = grok.getApplication()['groups'][gid]
        if self.context.__name__ not in group.uids:
            group.uids = group.uids + (self.context.__name__, )

            # TO-DO oh the hackery!!!
            group.principal_id = self.request.principal.id
            event.notify(grok.ObjectModifiedEvent(group))

            # save must be called after event notification, otherwise it
            # can't diff between the before and after states!
            group.save()
Beispiel #34
0
Datei: user.py Projekt: bcgsc/gum
 def update(self):
     gid = self.request.form.get('gid', None)
     group = grok.getApplication()['groups'][gid]
     if self.context.__name__ not in group.uids:
         group.uids = group.uids + (self.context.__name__,)
         
         # TO-DO oh the hackery!!!
         group.principal_id = self.request.principal.id
         event.notify( grok.ObjectModifiedEvent(group) )
         
         # save must be called after event notification, otherwise it
         # can't diff between the before and after states!
         group.save()
Beispiel #35
0
 def __getitem__(self, key):
     "Mapping between key (group cn) and LDAP-backed Group objects"
     app = grok.getApplication()
     dbc = app.ldap_connection()
     results = dbc.search( app.ldap_group_search_base,
                           scope='one',
                           filter="(&(objectclass=groupOfUniqueNames)(cn=%s))"
                           % key
                         )
     if not results:
         raise KeyError, "Group id %s does not exist." % key
     else:
         return self.create_group_from_ldap_results(results[0][1])
Beispiel #36
0
 def __call__(self, form):
     site = grok.getApplication()
     content = form.getContent()
     try:
         result = self.callback(content, site)
         assert isinstance(result, Result)
         return result
     except PluginError as exc:
         form.errors = Errors(*[
             Error(title=error, identifier=self.identifier)
             for error in exc.messages
         ])
     return FAILURE
Beispiel #37
0
    def __call__(self):
        application = grok.getApplication()
        application_url = getMultiAdapter(
            (application, self.request),
            zope.traversing.browser.interfaces.IAbsoluteURL)()

        stacked_objects = []
        context = self.context
        while context != application:
            if not interfaces.IEventContainer.providedBy(context):
                stacked_objects.append(context.__name__)
            context = context.__parent__
        stacked_objects.append(application_url)
        return "/".join(reversed(stacked_objects))
 def lookup_archetype_view(self):
     app = grok.getApplication()
     archetype_genericset = app['configuration']['meta']['p2_archetypes']
     plan = archetype_genericset.plan
     form = plan.forms['archetypes']
     view = getMultiAdapter(
         (form, self.request),
         context=IFormType,
         name='bareform'
         )
     # ATTENTION: Displaying the archetype form does not mean it is in archetype mode.
     # That mode is for ajax requests when dropping widget into designer form.
     self.request.form['mode'] = 'DESIGNER'
     return view()
Beispiel #39
0
Datei: user.py Projekt: bcgsc/gum
    def groups(self):
        search_term = ldap.filter.escape_filter_chars(
            self.request.form.get('search_term', None)
        )
        if not search_term or len(search_term) < 3:
            return {}

        groups = grok.getApplication()['groups']
        results = []
        
        for group in groups.search('cn', search_term, False):
            results.append(group)

        return results[:15]
Beispiel #40
0
    def getContent(self, request):
        # Somehow we don't have application when the request (traversing) starts
        # but we need the current language here and behold! We have the
        # application here.
        languages = zope.component.getAdapter(request, IUserPreferredLanguages)
        content = None
        for language in languages.getPreferredLanguages():
            if language in self.context:
                content = self.context[language]
                break

        if content is None:
            content = self.context[grok.getApplication().defaultLanguage]

        return content
Beispiel #41
0
    def render(self, **kw):
        access = self.context.access
        acecss.parms.update(kw)

        session = ISession(self.request)['OAuth2']
        session['info'] = access.info

        service = self.context.__parent__.service
        principal = component.queryAdapter(access,
                                           IOAuthPrincipal,
                                           name=service)
        session['principal'] = principal if principal else None

        grok.notify(OAuthenticatedEvent(self.context.access))
        self.redirect(self.url(grok.getApplication()))
Beispiel #42
0
    def crumbs(self):
        ''' Walk the tree up from current context, build crumbs.
        '''
        app = grok.getApplication()
        cl  = []
        curr = self.context

        while curr != app:
            cl.append(curr)
            curr = curr.__parent__
        cl.append(curr)
        cl.reverse()
        return ({'title': a.navTitle,
                 'hRef':self.url(a),
                 'isLast':a==self.context} for a in cl)
Beispiel #43
0
    def __new__(self, token):
        app = grok.getApplication()
        users = IOAuthPrincipalSource(app)
        uid = u"Mixer.{}".format(users.sequence)

        found = users.find(id=uid)
        if len(found)==0:
            user = users.new(id=uid)
        else:
            user = list(found)[0]

        user.authInfo = token.info
        user.domain = u'Mixer'
        user.login = token.info['id_token']
        user.secret = token.info['access_token']
        return user
Beispiel #44
0
 def recent_modifications(self, days=30):
     """
     User info for any user modified in the last 30 days
     """
     users = {}
     app = grok.getApplication()
     for mod in self.context['transcripts'].sorted_by_date():
         now = datetime.datetime.now()
         if now - datetime.timedelta(days) < mod.observation_datetime:
             name = mod.dn.split(',')[0].split('=')[1]
             try:
                 user = app['users'][name]
                 users[user.__name__] = self._marshall_user_info(user)
                 users[user.__name__]['modified'] = mod.observation_datetime
             except KeyError:
                 pass
     return users.values()
Beispiel #45
0
 def render(self):
     app = grok.getApplication()
     out = StringIO()
     out.write('"Name","Email","Phone","User Id","Office Location","Employee Type","Organizational Unit Type"\n')
     for user in app['users'].orgsearch(self.usersearch):
         if user.roomNumber:
             location = '%s - %s' % (user.street, user.roomNumber)
         else:
             location = user.street
         if user.telephoneNumber:
             phone = ', '.join(user.telephoneNumber)
         else:
             phone = ''
         out.write( '"%s","%s","%s","%s","%s","%s","%s"\n' % (
                    user.cn, user.email, phone, user.uid, location, user.employeeType, user.ou
                  ) )
     return out.getvalue()
Beispiel #46
0
    def update(self):
        gid = self.request.form.get('gid', None)
        if not gid: return
        group = grok.getApplication()['groups'][gid]
        new_group = []
        for uid in group.uids:
            if uid != self.context.__name__:
                new_group.append(uid)
        group.uids = new_group

        # TO-DO oh the hackery!!!
        group.principal_id = self.request.principal.id
        event.notify(grok.ObjectModifiedEvent(group))

        # save must be called after event notification, otherwise it
        # can't diff between the before and after states!
        group.save()
Beispiel #47
0
Datei: user.py Projekt: bcgsc/gum
 def update(self):
     gid = self.request.form.get('gid', None)
     if not gid: return
     group = grok.getApplication()['groups'][gid]
     new_group = []
     for uid in group.uids:
         if uid != self.context.__name__:
             new_group.append(uid)
     group.uids = new_group
     
     # TO-DO oh the hackery!!!
     group.principal_id = self.request.principal.id
     event.notify( grok.ObjectModifiedEvent(group) )
     
     # save must be called after event notification, otherwise it
     # can't diff between the before and after states!
     group.save()
Beispiel #48
0
 def search(self, param, term, exact_match=True):
     "Search through groups and return matches as Group objects in a list"
     app = grok.getApplication()
     dbc = app.ldap_connection()
     
     if not exact_match:
         term = '*' + term + '*'
     
     results = dbc.search( app.ldap_group_search_base,
                           scope='one',
                           filter="(&(objectclass=groupOfUniqueNames)(%s=%s))"
                           % (param, term)
                         )
     groups = []
     for x in results:
         groups.append( self.create_group_from_ldap_results( x[1] ) )
     return groups
Beispiel #49
0
 def recent_modifications(self, days=30):
     """
     User info for any user modified in the last 30 days
     """
     users = {}
     app = grok.getApplication()
     for mod in self.context['transcripts'].sorted_by_date():
         now = datetime.datetime.now()
         if now - datetime.timedelta(days) < mod.observation_datetime:            
             name = mod.dn.split(',')[0].split('=')[1]
             try:
                 user = app['users'][name]
                 users[user.__name__] = self._marshall_user_info(user)
                 users[user.__name__]['modified'] = mod.observation_datetime
             except KeyError:
                 pass
     return users.values()
Beispiel #50
0
 def edit(self, **data):
     # XXX validation hack
     # need to improve the validation and the UI experience
     app = grok.getApplication()
     unique_uids = {}
     for uid in data['uids']:
         unique_uids[uid] = None
     try:
         for uid in unique_uids.keys():
             app['users'][uid]
     except KeyError:
         pass
         # return "Uid %s does not exist.\nYou supplied the User Ids %s." % (uid, data['uids'])
     
     self.context.principal_id = self.request.principal.id # XXX oh the hackery!!!
     self.applyData(self.context, **data) # sends grok.ObjectModifedEvent
     self.context.save()
     self.redirect(self.url(self.context))