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))
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' )
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)
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)
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
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
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)
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)
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
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)
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()
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)
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)
def test_fail_invalid_access_token(self): user = ModelTestFactory.get_user() User.authenticate(user.username, '123')
def authenticate(self, username=None, password=None): return User.authenticate(username=username, password=password)
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')
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')
def test_authentication_ok(self): user = ModelTestFactory.get_user() user2 = User.authenticate(user.username, user.access_token) self.assertEquals(user.id, user2.id)