def test_expired_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token))
def post(self): data = user_create_reqparser.parse_args() if not validate_verify_code(data['telephone'], 'signup', data['code']): return api_abort(401, 'wrong verify code') user = User(data['nickname'], data['telephone'], data['password']) db.session.add(user) db.session.commit() return make_resp(user.to_json(detail=True))
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def deploy(): # python manage.py deploy """Run deployment tasks.""" from flask_migrate import upgrade from app.modules import Role, User # migrate database to latest revision upgrade() # create user roles Role.insert_roles() # create self-follows for all users User.add_self_follows()
def test_token_auth(self): # add a user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='*****@*****.**', password='******', confirmed=True, role=r) db.session.add(u) db.session.commit() # issue a request with a bad token response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('bad-token', '')) self.assertTrue(response.status_code == 401) # get a token response = self.client.get( url_for('api.get_token'), headers=self.get_api_headers('*****@*****.**', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('token')) token = json_response['token'] # issue a request with the token response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers(token, '')) self.assertTrue(response.status_code == 200)
def get(self, cid): students = g.current_course.students page = request.args.get("page", 1) per_page = request.args.get("per_page", 20) students = students[(page-1)*per_page:page*per_page] data = User.list_to_json(students) return make_resp(data)
def update_user_current_score(userid, score): user = User.from_blockchain(userid) if user is None: abort(403, "提供的用户未在记录当中") user.CreditScore.CurrentCreditScore = score user.bc_update() user.UserInfo.CurrentCreditScore = score user.UserInfo.save() return user
def register(): form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash(f"Your account has been created", 'success') return redirect(url_for('login')) return render_template("register.html", title="Register", form=form)
def test_invalid_confirmation_token(self): u1 = User(password='******') u2 = User(password='******') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_confirmation_token() self.assertFalse(u2.confirm(token))
def setUpClass(cls): # start Firefox try: cls.client = webdriver.Firefox() except: pass # skip these tests if the browser could not be started if cls.client: # create the application cls.app = create_app('testing') cls.app_context = cls.app.app_context() cls.app_context.push() # suppress logging to keep unittest output clean import logging logger = logging.getLogger('werkzeug') logger.setLevel("ERROR") # create the database and populate with some fake data db.create_all() Role.insert_roles() User.generate_fake(10) Post.generate_fake(10) # add an administrator user admin_role = Role.query.filter_by(permissions=0xff).first() admin = User(email='*****@*****.**', username='******', password='******', role=admin_role, confirmed=True) db.session.add(admin) db.session.commit() # start the Flask server in a thread threading.Thread(target=cls.app.run).start() # give the server a second to ensure it is up time.sleep(1)
def test_unconfirmed_account(self): # add an unconfirmed user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='*****@*****.**', password='******', confirmed=False, role=r) db.session.add(u) db.session.commit() # get list of posts with the unconfirmed account response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('*****@*****.**', 'cat')) self.assertTrue(response.status_code == 403)
def register(): form = RegisterForm() from werkzeug.security import generate_password_hash if form.validate_on_submit(): data = form.data user = User(name=data["name"], pwd=generate_password_hash(data["pwd"]), email=data["email"], phone=data["phone"], uuid=uuid.uuid4().hex) db.session().add(user) db.session.commit() flash("注册会员成功", 'ok') return render_template("home/register.html", form=form)
def test_bad_auth(self): # add a user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='*****@*****.**', password='******', confirmed=True, role=r) db.session.add(u) db.session.commit() # authenticate with bad password response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertTrue(response.status_code == 401)
def userinfo(userindex): # data = get_data_from_ajax() # if data is None: # return u = User.from_blockchain(userindex.UserID) if u is None: abort(403, u"用户不存在于区块链记录中或访问区块链失败") u.UserInfo.CurrentCreditScore = u.CreditScore.CurrentCreditScore u.UserInfo.TotalCreditScore = u.CreditScore.TotalCreditScore u.UserInfo.RateCount = u.CreditScore.Ratetimes u.UserInfo.save() d = UserController.wrapper_userinfo(u) # return return_data(None, data=u.dump_to_dict()) return return_data(None, data=d)
def test_users(self): # add two users r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) u2 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() # get users response = self.client.get( url_for('api.get_user', id=u1.id), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['username'] == 'john') response = self.client.get( url_for('api.get_user', id=u2.id), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['username'] == 'susan')
def create_user(userindex): user = User(userindex) userindex.UserID = unicode(uuid.uuid4()) userindex.save() # create to blockchain user.bc_create() user.save() return user
def regist(): form = RegistForm() if form.validate_on_submit(): data = form.data user = User( name=data['name'], email=data['email'], phone=data['phone'], pwd=generate_password_hash(data['pwd']), uuid=uuid.uuid4().hex ) db.session.add(user) db.session.commit() flash('注册成功!请登陆!', 'ok') return redirect(url_for('home.login')) return render_template("home/regist.html", form=form)
def delete_user(): #将json中的body字段解析出来,返回一个user对象 user = User.from_json(request.json) #删除数据库 if user is None: response = jsonify({'message': '邮箱地址不存在', 'code': 400}) response.status_code = 400 else: delete_user = user.deleteUser(user) if delete_user: response = jsonify({'message': '删除成功', 'code': 200}) response.status_code = 200 else: response = jsonify({'message': '删除失败', 'code': 400}) response.status_code = 400 return response
def verify_password(email_or_token, password): print(email_or_token+","+password) if email_or_token == '': g.current_user = AnonymousUser() #匿名用户,即游客 return True if password=='': # 验证token g.current_user = User.verify_auth_token(email_or_token) g.token_used=True return g.current_user is not None #邮箱和密码验证 user = User.query.filter_by(email = email_or_token).first() if not user: return False g.current_user = user g.token_used=False return user.verify_password(password)
def login(): if current_user.is_authenticated: return redirect(url_for('despesas.listar')) form = LoginForm() if form.validate_on_submit(): try: user = auth.sign_in_with_email_and_password( form.email.data, form.password.data) user = User(user['localId'], user['idToken'], user['refreshToken']) login_user(user) return redirect(url_for('despesas.listar')) except Exception as e: print(e) mensagem = json.loads(e.strerror)['error']['message'] mensagem = mensagem.replace('_', ' ') flash(mensagem) return redirect(url_for('login.login')) return render_template('login/login.html', form=form)
def post(self): parase.add_argument("name", type=str, required=True) parase.add_argument("password", type=str, required=True) parase.add_argument("email", type=str, required=True) args = parase.parse_args() email = args["email"] user_schema = UserSchema() result = User.query.filter_by(email=email).first() output = user_schema.dump(result).data print(output.keys()) if not result: user = User(args) db.session.add(user) db.session.commit() return args, 201 else: response = jsonify( {"Error": "Email {0} have been used".format(email)}) response.status_code = 400 return response
def test_no_password_getter(self): u = User(password='******') with self.assertRaises(AttributeError): u.password
def test_password_setter(self): u = User(password='******') self.assertTrue(u.password_hash is not None)
def test_password_salts_are_random(self): u = User(password='******') u2 = User(password='******') self.assertTrue(u.password_hash != u2.password_hash)
def test_password_verification(self): u = User(password='******') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog'))
def test_valid_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_confirmation_token() self.assertTrue(u.confirm(token))
def test_roles_and_permissions(self): Role.insert_roles() user = User(email='*****@*****.**', password='******') self.assertTrue(user.can(Permission.WRITE_ARTICLES)) self.assertFalse(user.can(Permission.MODERATE_COMMENTS))
from app import create_app from app.extensions import db_sql as db from app.modules import User, Course app = create_app('testing', static_url_path='/files') ctx = app.test_request_context() ctx.push() db.create_all() user1 = User('3927', '13110560639', '123456') user2 = User("lin", "13067258562", "123456") course1 = Course('test_course1', 1, 1, 1592144807.9424236, 1602144807.9424236, "test_course1") course2 = Course('test_course2', 0, 1, 1592144807.9424236, 1602144807.9424236, "test_course2") course2.students.append(user2) course1.students.append(user2) db.session.add(user1) db.session.add(user2) db.session.add(course1) db.session.add(course2) db.session.commit() app.run(debug=True)
def test_comments(self): # add two users r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) u2 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() # add a post post = Post(body='body of the post', author=u1) db.session.add(post) db.session.commit() # write a comment response = self.client.post( url_for('api.new_post_comment', id=post.id), headers=self.get_api_headers('*****@*****.**', 'dog'), data=json.dumps({'body': 'Good [post](http://example.com)!'})) self.assertTrue(response.status_code == 201) json_response = json.loads(response.data.decode('utf-8')) url = response.headers.get('Location') self.assertIsNotNone(url) self.assertTrue(json_response['body'] == 'Good [post](http://example.com)!') self.assertTrue( re.sub('<.*?>', '', json_response['body_html']) == 'Good post!') # get the new comment response = self.client.get( url, headers=self.get_api_headers('*****@*****.**', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['url'] == url) self.assertTrue(json_response['body'] == 'Good [post](http://example.com)!') # add another comment comment = Comment(body='Thank you!', author=u1, post=post) db.session.add(comment) db.session.commit() # get the two comments from the post response = self.client.get( url_for('api.get_post_comments', id=post.id), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('comments')) self.assertTrue(json_response.get('count', 0) == 2) # get all the comments response = self.client.get( url_for('api.get_comments', id=post.id), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('comments')) self.assertTrue(json_response.get('count', 0) == 2)
def test_posts(self): # add a user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='*****@*****.**', password='******', confirmed=True, role=r) db.session.add(u) db.session.commit() # write an empty post response = self.client.post( url_for('api.new_post'), headers=self.get_api_headers('*****@*****.**', 'cat'), data=json.dumps({'body': ''})) self.assertTrue(response.status_code == 400) # write a post response = self.client.post( url_for('api.new_post'), headers=self.get_api_headers('*****@*****.**', 'cat'), data=json.dumps({'body': 'body of the *blog* post'})) self.assertTrue(response.status_code == 201) url = response.headers.get('Location') self.assertIsNotNone(url) # get the new post response = self.client.get( url, headers=self.get_api_headers('*****@*****.**', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['url'] == url) self.assertTrue(json_response['body'] == 'body of the *blog* post') self.assertTrue(json_response['body_html'] == '<p>body of the <em>blog</em> post</p>') json_post = json_response # get the post from the user response = self.client.get( url_for('api.get_user_posts', id=u.id), headers=self.get_api_headers('*****@*****.**', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('posts')) self.assertTrue(json_response.get('count', 0) == 1) self.assertTrue(json_response['posts'][0] == json_post) # get the post from the user as a follower response = self.client.get( url_for('api.get_user_followed_posts', id=u.id), headers=self.get_api_headers('*****@*****.**', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('posts')) self.assertTrue(json_response.get('count', 0) == 1) self.assertTrue(json_response['posts'][0] == json_post) # edit post response = self.client.put( url, headers=self.get_api_headers('*****@*****.**', 'cat'), data=json.dumps({'body': 'updated body'})) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['url'] == url) self.assertTrue(json_response['body'] == 'updated body') self.assertTrue(json_response['body_html'] == '<p>updated body</p>')