def test_create_check_password_hash(self):
        self.assertRaises(TypeError, security.generate_password_hash, "foo",
                          "bar")

        password = "******"
        hashval = security.generate_password_hash(password, "sha1")
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password,
                                                  "sha1",
                                                  pepper="bar")
        self.assertTrue(
            security.check_password_hash(password, hashval, pepper="bar"))

        hashval = security.generate_password_hash(password, "md5")
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, "plain")
        v = security.check_password_hash(password, hashval)
        self.assertTrue(v)

        hashval = security.generate_password_hash(password, "plain")
        self.assertFalse(security.check_password_hash(password, ""))

        hashval1 = security.hash_password(str(password), "sha1", "bar")
        hashval2 = security.hash_password(str(password), "sha1", "bar")
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)

        hashval1 = security.hash_password(str(password), "md5", None)
        hashval2 = security.hash_password(str(password), "md5", None)
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)
    def test_create_check_password_hash(self):
        self.assertRaises(TypeError, security.generate_password_hash, 'foo',
                          'bar')

        password = '******'
        hashval = security.generate_password_hash(password, 'sha1')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password,
                                                  'sha1',
                                                  pepper='bar')
        self.assertTrue(
            security.check_password_hash(password, hashval, pepper='bar'))

        hashval = security.generate_password_hash(password, 'md5')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'plain')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'plain')
        self.assertFalse(security.check_password_hash(password, ''))

        hashval1 = security.hash_password(unicode(password), 'sha1', u'bar')
        hashval2 = security.hash_password(unicode(password), 'sha1', u'bar')
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)

        hashval1 = security.hash_password(unicode(password), 'md5', None)
        hashval2 = security.hash_password(unicode(password), 'md5', None)
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)
    def test_create_check_password_hash(self):
        self.assertRaises(TypeError, security.generate_password_hash, 'foo',
                          'bar')

        password = '******'
        hashval = security.generate_password_hash(password, 'sha1')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'sha1', pepper='bar')
        self.assertTrue(security.check_password_hash(password, hashval,
                                                     pepper='bar'))

        hashval = security.generate_password_hash(password, 'md5')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'plain')
        self.assertTrue(security.check_password_hash(password, hashval))

        hashval = security.generate_password_hash(password, 'plain')
        self.assertFalse(security.check_password_hash(password, ''))

        hashval1 = security.hash_password(unicode(password), 'sha1', u'bar')
        hashval2 = security.hash_password(unicode(password), 'sha1', u'bar')
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)

        hashval1 = security.hash_password(unicode(password), 'md5', None)
        hashval2 = security.hash_password(unicode(password), 'md5', None)
        self.assertTrue(hashval1 is not None)
        self.assertEqual(hashval1, hashval2)
Example #4
0
 def find_or_update(self, request):
     """Find  User or update password"""
     account = User.get_by_email(self.email)
     logging.error('Ther You go hiud')
     if request == 'GET':
         if account is not None:
             if account.password == ceaser_cipher(self.password):
                 return account.email, 0
             else:
                 return None, 404
         else:
             return None, 404
     else:
         if account is not None:
             if self.password is None:
                 Password = id_generator()
                 account.password = security.generate_password_hash(
                     Password, length=12)
                 account.active = False
                 return account.email, 406
             else:
                 account.password = security.generate_password_hash(
                     self.Password, length=12)
                 account.active = True
                 return account.email, 407
         else:
             return None, 405
Example #5
0
def changeNPass(email, passW):
    print email
    user = Users.query(Users.email == email).get()
    
    pwEncrypt = security.generate_password_hash(passWord, 'sha1').strip()
    user.pw = pwEncrypt
    user.put()
Example #6
0
 def __init__(self,hs=None, pw=None,pepper=None):
     if hs is None and  pw is None:
         self.hs=None
     elif hs:
         self.hs=hs
     else:
         self.hs=security.generate_password_hash(pw,pepper=pepper)
Example #7
0
    def create_user(cls, auth_id, **user_values):
        assert user_values.get('password') is None, \
            'Use password_raw instead of password to create new users.'

        assert not isinstance(auth_id, list), \
            'Creating a user with multiple auth_ids is not allowed, ' \
            'please provide a single auth_id.'

        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)

        user_values['auth_ids'] = [auth_id]
        user = cls(**user_values)

        # Set up unique properties
        uniques = []
        user_values['auth_id'] = auth_id
        for name in cls.unique_properties:
            key = '%s.%s:%s' % (cls.__name__, name, user_values[name])
            uniques.append((key, name))

        ok, existing = cls.unique_model.create_multi(k for k, v in uniques)
        if ok:
            user.put()
            return True, user
        else:
            properties = [v for k, v in uniques if k in existing]
            return False, properties
    def post(self, code):
        errors = []
        data = {
            'page_title': 'Reset Password',
            'errors': errors,
        }

        password = self.request.get('password')
        password_verify = self.request.get('password-verify')
        if not password or password != password_verify:
            errors.append(
                "Missing password or both passwords didn't match. Please try "
                "again."
            )
        else:
            user = User.user_from_reset_code(code)
            if not user:
                errors.append(
                    'No account for this reset code! Please contact admin.'
                )
            else:
                hash_pass = generate_password_hash(password)
                user.password = hash_pass
                user.pass_reset_code = None
                user.pass_reset_expire = None
                user.put()
                self.redirect('/login')
                return

        # reach here when there is an error to report
        self.render('password.html', **data)
Example #9
0
    def create(cls, id=None, parent=None, key=None, **user_values):
        """Create a new user and add it to the datastore.

        The user can be given either by setting id and possibly parent, or by
        setting key, but not both. If id is set, then the new user gets a key
        based on id, a string or int, and parent, which should be an ndb.Key.
        If key is set, then it becomes the new key of the entity.
        
        Return the new user, or None if the user already exists. May throw an
        ndb.TransactionFailedError.

        """
        assert user_values.get('password') is None, \
               "Use password_raw instead of password to create new users."

        assert (id or key) and not (id and key), \
               "Give an id or a key, but not both."
        
        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)
            
        user = cls(id=id, parent=parent, key=key, **user_values)

        if put_if_not_present(user):
            return user
        return None
Example #10
0
	def post(self):
		username = self.request.get('username')
		email = self.request.get('email')
		password = self.request.get('password')

		test_key = db.Key.from_path('User',email)
		test_user = db.get(test_key)
		if test_user == None:
			newUser = User(key_name = email)
			newUser.email = email
			newUser.name = username
			newUser.password = security.generate_password_hash(password,length=12)
			newUser.friends_list = []
			newUser.event_key_list = []
			newUser.auth_id = email
			newUser.all_start = []
			newUser.all_end = []
			newUser.all_content = []
			newUser.all_group = []
			newUser.all_className = []
			newUser.total_events = 0
			newUser.put()

			# user_id = newUser.get_id()

			# token = self.user_model.create_signup_token(user_id)

			u = self.auth().get_user_by_password(email,password,remember=True)

			self.redirect('/home')
		else:
			self.redirect('/?src=fail_signup')
 def set_password(self, raw_password):
     """Sets the password for the current user
     
     :param raw_password:
         The raw password which will be hashed and stored
     """
     self.password = security.generate_password_hash(raw_password, length=12)
Example #12
0
    def post(self):
        username = self.request.get('username')
        email = self.request.get('email')
        password = self.request.get('password')

        test_key = db.Key.from_path('User', email)
        test_user = db.get(test_key)
        if test_user == None:
            newUser = User(key_name=email)
            newUser.email = email
            newUser.name = username
            newUser.password = security.generate_password_hash(password,
                                                               length=12)
            newUser.friends_list = []
            newUser.event_key_list = []
            newUser.auth_id = email
            newUser.all_start = []
            newUser.all_end = []
            newUser.all_content = []
            newUser.all_group = []
            newUser.all_className = []
            newUser.total_events = 0
            newUser.put()

            # user_id = newUser.get_id()

            # token = self.user_model.create_signup_token(user_id)

            u = self.auth().get_user_by_password(email,
                                                 password,
                                                 remember=True)

            self.redirect('/home')
        else:
            self.redirect('/?src=fail_signup')
Example #13
0
    def post(self):

        password1 = self.request.get('password1').encode('utf-8')
        password2 = self.request.get('password2').encode('utf-8')
        key = self.request.get('key').encode('utf-8')
        email = self.request.get('email').encode('utf-8')

        if not hasNumbersAndLetters.match(password1):
            self.response.write(html.password_reset(key, numbers_and_letters=True))
            return
        if not correctLength.match(password1):
            self.response.write(html.password_reset(key, password_length=True))
            return
        if password1 != password2:
            self.response.write(html.password_reset(key, passwords_different=True))
            return

        passwordReset = db.get(key)
        if not passwordReset: #or passwordReset expired
            self.redirect(REDIRECT + "?token_expired=true&email=" + email)
            return

        user = my_db.get(passwordReset.email)
        if user.password:
            user.previous_passwords.append(user.password)
        user.password_resets += 1

        user.password = security.generate_password_hash(password1)
        user.login_attempts = 0
        user.put()
        passwordReset.delete()
        self.response.write('Password reset.')
Example #14
0
    def update_password(self, password, new_password):
        """Update the password for the user if the existing password matches."""
        if not security.check_password_hash(password, self.password):
            raise auth.InvalidPasswordError()

        self.password = security.generate_password_hash(new_password, length=12)
        self.put()
Example #15
0
    def create(cls, id=None, parent=None, key=None, **user_values):
        """Create a new user and add it to the datastore.

        The user can be given either by setting id and possibly parent, or by
        setting key, but not both. If id is set, then the new user gets a key
        based on id, a string or int, and parent, which should be an ndb.Key.
        If key is set, then it becomes the new key of the entity.
        
        Return the new user, or None if the user already exists. May throw an
        ndb.TransactionFailedError.

        """
        assert user_values.get('password') is None, \
               "Use password_raw instead of password to create new users."

        assert (id or key) and not (id and key), \
               "Give an id or a key, but not both."

        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)

        user = cls(id=id, parent=parent, key=key, **user_values)

        if put_if_not_present(user):
            return user
        return None
Example #16
0
    def set_password(self, raw_password):
        """Sets the password for the current user

        :param raw_password:
            The raw password which will be hashed and stored
        """
        self.password = security.generate_password_hash(raw_password, length=12)
Example #17
0
    def create_user(cls, username=None, raw_password=None, email=None):
        """
        Create a Login instance, but method NOT PUT Login TO DB
        You must run _.put() manually after creating the instance.

        :param username:
            username string
        :param raw_password:
            raw_password string
        :param email:
            emal (optional)
        :return:
            Login instance or None
        """
        logging.info('LoginClass:create_user() => Start creating user')

        if not(username and raw_password):
            logging.error('LoginClass:create_user() => username or raw_password is empty, return None')
            return None

        salt = security.generate_random_string(length=30)
        logging.info('LoginClass:create_user() => Making salt for password hash ... < %s >' % salt)

        pw_hash = security.generate_password_hash(raw_password, pepper=PEPPER)
        logging.info('LoginClass:create_user() => Generatin password hash ... < %s >' % pw_hash)
        u = Login()
        u.populate(username=username,
                   pw_hash=pw_hash,
                   email=email)
        logging.info('LoginClass:create_user() => Make and return Login instance')
        return u
Example #18
0
    def post(self, user_id, token):
        verify = models.User.get_by_auth_token(int(user_id), token)
        user = verify[0]
        password = str(self.request.POST.get('password')).strip()
        c_password = str(self.request.POST.get('c_password')).strip()
        if user:
            if password == "" or c_password == "":
                message = 'Password required.'
                self.add_message(message, 'error')
                return self.redirect_to('password-reset-check', user_id=user_id, token=token)

            if password != c_password:
                message = 'Sorry, Passwords are not identical, ' \
                          'you have to repeat again.'
                self.add_message(message, 'error')
                return self.redirect_to('password-reset-check', user_id=user_id, token=token)

            # Password to SHA512
            password = utils.encrypt(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('secure')

        else:
            self.add_message('Please correct the form errors.', 'error')
            return self.redirect_to('password-reset-check', user_id=user_id, token=token)
Example #19
0
    def post(self):
        form = forms.NewGameForm(self.request.POST)
        form.color1.choices = [(key, key) for key in _primaryColors.keys()]
        form.color2.choices = [(key, key) for key in _bonusColors.keys()]
        if form.validate():

            #player
            p = models.player()
            p.isAdmin = True
            p.score = 0
            p.primaryColor = form.color1.data
            p.bonusColor = form.color2.data
            p.put()
            
            #game
            g = models.game()
            g.name = form.name.data
            g.password =  security.generate_password_hash(form.password.data)
            g.primaryColorsChosen.append(form.color1.data)
            g.bonusColorsChosen.append(form.color2.data)
            g.players.append(p.key)
            g.put()

            #user
            
            self.user.players.append(p.key)
            self.user.put()

            self.redirect(self.uri_for('game', game_id=g.key.id()))

        context = {'form': form}
        self.render_response('NewGame.html', **context)
Example #20
0
    def create(cls, firstname, lastname, school, password_raw):
        """
		アカウント作成
		@param str firstname 名前
		@param str lastname  苗字
		@param str school 所属学校名
		@param str password_raw パスワード
		@return (bool, User|None) 成功か, ユーザ
		"""

        if not (firstname and lastname and school and password_raw):
            print(u"入力し忘れあるんじゃない?".encode("utf-8"))
            return False, None

        # Get the school'key. If it did not exist, quit this function.
        school_key = School.query(School.name == school).get(keys_only=True)
        if not school_key:
            return False, None

        # Create a user. returun this user.
        user = cls(firstname=firstname,
                   lastname=lastname,
                   school_key=school_key,
                   password_raw=security.generate_password_hash(password_raw,
                                                                length=20))
        user.put()
        return True, user
Example #21
0
 def create(cls, email, first_name, last_name, device_token, password=None):
     if not password:
         password = '******'
     password_hash = generate_password_hash(password, pepper=PEPPER)
     user = cls(key_name=email, first_name=first_name, last_name=last_name, device_token=device_token, password=password_hash)
     UserDocument().create(email, name="%s %s"%(first_name, last_name))
     user.put()
     return user
Example #22
0
 def create_user(cls, username, password):
     password = generate_password_hash(password,
                                       method='sha1',
                                       length=22,
                                       pepper=config.pepper)
     user = cls(username=username, password=password)
     user.put()
     return user
Example #23
0
 def create_user(cls, username, password):
     password = generate_password_hash(password,
                                       method='sha1',
                                       length=22,
                                       pepper=config.pepper)
     user = cls(username=username, password=password)
     user.put()
     return user
Example #24
0
 def save(cls, form):
     user = User(id=form['userId'],
                 email=form['email'],
                 name=form.get('name', ''),
                 birth=form.get('birth'),
                 password=security.generate_password_hash(
                     form['password'])).put()
     return user
Example #25
0
    def update_password(self, password, new_password):
        """Update the password for the user if the existing password matches."""
        if not security.check_password_hash(password, self.password):
            raise auth.InvalidPasswordError()

        self.password = security.generate_password_hash(new_password,
                                                        length=12)
        self.put()
Example #26
0
    def update( self, email, username, password ):
        """ Updates the User with new parameters.

        :param email:
            The new email_pending for the user
        :param username:
            The new username to assign to the user
        :param password:
            The new password to assign to the user
        :returns:
            A tuple (boolean, info) where on success, (True, user) is returned
            and on failure, (False, list) is returned where list gives names
            of the properties that conflict with existing unique properties.
        """
        # Set up unique properties
        uniques = [ ]
        if self.username_lower != username.lower( ):
            key = '%s.%s:%s' % ( self.__class__.__name__, 'username',
                                 username.lower( ) )
            uniques.append( ( key, 'username' ) )
        if( email
            and self.email_pending_lower != email.lower( )
            and self.email_verified_lower != email.lower( ) ):
            key = '%s.%s:%s' % ( self.__class__.__name__, 'email',
                                 email.lower( ) )
            uniques.append( ( key, 'email' ) )

        ok, existing = self.unique_model.create_multi( k for k, v in uniques )
        if ok:
            # No overlap with existing unique properties.
            # Remove the old unique values from the datastore.
            values = [ ]
            if self.username_lower != username.lower( ):
                key = '%s.%s:%s' % ( self.__class__.__name__, 'username',
                                     self.username_lower )
                values.append( key )
            if( self.email_pending
                and ( self.email_pending_lower != email.lower( ) )
                and ( self.email_pending_lower
                      != self.email_verified_lower ) ):
                key = '%s.%s:%s' % ( self.__class__.__name__, 'email',
                                     self.email_pending_lower )
                values.append( key )
            self.unique_model.delete_multi( values )

            # Update user
            self.username = username
            self.email_pending = email
            if password:
                self.password = security.generate_password_hash(
                    password, length=12 )
            self.put( )
            return True, self

        else:
            # Overlap with existing unique properties
            properties = [ v for k, v in uniques if k in existing ]
            return False, properties
Example #27
0
    def post(self):

        name = self.request.get('name')
        email = self.request.get('email')
        password = self.request.get('password')

        fbauth = None

        if self.request.session:
            stored_fb  = self.request.session.data.get('facebook_appcenter',None)

            if stored_fb:
                fbauth = pickle.loads(str(stored_fb))
                email = fbauth['user_info']['email']
                fb_auth_id = authprovider.AuthProvider.generate_auth_id('facebook', fbauth['user_info']['id'])

        if not name or not email or not password:
            raise Exception('Error not all values passed')

        auth_id = authprovider.AuthProvider.generate_auth_id('password', email)

        matched_at = authprovider.AuthProvider.get_by_auth_id(auth_id)

        password_hash = security.generate_password_hash(password=password,pepper=shg_utils.password_pepper)

        if fbauth is None:

            if matched_at:
                return self.json_response(json.dumps({'failure':'Email already exists in system &raquo; <a href="#login" class="btn btn-small btn-success" data-toggle="modal" >Login or reset password</a>'}))

            token = _user.EmailVerify.get_or_create(name=name,email=email,password_hash=password_hash)

            reason = token.limited()

            if reason:
                return self.json_response(json.dumps({'failure':reason}))

            if token.send_email(self.request.host_url):
                return self.json_response(json.dumps({'success':'Validation email sent. Please check your inbox!'}))
            else:
                return self.json_response(json.dumps({'failure':'Unable to send email - please try again shortly'}))
        else:

            if not matched_at:
                new_user = _user.User._create(display_name=name,verified_email=email)
                auth_id = authprovider.AuthProvider.generate_auth_id('password', email)
                new_at = authprovider.AuthProvider._create(user=new_user,auth_id=auth_id,password_hash=password_hash)
            else:
                new_user = _user.User._get_user_from_id(matched_at.user_id)

            new_fb_at = authprovider.AuthProvider._create(user=new_user,
                auth_id=fb_auth_id,
                user_info=fbauth['user_info'],
                credentials=fbauth['credentials'])

            self.request.session.upgrade_to_user_session(new_user._get_id())

            return self.json_response(json.dumps({'success':'Thank you for registering','redirect':'/'}))
Example #28
0
    def update( self, email, username, password ):
        """ Updates the User with new parameters.

        :param email:
            The new email_pending for the user
        :param username:
            The new username to assign to the user
        :param password:
            The new password to assign to the user
        :returns:
            A tuple (boolean, info) where on success, (True, user) is returned
            and on failure, (False, list) is returned where list gives names
            of the properties that conflict with existing unique properties.
        """
        # Set up unique properties
        uniques = [ ]
        if self.username_lower != username.lower( ):
            key = '%s.%s:%s' % ( self.__class__.__name__, 'username',
                                 username.lower( ) )
            uniques.append( ( key, 'username' ) )
        if( email
            and self.email_pending_lower != email.lower( )
            and self.email_verified_lower != email.lower( ) ):
            key = '%s.%s:%s' % ( self.__class__.__name__, 'email',
                                 email.lower( ) )
            uniques.append( ( key, 'email' ) )

        ok, existing = self.unique_model.create_multi( k for k, v in uniques )
        if ok:
            # No overlap with existing unique properties.
            # Remove the old unique values from the datastore.
            values = [ ]
            if self.username_lower != username.lower( ):
                key = '%s.%s:%s' % ( self.__class__.__name__, 'username',
                                     self.username_lower )
                values.append( key )
            if( self.email_pending
                and ( self.email_pending_lower != email.lower( ) )
                and ( self.email_pending_lower
                      != self.email_verified_lower ) ):
                key = '%s.%s:%s' % ( self.__class__.__name__, 'email',
                                     self.email_pending_lower )
                values.append( key )
            self.unique_model.delete_multi( values )

            # Update user
            self.username = username
            self.email_pending = email
            if password:
                self.password = security.generate_password_hash(
                    password, length=12 )
            self.put( )
            return True, self

        else:
            # Overlap with existing unique properties
            properties = [ v for k, v in uniques if k in existing ]
            return False, properties
Example #29
0
def register():
	register_error = None
	form = RegisterFormExt(csrf_enabled=False)
	if request.method == 'POST' and form.validate():
		password = security.generate_password_hash(form.password.data, length=32)
		user = Users(username=form.username.data, password=password)
		user.put()
		return redirect(url_for('login'), code=302)
	return render_template('register.html', form=form, register_error=register_error)
Example #30
0
 def create(cls, email, done=False):
     newsletterinvite = cls(
         token=security.generate_password_hash(
             password=email, length=12
         ),  # better than random string because of smaller possibility of duplicate token
         email=email,
         done=done)
     newsletterinvite.put()
     return newsletterinvite.token
Example #31
0
 def post(self, admin_id):
     admin_id = int(admin_id)
     admin = PushAdmin.get_by_id(admin_id)
     if not admin:
         self.abort(500)
     password = self.request.get('password')
     admin.password = security.generate_password_hash(password, length=12)
     admin.put()
     self.redirect_to('push_admin_main')
Example #32
0
  def create_user(cls, email, password, **other_properties):
    logging.info("Creating user with email '%s', other properties: %s." % \
                 (email, other_properties))

    password_hash = security.generate_password_hash(password, length=12)
    member = cls(email=email, password_hash=password_hash, **other_properties)
    member.put()

    return member
Example #33
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.encrypt(current_password, config.salt)
            try:
                user = models.User.get_by_auth_password(auth_id, current_password)
                # Password to SHA512
                password = utils.encrypt(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('secure')
            except (InvalidAuthIdError, InvalidPasswordError), e:
                # Returns error message to self.response.write in
                # the BaseHandler.dispatcher
                message = _("Your Current Password is wrong, please try again")
                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 #34
0
 def save(cls, form):
     user = User(
         id=form['userId'],
         email=form['email'],
         name=form.get('name', ''),
         birth=form.get('birth'),
         password=security.generate_password_hash(form['password'])
     ).put()
     return user
Example #35
0
    def _set_password(self, password):
        # TODO switch password encryption to bcrypt
        """
        Set the User's password attribute to the hashed password generated
        from the supplied password string

        :param password: a string representing the password
        """
        self.password = security.generate_password_hash(password, length=12)
Example #36
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 = self.user_model.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 = self.user_model.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, 'danger')
                return self.redirect_to('edit-password')
        except (AttributeError, TypeError), e:
            login_error_message = _('Your session has expired.')
            self.add_message(login_error_message, 'danger')
            self.redirect_to('login')
    def set_password(self, raw_password):
        """
        Sets the password for the current user.
        Doesn't update changes to user in datastore, however.

        :param raw_password:
            The raw password which will be hashed and stored
        """

        self.password = security.generate_password_hash(raw_password, length=12)
Example #38
0
 def update(cls, email, name=None, password=None, photo=None):
     user = cls.get_by_key_name(email)
     if user:
         if name:
             user.name = name
         if password:
             user.password = generate_password_hash(password)
         if photo:
             user.photo = photo
         user.put()
Example #39
0
    def post(self):
        password = self.request.get('password')
        if not password or password != self.request.get('confirm_password'):
            return self.display_message('passwords do not match')

        user = User.get_by_id(self.user_info['user_id'])
        user.password = security.generate_password_hash(password, length=12)
        user.put()

        return self.display_message('Password updated')
Example #40
0
 def Create(cls, lastname, firstname, gender, email, raw_password, phone):
   uniques = ['%s.%s:%s' % (cls.__name__, 'auth_id', email)]
   ok, existing = Unique.create_multi(uniques)
   if ok:
     password = security.generate_password_hash(raw_password, method='sha1', length=12, pepper=cls.Pepper)
     user = cls(auth_id=email, email=email, lastname=lastname, firstname=firstname, gender=gender, password=password, phone=phone)
     user.put()
     return user
   else:
     return None
Example #41
0
def createNewUser(email, un, pw, gender):
    newUser = Users()
    secure_pw = security.generate_password_hash(pw, 'sha1')

    newUser.email = email
    newUser.un = un
    newUser.pw = secure_pw
    newUser.gender = gender
    newUser_key = newUser.put()
    return newUser_key
Example #42
0
 def post(self):
     form = ForgotPasswordSetForm(self.request.POST)
     if form.validate():
         d = Developer.query(ndb.StringProperty('password_reset_token') == form.token.data, 
                             Developer.email == form.email.data).get()
         d.password = security.generate_password_hash(form.new_password.data, length=12)
         d.put()
         self.auth.set_session(self.auth.store.user_to_dict(d))
         return self.redirect_to('profile')
     self.render_response("auth/forgot_password_set.html", form=form)    
Example #43
0
    def set_password(self, raw_password):
        """Set the password for the current user.

        Args:
            raw_password: A string containing the raw password which will be
                hashed and stored.

        Source: https://blog.abahgat.com/2013/01/07/user-authentication-with-webapp2-on-google-app-engine/
        """

        self.password = security.generate_password_hash(raw_password)
Example #44
0
    def create_user(cls, **user_values):
        """Creates a new user.

        :param auth_id:
            A string that is unique to the user. Users may have multiple
            auth ids. Example auth ids:

            - own:username
            - own:[email protected]
            - google:username
            - yahoo:username

            The value of `auth_id` must be unique.
        :param unique_properties:
            Sequence of extra property names that must be unique.
        :param user_values:
            Keyword arguments to create a new user entity. Since the model is
            an ``Expando``, any provided custom properties will be saved.
            To hash a plain password, pass a keyword ``password_raw``.
        :returns:
            A tuple (boolean, info). The boolean indicates if the user
            was created. If creation succeeds, ``info`` is the verification code;
            otherwise it is a list of duplicated unique properties that
            caused creation to fail.
        """

        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)

        myclient = pymongo.MongoClient(server_config.mongodbURL)
        mydb = myclient[server_config.mongodbDB]
        mycol = mydb["users"]

        user_result = mycol.find_one({"email": user_values['email_address']})

        if user_result is None:
            verify = security.generate_random_string(
                length=12,
                pool=
                'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
            )
            user_dict = {
                "user_id": None,
                "password": user_values['password'],
                "email": user_values['email_address'],
                "activation_key": verify,
                "friendly_name": user_values['friendly'],
                "level": 5
            }
            mycol.insert_one(user_dict)
            return True, verify
        else:
            return False, "Email"
Example #45
0
 def create_or_update(cls,
                      email,
                      name=None,
                      organization=None,
                      designation=None,
                      website=None,
                      twitter_handle=None,
                      facebook_id=None,
                      bio=None,
                      image=None,
                      password=None,
                      image_coords=None,
                      image_url=None,
                      role=None):
     member = Member.get_by_email(email)
     if not member:
         member = Member(key_name=email)
     if name != None:
         member.name = name
     if email != None:
         member.email = email
     if designation != None:
         member.designation = designation
     if organization != None:
         member.organization = organization
     if website != None:
         member.website = website
     if twitter_handle != None:
         member.twitter_handle = twitter_handle
     if facebook_id != None:
         member.facebook_id = facebook_id
     if bio != None:
         member.bio = bio
     if image != None:
         if member.image:
             Member.delete_image(member.image)
         member.image = image
     if image_coords != None:
         member.image_coords = image_coords
     if password != None:
         member.password = generate_password_hash(password)
     if not member.influence_score:
         member.influence_score = random.randint(0, 100)
     if not member.activity_score:
         member.activity_score = random.randint(0, 100)
     if not member.proficiency_score:
         member.proficiency_score = random.randint(0, 100)
     if image_url is not None:
         member.image_url = image_url
     if role is not None:
         member.role = role
     member.put()
     return member
Example #46
0
 def set_password(self, password, save=True):
     if password:
         h = security.generate_password_hash(password,
                                             method='sha512',
                                             length=64,
                                             pepper=PEPPER)
         hashval, method, salt = h.split('$')
         self.password = hashval
         self.hash_method = method
         self.salt = salt
         if save:
             self.put()
Example #47
0
 def post(self):
     form = ForgotPasswordSetForm(self.request.POST)
     if form.validate():
         d = Developer.query(
             ndb.StringProperty('password_reset_token') == form.token.data,
             Developer.email == form.email.data).get()
         d.password = security.generate_password_hash(
             form.new_password.data, length=12)
         d.put()
         self.auth.set_session(self.auth.store.user_to_dict(d))
         return self.redirect_to('profile')
     self.render_response("auth/forgot_password_set.html", form=form)
Example #48
0
    def create_user(cls, auth_id, unique_properties=None, **user_values):
        """Creates a new user.

        :param auth_id:
            A string that is unique to the user. Users may have multiple
            auth ids. Example auth ids:

            - own:username
            - own:[email protected]
            - google:username
            - yahoo:username

            The value of `auth_id` must be unique.
        :param unique_properties:
            Sequence of extra property names that must be unique.
        :param user_values:
            Keyword arguments to create a new user entity. Since the model is
            an ``Expando``, any provided custom properties will be saved.
            To hash a plain password, pass a keyword ``password_raw``.
        :returns:
            A tuple (boolean, info). The boolean indicates if the user
            was created. If creation succeeds, ``info`` is the user entity;
            otherwise it is a list of duplicated unique properties that
            caused creation to fail.
        """
        assert user_values.get('password') is None, \
            'Use password_raw instead of password to create new users.'

        assert not isinstance(auth_id, list), \
            'Creating a user with multiple auth_ids is not allowed, ' \
            'please provide a single auth_id.'

        if 'password_raw' in user_values:
            user_values['password'] = security.generate_password_hash(
                user_values.pop('password_raw'), length=12)

        user_values['auth_ids'] = [auth_id]
        user = cls(**user_values)

        # Set up unique properties.
        uniques = [('%s.auth_id:%s' % (cls.__name__, auth_id), 'auth_id')]
        if unique_properties:
            for name in unique_properties:
                key = '%s.%s:%s' % (cls.__name__, name, user_values[name])
                uniques.append((key, name))

        ok, existing = cls.unique_model.create_multi(k for k, v in uniques)
        if ok:
            user.put()
            return True, user
        else:
            properties = [v for k, v in uniques if k in existing]
            return False, properties
Example #49
0
    def post(self, vanity_url=None):
        provider = db.get_provider_from_vanity_url(vanity_url)

        patient_form = RegistrationDetailsForNewPatient().get_form(
            self.request.POST)

        if patient_form.validate():
            booking_key_urlsafe = patient_form['booking_key'].data
            booking = db.get_from_urlsafe_key(booking_key_urlsafe)

            # create a new patient
            patient = Patient()

            patient_form.populate_obj(patient)
            self.set_gae_geography_from_headers(patient)
            patient.put()

            # create a new user
            user = self.create_empty_user_for_patient(patient)
            user.language = self.get_language()

            # set the password
            password = patient_form['password'].data
            password_hash = security.generate_password_hash(password,
                                                            length=12)
            user.password = password_hash
            user.put()

            # login with new password
            self.login_user(user.get_email(), password)

            # store booking
            user = patient.user.get()
            booking.patient = patient.key
            booking.confirmed = user.confirmed = False
            booking.put()

            # send a confirmation/activation email
            url_obj = urlparse.urlparse(self.request.url)
            activation_url = urlparse.urlunparse(
                (url_obj.scheme, url_obj.netloc,
                 '/login/booking/' + booking.key.urlsafe(), '', '', ''))
            logging.info(
                '(NewPatientHandler.post) generated activation url for user %s : %s '
                % (patient.email, activation_url))
            mail.email_booking_to_patient(self, booking, activation_url)

            PatientBaseHandler.render_confirmation_email_sent(self, booking)
        else:
            self.render_template('provider/public/booking_new_patient.html',
                                 provider=provider,
                                 patient_form=patient_form)
Example #50
0
  def activate(self):
    # k is used in emails
    # activation_key is the form name
    key = self.request.get('k')
    profile = Profile.get_by_activation_key(key)

    if not profile or profile.activated:
      self.session.add_flash(messages.PROFILE_ACTIVATION_NOT_FOUND,
                             level='error')
      self.redirect_to('home')

    form = ProfileActivationForm(self.request.POST, obj=profile)
    form.activation_key = key

    if self.request.method == 'POST' and form.validate():
      # Create the webapp2_extras.auth user.
      model = self.auth.store.user_model
      ok, user = model.create_user(profile.email,
                                   password_raw=form.data['password'])

      if not ok:
        self.session.add_flash(messages.PROFILE_ACTIVATION_ERROR,
                               level='error')
        return self.redirect_to('profile.activate', k=key)

      # Setup profile, create authentication token and activate
      profile.name = ' '.join([form.data['first_name'],
                               form.data['last_name']])

      # Set as activated (since they've confirmed their e-mail).
      profile.activated = True
      profile.activation_key = None
      profile.auth_user_id = user.key.id()
      profile.put()

      # Change the password for the auth_user.
      user = self.auth.store.user_model.get_by_id(profile.auth_user_id)
      user.password = security.generate_password_hash(form.data['password'],
                                                      length=12)
      user.put()

      # Log the user in.
      user_id = user.key.id()
      self.auth._user = None
      self.auth.get_user_by_token(user_id, user.create_auth_token(user_id))

      # Redirect to the dashboard.
      self.session.add_flash(messages.PROFILE_ACTIVATION_SUCCESS)
      return self.redirect_to('home')

    return self.render_to_response('activate.haml',
                                   {'profile': profile, 'form': form})
Example #51
0
    def post(self, vanity_url=None):
        provider = db.get_provider_from_vanity_url(vanity_url)
        new_password = self.request.get('password')
        if provider and new_password:
            user = db.get_user_from_email(provider.email)
            if user:
                # hash password (same as passing password_raw to user_create)
                password_hash = security.generate_password_hash(new_password,
                                                                length=12)
                user.password = password_hash
                user.put()

        self.redirect('/admin/provider/admin/' + provider.vanity_url)
Example #52
0
    def post(self, user_id):
        """ Get fields from POST dict """

        user_data = self._data()
        user_info = models.User.get_by_id(long(user_id))

        logging.info(user_data)

        if not user_info:
            raise Exception("User not found with id: " + user_id)

        username = user_data['username']
        try:
            message = ''
            # update username if it has changed and it isn't already taken

            user_info.unique_properties = ['username', 'email']
            uniques = [
                'User.username:%s' % username,
                'User.auth_id:own:%s' % username,
            ]
            # Create the unique username and auth_id.
            success, existing = Unique.create_multi(uniques)

            if not existing and not success:
                raise Exception("Error creating user")

            # free old uniques
            Unique.delete_multi(
                ['User.username:%s' % user_info.username, 'User.auth_id:own:%s' % user_info.username])
            # The unique values were created, so we can save the user.
            user_info.username = username
            user_info.auth_ids[0] = 'own:%s' % username
            user_info.name = user_data.get('name', None)
            user_info.last_name = user_data.get('last_name', None)

            if user_data.get('password', None) is not None:
                # Password to SHA512
                password = utils.hashing(user_data['password'], self.app.config.get('salt'))
                user_info.password = security.generate_password_hash(password, length=12)

            user_info.put()
            return True
        except (AttributeError, KeyError, ValueError), e:
            logging.error('Error updating profile: ')
            logging.exception(e)
            return False
Example #53
0
  def test_password_auth(self):
    # Give the user a password.
    password = "******"
    password_hash = security.generate_password_hash(password)
    self.user.password_hash = password_hash
    self.user.put()

    # Now, we should be able to authenticate with that password.
    user = membership.Membership.get_by_auth_password(self.user.email, password)
    self.assertEqual(self.user.properties(), user.properties())

    # Try with the wrong password.
    with self.assertRaises(auth.InvalidPasswordError):
      membership.Membership.get_by_auth_password(self.user.email, "badpassword")

    # Try with the wrong email altogether.
    with self.assertRaises(auth.InvalidAuthIdError):
      membership.Membership.get_by_auth_password("bademail", password)
Example #54
0
 def create_user(self, req_handler):
     photos = self.get_uploads("uploaded_photo")
     photo = self['image']
     email = req_handler['email']
     if photos:
         photo_blob_key = photos[0].key()
         photo = '/api/common/download_image/' + str(photo_blob_key)
     password_hash = generate_password_hash(req_handler['password'])
     user = User(key_name=email,
                 name=req_handler['name'],
                 password=password_hash,
                 photo=photo)
     intercomio_api.users(email=email,
                          name=req_handler['name'],
                          signed_up_at=int(time.time()))
     intercomio_api.events(email=email, event_name='signedup')
     mixpanel_api.users(email, req_handler['name'])
     mixpanel_api.events(email, 'signedup')
     user.put()
Example #55
0
 def Create(cls, lastname, firstname, gender, email, raw_password, phone):
     uniques = ['%s.%s:%s' % (cls.__name__, 'auth_id', email)]
     ok, existing = Unique.create_multi(uniques)
     if ok:
         password = security.generate_password_hash(raw_password,
                                                    method='sha1',
                                                    length=12,
                                                    pepper=cls.Pepper)
         user = cls(auth_id=email,
                    email=email,
                    lastname=lastname,
                    firstname=firstname,
                    gender=gender,
                    password=password,
                    phone=phone)
         user.put()
         return user
     else:
         return None
Example #56
0
    def post(self, token=None):
        password_form = PasswordForm().get_form(self.request.POST)
        
        user = self.validate_token(token)
        
        if user and password_form.validate():        
            # get password from request
            password = self.request.get('password')
                
            # hash password (same as passing password_raw to user_create)
            password_hash = security.generate_password_hash(password, length=12)    
            user.password = password_hash
            user.put()
            
            # login with new password
            self.login_user(user.get_email(), password)
               
            # clear the tokens to prevent further shenanigans
            provider = db.get_provider_from_user(user)
            
            redirect_url = None
            if user.resetpassword_token:
                self.delete_token(token, 'reset')
                redirect_url = '/provider/message/reset/' + provider.vanity_url
            
            elif user.claim_url:
                self.delete_token(token)
                redirect_url = '/provider/welcome/' + provider.vanity_url
            
            
            # redirect patient or provider
            if auth.PROVIDER_ROLE in user.roles:
                self.redirect(redirect_url)
                self.log_event(user, "User claimed their profile")
            
            elif auth.PATIENT_ROLE in user.roles:
                patient = db.get_patient_from_user(user)
                self.redirect('/patient/bookings/' + patient.key.urlsafe())

        # password form was not validate, re-render and try again!
        else:
            self.render_template('user/password.html', form=password_form, token=token)
Example #57
0
    def change_password(self):
        password_form = ProfilePasswordForm(self.request.POST)
        contact_form = ProfileContactForm(None, self.user_complete)
        dev = self.user_complete
        if password_form.validate():
            if security.check_password_hash(
                    password_form.current_password.data, dev.password):
                dev.password = security.generate_password_hash(
                    password_form.new_password.data, length=12)
                dev.put()
                self.session.add_flash("Password successfully changed.",
                                       "local")
                return self.redirect_to("profile_settings")
            else:
                password_form.current_password.errors.append(
                    "Current password was invalid.")

        self.render_response("auth/profile/settings.html",
                             contact_form=contact_form,
                             password_form=password_form)
Example #58
0
 def get_or_create_profile(self, auth_id, user_info, **kwargs):
     """
     Overrides to provide logic for checking and encrypting  passwords.
     :param auth_id:
     :param user_info:
     :param kwargs:
     :return:
     :raise:
     """
     password = kwargs.pop('password')
     profile = models.UserProfile.get_by_id(auth_id)
     if profile is None:
         # Create profile
         profile = models.UserProfile.get_or_create(auth_id, user_info,
             password=security.generate_password_hash(password, length=12))
     # Check password
     if not security.check_password_hash(password, profile.password):
         return self.raise_error('The password that you\'ve provided '
                                 'doesn\'t match our records. '
                                 'Please try again.')
     return profile