示例#1
0
    def post(self):

        from google.appengine.api import mail, app_identity
        from google.appengine.api.datastore_errors import BadValueError
        from google.appengine.runtime import apiproxy_errors
        import config
        from models import models

        to = self.request.get("to")
        subject = self.request.get("subject")
        body = self.request.get("body")
        sender = self.request.get("sender")

        if sender != '' or not utils.is_email_valid(sender):
            if utils.is_email_valid(config.contact_sender):
                sender = config.contact_sender
            else:
                app_id = app_identity.get_application_id()
                sender = "%s <no-reply@%s.appspotmail.com>" % (app_id, app_id)

        try:
            logEmail = models.LogEmail(
                sender = sender,
                to = to,
                subject = subject,
                body = body,
                when = utils.get_date_time("datetimeProperty")
            )
            logEmail.put()
        except (apiproxy_errors.OverQuotaError, BadValueError):
            logging.error("Error saving Email Log in datastore")

        mail.send_mail(sender, to, subject, body)
示例#2
0
    def post(self):

        from google.appengine.api import mail, app_identity
        from google.appengine.api.datastore_errors import BadValueError
        from google.appengine.runtime import apiproxy_errors
        import config
        from models import models

        to = self.request.get("to")
        subject = self.request.get("subject")
        body = self.request.get("body")
        sender = self.request.get("sender")

        if sender != '' or not utils.is_email_valid(sender):
            if utils.is_email_valid(config.contact_sender):
                sender = config.contact_sender
            else:
                app_id = app_identity.get_application_id()
                sender = "%s <no-reply@%s.appspotmail.com>" % (app_id, app_id)

        try:
            logEmail = models.LogEmail(
                sender=sender,
                to=to,
                subject=subject,
                body=body,
                when=utils.get_date_time("datetimeProperty"))
            logEmail.put()
        except (apiproxy_errors.OverQuotaError, BadValueError):
            logging.error("Error saving Email Log in datastore")

        mail.send_mail(sender, to, subject, body)
示例#3
0
	def create_account_from_social_provider(self, provider_name, uid, email=None, continue_url=None, user_data=None):
		"""Social user does not exist yet so create it with the federated identity provided (uid)
		and create prerequisite user and log the user account in
		"""
		provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label']
		if models.SocialUser.check_unique_uid(provider_name, uid):
			# create user
			# Returns a tuple, where first value is BOOL.
			# If True ok, If False no new user is created
			# Assume provider has already verified email address
			# if email is provided so set activated to True
			auth_id = "%s:%s" % (provider_name, uid)
			if email:
				unique_properties = ['email']
				user_info = self.auth.store.user_model.create_user(
					auth_id, unique_properties, email=email,
					activated=True
				)
			else:
				user_info = self.auth.store.user_model.create_user(
					auth_id, activated=True
				)
			if not user_info[0]: #user is a tuple
				message = _('The account %s is already in use.' % provider_display_name)
				self.add_message(message, 'error')
				return self.redirect_to('register')

			user = user_info[1]

			# create social user and associate with user
			social_user = models.SocialUser(
				user = user.key,
				provider = provider_name,
				uid = uid,
			)
			if user_data:
				social_user.extra_data = user_data
				self.session[provider_name] = json.dumps(user_data) # TODO is this needed?
			social_user.put()
			# authenticate user
			self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
			logVisit = models.LogVisit(
				user = user.key,
				uastring = self.request.user_agent,
				ip = self.request.remote_addr,
				timestamp = utils.get_date_time()
			)
			logVisit.put()

			message = _('Welcome!  You have been registered as a new user through %s and logged in.' % provider_display_name)
			self.add_message(message, 'success')
		else:
			message = _('This %s account is already in use.' % provider_display_name)
			self.add_message(message, 'error')
		if continue_url:
			self.redirect(continue_url)
		else:
			self.redirect_to('edit-profile')
    def get(self, provider_name):
        if provider_name == "twitter":
            oauth_token = self.request.get('oauth_token')
            oauth_verifier = self.request.get('oauth_verifier')
            twitter_helper = twitter.TwitterAuth(self)
            user_data = twitter_helper.auth_complete(oauth_token,
                oauth_verifier)
            if self.user:
                # new association with twitter
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'twitter', str(user_data['id'])):
                    social_user = models.SocialUser(
                        user = user_info.key,
                        provider = 'twitter',
                        uid = str(user_data['id']),
                        extra_data = user_data
                    )
                    social_user.put()

                    message = _('Twitter association added!')
                    self.add_message(message,'success')
                else:
                    message = _('This Twitter account is already in use!')
                    self.add_message(message,'error')
                self.redirect_to('edit-profile')
            else:
                # login with twitter
                social_user = models.SocialUser.get_by_provider_and_uid('twitter',
                    str(user_data['id']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                    logVisit = models.LogVisit(
                        user = user.key,
                        uastring = self.request.user_agent,
                        ip = self.request.remote_addr,
                        timestamp = utils.get_date_time()
                    )
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms
                    twitter_helper.save_association_data(user_data)
                    message = _('Account with association to your Twitter does not exist. You can associate it right now, if you login with existing site account or create new on Sign up page.')
                    self.add_message(message,'info')
                    self.redirect_to('login')
            # Debug Callback information provided
#            for k,v in user_data.items():
#                print(k +":"+  v )
        else:
            self.redirect_to('login')
示例#5
0
    def post(self):
        to = self.request.get("to")
        group_id = self.request.get("group_id")
        invitor_id = self.request.get("invitor_id")
        invite_url = self.request.get("invite_url")

        # admin of the pool
        sender = config.contact_sender

        # test to see if the sender_id and group number is real
        invitor = User.get_by_id(long(invitor_id))
        group = Group.get_by_id(long(group_id))

        # if we found the sending user and group
        if invitor and group:
            # rest of the email stuff
            subject = "You've Been Invited to the %s Group on %s" % (
                group.name, config.app_name)
            body = """
Howdy!

You've been invited to the %s group on the %s Compute Pool by %s.  Acceptance of the group invite will require linking the site to your Google account.

%s

This invite will allow you to start instances which are managed exclusively by appliances in the %s group.  Your membership also allows you to add your own OpenStack cluster and appliance to the group.  This is a very good thing for all involved.

If this email comes as a complete surprise to you, simply delete it.  We may yet meet again.

Cheers,

%s
%s
		""" % (group.name, config.app_name, invitor.username, invite_url, group.name,
            config.app_owner, config.app_name)

            logEmail = LogEmail(sender=sender,
                                to=to,
                                subject=subject,
                                body=body,
                                when=utils.get_date_time("datetimeProperty"))
            logEmail.put()

            try:
                mail.send_mail(sender, to, subject, body)
            except Exception as ex:
                logging.error(
                    "Failed attempt to send invite email because %s." % ex)
        else:
            # doing nothing, you fuckers
            logging.error("Failed attempt to send invite email.")
示例#6
0
    def get(self):

        #Next URL
        continue_url = self.request.get('continue_url')
        
        # get our request code back from the Alfresco login handler above
        code = self.request.get('code')

        # create our alfresco auth object
        scope = 'public_api'
        alfresco_helper = alfresco.AlfrescoAuth(self.app.config.get('alfresco_server'),
                                          self.app.config.get('alfresco_client_id'), \
                                          self.app.config.get('alfresco_client_secret'),
                                          self.app.config.get('alfresco_redirect_uri'),scope,self.app.config.get('alfresco_network'))

        # retrieve the access token using the code and auth object
        access_token = alfresco_helper.get_access_token(code)
        self.session['alfresco_access_token']= access_token # TODO: look for refresh token
        user_data = alfresco_helper.get_user_info(access_token)
        user_data = user_data['entry']#TODO: JC use get instead
       
       
        if self.user: 
            user_info = self.user_model.get_by_id(long(self.user_id))
            self.redirect_to('edit-profile') 
        else:
            
            # user is not logged in, but is trying to log in via alfresco
            user = models.User.get_by_username(user_data['id'])
            if user:
                # Alfresco user exists. Need authenticate related site account
                self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                if self.app.config['log_visit']:
                    try:
                        logVisit = models.LogVisit(
                            user=user.key,
                            uastring=self.request.user_agent,
                            ip=self.request.remote_addr,
                            timestamp=utils.get_date_time()
                        )
                        logVisit.put()
                    except (apiproxy_errors.OverQuotaError, BadValueError):
                        logging.error("Error saving Visit Log in datastore")
                        
                    self.redirect_to('login')
                     
            else: # Create Alfresco User
                uid = str(user_data['id'])
                email = str(user_data.get('email'))
                self.create_account_from_alfresco(uid, email,continue_url, user_data)
示例#7
0
	def post(self):
		to = self.request.get("to")
		group_id = self.request.get("group_id")
		invitor_id = self.request.get("invitor_id")
		invite_url = self.request.get("invite_url")

		# admin of the pool
		sender = config.contact_sender

		# test to see if the sender_id and group number is real
		invitor = User.get_by_id(long(invitor_id))
		group = Group.get_by_id(long(group_id))

		# if we found the sending user and group
		if invitor and group:
			# rest of the email stuff
			subject = "You've Been Invited to the %s Group on %s" % (group.name, config.app_name)
			body = """
Howdy!

You've been invited to the %s group on %s by %s.  Acceptance of the group invite will require linking the site to your Google account.

%s

This invite will allow you to start instances which are managed exclusively by appliances in the %s group.  Your membership also allows you to add your own OpenStack cluster and appliance to the group.  This is a very good thing for all involved.

If this email comes as a complete surprise to you, simply delete it.  We may yet meet again.

Cheers,

%s
%s
		""" % (group.name, config.app_name, invitor.username, invite_url, group.name, config.app_owner, config.app_name)

			logEmail = LogEmail(
				sender = sender,
				to = to,
				subject = subject,
				body = body,
				when = utils.get_date_time("datetimeProperty")
			)
			logEmail.put()

			try:
				mail.send_mail(sender, to, subject, body)
			except Exception as ex:
				logging.error("Failed attempt to send invite email because %s." % ex)
		else:
			# doing nothing, you fuckers
			logging.error("Failed attempt to send invite email.")
示例#8
0
    def create_account_from_alfresco(self, uid, email=None,continue_url=None, user_data=None):
        """
            Creates the app users from Alfresco
        """

        auth_id = "%s:%s" % ('alfresco', uid)
        unique_properties = ['email']
        
      
        # Returns a tuple, where first value is BOOL.
        # If True ok, If False no new user is created .
        user_info = self.auth.store.user_model.create_user(
        auth_id, unique_properties,password_raw='' ,
        username=email, name=user_data.get('firstName'), last_name=user_data.get('lastName'), email=email,
        ip=self.request.remote_addr, country='', tz='',activated=True )
    
        # If not user is created (dam !)
        if not user_info[0]: 
            message = _('The account  %s is not created')
            self.add_message(message, 'error')
            return self.redirect_to('home')
       
        user = user_info[1]
        user.extra_data = user_data
        self.session['alfresco'] = json.dumps(user_data) # TODO is this needed?
        
        
        # authenticate user
        self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
        if self.app.config['log_visit']:
            try:
                logVisit = models.LogVisit(
                    user=user.key,
                    uastring=self.request.user_agent,
                    ip=self.request.remote_addr,
                    timestamp=utils.get_date_time()
                )
                logVisit.put()
            except (apiproxy_errors.OverQuotaError, BadValueError):
                logging.error("Error saving Visit Log in datastore")

        message = _('Welcome!  You have been registered as a new user '
                    'and logged in through Alfresco.') 
        self.add_message(message, 'success')
        
        if continue_url:
            self.redirect(continue_url)
        else:
            self.redirect_to('edit-profile')
示例#9
0
    def post(self):
        to = self.request.get("to")
        invitor_id = self.request.get("invitor_id")
        invite_url = self.request.get("invite_url")

        # admin of the pool
        sender = config.contact_sender

        # test to see if the sender_id is real
        invitor = User.get_by_id(long(invitor_id))
        # if we found the sending user and group
        if invitor:
            # rest of the email stuff
            subject = "You've Been Invited to %s" % (config.app_name)
            body = """
Howdy!

You've been invited to %s by %s.  Acceptance of the invite will require linking the site to your Google account.

%s

This invite will allow you to start using the Lucidworks' instance launcher.

If this email comes as a complete surprise to you, simply delete it.  We may yet meet again.

Cheers,

%s
%s
		""" % (group.name, config.app_name, invitor.username, invite_url, group.name,
            config.app_owner, config.app_name)

            logEmail = LogEmail(sender=sender,
                                to=to,
                                subject=subject,
                                body=body,
                                when=utils.get_date_time("datetimeProperty"))
            logEmail.put()

            try:
                mail.send_mail(sender, to, subject, body)
            except Exception as ex:
                logging.error(
                    "Failed attempt to send invite email because %s." % ex)
        else:
            # doing nothing
            logging.error("Failed attempt to send invite email.")
示例#10
0
 def post(self):
     """
           username: Get the username from POST dict
           password: Get the password from POST dict
     """
     if not self.form.validate():
         return self.get()
     username = self.form.username.data.lower()
     
     try:
         if utils.is_email_valid(username):
             user = models.User.get_by_email(username)
             if user:
                 auth_id = user.auth_ids[0]
             else:
                 raise InvalidAuthIdError
         else:
             auth_id = "own:%s" % username
             user = models.User.get_by_auth_id(auth_id)
             
         password = self.form.password.data.strip()
         remember_me = True if str(self.request.POST.get('remember_me')) == 'on' else False
             
         # Password to SHA512
         password = utils.encrypt(password, config.salt)
 
         # Try to login user with password
         # Raises InvalidAuthIdError if user is not found
         # Raises InvalidPasswordError if provided password
         # doesn't match with specified user
         self.auth.get_user_by_password(
             auth_id, password, remember=remember_me)
         visitLog = models.VisitLog(
             user=user.key,
             uastring=self.request.user_agent,
             ip=self.request.remote_addr,
             timestamp=utils.get_date_time()
         )
         visitLog.put()
         self.redirect_to('secure')
     except (InvalidAuthIdError, InvalidPasswordError), e:
         # Returns error message to self.response.write in
         # the BaseHandler.dispatcher
         message = _("Login invalid, Try again") + ".&nbsp;&nbsp;&nbsp;&nbsp;" + _("Don't have an account?") + \
                 '  <a href="' + self.uri_for('register') + '">' + _("Sign Up") + '</a>'
         self.add_message(message, 'error')
         return self.redirect_to('login')
示例#11
0
    def get(self):
        oauth_token = self.request.get('oauth_token')
        oauth_verifier = self.request.get('oauth_verifier')
        twitter_helper = twitter.TwitterAuth(self)
        user_data = twitter_helper.auth_complete(oauth_token, oauth_verifier)
        if self.user:
            # new association with twitter
            user_info = models.User.get_by_id(long(self.user_id))
            if models.SocialUser.check_unique(user_info.key, 'twitter',
                                              str(user_data['id'])):
                social_user = models.SocialUser(user=user_info.key,
                                                provider='twitter',
                                                uid=str(user_data['id']),
                                                extra_data=user_data)
                social_user.put()

                message = _('Twitter association added!')
                self.add_message(message, 'success')
            else:
                message = _('This Twitter account is already in use!')
                self.add_message(message, 'error')
            self.redirect_to('edit-profile')
        else:
            # login with twitter
            social_user = models.SocialUser.get_by_provider_and_uid(
                'twitter', str(user_data['id']))
            if social_user:
                # Social user is exist. Need authenticate related site account
                user = social_user.user.get()
                self.auth.set_session(self.auth.store.user_to_dict(user),
                                      remember=True)
                visitLog = models.VisitLog(user=user.key,
                                           uastring=self.request.user_agent,
                                           ip=self.request.remote_addr,
                                           timestamp=utils.get_date_time())
                visitLog.put()
                self.redirect_to('secure')
            else:
                # Social user is not exist. Need show login and registration forms
                twitter_helper.save_association_data(user_data)
                message = _(
                    'Account with association to your Twitter does not exist. You can associate it right now, if you login with existing site account or create new on Sign up page.'
                )
                self.add_message(message, 'info')
                self.redirect_to('login')
        """
示例#12
0
文件: main.py 项目: coto/beecoss
    def get(self):

#        self.response.write(self.request.url)
        visitLog = models.VisitLog(
            uastring = self.request.user_agent,
            ip = self.request.remote_addr,
            timestamp = utils.get_date_time()
        )
        visitLog.put()

        if re.search('protoboard.cl', str(self.request.url)):
            new_url = re.sub('protoboard.cl', 'beecoss.com', str(self.request.url))
#            self.response.write(new_url)
            self.redirect(new_url)
        elif re.search('protoboard', str(self.request.url)):
            new_url = re.sub('protoboard', 'beecoss', str(self.request.url))
            self.redirect(new_url)
        else:
            self.response.write("This domain has been acquired by <a href='http://beecoss.com'>Beecoss.com</a>.")
示例#13
0
    def get(self):

        #        self.response.write(self.request.url)
        visitLog = models.VisitLog(uastring=self.request.user_agent,
                                   ip=self.request.remote_addr,
                                   timestamp=utils.get_date_time())
        visitLog.put()

        if re.search('protoboard.cl', str(self.request.url)):
            new_url = re.sub('protoboard.cl', 'beecoss.com',
                             str(self.request.url))
            #            self.response.write(new_url)
            self.redirect(new_url)
        elif re.search('protoboard', str(self.request.url)):
            new_url = re.sub('protoboard', 'beecoss', str(self.request.url))
            self.redirect(new_url)
        else:
            self.response.write(
                "This domain has been acquired by <a href='http://beecoss.com'>Beecoss.com</a>."
            )
示例#14
0
    def post(self):

        from google.appengine.api import mail, app_identity

        to = self.request.get("to")
        subject = self.request.get("subject")
        body = self.request.get("body")
        sender = self.request.get("sender")

        if sender != '' or not utils.is_email_valid(sender):
            if utils.is_email_valid(self.app.config.get('contact_sender')):
                sender = self.app.config.get('contact_sender')
            else:
                app_id = app_identity.get_application_id()
                sender = "%s <no-reply@%s.appspotmail.com>" % (app_id, app_id)

        if self.app.config['log_email']:
            try:
                logEmail = models.LogEmail(
                    sender=sender,
                    to=to,
                    subject=subject,
                    body=body,
                    when=utils.get_date_time("datetimeProperty")
                )
                logEmail.put()
            except (apiproxy_errors.OverQuotaError, BadValueError):
                logging.error("Error saving Email Log in datastore")

        try:
            message = mail.EmailMessage()
            message.sender = sender
            message.to = to
            message.subject = subject
            message.html = body
            message.send()
        except Exception, e:
            logging.error("Error sending email: %s" % e)
示例#15
0
    def post(self):
        """
        username: Get the username from POST dict
        password: Get the password from POST dict
        """

        if not self.form.validate():
            return self.get()
        username = self.form.username.data.lower()

        try:
            if utils.is_email_valid(username):
                user = models.User.get_by_email(username)
                if user:
                    auth_id = user.auth_ids[0]
                else:
                    raise InvalidAuthIdError
            else:
                auth_id = "own:%s" % username
                user = models.User.get_by_auth_id(auth_id)

            password = self.form.password.data.strip()
            remember_me = True if str(
                self.request.POST.get('remember_me')) == 'on' else False

            # Password to SHA512
            password = utils.hashing(password, config.salt)

            # Try to login user with password
            # Raises InvalidAuthIdError if user is not found
            # Raises InvalidPasswordError if provided password
            # doesn't match with specified user
            self.auth.get_user_by_password(auth_id,
                                           password,
                                           remember=remember_me)

            # if user account is not activated, logout and redirect to home
            if (user.activated == False):
                # logout
                self.auth.unset_session()

                # redirect to home with error message
                message = _(
                    'Your account has been suspended. Please contact support for more information.'
                )
                self.add_message(message, 'error')
                return self.redirect_to('login')

            # REMOVE ME
            #check twitter association in session
            twitter_helper = twitter.TwitterAuth(self)
            twitter_association_data = twitter_helper.get_association_data()
            if twitter_association_data is not None:
                if models.SocialUser.check_unique(
                        user.key, 'twitter',
                        str(twitter_association_data['id'])):
                    social_user = models.SocialUser(
                        user=user.key,
                        provider='twitter',
                        uid=str(twitter_association_data['id']),
                        extra_data=twitter_association_data)
                    social_user.put()

            logVisit = models.LogVisit(user=user.key,
                                       uastring=self.request.user_agent,
                                       ip=self.request.remote_addr,
                                       timestamp=utils.get_date_time())
            logVisit.put()
            self.redirect_to('home')
        except (InvalidAuthIdError, InvalidPasswordError), e:
            # Returns error message to self.response.write in
            # the BaseHandler.dispatcher
            message = _("Your username or password is incorrect.  Caps lock?")
            self.add_message(message, 'error')
            return self.redirect_to('login')
示例#16
0
	def get(self, provider_name):
		if not self.app.config.get('enable_federated_login'):
			message = _('Federated login is disabled.')
			self.add_message(message, 'warning')
			return self.redirect_to('login')
		continue_url = str(self.request.get('continue_url'))
		if provider_name == "twitter":
			oauth_token = self.request.get('oauth_token')
			oauth_verifier = self.request.get('oauth_verifier')
			twitter_helper = twitter.TwitterAuth(self)
			user_data = twitter_helper.auth_complete(oauth_token,
				oauth_verifier)
			logging.info('twitter user_data: ' + str(user_data))
			if self.user:
				# new association with twitter
				user_info = models.User.get_by_id(long(self.user_id))
				if models.SocialUser.check_unique(user_info.key, 'twitter', str(user_data['user_id'])):
					social_user = models.SocialUser(
						user = user_info.key,
						provider = 'twitter',
						uid = str(user_data['user_id']),
						extra_data = user_data
					)
					social_user.put()

					message = _('Twitter association added.')
					self.add_message(message, 'success')
				else:
					message = _('This Twitter account is already in use.')
					self.add_message(message, 'error')
				if continue_url:
					self.redirect(continue_url)
				else:
					self.redirect_to('edit-profile')
			else:
				# login with twitter
				social_user = models.SocialUser.get_by_provider_and_uid('twitter',
					str(user_data['user_id']))
				if social_user:
					# Social user exists. Need authenticate related site account
					user = social_user.user.get()
					self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
					logVisit = models.LogVisit(
						user = user.key,
						uastring = self.request.user_agent,
						ip = self.request.remote_addr,
						timestamp = utils.get_date_time()
					)
					logVisit.put()
					if continue_url:
						self.redirect(continue_url)
					else:
						self.redirect_to('home')
				else:
					uid = str(user_data['user_id'])
					email = str(user_data.get('email'))
					self.create_account_from_social_provider(provider_name, uid, email, continue_url, user_data)

		# github association
		elif provider_name == "github":
			# get our request code back from the social login handler above
			code = self.request.get('code')

			# create our github auth object 
			scope = 'gist'
			github_helper = github.GithubAuth(self.app.config.get('github_server'), self.app.config.get('github_client_id'), \
											  self.app.config.get('github_client_secret'), self.app.config.get('github_redirect_uri'), scope)

			# retrieve the access token using the code and auth object
			access_token = github_helper.get_access_token(code)
			user_data = github_helper.get_user_info(access_token)
			logging.info('github user_data: ' + str(user_data))
			if self.user:
				# user is already logged in so we set a new association with twitter
				user_info = models.User.get_by_id(long(self.user_id))
				if models.SocialUser.check_unique(user_info.key, 'github', str(user_data['login'])):
					social_user = models.SocialUser(
						user = user_info.key,
						provider = 'github',
						uid = str(user_data['login']),
						extra_data = user_data
					)
					social_user.put()

					message = _('Github association added.')
					self.add_message(message, 'success')
				else:
					message = _('This Github account is already in use.')
					self.add_message(message, 'error')
				self.redirect_to('edit-profile')
			else:
				# user is not logged in, but is trying to log in via github
				social_user = models.SocialUser.get_by_provider_and_uid('github', str(user_data['login']))
				if social_user:
					# Social user exists. Need authenticate related site account
					user = social_user.user.get()
					self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
					logVisit = models.LogVisit(
						user = user.key,
						uastring = self.request.user_agent,
						ip = self.request.remote_addr,
						timestamp = utils.get_date_time()
					)
					logVisit.put()
					self.redirect_to('home')
				else:
					uid = str(user_data['id'])
					email = str(user_data.get('email'))
					self.create_account_from_social_provider(provider_name, uid, email, continue_url, user_data)
		#end github

		# facebook association
		elif provider_name == "facebook":
			code = self.request.get('code')
			callback_url = "%s/social_login/%s/complete" % (self.request.host_url, provider_name)
			token = facebook.get_access_token_from_code(code, callback_url, self.app.config.get('fb_api_key'), self.app.config.get('fb_secret'))
			access_token = token['access_token']
			fb = facebook.GraphAPI(access_token)
			user_data = fb.get_object('me')
			logging.info('facebook user_data: ' + str(user_data))
			if self.user:
				# new association with facebook
				user_info = models.User.get_by_id(long(self.user_id))
				if models.SocialUser.check_unique(user_info.key, 'facebook', str(user_data['id'])):
					social_user = models.SocialUser(
						user = user_info.key,
						provider = 'facebook',
						uid = str(user_data['id']),
						extra_data = user_data
					)
					social_user.put()

					message = _('Facebook association added!')
					self.add_message(message,'success')
				else:
					message = _('This Facebook account is already in use!')
					self.add_message(message,'error')
				if continue_url:
					self.redirect(continue_url)
				else:
					self.redirect_to('edit-profile')
			else:
				# login with Facebook
				social_user = models.SocialUser.get_by_provider_and_uid('facebook',
					str(user_data['id']))
				if social_user:
					# Social user exists. Need authenticate related site account
					user = social_user.user.get()
					self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
					logVisit = models.LogVisit(
						user = user.key,
						uastring = self.request.user_agent,
						ip = self.request.remote_addr,
						timestamp = utils.get_date_time()
					)
					logVisit.put()
					if continue_url:
						self.redirect(continue_url)
					else:
						self.redirect_to('home')
				else:
					uid = str(user_data['id'])
					email = str(user_data.get('email'))
					self.create_account_from_social_provider(provider_name, uid, email, continue_url, user_data)

			# end facebook
		# association with linkedin
		elif provider_name == "linkedin":
			callback_url = "%s/social_login/%s/complete" % (self.request.host_url, provider_name)
			link = linkedin.LinkedIn(self.app.config.get('linkedin_api'), self.app.config.get('linkedin_secret'), callback_url)
			request_token = self.session['request_token']
			request_token_secret= self.session['request_token_secret']
			link._request_token = request_token
			link._request_token_secret = request_token_secret
			verifier = self.request.get('oauth_verifier')
			#~ print 'test'
			#~ print 'request_token= %s ; request_token_secret= %s ;verifier = %s ' % (request_token, request_token_secret, verifier)
			link.access_token(verifier=verifier)
			u_data = link.get_profile()
			logging.info('Linkedin u_data: {}'.format(u_data))
			user_key = re.search(r'key=(\d+)', u_data.private_url).group(1)
			user_data={'first_name':u_data.first_name, 'last_name':u_data.last_name ,'id':user_key}
			self.session['linkedin'] = json.dumps(user_data)
			logging.info('linkedin user_data: ' + str(user_data))

			if self.user:
				# new association with linkedin
				user_info = models.User.get_by_id(long(self.user_id))
				if models.SocialUser.check_unique(user_info.key, 'linkedin', str(user_data['id'])):
					social_user = models.SocialUser(
						user = user_info.key,
						provider = 'linkedin',
						uid = str(user_data['id']),
						extra_data = user_data
					)
					social_user.put()

					message = _('Linkedin association added!')
					self.add_message(message,'success')
				else:
					message = _('This Linkedin account is already in use!')
					self.add_message(message,'error')
				if continue_url:
					self.redirect(continue_url)
				else:
					self.redirect_to('edit-profile')
			else:
				# login with Linkedin
				social_user = models.SocialUser.get_by_provider_and_uid('linkedin',
					str(user_data['id']))
				if social_user:
					# Social user exists. Need authenticate related site account
					user = social_user.user.get()
					self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
					logVisit = models.LogVisit(
						user = user.key,
						uastring = self.request.user_agent,
						ip = self.request.remote_addr,
						timestamp = utils.get_date_time()
					)
					logVisit.put()
					if continue_url:
						self.redirect(continue_url)
					else:
						self.redirect_to('home')
				else:
					uid = str(user_data['id'])
					email = str(user_data.get('email'))
					self.create_account_from_social_provider(provider_name, uid, email, continue_url, user_data)

			#end linkedin

		# google, myopenid, yahoo OpenID Providers
		elif provider_name in models.SocialUser.open_id_providers():
			provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label']
			# get info passed from OpenId Provider
			from google.appengine.api import users
			current_user = users.get_current_user()
			if current_user:
				if current_user.federated_identity():
					uid = current_user.federated_identity()
				else:
					uid = current_user.user_id()
				email = current_user.email()
			else:
				message = _('No user authentication information received from %s. '
							'Please ensure you are logging in from an authorized OpenID Provider (OP).'
							% provider_display_name)
				self.add_message(message, 'error')
				return self.redirect_to('login', continue_url=continue_url) if continue_url else self.redirect_to('login')
			if self.user:
				# add social account to user
				user_info = models.User.get_by_id(long(self.user_id))
				if models.SocialUser.check_unique(user_info.key, provider_name, uid):
					social_user = models.SocialUser(
						user = user_info.key,
						provider = provider_name,
						uid = uid
					)
					social_user.put()

					message = _('%s association successfully added.' % provider_display_name)
					self.add_message(message, 'success')
				else:
					message = _('This %s account is already in use.' % provider_display_name)
					self.add_message(message, 'error')
				if continue_url:
					self.redirect(continue_url)
				else:
					self.redirect_to('edit-profile')
			else:
				# login with OpenId Provider
				social_user = models.SocialUser.get_by_provider_and_uid(provider_name, uid)
				if social_user:
					# Social user found. Authenticate the user
					user = social_user.user.get()
					self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
					logVisit = models.LogVisit(
						user = user.key,
						uastring = self.request.user_agent,
						ip = self.request.remote_addr,
						timestamp = utils.get_date_time()
					)
					logVisit.put()
					if continue_url:
						self.redirect(continue_url)
					else:
						self.redirect_to('home')
				else:
					self.create_account_from_social_provider(provider_name, uid, email, continue_url)
		else:
			message = _('This authentication method is not yet implemented.')
			self.add_message(message, 'warning')
			self.redirect_to('login', continue_url=continue_url) if continue_url else self.redirect_to('login')
示例#17
0
	def post(self):
		"""
		username: Get the username from POST dict
		password: Get the password from POST dict
		"""

		if not self.form.validate():
			return self.get()
		username = self.form.username.data.lower()
		continue_url = self.request.get('continue_url').encode('ascii', 'ignore')

		try:
			if utils.is_email_valid(username):
				user = models.User.get_by_email(username)
				if user:
					auth_id = user.auth_ids[0]
				else:
					raise InvalidAuthIdError
			else:
				auth_id = "own:%s" % username
				user = models.User.get_by_auth_id(auth_id)

			password = self.form.password.data.strip()
			remember_me = True if str(self.request.POST.get('remember_me')) == 'on' else False

			# Password to SHA512
			password = utils.hashing(password, self.app.config.get('salt'))

			# Try to login user with password
			# Raises InvalidAuthIdError if user is not found
			# Raises InvalidPasswordError if provided password
			# doesn't match with specified user
			self.auth.get_user_by_password(
				auth_id, password, remember=remember_me)

			# if user account is not activated, logout and redirect to home
			if (user.activated == False):
				# logout
				self.auth.unset_session()

				# redirect to home with error message
				resend_email_uri = self.uri_for('resend-account-activation', user_id=user.get_id(),
												token=models.User.create_resend_token(user.get_id()))
				message = _('Your account has not yet been activated. Please check your email to activate it or') +\
						  ' <a href="'+resend_email_uri+'">' + _('click here') + '</a> ' + _('to resend the email.')
				self.add_message(message, 'error')
				return self.redirect_to('home')

			# check twitter association in session
			twitter_helper = twitter.TwitterAuth(self)
			twitter_association_data = twitter_helper.get_association_data()
			if twitter_association_data is not None:
				if models.SocialUser.check_unique(user.key, 'twitter', str(twitter_association_data['id'])):
					social_user = models.SocialUser(
						user = user.key,
						provider = 'twitter',
						uid = str(twitter_association_data['id']),
						extra_data = twitter_association_data
					)
					social_user.put()

			# check facebook association
			fb_data = None
			try:
				fb_data = json.loads(self.session['facebook'])
			except:
				pass

			if fb_data is not None:
				if models.SocialUser.check_unique(user.key, 'facebook', str(fb_data['id'])):
					social_user = models.SocialUser(
						user = user.key,
						provider = 'facebook',
						uid = str(fb_data['id']),
						extra_data = fb_data
					)
					social_user.put()

			# check linkedin association
			li_data = None
			try:
				li_data = json.loads(self.session['linkedin'])
			except:
				pass
			if li_data is not None:
				if models.SocialUser.check_unique(user.key, 'linkedin', str(li_data['id'])):
					social_user = models.SocialUser(
						user = user.key,
						provider = 'linkedin',
						uid = str(li_data['id']),
						extra_data = li_data
					)
					social_user.put()

			# end linkedin

			logVisit = models.LogVisit(
				user=user.key,
				uastring=self.request.user_agent,
				ip=self.request.remote_addr,
				timestamp=utils.get_date_time()
			)
			logVisit.put()
			if continue_url:
				self.redirect(continue_url)
			else:
				self.redirect_to('home')
		except (InvalidAuthIdError, InvalidPasswordError), e:
			# Returns error message to self.response.write in
			# the BaseHandler.dispatcher
			message = _("Your username or password is incorrect. "
						"Please try again (make sure your caps lock is off)")
			self.add_message(message, 'error')
			self.redirect_to('login', continue_url=continue_url) if continue_url else self.redirect_to('login')
示例#18
0
    def post(self):
        """
        username: Get the username from POST dict
        password: Get the password from POST dict
        """

        if not self.form.validate():
            return self.get()
        username = self.form.username.data.lower()

        try:
            if utils.is_email_valid(username):
                user = models.User.get_by_email(username)
                if user:
                    auth_id = user.auth_ids[0]
                else:
                    raise InvalidAuthIdError
            else:
                auth_id = "own:%s" % username
                user = models.User.get_by_auth_id(auth_id)

            password = self.form.password.data.strip()
            remember_me = True if str(
                self.request.POST.get('remember_me')) == 'on' else False

            # Password to SHA512
            password = utils.encrypt(password, config.salt)

            # Try to login user with password
            # Raises InvalidAuthIdError if user is not found
            # Raises InvalidPasswordError if provided password
            # doesn't match with specified user
            self.auth.get_user_by_password(auth_id,
                                           password,
                                           remember=remember_me)

            # if user account is not activated, logout and redirect to home
            if (user.activated == False):
                # logout
                self.auth.unset_session()

                # redirect to home with error message
                resend_email_uri = self.uri_for('resend-account-activation',
                                                encoded_email=utils.encode(
                                                    user.email))
                message = _('Sorry, your account') + ' <strong>{0:>s}</strong>'.format(username) + " " +\
                          _('has not been activated. Please check your email to activate your account') + ". " +\
                          _('Or click') + " <a href='"+resend_email_uri+"'>" + _('this') + "</a> " + _('to resend the email')
                self.add_message(message, 'error')
                return self.redirect_to('home')

            # check twitter association in session
            twitter_helper = twitter.TwitterAuth(self)
            twitter_association_data = twitter_helper.get_association_data()
            if twitter_association_data is not None:
                if models.SocialUser.check_unique(
                        user.key, 'twitter',
                        str(twitter_association_data['id'])):
                    social_user = models.SocialUser(
                        user=user.key,
                        provider='twitter',
                        uid=str(twitter_association_data['id']),
                        extra_data=twitter_association_data)
                    social_user.put()

            logVisit = models.LogVisit(user=user.key,
                                       uastring=self.request.user_agent,
                                       ip=self.request.remote_addr,
                                       timestamp=utils.get_date_time())
            logVisit.put()
            self.redirect_to('home')
        except (InvalidAuthIdError, InvalidPasswordError), e:
            # Returns error message to self.response.write in
            # the BaseHandler.dispatcher
            message = _("Login invalid, Try again.") + "<br/>" + _("Don't have an account?") + \
                    '  <a href="' + self.uri_for('register') + '">' + _("Sign Up") + '</a>'
            self.add_message(message, 'error')
            return self.redirect_to('login')
示例#19
0
    def get(self, provider_name):
        if not config.enable_federated_login:
            message = _('Federated login is disabled.')
            self.add_message(message, 'warning')
            return self.redirect_to('login')
        if provider_name == "twitter":
            oauth_token = self.request.get('oauth_token')
            oauth_verifier = self.request.get('oauth_verifier')
            twitter_helper = twitter.TwitterAuth(self)
            user_data = twitter_helper.auth_complete(oauth_token,
                                                     oauth_verifier)
            if self.user:
                # new association with twitter
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'twitter',
                                                  str(user_data['id'])):
                    social_user = models.SocialUser(user=user_info.key,
                                                    provider='twitter',
                                                    uid=str(user_data['id']),
                                                    extra_data=user_data)
                    social_user.put()

                    message = _('Twitter association added!')
                    self.add_message(message, 'success')
                else:
                    message = _('This Twitter account is already in use!')
                    self.add_message(message, 'error')
                self.redirect_to('edit-profile')
            else:
                # login with twitter
                social_user = models.SocialUser.get_by_provider_and_uid(
                    'twitter', str(user_data['id']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user),
                                          remember=True)
                    logVisit = models.LogVisit(
                        user=user.key,
                        uastring=self.request.user_agent,
                        ip=self.request.remote_addr,
                        timestamp=utils.get_date_time())
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms
                    twitter_helper.save_association_data(user_data)
                    message = _(
                        'Account with association to your Twitter does not exist. You can associate it right now, if you login with existing site account or create new on Sign up page.'
                    )
                    self.add_message(message, 'info')
                    self.redirect_to('login')
            # Debug Callback information provided


#            for k,v in user_data.items():
#                print(k +":"+  v )
# google, myopenid, yahoo OpenID Providers
        elif provider_name in models.SocialUser.open_id_providers():
            provider_display_name = models.SocialUser.PROVIDERS_INFO[
                provider_name]['label']
            # get info passed from OpenId Provider
            from google.appengine.api import users
            current_user = users.get_current_user()
            if current_user:
                if current_user.federated_identity():
                    uid = current_user.federated_identity()
                else:
                    uid = current_user.user_id()
                email = current_user.email()
            else:
                message = _(
                    'No user authentication information received from %s.  Please ensure you are logging in from an authorized OpenID Provider (OP).'
                    % provider_display_name)
                self.add_message(message, 'error')
                return self.redirect_to('login')
            if self.user:
                # add social account to user
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, provider_name,
                                                  uid):
                    social_user = models.SocialUser(user=user_info.key,
                                                    provider=provider_name,
                                                    uid=uid)
                    social_user.put()

                    message = provider_display_name + _(' association added!')
                    self.add_message(message, 'success')
                else:
                    message = _('This %s account is already in use!' %
                                provider_display_name)
                    self.add_message(message, 'error')
                self.redirect_to('edit-profile')
            else:
                # login with OpenId Provider
                social_user = models.SocialUser.get_by_provider_and_uid(
                    provider_name, uid)
                if social_user:
                    # Social user found. Authenticate the user
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user),
                                          remember=True)
                    logVisit = models.LogVisit(
                        user=user.key,
                        uastring=self.request.user_agent,
                        ip=self.request.remote_addr,
                        timestamp=utils.get_date_time())
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exist yet so create it with the federated identity provided (uid)
                    # and create prerequisite user and log the user account in
                    if models.SocialUser.check_unique_uid(provider_name, uid):
                        # create user
                        # Returns a tuple, where first value is BOOL.
                        # If True ok, If False no new user is created
                        # Assume provider has already verified email address
                        # if email is provided so set activated to True
                        auth_id = "%s:%s" % (provider_name, uid)
                        if email:
                            unique_properties = ['email']
                            user_info = self.auth.store.user_model.create_user(
                                auth_id,
                                unique_properties,
                                email=email,
                                activated=True)
                        else:
                            user_info = self.auth.store.user_model.create_user(
                                auth_id, activated=True)
                        if not user_info[0]:  #user is a tuple
                            message = _('This %s account is already in use!' %
                                        provider_display_name)
                            self.add_message(message, 'error')
                            return self.redirect_to('register')

                        user = user_info[1]

                        # create social user and associate with user
                        social_user = models.SocialUser(user=user.key,
                                                        provider=provider_name,
                                                        uid=uid)
                        social_user.put()
                        # authenticate user
                        self.auth.set_session(
                            self.auth.store.user_to_dict(user), remember=True)
                        logVisit = models.LogVisit(
                            user=user.key,
                            uastring=self.request.user_agent,
                            ip=self.request.remote_addr,
                            timestamp=utils.get_date_time())
                        logVisit.put()
                        self.redirect_to('home')

                        message = provider_display_name + _(
                            ' association added!')
                        self.add_message(message, 'success')
                        self.redirect_to('home')
                    else:
                        message = _('This %s account is already in use!' %
                                    provider_display_name)
                        self.add_message(message, 'error')
                    self.redirect_to('login')
        else:
            message = _('%s authentication is not implemented yet.'
                        ) % provider_display_name
            self.add_message(message, 'warning')
            self.redirect_to('login')
示例#20
0
    def post(self):
        """
        username: Get the username from POST dict
        password: Get the password from POST dict
        """

        if not self.form.validate():
            return self.get()
        username = self.form.username.data.lower()
        
        try:
            if utils.is_email_valid(username):
                user = models.User.get_by_email(username)
                if user:
                    auth_id = user.auth_ids[0]
                else:
                    raise InvalidAuthIdError
            else:
                auth_id = "own:%s" % username
                user = models.User.get_by_auth_id(auth_id)
            
            password = self.form.password.data.strip()
            remember_me = True if str(self.request.POST.get('remember_me')) == 'on' else False
                
            # Password to SHA512
            password = utils.encrypt(password, config.salt)
    
            # Try to login user with password
            # Raises InvalidAuthIdError if user is not found
            # Raises InvalidPasswordError if provided password
            # doesn't match with specified user
            self.auth.get_user_by_password(
                auth_id, password, remember=remember_me)
                
            # if user account is not activated, logout and redirect to home
            if (user.activated == False):
                # logout
                self.auth.unset_session()
                
                # redirect to home with error message
                resend_email_uri = self.uri_for('resend-account-activation', encoded_email=utils.encode(user.email))
                message = _('Sorry, your account') + ' <strong>{0:>s}</strong>'.format(username) + " " +\
                          _('has not been activated. Please check your email to activate your account') + ". " +\
                          _('Or click') + " <a href='"+resend_email_uri+"'>" + _('this') + "</a> " + _('to resend the email')
                self.add_message(message, 'error')
                return self.redirect_to('home')

            #check twitter association in session
            twitter_helper = twitter.TwitterAuth(self)
            twitter_association_data = twitter_helper.get_association_data()
            if twitter_association_data is not None:
                if models.SocialUser.check_unique(user.key, 'twitter', str(twitter_association_data['id'])):
                    social_user = models.SocialUser(
                        user = user.key,
                        provider = 'twitter',
                        uid = str(twitter_association_data['id']),
                        extra_data = twitter_association_data
                    )
                    social_user.put()

            logVisit = models.LogVisit(
                user=user.key,
                uastring=self.request.user_agent,
                ip=self.request.remote_addr,
                timestamp=utils.get_date_time()
            )
            logVisit.put()
            self.redirect_to('home')
        except (InvalidAuthIdError, InvalidPasswordError), e:
            # Returns error message to self.response.write in
            # the BaseHandler.dispatcher
            message = _("Login invalid, Try again.") + "<br/>" + _("Don't have an account?") + \
                    '  <a href="' + self.uri_for('register') + '">' + _("Sign Up") + '</a>'
            self.add_message(message, 'error')
            return self.redirect_to('login')
示例#21
0
    def get(self, provider_name):
        if not config.enable_federated_login:
            message = _('Federated login is disabled.')
            self.add_message(message,'warning')
            return self.redirect_to('login')
        if provider_name == "twitter":
            oauth_token = self.request.get('oauth_token')
            oauth_verifier = self.request.get('oauth_verifier')
            twitter_helper = twitter.TwitterAuth(self)
            user_data = twitter_helper.auth_complete(oauth_token,
                oauth_verifier)
            if self.user:
                # new association with twitter
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'twitter', str(user_data['id'])):
                    social_user = models.SocialUser(
                        user = user_info.key,
                        provider = 'twitter',
                        uid = str(user_data['id']),
                        extra_data = user_data
                    )
                    social_user.put()

                    message = _('Twitter association added!')
                    self.add_message(message,'success')
                else:
                    message = _('This Twitter account is already in use!')
                    self.add_message(message,'error')
                self.redirect_to('edit-profile')
            else:
                # login with twitter
                social_user = models.SocialUser.get_by_provider_and_uid('twitter',
                    str(user_data['id']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                    logVisit = models.LogVisit(
                        user = user.key,
                        uastring = self.request.user_agent,
                        ip = self.request.remote_addr,
                        timestamp = utils.get_date_time()
                    )
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms
                    twitter_helper.save_association_data(user_data)
                    message = _('Account with association to your Twitter does not exist. You can associate it right now, if you login with existing site account or create new on Sign up page.')
                    self.add_message(message,'info')
                    self.redirect_to('login')
            # Debug Callback information provided
#            for k,v in user_data.items():
#                print(k +":"+  v )
        # google, myopenid, yahoo OpenID Providers
        elif provider_name in models.SocialUser.open_id_providers():
            provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label']
            # get info passed from OpenId Provider
            from google.appengine.api import users
            current_user = users.get_current_user()
            if current_user:
                if current_user.federated_identity():
                    uid = current_user.federated_identity()
                else:
                    uid = current_user.user_id()
                email = current_user.email()
            else:
                message = _('No user authentication information received from %s.  Please ensure you are logging in from an authorized OpenID Provider (OP).' % provider_display_name)
                self.add_message(message,'error')
                return self.redirect_to('login')
            if self.user:
                # add social account to user
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, provider_name, uid):
                    social_user = models.SocialUser(
                        user = user_info.key,
                        provider = provider_name,
                        uid = uid
                    )
                    social_user.put()

                    message = provider_display_name + _(' association added!')
                    self.add_message(message,'success')
                else:
                    message = _('This %s account is already in use!' % provider_display_name)
                    self.add_message(message,'error')
                self.redirect_to('edit-profile')
            else:
                # login with OpenId Provider
                social_user = models.SocialUser.get_by_provider_and_uid(provider_name, uid)
                if social_user:
                    # Social user found. Authenticate the user
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                    logVisit = models.LogVisit(
                        user = user.key,
                        uastring = self.request.user_agent,
                        ip = self.request.remote_addr,
                        timestamp = utils.get_date_time()
                    )
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exist yet so create it with the federated identity provided (uid)
                    # and create prerequisite user and log the user account in
                    if models.SocialUser.check_unique_uid(provider_name, uid):
                        # create user
                        # Returns a tuple, where first value is BOOL.
                        # If True ok, If False no new user is created
                        # Assume provider has already verified email address
                        # if email is provided so set activated to True
                        auth_id = "%s:%s" % (provider_name, uid)
                        if email:
                            unique_properties = ['email']
                            user_info = self.auth.store.user_model.create_user(
                                auth_id, unique_properties, email=email,
                                activated=True
                            )
                        else:
                            user_info = self.auth.store.user_model.create_user(
                                auth_id, activated=True
                            )
                        if not user_info[0]: #user is a tuple
                            message = _('This %s account is already in use!' % provider_display_name)
                            self.add_message(message, 'error')
                            return self.redirect_to('register')

                        user = user_info[1]
                        
                        # create social user and associate with user
                        social_user = models.SocialUser(
                            user = user.key,
                            provider = provider_name,
                            uid = uid
                        )
                        social_user.put()
                        # authenticate user
                        self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                        logVisit = models.LogVisit(
                            user = user.key,
                            uastring = self.request.user_agent,
                            ip = self.request.remote_addr,
                            timestamp = utils.get_date_time()
                        )
                        logVisit.put()
                        self.redirect_to('home')

                        message = provider_display_name + _(' association added!')
                        self.add_message(message,'success')
                        self.redirect_to('home')
                    else:
                        message = _('This %s account is already in use!' % provider_display_name)
                        self.add_message(message,'error')
                    self.redirect_to('login')
        else:
            message = _('%s authentication is not implemented yet.') % provider_display_name
            self.add_message(message,'warning')
            self.redirect_to('login')
示例#22
0
    def get(self, provider_name):
        if not config.enable_federated_login:
            message = _('Federated login is disabled.')
            self.add_message(message, 'warning')
            return self.redirect_to('login')

        # callback handler for twitter oauth
        if provider_name == "twitter":
            oauth_token = self.request.get('oauth_token')
            oauth_verifier = self.request.get('oauth_verifier')
            twitter_helper = twitter.TwitterAuth(self)
            user_data = twitter_helper.auth_complete(oauth_token, oauth_verifier)
            screen_name = user_data['screen_name']

            if self.user:
                # user is already logged in so we set a new association with twitter
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'twitter', str(user_data['id'])):
                    social_user = models.SocialUser(
                        user = user_info.key,
                        provider = 'twitter',
                        uid = str(user_data['id']),
                        extra_data = user_data,
                        screen_name = screen_name,
                    )
                    social_user.put()

                    message = _('Twitter association added.')
                    self.add_message(message, 'success')
                else:
                    message = _('This Twitter account is already in use.')
                    self.add_message(message, 'error')
                self.redirect_to('edit-profile')
            else:
                # user is not logged in, but is trying to log in via twitter
                social_user = models.SocialUser.get_by_provider_and_uid('twitter', str(user_data['id']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                    logVisit = models.LogVisit(
                        user = user.key,
                        uastring = self.request.user_agent,
                        ip = self.request.remote_addr,
                        timestamp = utils.get_date_time()
                    )
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms!
                    twitter_helper.save_association_data(user_data)
                    message = _('This Twitter account is not associated with a StackGeek account. '
                                'Please sign in or create a StackGeek account before continuing.')
                    self.add_message(message, 'warning')
                    self.redirect_to('login')

        # callback handler for github oauth
        elif provider_name == "github":
            # get our request code back from the social login handler above
            code = self.request.get('code')

            # create our github auth object (again)
            scope = 'gist'
            github_helper = github.GithubAuth(scope)

            # retrieve the access token using the code and auth object
            try:
                access_token = github_helper.get_access_token(code)
                user_data = github_helper.get_user_info(access_token)
            except:
                message = _('An error was encountered while exchanging tokens with Github.')
                self.add_message(message, 'error')
                self.redirect_to('edit-profile')
                return
            
            if self.user:
                # user is already logged in so we set a new association with github
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'github', str(user_data['login'])):
                    social_user = models.SocialUser(
                        user = user_info.key,
                        provider = 'github',
                        uid = str(user_data['login']),
                        access_token = access_token,
                        extra_data = user_data
                    )
                    social_user.put()

                    message = _('The StackGeek application has been added to your Github account.')
                    self.add_message(message, 'success')
                else:
                    message = _('The currently logged in Github account is already in use with another account.')
                    self.add_message(message, 'error')
                    self.redirect_to('edit-profile')
                    return

                # check to see if we are headed anywhere else besides the profile page
                next_page = utils.read_cookie(self, 'oauth_return_url')
                utils.write_cookie(self, 'oauth_return_url', '', '/', 15)

                # try out what we found or redirect to profile if it's a bad value
                if next_page:
                    try:
                        self.redirect_to(next_page)
                    except:
                        self.redirect_to('edit-profile')
                else:
                    self.redirect_to('edit-profile')
            else:
                # user is not logged in, but is trying to log in via github
                social_user = models.SocialUser.get_by_provider_and_uid('github', str(user_data['login']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                    logVisit = models.LogVisit(
                        user = user.key,
                        uastring = self.request.user_agent,
                        ip = self.request.remote_addr,
                        timestamp = utils.get_date_time()
                    )
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms!
                    message = _('This Github account is not associated with a StackGeek account. '
                                'Please sign in or create a StackGeek account before continuing.')
                    self.add_message(message, 'warning')
                    self.redirect_to('login')

        # google, myopenid, yahoo OpenID Providers
        elif provider_name in models.SocialUser.open_id_providers():
            provider_display_name = models.SocialUser.PROVIDERS_INFO[provider_name]['label']
            # get info passed from OpenId Provider
            from google.appengine.api import users
            current_user = users.get_current_user()
            if current_user:
                if current_user.federated_identity():
                    uid = current_user.federated_identity()
                else:
                    uid = current_user.user_id()
                email = current_user.email()
            else:
                message = _('No user authentication information received from %s. '
                            'Please ensure you are logging in from an authorized OpenID Provider (OP).'
                            % provider_display_name)
                self.add_message(message, 'error')
                return self.redirect_to('login')
            if self.user:
                # add social account to user
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, provider_name, uid):
                    social_user = models.SocialUser(
                        user = user_info.key,
                        provider = provider_name,
                        uid = uid
                    )
                    social_user.put()

                    message = _('%s association successfully added.' % provider_display_name)
                    self.add_message(message, 'success')
                else:
                    message = _('This %s account is already in use.' % provider_display_name)
                    self.add_message(message, 'error')
                self.redirect_to('edit-profile')
            else:
                # login with OpenId Provider
                social_user = models.SocialUser.get_by_provider_and_uid(provider_name, uid)
                if social_user:
                    # Social user found. Authenticate the user
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user), remember=True)
                    logVisit = models.LogVisit(
                        user = user.key,
                        uastring = self.request.user_agent,
                        ip = self.request.remote_addr,
                        timestamp = utils.get_date_time()
                    )
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    message = _('This OpenID based account is not associated with a StackGeek account. '
                                'Please sign in or create a StackGeek account before continuing.')
                    self.add_message(message, 'warning')
                    self.redirect_to('login')
        else:
            message = _('This authentication method is not yet implemented!')
            self.add_message(message, 'warning')
            self.redirect_to('login')
示例#23
0
    def get(self, provider_name):
        if not config.enable_federated_login:
            message = _('Federated login is disabled.')
            self.add_message(message, 'warning')
            return self.redirect_to('login')

        # callback handler for twitter oauth
        if provider_name == "twitter":
            oauth_token = self.request.get('oauth_token')
            oauth_verifier = self.request.get('oauth_verifier')
            twitter_helper = twitter.TwitterAuth(self)
            user_data = twitter_helper.auth_complete(oauth_token,
                                                     oauth_verifier)
            screen_name = user_data['screen_name']

            if self.user:
                # user is already logged in so we set a new association with twitter
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'twitter',
                                                  str(user_data['id'])):
                    social_user = models.SocialUser(
                        user=user_info.key,
                        provider='twitter',
                        uid=str(user_data['id']),
                        extra_data=user_data,
                        screen_name=screen_name,
                    )
                    social_user.put()

                    message = _('Twitter association added.')
                    self.add_message(message, 'success')
                else:
                    message = _('This Twitter account is already in use.')
                    self.add_message(message, 'error')
                self.redirect_to('edit-profile')
            else:
                # user is not logged in, but is trying to log in via twitter
                social_user = models.SocialUser.get_by_provider_and_uid(
                    'twitter', str(user_data['id']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user),
                                          remember=True)
                    logVisit = models.LogVisit(
                        user=user.key,
                        uastring=self.request.user_agent,
                        ip=self.request.remote_addr,
                        timestamp=utils.get_date_time())
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms!
                    twitter_helper.save_association_data(user_data)
                    message = _(
                        'This Twitter account is not associated with a StackGeek account. '
                        'Please sign in or create a StackGeek account before continuing.'
                    )
                    self.add_message(message, 'warning')
                    self.redirect_to('login')

        # callback handler for github oauth
        elif provider_name == "github":
            # get our request code back from the social login handler above
            code = self.request.get('code')

            # create our github auth object (again)
            scope = 'gist'
            github_helper = github.GithubAuth(scope)

            # retrieve the access token using the code and auth object
            try:
                access_token = github_helper.get_access_token(code)
                user_data = github_helper.get_user_info(access_token)
            except:
                message = _(
                    'An error was encountered while exchanging tokens with Github.'
                )
                self.add_message(message, 'error')
                self.redirect_to('edit-profile')
                return

            if self.user:
                # user is already logged in so we set a new association with github
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, 'github',
                                                  str(user_data['login'])):
                    social_user = models.SocialUser(user=user_info.key,
                                                    provider='github',
                                                    uid=str(
                                                        user_data['login']),
                                                    access_token=access_token,
                                                    extra_data=user_data)
                    social_user.put()

                    message = _(
                        'The StackGeek application has been added to your Github account.'
                    )
                    self.add_message(message, 'success')
                else:
                    message = _(
                        'The currently logged in Github account is already in use with another account.'
                    )
                    self.add_message(message, 'error')
                    self.redirect_to('edit-profile')
                    return

                # check to see if we are headed anywhere else besides the profile page
                next_page = utils.read_cookie(self, 'oauth_return_url')
                utils.write_cookie(self, 'oauth_return_url', '', '/', 15)

                # try out what we found or redirect to profile if it's a bad value
                if next_page:
                    try:
                        self.redirect_to(next_page)
                    except:
                        self.redirect_to('edit-profile')
                else:
                    self.redirect_to('edit-profile')
            else:
                # user is not logged in, but is trying to log in via github
                social_user = models.SocialUser.get_by_provider_and_uid(
                    'github', str(user_data['login']))
                if social_user:
                    # Social user exists. Need authenticate related site account
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user),
                                          remember=True)
                    logVisit = models.LogVisit(
                        user=user.key,
                        uastring=self.request.user_agent,
                        ip=self.request.remote_addr,
                        timestamp=utils.get_date_time())
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    # Social user does not exists. Need show login and registration forms!
                    message = _(
                        'This Github account is not associated with a StackGeek account. '
                        'Please sign in or create a StackGeek account before continuing.'
                    )
                    self.add_message(message, 'warning')
                    self.redirect_to('login')

        # google, myopenid, yahoo OpenID Providers
        elif provider_name in models.SocialUser.open_id_providers():
            provider_display_name = models.SocialUser.PROVIDERS_INFO[
                provider_name]['label']
            # get info passed from OpenId Provider
            from google.appengine.api import users
            current_user = users.get_current_user()
            if current_user:
                if current_user.federated_identity():
                    uid = current_user.federated_identity()
                else:
                    uid = current_user.user_id()
                email = current_user.email()
            else:
                message = _(
                    'No user authentication information received from %s. '
                    'Please ensure you are logging in from an authorized OpenID Provider (OP).'
                    % provider_display_name)
                self.add_message(message, 'error')
                return self.redirect_to('login')
            if self.user:
                # add social account to user
                user_info = models.User.get_by_id(long(self.user_id))
                if models.SocialUser.check_unique(user_info.key, provider_name,
                                                  uid):
                    social_user = models.SocialUser(user=user_info.key,
                                                    provider=provider_name,
                                                    uid=uid)
                    social_user.put()

                    message = _('%s association successfully added.' %
                                provider_display_name)
                    self.add_message(message, 'success')
                else:
                    message = _('This %s account is already in use.' %
                                provider_display_name)
                    self.add_message(message, 'error')
                self.redirect_to('edit-profile')
            else:
                # login with OpenId Provider
                social_user = models.SocialUser.get_by_provider_and_uid(
                    provider_name, uid)
                if social_user:
                    # Social user found. Authenticate the user
                    user = social_user.user.get()
                    self.auth.set_session(self.auth.store.user_to_dict(user),
                                          remember=True)
                    logVisit = models.LogVisit(
                        user=user.key,
                        uastring=self.request.user_agent,
                        ip=self.request.remote_addr,
                        timestamp=utils.get_date_time())
                    logVisit.put()
                    self.redirect_to('home')
                else:
                    message = _(
                        'This OpenID based account is not associated with a StackGeek account. '
                        'Please sign in or create a StackGeek account before continuing.'
                    )
                    self.add_message(message, 'warning')
                    self.redirect_to('login')
        else:
            message = _('This authentication method is not yet implemented!')
            self.add_message(message, 'warning')
            self.redirect_to('login')
示例#24
0
    def post(self):
        """
        username: Get the username from POST dict
        password: Get the password from POST dict
        """

        if not self.form.validate():
            return self.get()
        username = self.form.username.data.lower()

        try:
            if utils.is_email_valid(username):
                user = models.User.get_by_email(username)
                if user:
                    auth_id = user.auth_ids[0]
                else:
                    raise InvalidAuthIdError
            else:
                auth_id = "own:%s" % username
                user = models.User.get_by_auth_id(auth_id)

            password = self.form.password.data.strip()
            remember_me = True if str(self.request.POST.get('remember_me')) == 'on' else False

            # Password to SHA512
            password = utils.hashing(password, config.salt)

            # Try to login user with password
            # Raises InvalidAuthIdError if user is not found
            # Raises InvalidPasswordError if provided password
            # doesn't match with specified user
            self.auth.get_user_by_password(
                auth_id, password, remember=remember_me)

            # if user account is not activated, logout and redirect to home
            if (user.activated == False):
                # logout
                self.auth.unset_session()

                # redirect to home with error message
                message = _('Your account has been suspended. Please contact support for more information.')
                self.add_message(message, 'error')
                return self.redirect_to('login')

            # REMOVE ME
            #check twitter association in session
            twitter_helper = twitter.TwitterAuth(self)
            twitter_association_data = twitter_helper.get_association_data()
            if twitter_association_data is not None:
                if models.SocialUser.check_unique(user.key, 'twitter', str(twitter_association_data['id'])):
                    social_user = models.SocialUser(
                        user = user.key,
                        provider = 'twitter',
                        uid = str(twitter_association_data['id']),
                        extra_data = twitter_association_data
                    )
                    social_user.put()

            logVisit = models.LogVisit(
                user=user.key,
                uastring=self.request.user_agent,
                ip=self.request.remote_addr,
                timestamp=utils.get_date_time()
            )
            logVisit.put()
            self.redirect_to('home')
        except (InvalidAuthIdError, InvalidPasswordError), e:
            # Returns error message to self.response.write in
            # the BaseHandler.dispatcher
            message = _("Your username or password is incorrect.  Caps lock?")
            self.add_message(message, 'error')
            return self.redirect_to('login')