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)
Esempio n. 4
0
 def get_by_auth_password(cls, auth_id, password):
     user = cls.get_by_auth_id(auth_id)
     if not user:
         raise auth.InvalidAuthIdError()
     if not security.check_password_hash(password, user.password):
         raise auth.InvalidPasswordError()
     return user
Esempio n. 5
0
 def callback(self, req):
     token = req.GET['token']
     email = req.GET['email']
     timestamp = req.GET['ts']
     
     if not token or not email:
         self.raise_error('Invalid confirmation link, please validate.')
     
     auth_id = models.User.generate_auth_id(req.provider, email)
     profile = models.UserProfile.get_by_id(auth_id)
     
     if not profile:
         return self.raise_error('The information that you\'ve provided '
                                 'doesn\'t match our records. '
                                 'Please try again.')
     
     if not security.check_password_hash(profile.password+timestamp, token):
         return self.raise_error('The information that you\'ve provided '
                                 'doesn\'t match our records. '
                                 'Please try again.')
                                 
     delta_time = datetime.date.fromtimestamp(float(timestamp)) - datetime.date.today()
     if delta_time.days >= 1:
         return self.raise_error('Expired validation link. '
                                 'Please try again.')
         
                                 
     profile.verified = True
     profile.put()
     
     req.load_user_by_profile(profile)
     
     return req.get_redirect_uri()
Esempio n. 6
0
 def validate_password(self, new_raw_password):
     testHash = security.check_password_hash(new_raw_password,
                                             self.password)
     if (testHash):
         return True
     else:
         return False
Esempio n. 7
0
    def post(self):
        changed = str(self.request.get('type'))

        # Change the name
        if changed == 'name':
            logging.info("Changed Name")
            self.user.name = str(self.request.get('newValue'))
            self.user.put()

        # Change the password
        elif changed == 'password':
            oldPass = str(self.request.get('oldValue'))
            newPass = str(self.request.get('newValue'))
            # logging.info("Passed Old Passwpord: " + oldPass)

            if security.check_password_hash(oldPass, self.user.password) is False:
                self.response.write('Failed')
                return

            self.user.set_password(newPass)
            self.user.put()
            # logging.info("Password Changed")

        elif changed == 'picture':
            logging.info("Chnagee picture")

        elif changed == 'deactivate':
            logging.info("Deactivated Account")
Esempio n. 8
0
	def get(self, create_by):
		q = self.request.GET

		if create_by not in ('uuid', 'password'):
			return

		new_userid =  create_by +":"+str( q['userid'] )

		a = AccountDB.get_by_id(new_userid)
		if a: #IDの存在チェック
			if security.check_password_hash(q['password'], a.password, pepper=PASSWORD_PEPPER):
				#パスワードOK
				p = PlayerDB.get_by_id(new_userid)

				self.session = session(self.request)
				self.session.start(new_userid, {"plkey":p.key})

				#playerdb+ssid 返す
				return webapp2.Response( json.dumps( {"result":p.to_dict()}, self.session) )

			return webapp2.Response(  json.dumps( {"code":1, "message":"ログインに失敗しました。"} )  )

		passh = security.create_password_hash(q['password'], pepper=PASSWORD_PEPPER)
		a = AccountDB(id = new_userid, userid = new_userid, password = passh, create_by = create_by)
		p = PlayerDB(id = new_userid, userid = new_userid, namae=q['namae'])
		ndb.put_multi( (a, p) )

		self.session = session(self.request)
		self.session.start(new_userid, {"plkey":p.key})

		return webapp2.Response(  json.dumps( {"result":p.to_dict()}, self.session  )  )
Esempio n. 9
0
    def get_by_auth_password(cls, auth_id, password):
        """Returns a user object, validating password.

        :param auth_id:
            Authentication id. In this application, the email
        :param password:
            Password to be checked.
        :returns:
            A user object, if found and password matches.
        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """
        myclient = pymongo.MongoClient(server_config.mongodbURL)
        mydb = myclient[server_config.mongodbDB]
        mycol = mydb["users"]

        user_result = mycol.find_one({"email": auth_id})

        if user_result is None:
            raise auth.InvalidAuthIdError()

        if not security.check_password_hash(password, user_result['password']):
            raise auth.InvalidPasswordError()

        return User(user_result['user_id'], auth_id,
                    user_result['friendly_name'], user_result['level'])
Esempio n. 10
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()
Esempio n. 11
0
    def check_user_password(cls, login=None, raw_password=None):
        """
        Check if user and password match whith user and password in DB
        Method make a DB query and checking if password hashes is same
        with security.check_user_password() method

        :param login:
            login
        :param raw_password:
            password
       :return:
            Login instance or None
        """
        logging.info('LoginClass:check_user_password() => Strat check_user_password()')
        if not raw_password:
            logging.info('LoginClass:check_user_password() => raw_password is empty, return None')
            return None
        logging.info('LoginClass:check_user_password() => Making QUERY to DB to get user instance')
        u = cls.query(Login.username == login).get()
        if not u:
            logging.error('LoginClass:check_user_password() => User NOT found. Return None')
            return None
        logging.info('LoginClass:check_user_password() => User FOUND')

        # comment for production
        # return u if security.check_password_hash(raw_password, u.pw_hash, pepper=PEPPER) else None

        sec_check = security.check_password_hash(raw_password, u.pw_hash, pepper=PEPPER)
        logging.info('LoginClass:check_user_password() => Result of security.check_password_hash() is %s' % sec_check)
        logging.info('LoginClass:check_user_password() => Return user instance or if True and None otherwise')
        return u if sec_check else None
Esempio n. 12
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()
Esempio n. 13
0
 def post(self):
     '''
     Corresponds to a possible attempt to change some account settings.
     Possible fields to change:
     - name
     - email_address
     - password
     '''
     should_update_user = False
     new_name = self.request.POST['name']
     try:
         new_email = self.request.POST['email']
     except KeyError:
         new_email = self.user.email_address
     if self.user.name != new_name:
         self.user.name = new_name
         should_update_user = True
     if self.user.email_address != new_email:
         if self.user.change_auth_id(new_email):
             self.user.email_address = new_email
             should_update_user = True
         else:
             context = {
                 'name': self.user.name,
                 'email_address': self.user.email_address,
                 'error_alert': 'A user with that email address already exists.'
             }
             return self.render_response('account_settings.html', **context)
     
     try:
         new_password = self.request.POST["password"]
         current_password = self.request.POST["current_password"]
     except KeyError:
         new_password = None
     
     if new_password not in [None, '']:
         # Check that correct current password was entered
         if security.check_password_hash(current_password, self.user.password):
             # Correct
             self.user.set_password(new_password)
             should_update_user = True
         else:
             # Incorrect
             context = {
                 'name': self.user.name,
                 'email_address': self.user.email_address,
                 'error_alert': 'Incorrect password.'
             }
             return self.render_response('account_settings.html', **context)
     
     if should_update_user:
         self.user.put()
         context = {
             'name': self.user.name,
             'email_address': self.user.email_address,
             'success_alert': 'Successfully updated account settings!'
         }
         return self.render_response('account_settings.html', **context)
Esempio n. 14
0
    def authenticate(cls, username, password):
        user = cls.query().filter(cls.username == username).get()
        if user is None:
            return None

        if check_password_hash(password, user.password_hash):
            return user

        return None
Esempio n. 15
0
    def get_by_auth_password(cls, auth_id, password):
        user = cls.get_by_auth_id(auth_id)
        if user == None:
            raise auth.InvalidAuthIdError()

        if not security.check_password_hash(password, user.password):
            raise auth.InvalidPasswordError()

        return user
Esempio n. 16
0
  def get_by_auth_password(cls, email, password):
    user = cls.get_by_email(email)
    if not user:
      raise auth.InvalidAuthIdError("No user with email '%s'." % (email))

    if not security.check_password_hash(password, user.password_hash):
      raise auth.InvalidPasswordError("Bad password for user '%s'." % (email))

    return user
Esempio n. 17
0
    def post(self, *args, **kwargs):
        if not 'u' in self.session:
            email = self.request.POST['email']
            password = self.request.POST['password']

            user = User.query(ndb.AND(User.email == email), namespace='_x_')

            if user.get() is None:
                self.render_user_login(is_loggedin=False,
                                       error='Email or Password is wrong!.')
                return

            if user.get().is_admin:
                self.render_user_login(is_loggedin=False,
                                       error='Email or Password is wrong!.')
                return

            else:
                if check_password_hash(password, user.get().password):
                    self.delete_session()
                    self.set_current_user(user)
                else:
                    self.render_user_login(
                        is_loggedin=False,
                        error='Email or Password is wrong!.')
                    return

        user_key = self.session.get('u')
        user = ndb.Key(urlsafe=user_key).get()
        school_length = len(user.schools)

        #check schools that user was asigned
        if school_length == 1:
            school_key = user.schools[0]
            school_key = school_key.get().key.urlsafe()
            self.set_current_school(school_key)
            self.redirect("/")
            return

        if school_length == 0:
            self.render_user_login(
                is_loggedin=False,
                error=
                "You don't have any schools!. Please contact with admin for this reason."
            )
            self.delete_session()
            return

        if school_length > 1 and 'school' not in self.request.POST:
            schools = [school_key.get() for school_key in user.schools]
            self.render_user_login(is_loggedin=True, schools=schools)
            return

        school_key = self.request.POST['school']
        self.set_current_school(school_key)
        self.redirect("/")
Esempio n. 18
0
    def _check_password(self, password):
        # TODO switch password encryption to bcrypt
        """
        Validate that the user supplied password matches the the hashed
        password saved to the datastore.

        :param password: string representing the password
        :return: boolean True if match False if not.
        """
        return security.check_password_hash(password, self.password)
Esempio n. 19
0
    def validate_username_and_password(cls, username, password):
        """Returns (user, reason-if-not-valid)."""
        # TODO: check if user.status != 0 here?
        user = cls.get_by_username(username)
        if not user:
            return None, 'invalid-username'

        if not security.check_password_hash(password, user.password):
            return None, 'invalid-password'

        return user, None
Esempio n. 20
0
 def check_password( self, password ):
     """ Checks that password is valid.
     :param password:
         The password to check
     :returns:
         True if password matches database, False otherwise
     """
     if password is not None and self.password is not None:
         return security.check_password_hash( password, self.password )
     else:
         return False
Esempio n. 21
0
 def check_password( self, password ):
     """ Checks that password is valid.
     :param password:
         The password to check
     :returns:
         True if password matches database, False otherwise
     """
     if password is not None and self.password is not None:
         return security.check_password_hash( password, self.password )
     else:
         return False
Esempio n. 22
0
    def post(self):
        """Update user info"""
        first_name = self.request.POST['first_name']
        last_name = self.request.POST['last_name']
        email = self.request.POST['email']
        phone = self.request.POST['phone']

        current_password = self.request.POST['current_password']
        new_password = self.request.POST['new_password']
        confirm_password = self.request.POST['confirm_password']

        errors = {
            'wrong': 'Current password is wrong.',
            'required': 'Field current password is required.',
            'not_correct': 'Confirm password is not correct.',
            'success': 'Account updated successfully.'
        }

        user_key = self.session.get('u')
        user = ndb.Key(urlsafe=user_key).get()

        if not current_password:
            self.render_account(error=errors['required'],
                                user=user,
                                school_name=self.school_name,
                                schools=self.list_school)

        else:
            if check_password_hash(current_password, user.password):
                if new_password:
                    if new_password != confirm_password:
                        self.render_account(error=errors['not_correct'],
                                            user=user,
                                            school_name=self.school_name,
                                            schools=self.list_school)
                    else:
                        self.update_user(user, first_name, last_name, phone,
                                         email, new_password)
                        self.render_account(error=errors['success'],
                                            user=user,
                                            school_name=self.school_name,
                                            schools=self.list_school)
                else:
                    self.update_user(user, first_name, last_name, phone, email,
                                     user.password)
                    self.render_account(error=errors['success'],
                                        user=user,
                                        school_name=self.school_name,
                                        schools=self.list_school)
            else:
                self.render_account(error=errors['wrong'],
                                    user=user,
                                    school_name=self.school_name,
                                    schools=self.list_school)
Esempio n. 23
0
    def post(self):
        '''
        Corresponds to a possible attempt to change some account settings.
        Possible fields to change:
        - name
        - email_address
        - password
        '''
        should_update_user = False
        new_name = self.request.POST['name']
        # new_email = self.request.POST['email']
        if self.user.name != new_name:
            self.user.name = new_name
            should_update_user = True
        # if self.user.email_address != new_email:
        #     if self.user.change_auth_id(new_email):
        #         self.user.email_address = new_email
        #         should_update_user = True
        #     else:
        #         context = {
        #             'name': self.user.name,
        #             'email_address': self.user.email_address,
        #             'error_alert': 'A user with that email address already exists.'
        #         }
        #         return self.render_response('account_settings.html', **context)
        context = {
            'name': self.user.name,
            'email_address': self.user.email_address
        }
        try:
            new_password = self.request.POST["password"]
            current_password = self.request.POST["current_password"]
        except KeyError:
            new_password = None

        if new_password not in [None, '']:
            # Check that correct current password was entered
            if security.check_password_hash(current_password,
                                            self.user.password):
                # Correct
                self.user.set_password(new_password)
                should_update_user = True
            else:
                # Incorrect
                context['error_alert'] = 'Incorrect password.'
                return self.render_response('account_settings.html', **context)
        # Was anything updated?
        if should_update_user:
            self.user.put()
            context['success_alert'] = 'Successfully updated account settings!'
        else:
            context['error_alert'] = "You didn't request any changes."
        return self.render_response('account_settings.html', **context)
Esempio n. 24
0
 def post(self):
     redirect_url = util.get_redirect_url_from_session()
     email = self['email']
     user = User.get_by_key_name(email)
     if check_password_hash(self['password'], user.password):
         create_tpld(email, self['network'])
         modify_session(email)
         self.redirect(redirect_url)
     else:
         session = get_current_session()
         session.terminate()
         self.redirect('/member/verification_failed')
Esempio n. 25
0
    def post(self):
        old_password = self.request.get('oldpwd')
        new_password = self.request.get('newpwd')

        user = self.user
        if not security.check_password_hash(old_password, user.password):
            self.abort(501)

        user.set_password(new_password)
        user.put()

        self.response.out.write("OK")
Esempio n. 26
0
 def post(self):
     redirect_url = util.get_redirect_url_from_session()
     email = self['email']
     user = User.get_by_key_name(email)
     if check_password_hash(self['password'], user.password):
         create_tpld(email, self['network'])
         modify_session(email)
         self.redirect(redirect_url)
     else:
         session = get_current_session()
         session.terminate()
         self.redirect('/member/verification_failed')
Esempio n. 27
0
    def post(self):
        """Update user info"""
        first_name = self.request.POST['first_name']
        last_name = self.request.POST['last_name']
        email = self.request.POST['email']
        phone = self.request.POST['phone']

        current_password = self.request.POST['current_password']
        new_password = self.request.POST['new_password']
        confirm_password = self.request.POST['confirm_password']

        errors = {
            'wrong' : 'Current password is wrong.',
            'required' : 'Field current password is required.',
            'not_correct' : 'Confirm password is not correct.',
            'success' : 'Account updated successfully.'
        }

        user_key = self.session.get('u')
        user = ndb.Key(urlsafe = user_key).get()

        if not current_password:
            self.render_account(error = errors['required'],
                user = user,
                school_name = self.school_name,
                schools = self.list_school)

        else:
            if check_password_hash(current_password, user.password):
                if new_password:
                    if new_password != confirm_password:
                        self.render_account(error = errors['not_correct'],
                            user = user,
                            school_name = self.school_name,
                            schools = self.list_school)
                    else:
                        self.update_user(user, first_name, last_name, phone, email, new_password)
                        self.render_account(error = errors['success'],
                            user = user,
                            school_name = self.school_name,
                            schools = self.list_school)
                else:
                    self.update_user(user, first_name, last_name, phone, email, user.password)
                    self.render_account(error = errors['success'],
                        user = user,
                        school_name = self.school_name,
                        schools = self.list_school)
            else:
                self.render_account(error = errors['wrong'],
                    user = user,
                    school_name = self.school_name,
                    schools = self.list_school)
Esempio n. 28
0
def getUser(email, pw):
    result = list()
    secure_pw = security.generate_password_hash(pw, 'sha1')
    query = Users.query(Users.email==email)
    user = query.fetch(1)
    
    
    if len(user) > 0:
        if security.check_password_hash(pw, user[0].pw):
            user[0].user_id = user[0].key.id()
            result.append(user[0])
    
    return result
Esempio n. 29
0
    def get_by_auth_password(cls, auth_id, password):
        """Returns user, validating password.

        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """
        user = cls.get_by_auth_id(auth_id)
        if not user:
            raise auth.InvalidAuthIdError()

        if not security.check_password_hash(password, user.password):
            raise auth.InvalidPasswordError()

        return user
Esempio n. 30
0
    def get_by_auth_password(cls, auth_id, password):
        """Returns user, validating password.

        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """
        user = cls.get_by_auth_id(auth_id)
        if not user:
            raise auth.InvalidAuthIdError()

        if not security.check_password_hash(password, user.password):
            raise auth.InvalidPasswordError()

        return user
Esempio n. 31
0
    def post(self):
        form = forms.JoinGameForm(self.request.POST)

        try:
            game_id = int(form.game.data)
            game = models.game.get_by_id(game_id)
        except:
            game = None

        auth_error = None
        if game:
            form.game.value = form.game.data
            form.color1.choices = [(key, key) for key in _primaryColors.keys() if key not in game.primaryColorsChosen]
            form.color2.choices = [(key, key) for key in _bonusColors.keys() if key not in game.bonusColorsChosen]

            # to do: validate game exists
            # to do: validate colors are valid (i.e., not chosen allready)
            # to do: validate password?
            # to do: validate user cannot join game twice
            if form.validate:
                if security.check_password_hash(form.password.data, game.password):
                    
                    #player
                    p = models.player()
                    p.isAdmin = False
                    p.score = 0
                    p.primaryColor = form.color1.data
                    p.bonusColor = form.color2.data
                    p.put()

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

                    #game
                    game.players.append(p.key)
                    game.primaryColorsChosen.append(form.color1.data)
                    game.bonusColorsChosen.append(form.color2.data)
                    game.put()

                    self.redirect(self.uri_for('game', game_id=game.key.id()))
                else:
                    auth_error = "Invalid game password"

        context = {
            'game': game,
            'form': form, 
            'auth_error': auth_error
        }
        self.render_response('joingame.html', **context)
Esempio n. 32
0
    def post(self, *args, **kwargs):
        if not 'u' in self.session:
            email    = self.request.POST['email']
            password = self.request.POST['password']

            user = User.query(ndb.AND(User.email == email),
                namespace = '_x_')

            if user.get() is None:
                self.render_user_login(is_loggedin = False, error='Email or Password is wrong!.')
                return

            if user.get().is_admin:
                self.render_user_login(is_loggedin = False, error='Email or Password is wrong!.')
                return

            else:
                if check_password_hash(password, user.get().password):
                    self.delete_session()
                    self.set_current_user(user)
                else:
                    self.render_user_login(is_loggedin = False, error='Email or Password is wrong!.')
                    return

        user_key = self.session.get('u')
        user = ndb.Key(urlsafe=user_key).get()
        school_length = len(user.schools)

        #check schools that user was asigned
        if school_length == 1:
            school_key = user.schools[0]
            school_key = school_key.get().key.urlsafe()
            self.set_current_school(school_key)
            self.redirect("/")
            return

        if school_length == 0:
            self.render_user_login(is_loggedin = False, error="You don't have any schools!. Please contact with admin for this reason.")
            self.delete_session()
            return

        if school_length > 1 and 'school' not in self.request.POST:
            schools = [school_key.get() for school_key in user.schools]
            self.render_user_login(is_loggedin = True, schools=schools)
            return

        school_key = self.request.POST['school']
        self.set_current_school(school_key)
        self.redirect("/")
Esempio n. 33
0
 def post(self):
     email = self['email']
     user = util.get_user(email)
     if not user:
         rd_url = '/member/check_email'
     else:
         rd_url = util.get_redirect_url_from_session()
         if check_password_hash(self['password'], user.password):
             self.login_user()
             util.add_user_to_memcache(email)
         else:
             session = get_current_session()
             session.terminate()
             rd_url = '/member/verification_failed'
     self.redirect(rd_url)
Esempio n. 34
0
 def post(self):
     email = self['email']
     password = self['password'] if self['password'] else None
     redirect_url = str(self['redirect_url']) if self['redirect_url'] else '/community'
     member = Member.get_by_email(email)
     if 'member' in self.session and not email is self.session['member']:
         self.response.out.write('another user already logged in')
         return
     if not email or not member:
         self.response.out.write('user not in db')
         return
     if not check_password_hash(password, member.password):
         self.response.out.write('wrong password')
         return
     self.session['member'] = email
     self.redirect(redirect_url)
Esempio n. 35
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)
Esempio n. 36
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)
 def get(self):
     timestamp = self.request.get('ts')
     email = self.request.get('email')
     token = self.request.get('token')
     
     # validate url token
     auth_id = models.User.generate_auth_id('email', email)
     profile = models.UserProfile.get_by_auth_id(auth_id)
     
     if not security.check_password_hash(profile.password+timestamp, token):
         self.add_message('The information that you\'ve provided '
                         'doesn\'t match our records. '
                         'Please try again.')
         return self.redirect_to('password-reset')
     
     # show update password form
     return self.render_template('auth/password_reset_complete.html', {'form':self.form})
Esempio n. 38
0
 def post(self):
     email = self['email']
     password = self['password'] if self['password'] else None
     redirect_url = str(
         self['redirect_url']) if self['redirect_url'] else '/community'
     member = Member.get_by_email(email)
     if 'member' in self.session and not email is self.session['member']:
         self.response.out.write('another user already logged in')
         return
     if not email or not member:
         self.response.out.write('user not in db')
         return
     if not check_password_hash(password, member.password):
         self.response.out.write('wrong password')
         return
     self.session['member'] = email
     self.redirect(redirect_url)
Esempio n. 39
0
    def get_by_password(self, firstname, lastname, password):
        u"""
		
		@param str firstname 名前
		@param str lastname  苗字
		@param str password パスワード
		@return User
		@raises auth.InvalidAuthIdError() | auth.InvalidPasswordError()
		"""

        user = cls.query(firstname == firstname and lastname == lastname).get()

        if not user:
            raise auth.InvalidAuthIdError()
        if not security.check_password_hash(password, user.password):
            raise auth.InvalidPasswordError()

        return user
Esempio n. 40
0
    def get_by_auth_password(cls, auth_id, password):
        """Returns a user object, validating password.

        :param auth_id:
            Authentication id.
        :param password:
            Password to be checked.
        :returns:
            A user object, if found and password matches.
        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """
        user = cls.get_by_auth_id(auth_id)
        if not user:
            raise auth.InvalidAuthIdError()

        if not security.check_password_hash(password, user.password):
            raise auth.InvalidPasswordError()

        return user
Esempio n. 41
0
    def get_by_auth_password(cls, auth_id, password):
        """Returns a user object, validating password.

        :param auth_id:
            Authentication id.
        :param password:
            Password to be checked.
        :returns:
            A user object, if found and password matches.
        :raises:
            ``auth.InvalidAuthIdError`` or ``auth.InvalidPasswordError``.
        """
        user = cls.get_by_auth_id(auth_id)
        if not user:
            raise auth.InvalidAuthIdError()

        if not security.check_password_hash(password, user.password):
            raise auth.InvalidPasswordError()

        return user
Esempio n. 42
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)
Esempio n. 43
0
    def post(self, *args, **kwargs):
        if not 'ad' in self.session:
            email    = self.request.POST['email']
            password = self.request.POST['password']

            user = User.query(ndb.AND(User.email == email,
                User.is_admin == True),
                namespace = '_x_')

            if user.get() is None:
                self.render_admin_login(error='Email or Password is wrong!.')
                return
            else:
                if check_password_hash(password, user.get().password):
                    self.setup_admin_session(user)
                else:
                    self.render_admin_login(error='Email or Password is wrong!.')
                    return

        self.redirect("/admin")
Esempio n. 44
0
 def post(self):
     '''
     Corresponds to a possible attempt to change some account settings.
     Possible fields to change:
     - name
     - email_address
     - password
     '''
     should_update_user = False
     new_name = self.request.POST['name']
     # new_email = self.request.POST['email']
     if self.user.name != new_name:
         self.user.name = new_name
         should_update_user = True
     context = {
         'name': self.user.name,
         'email_address': self.user.email_address
     }
     try:
         new_password = self.request.POST["password"]
         current_password = self.request.POST["current_password"]
     except KeyError:
         new_password = None
     
     if new_password not in [None, '']:
         # Check that correct current password was entered
         if security.check_password_hash(current_password, self.user.password):
             # Correct
             self.user.set_password(new_password)
             should_update_user = True
         else:
             # Incorrect
             context['error_alert'] = 'Incorrect password.'
             return self.render_response('account_settings.html', **context)
     # Was anything updated?
     if should_update_user:
         self.user.put()
         context['success_alert'] = 'Successfully updated account settings!'
     else:
         context['error_alert'] = "You didn't request any changes."
     return self.render_response('account_settings.html', **context)
Esempio n. 45
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
Esempio n. 46
0
    def post(self, *args, **kwargs):
        if not 'ad' in self.session:
            email = self.request.POST['email']
            password = self.request.POST['password']

            user = User.query(ndb.AND(User.email == email,
                                      User.is_admin == True),
                              namespace='_x_')

            if user.get() is None:
                self.render_admin_login(error='Email or Password is wrong!.')
                return
            else:
                if check_password_hash(password, user.get().password):
                    self.setup_admin_session(user)
                else:
                    self.render_admin_login(
                        error='Email or Password is wrong!.')
                    return

        self.redirect("/admin")
Esempio n. 47
0
    def get_by_auth_password(cls, auth_id, password):
        """Return a user object, validating password.

        If the user exists and has no password, then it will match only an empty password.

        Raise webapp2_extras.auth.InvalidAuthIdError or webapp2_extras.auth.InvalidPasswordError if
        the username or password is wrong.
        
        """
        user = ndb.Key(flat=auth_id).get()
        if not user:
            raise webapp2_extras.auth.InvalidAuthIdError()

        # no password check if both password and user.password are unspecified
        if user.password and password:
            if not security.check_password_hash(password, user.password):
                raise webapp2_extras.auth.InvalidPasswordError()
        elif user.password or password:
            raise webapp2_extras.auth.InvalidPasswordError()

        return user
Esempio n. 48
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
Esempio n. 49
0
    def post(self):
        #temp!
        email = self.request.get('email').encode('utf-8')
        password = self.request.get('password').encode('utf-8')
        user = my_db.get(email)

        if not user:
            self.response.write("nope")
            return

        if not security.check_password_hash(password, user.password):
            self.response.write('nope')
            return

        if not user.txn_id:
            self.response.write('nope')
            return

        user.login_attempts += 1
        self.response.write(user.login_attempts)
        user.put()
Esempio n. 50
0
    def get_by_auth_password(cls, auth_id, password):
        """Return a user object, validating password.

        If the user exists and has no password, then it will match only an empty password.

        Raise webapp2_extras.auth.InvalidAuthIdError or webapp2_extras.auth.InvalidPasswordError if
        the username or password is wrong.
        
        """
        user = ndb.Key(flat=auth_id).get()
        if not user:
            raise webapp2_extras.auth.InvalidAuthIdError()

        # no password check if both password and user.password are unspecified
        if user.password and password:
            if not security.check_password_hash(password, user.password):
                raise webapp2_extras.auth.InvalidPasswordError()
        elif user.password or password:
            raise webapp2_extras.auth.InvalidPasswordError()

        return user
Esempio n. 51
0
 def post(self):
     result_json = {
         'redirect_url': str(self['redirect_url'])
         if self['redirect_url'] else '/community',
         'error': False
     }
     email = self['email']
     password = self['password'] if self['password'] else None
     member = Member.get_by_email(email)
     if 'member' in self.session and not email is self.session['member']:
         del self.session['member']
     if not email or not member:
         result_json['error'] = True
         result_json['errormsg'] = 'Member not found'
     elif not check_password_hash(password, member.password):
         result_json['error'] = True
         result_json['errormsg'] = 'Incorrect password'
     else:
         self.session['member'] = email
         redirect_url = '/tracks'
         result_json['redirect_url'] = redirect_url
     self.write(json.dumps(result_json), 200, 'application/json')
Esempio n. 52
0
 def get_or_create_profile(self, auth_id, user_info, user, **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:
         if user:
             # Create profile
             profile = models.UserProfile.get_or_create(auth_id, user_info,
                 password=security.generate_password_hash(password, length=12))
         else:
             return self.raise_error("Non e' stato trovato un profilo associato all'email indicata.")
     # Check password
     if not security.check_password_hash(password, profile.password):
         return self.raise_error("La password non e' corretta.")
     return profile
Esempio n. 53
0
 def post(self):
     result_json = {'redirect_url': str(self['redirect_url']) if self['redirect_url'] else '/community', 'error': False}
     email = self['email']
     password = self['password'] if self['password'] else None
     member = Member.get_by_email(email)
     if 'member' in self.session and not email is self.session['member']:
         del self.session['member']
     if not email or not member:
         result_json['error'] = True
         result_json['errormsg'] = 'Member not found'
     elif not check_password_hash(password, member.password):
         result_json['error'] = True
         result_json['errormsg'] = 'Incorrect password'
     else:
         self.session['member'] = email
         redirect_url = '/tracks'
         result_json['redirect_url'] = redirect_url
     self.write(
         json.dumps(
             result_json
         ),200,'application/json'
     )
Esempio n. 54
0
    def start(self):
        error_msg = 'We were unable to log you on using the supplied email address and password. Do you need to reset your password?'

        password = self.request.POST.get('password',None)
        email = self.request.POST.get('email',None)

        if not password or not email:
            return self.generic_error(title='Error logging in',message="We're sorry, you didn't supply all the required login credentials.")

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

        auth_token = authprovider.AuthProvider._get_by_auth_id(auth_id)

        if auth_token is None or not security.check_password_hash(password=password,pwhash=auth_token.password_hash,pepper=password_pepper):
            return self.generic_error(title='Error logging in',message=error_msg,action='Password reset »',
                      action_link="""#login" data-toggle="modal" onclick="$('#password-reset').click();" """)

        self.request.session.upgrade_to_user_session(auth_token.user_id)
        if self.request.POST.get('dont_persist') == "True":
            self.response.set_cookie('_eauth', self.request.session.serialize(),expires=None)



        return self.redirect('/')
Esempio n. 55
0
 def check_password(self, password):
     return security.check_password_hash(password, self.password)
Esempio n. 56
0
 def validate_password(self, password):
     if not self.password:
         return True
     pwhash = '$'.join([self.password, self.hash_method, self.salt])
     return security.check_password_hash(password, pwhash, pepper=PEPPER)
Esempio n. 57
0
 def authenticate(cls, user_id, password):
     user = User.get_by_id(user_id)
     return user and security.check_password_hash(password, user.password)
Esempio n. 58
0
 def check_password(self, guess):
     return check_password_hash(guess, self.password, pepper=config.pepper)
Esempio n. 59
0
 def auth_password(self, raw_password):
     return security.check_password_hash(raw_password,
                                         self.password,
                                         pepper=self.Pepper)