Example #1
0
	def post(self):
		""" Get fields from POST dict """

		if not self.form.validate():
			return self.get()
		current_password = self.form.current_password.data.strip()
		password = self.form.password.data.strip()

		try:
			user_info = models.User.get_by_id(long(self.user_id))
			auth_id = "own:%s" % user_info.username

			# Password to SHA512
			current_password = utils.hashing(current_password, self.app.config.get('salt'))
			try:
				user = models.User.get_by_auth_password(auth_id, current_password)
				# Password to SHA512
				password = utils.hashing(password, self.app.config.get('salt'))
				user.password = security.generate_password_hash(password, length=12)
				user.put()

				# send email
				subject = self.app.config.get('app_name') + " Account Password Changed"

				# load email's template
				template_val = {
					"app_name": self.app.config.get('app_name'),
					"first_name": user.name,
					"username": user.username,
					"email": user.email,
					"reset_password_url": self.uri_for("password-reset", _full=True)
				}
				email_body_path = "emails/password_changed.txt"
				email_body = self.jinja2.render_template(email_body_path, **template_val)
				email_url = self.uri_for('taskqueue-send-email')
				taskqueue.add(url = email_url, params={
					'to': user.email,
					'subject' : subject,
					'body' : email_body,
					'sender' : self.app.config.get('contact_sender'),
					})

				#Login User
				self.auth.get_user_by_password(user.auth_ids[0], password)
				self.add_message(_('Password changed successfully.'), 'success')
				return self.redirect_to('edit-profile')
			except (InvalidAuthIdError, InvalidPasswordError), e:
				# Returns error message to self.response.write in
				# the BaseHandler.dispatcher
				message = _("Incorrect password! Please enter your current password to change your account settings.")
				self.add_message(message, 'error')
				return self.redirect_to('edit-password')
		except (AttributeError,TypeError), e:
			login_error_message = _('Sorry you are not logged in.')
			self.add_message(login_error_message, 'error')
			self.redirect_to('login')
Example #2
0
    def post(self, encoded_email=""):
        """ Get fields from POST dict """

        if not self.form.validate():
            logging.info("didn't validate")
            return self.get(encoded_email)

        username = self.form.username.data.lower()
        email = utils.decode(encoded_email)
        password = self.form.password.data.strip()

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

        # gravatar goodness
        email = utils.decode(encoded_email)
        gravatar_url = "http://en.gravatar.com/%s.json" % hashlib.md5(email.lower()).hexdigest()
        try:
            data = json.load(urllib2.urlopen(gravatar_url))
            firstname = data['entry'][0]['name']['givenName']
            lastname = data['entry'][0]['name']['familyName']
            gravatar_url = data['entry'][0]['photos'][0]['value']
            country = get_territory_from_ip(self)
        except:
            firstname = ""
            lastname = ""
            gravatar_url = ""
            country = get_territory_from_ip(self)
            logging.info("no data pulled from gravatar")

        # Passing password_raw=password so password will be hashed
        # Returns a tuple, where first value is BOOL.
        # If True ok, If False no new user is created
        unique_properties = ['username', 'email']
        auth_id = "own:%s" % username
        user = self.auth.store.user_model.create_user(
            auth_id, unique_properties, password_raw=password,
            username=username, name=firstname, last_name=lastname, email=email,
            ip=self.request.remote_addr, country=country, gravatar_url=gravatar_url, activated=True
        )

        if not user[0]: #user is a tuple
            if "username" in str(user[1]):
                message = _('Sorry, The username %s is already registered.' % '<strong>{0:>s}</strong>'.format(username) )
            elif "email" in str(user[1]):
                message = _('Sorry, The email %s is already registered.' % '<strong>{0:>s}</strong>'.format(email) )
            else:
                message = _('Sorry, The user is already registered.')
            self.add_message(message, 'error')
            return self.redirect_to('register', encoded_email=encoded_email)
        else:
            # If the user didn't register using registration form ???
            db_user = self.auth.get_user_by_password(user[1].auth_ids[0], password)
            
            message = _('Welcome %s, you are now logged in.  Please fill out the rest of your profile!' % '<strong>{0:>s}</strong>'.format(username) )
            self.add_message(message, 'success')
            return self.redirect_to('edit-profile')
Example #3
0
    def login(self, request):
        """Exposes an API endpoint to query for an upload URL.

        Args:


        Returns:

        """
        salt=config.get('salt')
        aes_key=config.get('aes_key')
        if not request.username:
            LoginResponse(message="Provide a username")
        username = request.username.lower()

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

        password = request.password.strip()
        remember_me=False

        # Password to SHA512
        password = utils.hashing(password, 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
        user = User.get_by_auth_id(auth_id)
        if not user:
            raise endpoints.BadRequestException('Password/Username Do Not Match')

        if not security.check_password_hash(password, user.password):
            raise endpoints.BadRequestException('Password/Username Do Not Match')

        else:
            self.user_apikey = ApiKeys.get_apikey_by_user_id(user.key.id()).key.id()

        return LoginResponse(apikey=self.user_apikey)
Example #4
0
	def post(self, user_id, token):
		verify = models.User.get_by_auth_token(int(user_id), token)
		user = verify[0]
		password = self.form.password.data.strip()
		if user and self.form.validate():
			# Password to SHA512
			password = utils.hashing(password, self.app.config.get('salt'))

			user.password = security.generate_password_hash(password, length=12)
			user.put()
			# Delete token
			models.User.delete_auth_token(int(user_id), token)
			# Login User
			self.auth.get_user_by_password(user.auth_ids[0], password)
			self.add_message(_('Password changed successfully.'), 'success')
			return self.redirect_to('home')

		else:
			self.add_message(_('The two passwords must match.'), 'error')
			return self.redirect_to('password-reset-check', user_id=user_id, token=token)
Example #5
0
    def post(self, user_id, token):
        verify = models.User.get_by_auth_token(int(user_id), token)
        user = verify[0]
        password = self.form.password.data.strip()
        if user and self.form.validate():
            # Password to SHA512
            password = utils.hashing(password, config.salt)

            user.password = security.generate_password_hash(password,
                                                            length=12)
            user.put()
            # Delete token
            models.User.delete_auth_token(int(user_id), token)
            # Login User
            self.auth.get_user_by_password(user.auth_ids[0], password)
            self.add_message(_('Password changed successfully.'), 'success')
            return self.redirect_to('home')

        else:
            self.add_message(_('The two passwords must match.'), 'error')
            return self.redirect_to('password-reset-check',
                                    user_id=user_id,
                                    token=token)
Example #6
0
	def post(self):
		""" Get fields from POST dict """

		if not self.form.validate():
			return self.get()
		username = self.form.username.data.lower()
		name = self.form.name.data.strip()
		last_name = self.form.last_name.data.strip()
		email = self.form.email.data.lower()
		password = self.form.password.data.strip()
		country = self.form.country.data

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

		# Passing password_raw=password so password will be hashed
		# Returns a tuple, where first value is BOOL.
		# If True ok, If False no new user is created
		unique_properties = ['username', 'email']
		auth_id = "own:%s" % username
		user = self.auth.store.user_model.create_user(
			auth_id, unique_properties, password_raw=password,
			username=username, name=name, last_name=last_name, email=email,
			ip=self.request.remote_addr, country=country
		)

		if not user[0]: #user is a tuple
			if "username" in str(user[1]):
				message = _('Sorry, The username %s is already registered.' % '<strong>{0:>s}</strong>'.format(username) )
			elif "email" in str(user[1]):
				message = _('Sorry, The email %s is already registered.' % '<strong>{0:>s}</strong>'.format(email) )
			else:
				message = _('Sorry, The user is already registered.')
			self.add_message(message, 'error')
			return self.redirect_to('register')
		else:
			# User registered successfully
			# But if the user registered using the form, the user has to check their email to activate the account ???
			try:
				user_info = models.User.get_by_email(email)
				if (user_info.activated == False):
					# send email
					subject =  _("%s Account Verification" % self.app.config.get('app_name'))
					confirmation_url = self.uri_for("account-activation",
						user_id=user_info.get_id(),
						token = models.User.create_auth_token(user_info.get_id()),
						_full = True)

					# load email's template
					template_val = {
						"app_name": self.app.config.get('app_name'),
						"username": username,
						"confirmation_url": confirmation_url,
						"support_url": self.uri_for("contact", _full=True)
					}
					body_path = "emails/account_activation.txt"
					body = self.jinja2.render_template(body_path, **template_val)

					email_url = self.uri_for('taskqueue-send-email')
					taskqueue.add(url = email_url, params={
						'to': str(email),
						'subject' : subject,
						'body' : body,
						})

					message = _('You were successfully registered. '
								'Please check your email to activate your account.')
					self.add_message(message, 'success')
					return self.redirect_to('home')

				# If the user didn't register using registration form ???
				db_user = self.auth.get_user_by_password(user[1].auth_ids[0], password)
				# 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[1].key, 'twitter', str(twitter_association_data['id'])):
						social_user = models.SocialUser(
							user = user[1].key,
							provider = 'twitter',
							uid = str(twitter_association_data['id']),
							extra_data = twitter_association_data
						)
						social_user.put()

				#check facebook association
				fb_data = json.loads(self.session['facebook'])

				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 = json.loads(self.session['linkedin'])
				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()


				message = _('Welcome %s, you are now logged in.' % '<strong>{0:>s}</strong>'.format(username) )
				self.add_message(message, 'success')
				return self.redirect_to('home')
			except (AttributeError, KeyError), e:
				logging.error('Unexpected error creating the user %s: %s' % (username, e ))
				message = _('Unexpected error creating the user %s' % username )
				self.add_message(message, 'error')
				return self.redirect_to('home')
Example #7
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')
Example #8
0
	def post(self):
		""" Get fields from POST dict """

		if not self.form.validate():
			return self.get()
		new_email = self.form.new_email.data.strip()
		password = self.form.password.data.strip()

		try:
			user_info = models.User.get_by_id(long(self.user_id))
			auth_id = "own:%s" % user_info.username
			# Password to SHA512
			password = utils.hashing(password, self.app.config.get('salt'))

			try:
				# authenticate user by its password
				user = models.User.get_by_auth_password(auth_id, password)

				# if the user change his/her email address
				if new_email != user.email:

					# check whether the new email has been used by another user
					aUser = models.User.get_by_email(new_email)
					if aUser is not None:
						message = _("The email %s is already registered." % new_email)
						self.add_message(message, 'error')
						return self.redirect_to("edit-email")

					# send email
					subject = _("%s Email Changed Notification" % self.app.config.get('app_name'))
					user_token = models.User.create_auth_token(self.user_id)
					confirmation_url = self.uri_for("email-changed-check",
						user_id = user_info.get_id(),
						encoded_email = utils.encode(new_email),
						token = user_token,
						_full = True)

					# load email's template
					template_val = {
						"app_name": self.app.config.get('app_name'),
						"first_name": user.name,
						"username": user.username,
						"new_email": new_email,
						"confirmation_url": confirmation_url,
						"support_url": self.uri_for("contact", _full=True)
					}

					old_body_path = "emails/email_changed_notification_old.txt"
					old_body = self.jinja2.render_template(old_body_path, **template_val)

					new_body_path = "emails/email_changed_notification_new.txt"
					new_body = self.jinja2.render_template(new_body_path, **template_val)

					email_url = self.uri_for('taskqueue-send-email')
					taskqueue.add(url = email_url, params={
						'to': user.email,
						'subject' : subject,
						'body' : old_body,
						})
					taskqueue.add(url = email_url, params={
						'to': new_email,
						'subject' : subject,
						'body' : new_body,
						})

					# display successful message
					msg = _("Please check your new email for confirmation. Your email will be updated after confirmation.")
					self.add_message(msg, 'success')
					return self.redirect_to('edit-profile')

				else:
					self.add_message(_("You didn't change your email."), "warning")
					return self.redirect_to("edit-email")


			except (InvalidAuthIdError, InvalidPasswordError), e:
				# Returns error message to self.response.write in
				# the BaseHandler.dispatcher
				message = _("Incorrect password! Please enter your current password to change your account settings.")
				self.add_message(message, 'error')
				return self.redirect_to('edit-email')

		except (AttributeError,TypeError), e:
			login_error_message = _('Sorry you are not logged in.')
			self.add_message(login_error_message,'error')
			self.redirect_to('login')
Example #9
0
    def post(self):
        """ Get fields from POST dict """

        if not self.form.validate():
            return self.get()
        new_email = self.form.new_email.data.strip()
        password = self.form.password.data.strip()

        try:
            user_info = models.User.get_by_id(long(self.user_id))
            auth_id = "own:%s" % user_info.username
            # Password to SHA512
            password = utils.hashing(password, config.salt)

            try:
                # authenticate user by its password
                user = models.User.get_by_auth_password(auth_id, password)

                # if the user change his/her email address
                if new_email != user.email:

                    # check whether the new email has been used by another user
                    aUser = models.User.get_by_email(new_email)
                    if aUser is not None:
                        message = _("The email %s is already registered." %
                                    new_email)
                        self.add_message(message, 'error')
                        return self.redirect_to("edit-email")

                    # send email
                    subject = _("%s Email Changed Notification" %
                                config.app_name)
                    user_token = models.User.create_auth_token(self.user_id)
                    confirmation_url = self.uri_for(
                        "email-changed-check",
                        user_id=user_info.get_id(),
                        encoded_email=utils.encode(new_email),
                        token=user_token,
                        _full=True)

                    # load email's template
                    template_val = {
                        "app_name": config.app_name,
                        "first_name": user.name,
                        "username": user.username,
                        "new_email": new_email,
                        "confirmation_url": confirmation_url,
                        "support_url": self.uri_for("contact", _full=True)
                    }

                    old_body_path = "emails/email_changed_notification_old.txt"
                    old_body = self.jinja2.render_template(
                        old_body_path, **template_val)

                    new_body_path = "emails/email_changed_notification_new.txt"
                    new_body = self.jinja2.render_template(
                        new_body_path, **template_val)

                    email_url = self.uri_for('taskqueue-send-email')
                    taskqueue.add(url=email_url,
                                  params={
                                      'to': user.email,
                                      'subject': subject,
                                      'body': old_body,
                                  })
                    taskqueue.add(url=email_url,
                                  params={
                                      'to': new_email,
                                      'subject': subject,
                                      'body': new_body,
                                  })

                    # display successful message
                    msg = _(
                        "Please check your new email for confirmation. Your email will be updated after confirmation."
                    )
                    self.add_message(msg, 'success')
                    return self.redirect_to('edit-profile')

                else:
                    self.add_message(_("You didn't change your email."),
                                     "warning")
                    return self.redirect_to("edit-email")

            except (InvalidAuthIdError, InvalidPasswordError), e:
                # Returns error message to self.response.write in
                # the BaseHandler.dispatcher
                message = _(
                    "Incorrect password! Please enter your current password to change your account settings."
                )
                self.add_message(message, 'error')
                return self.redirect_to('edit-email')

        except (AttributeError, TypeError), e:
            login_error_message = _('Sorry you are not logged in.')
            self.add_message(login_error_message, 'error')
            self.redirect_to('login')
Example #10
0
    def post(self):
        """ Get fields from POST dict """

        if not self.form.validate():
            return self.get()
        current_password = self.form.current_password.data.strip()
        password = self.form.password.data.strip()

        try:
            user_info = models.User.get_by_id(long(self.user_id))
            auth_id = "own:%s" % user_info.username

            # Password to SHA512
            current_password = utils.hashing(current_password, config.salt)
            try:
                user = models.User.get_by_auth_password(
                    auth_id, current_password)
                # Password to SHA512
                password = utils.hashing(password, config.salt)
                user.password = security.generate_password_hash(password,
                                                                length=12)
                user.put()

                # send email
                subject = config.app_name + " Account Password Changed"

                # load email's template
                template_val = {
                    "app_name":
                    config.app_name,
                    "first_name":
                    user.name,
                    "username":
                    user.username,
                    "email":
                    user.email,
                    "reset_password_url":
                    self.uri_for("password-reset", _full=True)
                }
                email_body_path = "emails/password_changed.txt"
                email_body = self.jinja2.render_template(
                    email_body_path, **template_val)
                email_url = self.uri_for('taskqueue-send-email')
                taskqueue.add(url=email_url,
                              params={
                                  'to': user.email,
                                  'subject': subject,
                                  'body': email_body,
                                  'sender': config.contact_sender,
                              })

                #Login User
                self.auth.get_user_by_password(user.auth_ids[0], password)
                self.add_message(_('Password changed successfully.'),
                                 'success')
                return self.redirect_to('edit-profile')
            except (InvalidAuthIdError, InvalidPasswordError), e:
                # Returns error message to self.response.write in
                # the BaseHandler.dispatcher
                message = _(
                    "Incorrect password! Please enter your current password to change your account settings."
                )
                self.add_message(message, 'error')
                return self.redirect_to('edit-password')
        except (AttributeError, TypeError), e:
            login_error_message = _('Sorry you are not logged in.')
            self.add_message(login_error_message, 'error')
            self.redirect_to('login')
Example #11
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')
Example #12
0
    def post(self, encoded_email=""):
        """ Get fields from POST dict """

        if not self.form.validate():
            logging.info("didn't validate")
            return self.get(encoded_email)

        username = self.form.username.data.lower()
        email = utils.decode(encoded_email)
        password = self.form.password.data.strip()

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

        # gravatar goodness
        email = utils.decode(encoded_email)
        gravatar_url = "http://en.gravatar.com/%s.json" % hashlib.md5(
            email.lower()).hexdigest()
        try:
            data = json.load(urllib2.urlopen(gravatar_url))
            firstname = data['entry'][0]['name']['givenName']
            lastname = data['entry'][0]['name']['familyName']
            gravatar_url = data['entry'][0]['photos'][0]['value']
            country = get_territory_from_ip(self)
        except:
            firstname = ""
            lastname = ""
            gravatar_url = ""
            country = get_territory_from_ip(self)
            logging.info("no data pulled from gravatar")

        # Passing password_raw=password so password will be hashed
        # Returns a tuple, where first value is BOOL.
        # If True ok, If False no new user is created
        unique_properties = ['username', 'email']
        auth_id = "own:%s" % username
        user = self.auth.store.user_model.create_user(
            auth_id,
            unique_properties,
            password_raw=password,
            username=username,
            name=firstname,
            last_name=lastname,
            email=email,
            ip=self.request.remote_addr,
            country=country,
            gravatar_url=gravatar_url,
            activated=True)

        if not user[0]:  #user is a tuple
            if "username" in str(user[1]):
                message = _('Sorry, The username %s is already registered.' %
                            '<strong>{0:>s}</strong>'.format(username))
            elif "email" in str(user[1]):
                message = _('Sorry, The email %s is already registered.' %
                            '<strong>{0:>s}</strong>'.format(email))
            else:
                message = _('Sorry, The user is already registered.')
            self.add_message(message, 'error')
            return self.redirect_to('register', encoded_email=encoded_email)
        else:
            # If the user didn't register using registration form ???
            db_user = self.auth.get_user_by_password(user[1].auth_ids[0],
                                                     password)

            message = _(
                'Welcome %s, you are now logged in.  Please fill out the rest of your profile!'
                % '<strong>{0:>s}</strong>'.format(username))
            self.add_message(message, 'success')
            return self.redirect_to('edit-profile')
Example #13
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')
Example #14
0
 def gethashkey(self):
     return str(utils.hashing(self.key.id(), config.salt))
Example #15
0
 def gethashkey(self):
     return str(utils.hashing(self.key.id(), config.salt))
Example #16
0
    def post(self):
        """ Get fields from POST dict """

        if not self.form.validate():
            return self.get()
        username = self.form.username.data.lower()
        name = self.form.name.data.strip()
        last_name = self.form.last_name.data.strip()
        email = self.form.email.data.lower()
        password = self.form.password.data.strip()
        country = self.form.country.data
        tz = self.form.tz.data

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

        # Passing password_raw=password so password will be hashed
        # Returns a tuple, where first value is BOOL.
        # If True ok, If False no new user is created
        unique_properties = ['username', 'email']
        auth_id = "own:%s" % username
        user = self.auth.store.user_model.create_user(
            auth_id, unique_properties, password_raw=password,
            username=username, name=name, last_name=last_name, email=email,
            ip=self.request.remote_addr, country=country, tz=tz
        )

        if not user[0]: #user is a tuple
            if "username" in str(user[1]):
                message = _(
                    'Sorry, The username <strong>{}</strong> is already registered.').format(username)
            elif "email" in str(user[1]):
                message = _('Sorry, The email <strong>{}</strong> is already registered.').format(email)
            else:
                message = _('Sorry, The user is already registered.')
            self.add_message(message, 'error')
            return self.redirect_to('register')
        else:
            # User registered successfully
            # But if the user registered using the form, the user has to check their email to activate the account ???
            try:
                if not user[1].activated:
                    # send email
                    subject = _("%s Account Verification" % self.app.config.get('app_name'))
                    confirmation_url = self.uri_for("account-activation",
                                                    user_id=user[1].get_id(),
                                                    token=self.user_model.create_auth_token(user[1].get_id()),
                                                    _full=True)

                    # load email's template
                    template_val = {
                        "app_name": self.app.config.get('app_name'),
                        "username": username,
                        "confirmation_url": confirmation_url,
                        "support_url": self.uri_for("contact", _full=True)
                    }
                    body_path = "emails/account_activation.txt"
                    body = self.jinja2.render_template(body_path, **template_val)

                    email_url = self.uri_for('taskqueue-send-email')
                    taskqueue.add(url=email_url, params={
                        'to': str(email),
                        'subject': subject,
                        'body': body,
                    })

                    message = _('You were successfully registered. '
                                'Please check your email to activate your account.')
                    self.add_message(message, 'success')
                    return self.redirect_to('home')

                # If the user didn't register using registration form ???
                db_user = self.auth.get_user_by_password(user[1].auth_ids[0], password)


                message = _('Welcome <strong>{}</strong>, you are now logged in.').format(username)
                self.add_message(message, 'success')
                return self.redirect_to('home')
            except (AttributeError, KeyError), e:
                logging.error('Unexpected error creating the user %s: %s' % (username, e ))
                message = _('Unexpected error creating the user %s' % username)
                self.add_message(message, 'error')
                return self.redirect_to('home')