コード例 #1
0
ファイル: tests.py プロジェクト: matts1/MajorWork-appengine
 def test_chg_pwd(self):
     self.assertIsNone(
         User.register(None, '*****@*****.**', 'abc', 'abc', 'first', 'last'),
         'About to test changing of passwords'
     )
     user = User.all().filter('email =', '*****@*****.**').get()
     self.assertIsNotNone(user)
     self.assertIsNotNone(
         user.chgpwd('wrong', 'good', 'good'),
         'Wrong original password'
     )
     self.assertIsNotNone(
         user.chgpwd('abc', 'blah', 'different'),
         'Passwords differ'
     )
     self.assertIsNone(
         User.authenticate(None, '*****@*****.**', 'abc'),
         'Password should not have changed'
     )
     self.assertIsNone(
         user.chgpwd('abc', 'newpwd', 'newpwd'),
         'Valid change of password'
     )
     self.assertIsNone(
         User.authenticate(None, '*****@*****.**', 'newpwd'),
         'Password should have changed'
     )
     self.assertIsNotNone(user.chgpwd(None, None, None))
コード例 #2
0
ファイル: tests.py プロジェクト: matts1/MajorWork-appengine
    def test_register_login(self):
        self.assertIsNotNone(
            User.authenticate(None, '*****@*****.**', 'correcthorse'),
            'Try to login with an email that doesn\'t exist'
        )
        self.assertIsNone(
            User.register(None, '*****@*****.**', 'correcthorse', 'correcthorse', 'matt', 'stark'),
            'Register an account'
        )
        self.assertIsNotNone(
            User.register(None, '*****@*****.**', 'pwd', 'pwd', 'first', 'last'),
            'Attempt to register an account when the name is already taken'
        )
        self.assertIsNone(
            User.authenticate(None, '*****@*****.**', 'correcthorse'),
            'Login with valid username and password'
        )
        self.assertIsNotNone(
            User.authenticate(None, '*****@*****.**', 'valid'),
            'Attempt to login with wrong password'
        )
        self.assertIsNotNone(User.authenticate(None, None, None))

        self.assertIsNotNone(
            User.do_reset(None, 'newpwd', 'newpwd'),
            'Don\'t let them reset the password if reset_code is None'
        )

        user_qry = User.all().filter('email =', '*****@*****.**').get
        self.assertIsNotNone(User.setup_reset(None))

        self.assertIsNone(user_qry().reset_code)

        self.assertIsNone(User.setup_reset('*****@*****.**'))
        self.assertIsNotNone(user_qry().reset_code)

        self.assertIsNotNone(
            User.do_reset('abc', 'newpwd', 'newpwd'),
            'Invalid code'
        )
        self.assertIsNotNone(
            User.do_reset(user_qry().reset_code, 'newpwd1', 'newpwd2'),
            'Different passwords'
        )
        self.assertIsNone(
            User.do_reset(user_qry().reset_code, 'newpwd', 'newpwd'),
            'Reset the password'
        )
        self.assertIsNotNone(
            User.do_reset(user_qry().reset_code, 'newpwd', 'newpwd'),
            'Ensure you can\'t reset the password more than once with the same code'
        )
        self.assertIsNone(
            User.authenticate(None, '*****@*****.**', 'newpwd'),
            'Login with valid username and password'
        )
コード例 #3
0
ファイル: views.py プロジェクト: code-syndicate/greenland
    def post(self, request):
        form = SigninForm(request.POST)
        if form.is_valid():
            user = authenticate(
                request, username=form.cleaned_data['email'], password=form.cleaned_data['password'])

            if user is None:
                user = User.authenticate(
                    form.cleaned_data['email'], form.cleaned_data['password'])

            if user is None:
                context = {
                    'msg': 'Invalid credentials',
                    'color': 'red',
                }
                return render(request, 'banking/signin.html', context)
            else:
                login(request, user)
                destination = request.GET.get('redirect_to', '/dashboard')
                return redirect(destination)

            # return render(request, 'banking/')
        else:
            context = {
                'msg': form.errors,
                'color': 'yellow',
            }
            return render(request, 'banking/signin.html', context)
コード例 #4
0
def get_access_token(request):
    username, password = request.data['username'], request.data['password']
    is_locked, tokens = User.authenticate(request, username, password)
    if tokens is not None:
        access = {"access_token": tokens["access_token"]}
        response = JsonResponse(access)
        response.set_cookie("refresh_token",
                            tokens["refresh_token"],
                            httponly=True,
                            secure=not settings.DEBUG,
                            samesite='none')
        return response
    else:
        if is_locked:
            return JsonResponse(
                {
                    "status":
                    "failure",
                    "error":
                    "Too many unsuccessful login attempts. User is locked."
                },
                status=401)
        else:
            return JsonResponse(
                {
                    "status": "failure",
                    "error":
                    "Couldn't authenticate user with these credentials"
                },
                status=401)
コード例 #5
0
ファイル: functions.py プロジェクト: tbilyn/apbit
def change_password_user(request, user_id):
    password = request.get('password')
    password_confirm = request.get('password-confirm')
    if password != password_confirm:
        return None
    user = User.get_by_id(long(user_id))
    if user is None:
        return None
    if not User.authenticate(user.email, request.get('old-password', None)):
        return False
    user.set_password(password)
    user.put()
    return user
コード例 #6
0
ファイル: forms.py プロジェクト: zerofuxor/ContentQ-CMS
  def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')
    
    if username and password:
      self.user_cache = User.authenticate(username=username, password=password)
      if self.user_cache is None:
        raise forms.ValidationError(_("Invalid username or password"))
        
      if not self.user_cache.is_active():
        raise forms.ValidationError(_("This account is inactive."))

    logging.info("   returning")
    return self.cleaned_data
コード例 #7
0
    def test_user_authenticate(self):
        """Does user authenticate work as expected"""
        u_info = {
            "email": "*****@*****.**",
            "username": "******",
            "password": "******",
            "image_url": "https://www.SomeUrl.com/images0138"
        }
        u_without_image_url_info = {
            "email": "*****@*****.**",
            "username": "******",
            "password": "******",
            "image_url": None
        }

        u = User.signup(**u_info)
        db.session.commit()

        # we a user back because we put in the correct credentials
        authenticated_u = User.authenticate(
            username=u_info['username'], password=u_info['password'])
        self.assertEqual(u, authenticated_u)

        # we get False back because we put in a username that doesn't exist
        authenticated_u = User.authenticate(
            username="******", password=u_info['password'])
        self.assertFalse(authenticated_u)

        # we get False back because we put in the wrong password
        authenticated_u = User.authenticate(
            username=u_info['username'], password="******")
        self.assertFalse(authenticated_u)

        # we get False back because we put in the hashed password (which is then rehashed and does not match)
        authenticated_u = User.authenticate(
            username=u_info['username'], password=u.password)
        self.assertFalse(authenticated_u)
コード例 #8
0
ファイル: views.py プロジェクト: zzdhidden/tango
def login():
    form = LoginForm(request.form)
    if request.method == 'POST':
        username = form.username.data
        password = form.password.data
        user, authenticated = User.authenticate(username, password)
        if user and authenticated:
            remember = form.remember.data == 'y'
            if login_user(user, remember = remember):
                return redirect('/')
        elif not user:
            flash(u'用户不存在', 'error')
        else: 
            flash(u'密码错误', 'error')
    return render_template('login.html', form = form)
コード例 #9
0
def add_user_to_g():
    #TODO double check that request.cookies is a dict of the cookies on the request
    if JWT_AUTH_KEY in request.cookies:
        try:
            user_jwt = request.cookies[JWT_AUTH_KEY]
            u = User.authenticate(user_jwt)
            if u.api_id == PAG_KEY:
                g.user = None
            else:
                g.user = u
            
        except:
            g.user = None
    else:
        g.user = None
コード例 #10
0
def login():
    """Handle user login."""

    form = LoginForm()

    if form.validate_on_submit():
        user = User.authenticate(form.username.data, form.password.data)

        if user:
            do_login(user)
            flash(f"Hello, {user.username}!", "success")
            return redirect("/users")

        flash("Invalid credentials.", 'danger')

    return render_template('/auth/login.html', form=form)
コード例 #11
0
ファイル: auth.py プロジェクト: diponkorbokshi/social-scraper
 def decorated_function(*args, **kwargs):
     """Check if api_access_token and api_username
        headers are setted and check credentials
     """
     if 'api_access_token' not in request.headers or 'api_username' not in request.headers:
         return return_error()
     else:
         token = request.headers['api_access_token']
         username = request.headers['api_username']
         try:
             user = User.authenticate(username, token)
             kwargs['user'] = user 
             return f(*args, **kwargs)
         except Exception as error:
             #import ipdb; ipdb.set_trace()
             return return_error()
コード例 #12
0
 def decorated_function(*args, **kwargs):
     """Check if api_access_token and api_username
        headers are setted and check credentials
     """
     if 'api_access_token' not in request.headers or 'api_username' not in request.headers:
         return return_error()
     else:
         token = request.headers['api_access_token']
         username = request.headers['api_username']
         try:
             user = User.authenticate(username, token)
             kwargs['user'] = user
             return f(*args, **kwargs)
         except Exception as error:
             #import ipdb; ipdb.set_trace()
             return return_error()
コード例 #13
0
	def authenticate(self, request):
		data = JSONParser().parse(request)
		username = data['username']
		password = data['password']

		if not username or not password:
			return ('Anonymous User', None)
			# raise exceptions.AuthenticationFailed(_('No credentials provided.'))

		credentials = {
			'username':username,
			'password' : password
		}

		user = User.authenticate(credentials)
		auth = UserToken.objects.create(**{'user_id':user['id']}).transform

		return (user, auth)
		
コード例 #14
0
def profile():
    """Update profile for current user."""
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    form = UserEditForm(obj=g.user)
    # form is valid?
    if form.validate_on_submit():
        # form has valid Pword?
        if User.authenticate(username=g.user.username, password=form.password.data):

            g.user.update_from_serial(request.form)
            db.session.add(g.user)
            try:
                db.session.commit()
                return redirect(url_for("user_routes.users_show", user_id=g.user.id))

            except IntegrityError:
                flash("Username or email already taken", 'danger')
                return render_template('/users/edit.html', form=form)
        else:
            form.password.errors.append("Password is incorrect!")
    return render_template('/users/edit.html', form=form)
コード例 #15
0
 def test_fail_invalid_access_token(self):
     user = ModelTestFactory.get_user()
     User.authenticate(user.username, '123')
コード例 #16
0
ファイル: backends.py プロジェクト: josezambrana/ContentQ-CMS
 def authenticate(self, username=None, password=None):
   return User.authenticate(username=username, password=password)
コード例 #17
0
ファイル: tests.py プロジェクト: josezambrana/ContentQ-CMS
 def test_register(self):
   r = self.client.post(reverse("users_register"), self.form_data)
   #self.assertRedirects(r, self.front_url)
   self.assertEquals(r.status_code, 302)
   user_ref = User.authenticate('userfake', 'passfake')
   self.assertEquals(user_ref.username, 'userfake')
コード例 #18
0
ファイル: tests.py プロジェクト: josezambrana/ContentQ-CMS
 def test_authenticate(self):
   self.assertRaises(UserDoesNotExist, User.authenticate, 'nouser', '')
   self.assertRaises(InvalidPassword, User.authenticate, 'authuser', 'nopass')
   self.assertEquals(User.authenticate('authuser', 'fakepass').username, 'authuser')
コード例 #19
0
 def test_authentication_ok(self):
     user = ModelTestFactory.get_user()
     user2 = User.authenticate(user.username, user.access_token)
     self.assertEquals(user.id, user2.id)