def uploadUsers(self):
        loggedInUser = self.current_user
        if loggedInUser and loggedInUser.admin:                    
            userNames=self.request.get('userNames')
            names = string.split(userNames, '\n')
            bigMessage = ['username,password']
            for name in names:
                username = name.strip()      
                try:
                    randomPassword = WhysaurusUser.random_password(8)
                    user = WhysaurusUser.signup(self, email=None, name=username, 
                                                password=randomPassword, website=None, areas=None, 
                                                profession=None, bio=None)
                    user.updatePrivateArea('Good_Judgment_Project')
                    bigMessage.append('%s,%s' % ( username, randomPassword))
                except WhysaurusException as e:
                    bigMessage.append('Could not create user: %s. Error was:%s' % (username, str(e)))
                
            template_values = {
                'user': loggedInUser,
                'messages': bigMessage
            }    
            path = os.path.join(os.path.dirname(__file__), '../templates/message.html')
            self.response.out.write(template.render(path, template_values))   
        else:
            self.response.out.write('User not authorized. ')


            
            
            
Beispiel #2
0
    def MakeFollows(self):
        """
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ADD FOLLOWS FOR ADMIN USERS
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
        """
        nextURL = None
        firstURL = self.request.get('nexturl')
        query = PointRoot.query().order(PointRoot.url)
        if firstURL:
            query = query.filter(PointRoot.url >= firstURL)
        pointRoots = query.fetch(11)
        if len(pointRoots) == 11:
            nextURL = pointRoots[-1].url
            pointRootsToReview = pointRoots[:10]
        else:
            pointRootsToReview = pointRoots

        i = 0
        for pointRoot in pointRootsToReview:
            pointRootKey = pointRoot.key
            followers = {}

            versions = pointRoot.getAllVersions()
            for point in versions:
                if point.version == 1:
                    followers[point.authorURL] = 'created'
                elif not point.authorURL in followers:
                    followers[point.authorURL] = 'edited'

            for comment in pointRoot.getComments():
                if not comment.userUrl in followers:
                    followers[comment.userUrl] = 'commented'

            logging.info('ROOT: %s FOLLOWERS: %s' %
                         (pointRoot.url, str(followers)))
            for url in followers.iterkeys():
                followType = followers[url]
                previousNamespace = namespace_manager.get_namespace()
                if previousNamespace and previousNamespace != '':
                    namespace_manager.set_namespace('')  # DEFAULT NAMESPACE
                    usr = WhysaurusUser.getByUrl(url)
                    namespace_manager.set_namespace(previousNamespace)
                else:
                    usr = WhysaurusUser.getByUrl(url)
                logging.info('Trying to follow for U:%s, R:%s, T:%s' %
                             (url, pointRoot.url, followType))
                f = None
                f = Follow.createFollow(usr.key, pointRootKey, followType)
                if f:
                    i = i + 1
                    logging.info('ADDED follow for U:%s, R:%s, T:%s' %
                                 (url, pointRoot.url, followType))

        logging.info('Added %d follows' % i)
        if nextURL:
            t = Task(url="/MakeFollows", params={'nexturl': nextURL})
            t.add(queue_name="notifications")
            logging.info('Requeing MakeFollows task to start at url %s ' %
                         nextURL)
Beispiel #3
0
    def forgotPassword(self):
        results = {'result': False}
        email = self.request.get('email')
        user = None
        if email.find('@') != -1:
            user = WhysaurusUser.get_by_email(email)
            if not user:
                logging.info('Could not find any user entry for email %s' %
                             email)
                results[
                    'error'] = 'Could not find user entry with email %s' % email
        else:
            user = WhysaurusUser.get_by_name(email)
            if not user:
                logging.info('Could not find any user entry for username %s' %
                             email)
                results[
                    'error'] = 'Could not find user entry with username %s' % email
        if user:
            if hasattr(
                    user,
                    'email') and user.email is not None and user.email != '':
                user_id = user.get_id()
                token = self.auth.store.user_model.create_signup_token(user_id)
                verification_url = self.uri_for('verification',
                                                type='p',
                                                user_id=user_id,
                                                signup_token=token,
                                                _full=True)
                mail.send_mail(
                    sender='Whysaurus <*****@*****.**>',
                    to=user.email,
                    subject='Whysaurus password reset',
                    html=
                    "A password reset request has been received for your account. <br> \
                        Please reset your password  \
                        <a href=\"%s\">here</a>.<br><br>Thanks,<br>Whysaurus<br> \
                        " % verification_url,
                    body=
                    "A password reset request has been received for your account. \n \
                        Please reset your password by visiting this URL:  \
                        %s. \n\n Thanks,\n Whysaurus\n" % verification_url,
                    reply_to="*****@*****.**")
                results = {'result': True}
            else:
                results = {
                    'result':
                    True,
                    'message':
                    'There is no email on file for this \
                               username. Please email [email protected] \
                               and request a password reset.'
                }

        resultJSON = json.dumps(results)
        self.response.headers[
            "Content-Type"] = 'application/json; charset=utf-8'
        self.response.out.write(resultJSON)
Beispiel #4
0
    def MakeFollows(self):
        """
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ADD FOLLOWS FOR ADMIN USERS
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
        """
        nextURL = None
        firstURL = self.request.get('nexturl')
        query = PointRoot.query().order(PointRoot.url)
        if firstURL:
            query = query.filter(PointRoot.url >= firstURL)
        pointRoots = query.fetch(11)
        if len(pointRoots) == 11:
            nextURL = pointRoots[-1].url
            pointRootsToReview = pointRoots[:10]
        else:
            pointRootsToReview = pointRoots
        
        i = 0
        for pointRoot in pointRootsToReview:
            pointRootKey = pointRoot.key
            followers = {}     
                          
            versions = pointRoot.getAllVersions()
            for point in versions:
                if point.version == 1:
                    followers[point.authorURL] = 'created'         
                elif not point.authorURL in followers:
                    followers[point.authorURL] = 'edited'  
            
            for comment in pointRoot.getComments():
                if not comment.userUrl in followers:
                    followers[comment.userUrl] = 'commented'  
                
            logging.info('ROOT: %s FOLLOWERS: %s' % (pointRoot.url, str(followers)))       
            for url in followers.iterkeys():
                followType = followers[url]
                previousNamespace = namespace_manager.get_namespace()
                if previousNamespace and previousNamespace != '':                
                    namespace_manager.set_namespace('') # DEFAULT NAMESPACE
                    usr = WhysaurusUser.getByUrl(url)
                    namespace_manager.set_namespace(previousNamespace)
                else:
                    usr = WhysaurusUser.getByUrl(url)
                logging.info('Trying to follow for U:%s, R:%s, T:%s' % (url, pointRoot.url, followType))
                f = None
                f = Follow.createFollow(usr.key, pointRootKey, followType)
                if f:
                    i = i + 1
                    logging.info('ADDED follow for U:%s, R:%s, T:%s' % (url, pointRoot.url, followType))

                       
        logging.info('Added %d follows' % i)
        if nextURL:
            t = Task(url="/MakeFollows", params={'nexturl':nextURL})
            t.add(queue_name="notifications")
            logging.info('Requeing MakeFollows task to start at url %s ' % nextURL)
 def sendNotificationEmails(self):
     appId = app_identity.get_application_id()
     logging.info('GAE App Id: %s' % appId)
     if appId != 'whysaurus':
         logging.warning('Bypassing email notifications outside primary app. App Id: %s' % appId)
         self.response.out.write('Bypass!')
         return
     WhysaurusUser.sendNotificationEmails(self)
     self.response.out.write('') # succeed!
Beispiel #6
0
    def sendNotificationEmails(self):
        WhysaurusUser.sendNotificationEmails(self)
        self.response.out.write('') # succeed!
        
        
        
        
        
        

        
Beispiel #7
0
    def uploadUsers(self):

        userNamespace = namespace_manager.get_namespace()
        namespace_manager.set_namespace('')

        loggedInUser = self.current_user
        if loggedInUser and loggedInUser.isAdmin:
            userNames = self.request.get('userNames')
            privateArea = self.request.get('areaToAdd')
            userLines = string.split(userNames, '\n')

            bigMessage = []
            if privateArea:
                bigMessage.append('Creating users in classroom %s' %
                                  privateArea)
            bigMessage.append('username,password')
            for userLine in userLines:
                userFields = string.split(userLine, ',')
                numFields = len(userFields)
                username = userFields[0].strip()
                try:
                    newPassword = ''
                    if numFields == 1:
                        newPassword = WhysaurusUser.random_password(8)
                    else:
                        newPassword = userFields[1].strip()
                    if username != '':
                        user = WhysaurusUser.signup(self,
                                                    email=username,
                                                    name=username,
                                                    password=newPassword,
                                                    website=None,
                                                    areas=None,
                                                    profession=None,
                                                    bio=None)
                        user.updateUserSettings([privateArea])
                        bigMessage.append('%s,%s' % (username, newPassword))
                except WhysaurusException as e:
                    bigMessage.append(
                        'Could not create user: %s. Error was:%s' %
                        (username, str(e)))

            template_values = {'user': loggedInUser, 'messages': bigMessage}
            self.response.out.write(
                self.template_render('message.html', template_values))
        else:
            self.response.out.write('User not authorized. ')

        namespace_manager.set_namespace(userNamespace)
Beispiel #8
0
    def get(self, userURL):
        userNamespace = namespace_manager.get_namespace()
        user = self.current_user

        # USERS ARE STORED IN THE DEFAULT NAMESPACE
        namespace_manager.set_namespace('')
        profileUser = WhysaurusUser.getByUrl(userURL)
        if profileUser:
            logging.info("got Profile User. Areas were: " +
                         str(profileUser.privateAreas))
        namespace_manager.set_namespace(userNamespace)

        if user:
            permissionToView = user.isAdmin or profileUser.privateAreas == [] or self.session.get(
                'currentArea') in profileUser.privateAreas
        else:
            permissionToView = len(profileUser.privateAreas) == 0

        if profileUser and permissionToView:
            self.response.out.write(
                self.template_render(
                    'profile.html', self.makeTemplateValues(user,
                                                            profileUser)))
        else:
            self.response.out.write('Could not find user: ' + userURL)
Beispiel #9
0
    def uploadUsers(self):

        userNamespace = namespace_manager.get_namespace()        
        namespace_manager.set_namespace('')
        
        loggedInUser = self.current_user
        if loggedInUser and loggedInUser.isAdmin:                    
            userNames=self.request.get('userNames')
            privateArea = self.request.get('areaToAdd')
            userLines = string.split(userNames, '\n')
            
            bigMessage = []
            if privateArea:
              bigMessage.append('Creating users in classroom %s' % privateArea)
            bigMessage.append('username,password')
            for userLine in userLines:
                userFields = string.split(userLine, ',')
                numFields = len(userFields)
                username = userFields[0].strip()
                try:
                    newPassword = ''
                    if numFields == 1:                      
                      newPassword = WhysaurusUser.random_password(8)
                    else:
                      newPassword = userFields[1].strip()
                    if username != '':
                      user = WhysaurusUser.signup(self, email=username, name=username, 
                                                  password=newPassword, website=None, areas=None, 
                                                  profession=None, bio=None)
                      user.updateUserSettings([privateArea])
                      bigMessage.append('%s,%s' % ( username, newPassword))
                except WhysaurusException as e:
                    bigMessage.append('Could not create user: %s. Error was:%s' % (username, str(e)))
                
            template_values = {
                'user': loggedInUser,
                'messages': bigMessage
            }    
            self.response.out.write(
                self.template_render('message.html', template_values))   
        else:
            self.response.out.write('User not authorized. ')

        namespace_manager.set_namespace(userNamespace)
Beispiel #10
0
    def forgotPassword(self):
        results = {'result': False}
        email = self.request.get('email')
        user = None
        if email.find('@')!=-1:
            user = WhysaurusUser.get_by_email(email)
            if not user:
                logging.info('Could not find any user entry for email %s' % email)
                results['error'] = 'Could not find user entry with email %s' % email
        else:
            user = WhysaurusUser.get_by_name(email)
            if not user:
                logging.info('Could not find any user entry for username %s' % email)
                results['error'] = 'Could not find user entry with username %s' % email
        if user:
            if hasattr(user, 'email') and user.email is not None and user.email != '':
                user_id = user.get_id()
                token = self.auth.store.user_model.create_signup_token(user_id)    
                verification_url = self.uri_for('verification', type='p', user_id=user_id,
                                                signup_token=token, _full=True)                        
                mail.send_mail(sender='Whysaurus Admin <*****@*****.**>',
                    to=user.email,
                    subject='Whysaurus password reset',
                    html="A password reset request has been received for your account. <br> \
                        Please reset your password  \
                        <a href=\"%s\">here</a>.<br><br>Aaron Lifshin <br> \
                        CTO" % verification_url,
                    body="A password reset request has been received for your account. \n \
                        Please reset your password by visiting this URL:  \
                        %s. \n\nAaron Lifshin \n CTO" % verification_url,
                    reply_to="*****@*****.**"
                )
                results = {'result': True}
            else:
                results = {'result': True, 
                           'message': 'There is no email on file for this \
                               username. Please email [email protected] \
                               and request a password reset.'}

        resultJSON = json.dumps(results)
        self.response.headers["Content-Type"] = 'application/json; charset=utf-8'
        self.response.out.write(resultJSON)
 def saveUsers(self, users):
     for user in users:
         u = WhysaurusUser.getByUrl(user['url'])
         if u:
             u.updatePrivateArea(user['newPrivateArea'])
         else:
             results = {
                 'result': False, 
                 'error': "COuld not find user %s. Other users may have been updated." % user['userAuthIDs']
             } 
             return results       
     return {'result': True}
Beispiel #12
0
    def PopulateGaids(self):
        maxCreates = 250
        bigMessage = ['Populating GA Ids']
        gaIds = []

        query = WhysaurusUser.query()
        for yUser in query.iter():
            if yUser.gaId is None:
                continue
            gaIds.append(yUser.gaId)

        bigMessage.append('Existing gaIds: %s' % (len(gaIds)))

        cntNewIds = 0
        query = WhysaurusUser.query()
        for yUser in query.iter():
            if yUser.gaId is not None:
                continue

            newId = yUser.generateUserGaid(isNewUser=False, existingGaids=gaIds)

            if newId is None:
                bigMessage.append('User %s (%s) failed generation: %s' % (yUser.name, str(yUser.auth_ids), yUser.gaId))
                continue

            yUser.put()

            bigMessage.append('User %s (%s) got gaId: %s' % (yUser.name, str(yUser.auth_ids), yUser.gaId))

            cntNewIds += 1
            if cntNewIds >= maxCreates:
                break

        bigMessage.append('Generated %s new gaIds' % (cntNewIds))

        template_values = {
            'messages': bigMessage
        }
        path = os.path.join(os.path.dirname(__file__), '../templates/django/message.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #13
0
 def setInternalUser(self):
     results = {'result': False}
     loggedInUser = self.current_user
     if loggedInUser and loggedInUser.isAdmin:
         targetUserUrl = self.request.get('userurl')
         if targetUserUrl:
             u = WhysaurusUser.getByUrl(targetUserUrl)
             if u:
                 u.setInternalUser()
                 results = {'result': True, 'username': u.name}
     resultJSON = json.dumps(results)
     self.response.headers["Content-Type"] = 'application/json; charset=utf-8'
     self.response.out.write(resultJSON)
Beispiel #14
0
 def resetPassword(self): 
     results = {'result': False}
     loggedInUser = self.current_user 
     if loggedInUser and loggedInUser.isAdmin:                             
         targetUserUrl = self.request.get('userurl')
         if targetUserUrl:
             u = WhysaurusUser.getByUrl(targetUserUrl)
             if u:
                 newPassword = u.resetPassword()
                 results = {'result': True, 'username': u.name, 'password': newPassword}
     resultJSON = json.dumps(results)
     self.response.headers["Content-Type"] = 'application/json; charset=utf-8'
     self.response.out.write(resultJSON)
Beispiel #15
0
    def get(self):
        userNamespace = namespace_manager.get_namespace()
        namespace_manager.set_namespace('')

        user = self.current_user
        if user is None:
            self.response.out.write('Need to login.')
            return

        if not user.isAdmin:
            self.response.out.write('User not authorized.')
            return

        queryUsr = WhysaurusUser.query().order(-WhysaurusUser.lastLogin)
        areas = PrivateArea.query()
        users = []
        i = 0
        for yUser in queryUsr.iter():
            users = users + [{
                'u': yUser,
                'index': i,
                'userKey': yUser.key.urlsafe()
            }]
            i = i + 1

        paginator = Paginator(users, self.USERS_PER_PAGE)
        page = self.request.get('page')

        try:
            paginatedUsers = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            paginatedUsers = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            paginatedUsers = paginator.page(paginator.num_pages)

        template_values = {
            'user': user,
            'users': paginatedUsers,
            'areas': areas,
            'currentArea': self.session.get('currentArea'),
            'currentAreaDisplayName':
            self.session.get('currentAreaDisplayName')
        }

        self.response.out.write(
            self.template_render('admin.html', template_values))

        namespace_manager.set_namespace(userNamespace)
Beispiel #16
0
    def saveUsers(self, users):

        for user in users:
            u = WhysaurusUser.getByUrl(user['url'])
            if u:
                u.updateUserSettings(user['privateAreas'], user['role'])
            else:
                results = {
                    'result': False, 
                    'error': "Could not find user %s. Other users may have been updated." % user['userAuthIDs']
                } 
                return results     
        
        return {'result': True}
    def signup(self):
        email = self.request.get('email')
        name = self.request.get('userName')
        password = self.request.get('password')
        website =self.request.get('website')
        areas=self.request.get('areas')
        profession =self.request.get('profession')
        bio=self.request.get('bio')
        try:
            user = WhysaurusUser.signup(self, email, name, password, website, areas, profession, bio)
            results = {'result': True}
        except WhysaurusException as e:
            results = {'result': False, 'error': str(e)}

        resultJSON = json.dumps(results)
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(resultJSON)
Beispiel #18
0
    def get(self):
        userNamespace = namespace_manager.get_namespace()        
        namespace_manager.set_namespace('')
   
        user = self.current_user
        if user is None:
            self.response.out.write('Need to login.')
            return

        if not user.isAdmin:
            self.response.out.write('User not authorized.')
            return

        queryUsr = WhysaurusUser.query().order(-WhysaurusUser.lastLogin)
        areas = PrivateArea.query()
        users = []
        i = 0
        for yUser in queryUsr.iter():
            users = users + [{'u':yUser, 'index':i, 'userKey': yUser.key.urlsafe()}]
            i = i+1
            
        paginator = Paginator(users, 25) 
        page = self.request.get('page')

        try:
            paginatedUsers = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            paginatedUsers = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            paginatedUsers = paginator.page(paginator.num_pages)

            
        template_values = {
            'user': user,
            'users': paginatedUsers,
            'areas': areas,
            'currentArea':self.session.get('currentArea'),
            'currentAreaDisplayName':self.session.get('currentAreaDisplayName')
        }

        self.response.out.write(
            self.template_render('admin.html', template_values))

        namespace_manager.set_namespace(userNamespace)  
    def get(self, userURL):
        userNamespace = namespace_manager.get_namespace()
        user = self.current_user

        # USERS ARE STORED IN THE DEFAULT NAMESPACE
        namespace_manager.set_namespace('')
        profileUser = WhysaurusUser.getByUrl(userURL)
        namespace_manager.set_namespace(userNamespace)

        if user:
            permissionToView = user.admin or user.privateArea == profileUser.privateArea 
        else:
            permissionToView = profileUser.privateArea is None or profileUser.privateArea == ''
        if profileUser and permissionToView:                
            path = os.path.join(constants.ROOT, 'templates/profile.html')
            # self.response.headers["Pragma"]="no-cache"
            # self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0"
            # self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00"
            self.response.out.write(template.render(path, self.makeTemplateValues(user, profileUser))) 
        else:
            self.response.out.write('Could not find user: ' + userURL)
    def get(self):
        user = self.current_user
        queryUsr = WhysaurusUser.query()
        areas = PrivateArea.query().fetch(50)
        users = []
        i = 0
        for yUser in queryUsr.iter():            
            users = users + [{'u':yUser, 'index':i, 'userKey': yUser.key.urlsafe()}]
            i = i+1
        template_values = {
            'user': user,
            'users': users,
            'areas': areas,
            'currentArea':self.session.get('currentArea')
        }

        if user and user.admin:                
            path = os.path.join(constants.ROOT, 'templates/admin.html')
            self.response.out.write(template.render(path, template_values)) 
        else:
            self.response.out.write('User not authorized. ')
Beispiel #21
0
    def UpdateUserName(self, userUrl, userName):
        maxUpdates = 1
        bigMessage = ['Populating user name (%s): %s' % (userUrl, userName)]
        
        updates = 0
        query = WhysaurusUser.query()
        for yUser in query.iter():
            if yUser.url != userUrl:
                continue
            bigMessage.append('Changing user name (%s / %s): %s' % (yUser.url, yUser.name, userName))
            yUser.name = userName
            yUser.put()
            updates += 1
            
        bigMessage.append('Users: %s' % (updates))

        template_values = {
            'messages': bigMessage
        }
        path = os.path.join(os.path.dirname(__file__), '../templates/django/message.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #22
0
    def signup(self):
        email = self.request.get('email')
        name = self.request.get('userName')
        password = self.request.get('password')
        website = self.request.get('website')
        areas = self.request.get('areas')
        profession = self.request.get('profession')
        bio = self.request.get('bio')
        try:
            user = WhysaurusUser.signup(self, email, name, password, website,
                                        areas, profession, bio)
            results = {'result': True}

            # See if we can log them into a private area
            if 'postloginaction' in self.session:
                # need to figure out how to pass this over to AJAX
                # and what the point creation will look like
                logging.info(
                    "Have post login action when signing up as an email user")
            elif len(user.privateAreas) == 1 and not user.admin:
                self.setUserArea(user.privateAreas[0])
                results['redirect'] = "/"

            # login newly created user
            auth_id = 'email: %s' % email
            u = self.auth.get_user_by_password(auth_id,
                                               password,
                                               remember=True,
                                               save_session=True)
            user = self.auth.store.user_model.get_by_id(u['user_id'])
            self.current_user = user
            user.login()

        except WhysaurusException as e:
            results = {'result': False, 'error': str(e)}

        resultJSON = json.dumps(results)
        self.response.headers[
            "Content-Type"] = 'application/json; charset=utf-8'
        self.response.out.write(resultJSON)
Beispiel #23
0
    def get(self, userURL):
        userNamespace = namespace_manager.get_namespace()
        user = self.current_user

        # USERS ARE STORED IN THE DEFAULT NAMESPACE
        namespace_manager.set_namespace('')
        profileUser = WhysaurusUser.getByUrl(userURL)
        if profileUser:
            logging.info("got Profile User. Areas were: " + str(profileUser.privateAreas))
        namespace_manager.set_namespace(userNamespace)

        if user:
            permissionToView = user.isAdmin or profileUser.privateAreas == [] or self.session.get('currentArea') in profileUser.privateAreas
        else:
            permissionToView = len(profileUser.privateAreas) == 0

        if profileUser and permissionToView:
            self.response.out.write(
                self.template_render(
                    'profile.html', 
                    self.makeTemplateValues(user, profileUser))) 
        else:
            self.response.out.write('Could not find user: ' + userURL)
Beispiel #24
0
    def signup(self):
        email = self.request.get('email')
        name = self.request.get('userName')
        password = self.request.get('password')
        website =self.request.get('website')
        areas=self.request.get('areas')
        profession =self.request.get('profession')
        bio=self.request.get('bio')
        try:
            user = WhysaurusUser.signup(self, email, name, password, website, areas, profession, bio)
            results = {'result': True}

            # See if we can log them into a private area
            if 'postloginaction' in self.session:
                # need to figure out how to pass this over to AJAX
                # and what the point creation will look like
                logging.info("Have post login action when signing up as an email user")
            elif len(user.privateAreas) == 1:
                self.setUserArea(user.privateAreas[0])
                results['redirect'] = "/"
            
            # login newly created user
            auth_id = 'email: %s' %  email
            u = self.auth.get_user_by_password(auth_id, password, remember=True,
              save_session=True)
            user = self.auth.store.user_model.get_by_id(u['user_id'])
            self.current_user = user
            user.login()
            

        except WhysaurusException as e:
            results = {'result': False, 'error': str(e)}

        resultJSON = json.dumps(results)
        self.response.headers["Content-Type"] = 'application/json; charset=utf-8'
        self.response.out.write(resultJSON)
Beispiel #25
0
    def _on_signin(self, data, auth_info, provider):
        auth_id = '%s: %s' % (provider, data['id'])
        logging.info('Looking for a user with id %s', auth_id)

        user = self.auth.store.user_model.get_by_auth_id(auth_id)
        _attrs = self._to_user_model_attrs(data, self.USER_ATTRS[provider])
        if user:
            logging.info('Found existing user to log in: ' + str(_attrs))
            # Existing users might've changed their profile data so we update our
            # local model anyway. This might result in quite inefficient usage
            # of the Datastore, but we do this anyway for demo purposes.
            #
            # In a real app you could compare _attrs with user's properties fetched
            # from the datastore and update local user in case something's changed.

            self.auth.set_session(self.auth.store.user_to_dict(user))
            self.current_user = user
            user.login()
            if 'postloginaction' in self.session:
                logging.info(
                    'There was a post login action, so the user is not logged into the private area.'
                )
            elif len(user.privateAreas) > 0 and not user.admin:
                self.setUserArea(user.privateAreas[0])
        else:
            # check whether there's a user currently logged in
            # then, create a new user if nobody's signed in,
            # otherwise add this auth_id to currently logged in user.

            if self.logged_in and self.current_user:
                # This code is currently not triggered,
                # there is no way to log in again once logged in
                logging.info('Updating currently logged in user')

                u = self.current_user
                u.populate(**_attrs)
                # The following will also do u.put(). Though, in a real app
                # you might want to check the result, which is
                # (boolean, info) tuple where boolean == True indicates success
                # See webapp2_extras.appengine.auth.models.User for details.
                u.add_auth_id(auth_id)
                u.login()

            else:
                logging.info('Creating a brand new user. Auth_id: %s ',
                             str(auth_id))
                _attrs['url'] = WhysaurusUser.constructURL(_attrs['name'])
                _attrs['gaId'] = WhysaurusUser.generateUniqueUserGaid(True)
                currentArea = self.session.get('currentArea')
                currentAreaDisplayName = self.session.get(
                    'currentAreaDisplayName')
                if currentArea:
                    _attrs['privateAreas'] = [currentArea]

                ok, user = self.auth.store.user_model.create_user(
                    auth_id, **_attrs)
                if ok:
                    if currentArea:
                        areaUser = AreaUser(userKey=user.key.urlsafe(),
                                            privateArea=currentArea)
                        areaUser.putUnique()
                    user.login()
                    self.current_user = user
                    self.auth.set_session(self.auth.store.user_to_dict(user))
                    ReportEvent.queueEventRecord(user.key.urlsafe(), None,
                                                 None, "New User")
                    user.addToSearchIndex()
                else:
                    logging.info('Creation failed: ' + str(ok))
        # Remember auth data during redirect, just for this demo. You wouldn't
        # normally do this.
        # self.session.add_flash(data, 'data - from _on_signin(...)')
        # self.session.add_flash(auth_info, 'auth_info - from _on_signin(...)')
        if 'postloginaction' in self.session:
            postLoginAction = str(self.session['postloginaction'])
            logging.info('Doing post login action: ' + postLoginAction)
            self.doPostLoginAction(postLoginAction, self.session)
        else:
            target = str(self.session['original_url'])
            currentArea = self.session.get('currentArea')
            currentAreaDisplayName = self.session.get('currentAreaDisplayName')
            if target.find("/login") != -1 or currentArea:
                target = "/"
            logging.info('_ON_SIGNIN: Redirecting to %s' % target)
            self.redirect(target)
    def _on_signin(self, data, auth_info, provider):
        auth_id = '%s: %s' % (provider, data['id'])
        logging.info('Looking for a user with id %s', auth_id)

        user = self.auth.store.user_model.get_by_auth_id(auth_id)
        _attrs = self._to_user_model_attrs(data, self.USER_ATTRS[provider])
        if user:
            logging.info('Found existing user to log in: ' + str(_attrs))
            # Existing users might've changed their profile data so we update our
            # local model anyway. This might result in quite inefficient usage
            # of the Datastore, but we do this anyway for demo purposes.
            #
            # In a real app you could compare _attrs with user's properties fetched
            # from the datastore and update local user in case something's changed.  
            
            # AL: Users will now manage their profiles within Whysaurus
            # There is no need to retrieve the ATTRS again          
            # user.populate(**_attrs)
            # user.put()
            self.auth.set_session(self.auth.store.user_to_dict(user))
            self.current_user = user
            user.login()
            if user.privateArea and user.privateArea is not None:
                self.setUserArea(usePrivate=True)
        else:
            # check whether there's a user currently logged in
            # then, create a new user if nobody's signed in,
            # otherwise add this auth_id to currently logged in user.

            if self.logged_in and self.current_user:
                # This code is currently not triggered, 
                # there is no way to log in again once logged in
                logging.info('Updating currently logged in user')

                u = self.current_user
                u.populate(**_attrs)
                # The following will also do u.put(). Though, in a real app
                # you might want to check the result, which is
                # (boolean, info) tuple where boolean == True indicates success
                # See webapp2_extras.appengine.auth.models.User for details.
                u.add_auth_id(auth_id)
                u.login()


            else:
                logging.info('Creating a brand new user. Auth_id: %s ', str(auth_id))                
                _attrs['url'] = WhysaurusUser.constructURL(_attrs['name'])
                ok, user = self.auth.store.user_model.create_user(auth_id, **_attrs)
                if ok:
                    user.login()
                    self.auth.set_session(self.auth.store.user_to_dict(user))
                    self.redirect("/")
                else:
                    logging.info('Creation failed: ' + str(ok))
        # Remember auth data during redirect, just for this demo. You wouldn't
        # normally do this.
        # self.session.add_flash(data, 'data - from _on_signin(...)')
        # self.session.add_flash(auth_info, 'auth_info - from _on_signin(...)')
        target = str(self.session['original_url'])
        if target.find("/login") != -1: # LOGIN page cannot handle it
            target = "/"
        logging.info('_ON_SIGNIN: Redirecting to %s' % target)
        self.redirect(target)
Beispiel #27
0
 def sendNotificationEmails(self):
     WhysaurusUser.sendNotificationEmails(self)
     self.response.out.write('')  # succeed!
Beispiel #28
0
    def _on_signin(self, data, auth_info, provider):
        auth_id = '%s: %s' % (provider, data['id'])
        logging.info('Looking for a user with id %s', auth_id)

        user = self.auth.store.user_model.get_by_auth_id(auth_id)
        _attrs = self._to_user_model_attrs(data, self.USER_ATTRS[provider])
        if user:
            logging.info('Found existing user to log in: ' + str(_attrs))
            # Existing users might've changed their profile data so we update our
            # local model anyway. This might result in quite inefficient usage
            # of the Datastore, but we do this anyway for demo purposes.
            #
            # In a real app you could compare _attrs with user's properties fetched
            # from the datastore and update local user in case something's changed.  

            self.auth.set_session(self.auth.store.user_to_dict(user))
            self.current_user = user
            user.login()
            if 'postloginaction' in self.session:
                logging.info('There was a post login action, so the user is not logged into the private area.')
            elif len(user.privateAreas) > 0:
                self.setUserArea(user.privateAreas[0])
        else:
            # check whether there's a user currently logged in
            # then, create a new user if nobody's signed in,
            # otherwise add this auth_id to currently logged in user.

            if self.logged_in and self.current_user:
                # This code is currently not triggered, 
                # there is no way to log in again once logged in
                logging.info('Updating currently logged in user')

                u = self.current_user
                u.populate(**_attrs)
                # The following will also do u.put(). Though, in a real app
                # you might want to check the result, which is
                # (boolean, info) tuple where boolean == True indicates success
                # See webapp2_extras.appengine.auth.models.User for details.
                u.add_auth_id(auth_id)
                u.login()

            else:
                logging.info('Creating a brand new user. Auth_id: %s ', str(auth_id))  
                _attrs['url'] = WhysaurusUser.constructURL(_attrs['name'])
                currentArea = self.session.get('currentArea')
                currentAreaDisplayName = self.session.get('currentAreaDisplayName')
                if currentArea:                    
                    _attrs['privateAreas'] = [currentArea]
                
                ok, user = self.auth.store.user_model.create_user(auth_id, **_attrs)
                if ok:
                    if currentArea:
                        areaUser = AreaUser(userKey=user.key.urlsafe(), privateArea=currentArea)
                        areaUser.putUnique()
                    user.login()
                    self.current_user = user
                    self.auth.set_session(self.auth.store.user_to_dict(user))
                    ReportEvent.queueEventRecord(user.key.urlsafe(), None, None, "New User")
                    user.addToSearchIndex()                                                               
                else:
                    logging.info('Creation failed: ' + str(ok))
        # Remember auth data during redirect, just for this demo. You wouldn't
        # normally do this.
        # self.session.add_flash(data, 'data - from _on_signin(...)')
        # self.session.add_flash(auth_info, 'auth_info - from _on_signin(...)')
        if 'postloginaction' in self.session:
            postLoginAction = str(self.session['postloginaction'])
            logging.info('Doing post login action: ' + postLoginAction)            
            self.doPostLoginAction(postLoginAction, self.session)
        else:  
            target = str(self.session['original_url'])
            currentArea = self.session.get('currentArea')
            currentAreaDisplayName = self.session.get('currentAreaDisplayName')
            if target.find("/login") != -1 or currentArea:
                target = "/"
            logging.info('_ON_SIGNIN: Redirecting to %s' % target)
            self.redirect(target)