def add_user(obj_response, user_main_add_form): ''' Let WTForm perform the form validations ''' # pass the dictionary to the form form = UserMaintenanceForm(data=user_main_add_form) # validate the form form.validate() # run action to perform if not form.errors.items(): if check_user := User.query.filter_by( username=form.username.data).first(): flash(u'Username is aready taken!', 'danger') else: # instantiate new_user = User() # Copies matching attributes from form onto user form.populate_obj(new_user) # genereate new uuid new_user.uuid = str(uuid.uuid4()) new_user.hash_password(password=new_user.password) # save changes to db db.session.add(new_user) db.session.commit() form = UserMaintenanceForm() flash( u'<a href="javascript:;" onclick="javascript:UpdateUser(' + "'" + str(new_user.uuid) + "'" + ');"><strong>New User</strong></a> has been saved! The form is now back to add mode.', 'success')
def get(self, request: HttpRequest, user: User) -> HttpResponse: if user.email_verified: return redirect('profile:instruction') token = None try: token = request.session['token'] except KeyError: request.session.clear() redirect('main:login') new_user = fetch_user(token) try: if new_user['error'] == 'invalid_token': request.session.clear() return redirect('main:login') else: if DEBUG: return HttpResponse( json.dumps(new_user, ensure_ascii=False)) else: raise HttpResponseServerError except KeyError: pass if new_user['email_verified']: user.email_verified = True user.save() return redirect('profile:instruction') return render(request, 'email_confirm.html', { 'user': user, 'debug': DEBUG })
def verify_email(**kwargs): email = kwargs["email"] if not User.exists(email): return ERROR_USER_NOT_EXISTS.get_response() u = User.get_info(email) if u.token != kwargs["token"]: return ERROR_SIGNUP_VERIFICATION.get_response() else: u.confirmed = True db.session.commit() return SUCCESS_VERIFICATION.get_response()
def create_user(*, username: str, password_hash: str, name: Optional[str] = None) -> User: """Create and save an user into database, then return the user""" user = get_user_by_username(username) if user: raise BadRequestError("Username already exists") user = User(username=username, password_hash=password_hash, name=name) user.save() return user
def signup(**kwargs): email = kwargs.get('email', None) password = kwargs.get('password', None) if User.exists(email): return ERROR_USER_EMAIL_EXISTS.get_response() user_info = User(**kwargs) db.session.add(user_info) db.session.commit() try: email_sender.sendmail(user_info.email, SignupCheck(user_info)) except Exception as e: return ERROR_SEND_MAIL.get_response() return SUCCESS_SIGNUP.get_response()
def test_user_create(db_populate_users, users_in_db_getter): """Test that valid users are created correctly""" users_before = users_in_db_getter() new_user = User(username="******", password_hash="abcde12345") new_user.save() users_after = users_in_db_getter() new_user_in_db = [ user for user in users_after if user not in users_before ][0] assert len(users_after) == len(users_before) + 1 assert new_user_in_db.username == new_user.username assert new_user_in_db.password_hash == new_user.password_hash assert new_user_in_db.name == new_user.name
def register_new_user(**kwargs): args = kwargs['args'] email = args['email'] if User.get_user_by_email(email) is not None: raise Error(StatusCode.BAD_REQUEST, 'This email has been registered before') user = User(**args, status=UserStatus.ACTIVE, online=0) db.session.add(user) db.session.commit() return jsonify({ 'message': 'Your account was created successfully', 'data': UserSchema().dump(user).data }), 200
def post(self, request: HttpRequest, user: User) -> HttpResponse: resp = {'type': None, 'message': None} form = DbPassResetForm(request.POST) if not form.is_valid(): message = '' # TODO: обвязать функцией эту дрисню for _, error in form.errors.as_data().items(): for vld_error in error: for msg in vld_error: message += msg resp['type'] = 'danger' resp['message'] = message return HttpResponse(json.dumps(resp, ensure_ascii=False), content_type='application/json') password = form.cleaned_data.get('db_password') host = CONFIG.get('database', 'host') try: con = connector.connect( user=CONFIG.get('database', 'user'), password=CONFIG.get('database', 'password'), host=host, ) cur = con.cursor() cur._defer_warnings = False cur.execute("CREATE USER IF NOT EXISTS %s@%s IDENTIFIED BY %s;", (user.linux_user, host, password)) cur.execute( "GRANT ALL ON `{}_%`.* TO %s@%s;".format(user.linux_user), (user.linux_user, host)) except Exception as e: resp['type'] = 'danger' resp['message'] = str(e) return HttpResponse(json.dumps(resp, ensure_ascii=False), content_type='application/json') else: cur.close() con.close() user.db_password = password user.save() resp['type'] = 'success' resp['message'] = 'Пароль успешно установлен!' return HttpResponse(json.dumps(resp, ensure_ascii=False), content_type='application/json')
def signin(**kwargs): email = kwargs.get('email', None) password = kwargs.get('password', None) if not email: return ERROR_NULL_EMAIL.get_response() if not password: return ERROR_NULL_PASSWORD.get_response() if not User.exists(email): return ERROR_USER_EMAIL_NOT_EXISTS.get_response() u = User.get_info(email) if not u.verify_password(password): return ERROR_VERIFY_EMAIL_PASSWORD.get_response() if not u.confirmed: return ERROR_NOT_VALIDATED_ACCOUNT.get_response() return u.to_dict()
def db_populate_users(): """Add test users to db""" test_user_dicts = ( { "username": "******", "password": "******", "name": "Main Tester" }, { "username": "******", "password": "******" }, ) for user_dict in test_user_dicts: password_hash = bcrypt.hashpw(user_dict["password"].encode("utf-8"), bcrypt.gensalt(8)) data = user_dict.copy() data.pop("password") data["password_hash"] = password_hash user = User(**data) db.session.add(user) db.session.commit() return test_user_dicts
def random_email(): email = 'test_{}@test.com'.format(random_id()) while User.get_user_by_email(email) is not None: email = 'test_{}@test.com'.format(random_id()) return email
def refresh(): current_user = get_jwt_identity() if not User.exists(current_user["email"]): return ERROR_USER_NOT_EXISTS.get_response() access_token = create_access_token(identity=dict(email=current_user["email"])) TokenBlacklist.add_token_to_database(access_token, app.config["JWT_IDENTITY_CLAIM"]) return {"access_token": access_token}
def setup_user(session, email=None, password='******', name='Testing User'): """Set up a mock account""" if email is None: email = random_email() user = User(name=name, email=email, password=password) session.add(user) session.commit() return user
def subscription(): con=None if request.method=='POST': if request.form['submit']=="S'abonner": try : register_user=False id="usr"+time_number() name= request.form.get('name') last_name=request.form.get('last_name') email=request.form.get('email') tel=request.form.get('phone') user_name=request.form.get('user_name') password=request.form.get('password') user_type=request.form.get('user_type') user=User( name=name, last_name=last_name, email=email, tel=tel, id=id, user_name=user_name, password=password, user_type=user_type) except Exception as error: print(error) abort(400) try: con=postgres_connetion( host_postgres, db_name_postgres, db_user_postgres, db_password_postgres) cur=con.cursor() create_user(user,con,cur) register_user=True except (Exception, psycopg2.Error) as error: print(error) if isinstance(error,UniqueViolation): flash('Les informations choisies existent déjà') else: abort(422) finally: if con is not None: cur.close() con.close() if register_user==True: flash('Utilisateur répertorié avec succès') return render_template("user/subscription_user.html")
def set(): click.echo('设定管理员……') admin_user = User(email='*****@*****.**', name='管理员', username='******') admin_user.set_password('admin') admin_user.set_role_by_role_name('Administrator') ''' click.echo('设定用户……') normal_user = User(email='*****@*****.**', name='用户', username='******') # 若想 role_id=4,则需注释掉 models/user.py self.set_role_by_role_name() normal_user.set_password('user') click.echo('设定审核者一……') ins_user = User(email='*****@*****.**', name='审核者一', username='******') ins_user.set_password('ins') ins_user.set_role_by_role_name('Inspector') click.echo('设定审核者二……') mod_user = User(email='*****@*****.**', name='审核者二', username='******') mod_user.set_password('mod') mod_user.set_role_by_role_name('Moderator') db.session.add_all([admin_user, normal_user, ins_user, mod_user]) ''' db.session.add(admin_user) db.session.commit() click.echo('设定完成!')
def setUp(self): app = create_app('testing') self.context = app.test_request_context() self.context.push() self.client = app.test_client() self.runner = app.test_cli_runner() db.create_all() Role.init_role() admin_user = User(email='*****@*****.**', name='管理员', username='******') admin_user.set_password('150402207') normal_user = User(email='*****@*****.**', name='远哥制造', username='******') normal_user.set_password('yuangezhizao') db.session.add_all([admin_user, normal_user]) db.session.commit()
def register(): if request.method == 'POST': depart_name = request.form.get('depart_name') role_name = request.form.get('role_name') email = request.form.get('email') about_me = request.form.get('about_me') username = request.form.get('username') name = request.form.get('name') password = request.form.get('password') user = User(email=email, username=username, name=name, about_me=about_me) user.set_password(password) user.set_role_by_role_name(role_name) user.set_depart_by_depart_name(depart_name) db.session.add(user) db.session.commit() flash(f'新用户注册成功,邮箱:{email},用户名:{username},昵称:{name}', 'info') return redirect(request.url) departs_list = Depart.query.all() # TODO:这咋分页? return render_template('admin/register.html', departs_list=departs_list)
def handle_message(event): if event.type == "message" and event.message.type == "text": if event.message.text == "show": messages = [] contents = db.session.query(User).filter_by(user_id=event.source.user_id).all() for content in contents: messages.append(TextSendMessage(content.content)) line_bot_api.reply_message(event.reply_token, messages[-5:]) elif event.message.text == "画像": main_image_path = "static/images/hina.jpg" preview_image_path = "static/images/hina.jpg" image_message = ImageSendMessage( original_content_url=f"https://tetsupy.herokuapp.com/{main_image_path}", preview_image_url=f"https://tetsupy.herokuapp.com/{preview_image_path}", ) line_bot_api.reply_message(event.reply_token, image_message) elif event.message.text == "動画": main_video_path = "static/videos/hina.MP4" preview_video_path = "static/videos/hina.MP4" video_message = VideoSendMessage( original_content_url=f"https://tetsupy.herokuapp.com/{main_video_path}", preview_image_url=f"https://tetsupy.herokuapp.com/{preview_video_path}", ) line_bot_api.reply_message(event.reply_token, video_message) else: #データベースに追加 user = User(event.source.user_id, event.message.text) db.session.add(user) db.session.commit() line_bot_api.reply_message(event.reply_token,TextSendMessage("記憶しました"))
def set_user_info(stu_id, stu_name): if not is_user_exists(stu_id, stu_name): user_mod = User(stu_id=stu_id, stu_name=stu_name) user_mod.save() return True
from main.models.company import Company from main.models.sequence import Sequence import uuid from main.models.loan import Loan from main.models.loan_detail import LoanDetail from main.models.contribution import Contribution from main.models.member import Member from main.models.borrower import Borrower app.config.from_object('config.DevConfig') get_user = User.query.filter_by(username='******').first() if not get_user: dev_user = User(username='******', password='******', display_name='Developer') dev_user.uuid = str(uuid.uuid4()) dev_user.hash_password(password=dev_user.password) db.session.add(dev_user) db.session.commit() get_company = Company.query.first() if not get_company: company = Company(company_name='Hello Cooperative', address='Novaliches Quezon City', phone='1234-123', mobile='09321234567', total_fund=0, available_fund=0, lended_fund=0, total_profit=0,
def update_user(user: User, data: dict) -> User: """Update an user by id""" User.update_by_id(user.id, data) return User.find_by_id(user.id)
def wrapper(): if request.headers.get('auth-key') is not None: user = User.verify_auth_token(request.headers.get('auth-key')) if user is not None: return func(user) return unauthorized('Authentication required.')
def get_user(user_id: int) -> Optional[User]: """Return an user by id or None if user not found""" return User.find_by_id(user_id)
def register(): user = User.from_json(request.json) return render_response(201, {'message': 'User is successfully created.'})
def setUp(self): app = create_app('testing') self.context = app.test_request_context() self.context.push() self.client = app.test_client() self.runner = app.test_cli_runner() db.create_all() Role.init_roles() Depart.init_departs() Task.init_tasks() admin_user = User(email='*****@*****.**', name='管理员', username='******') admin_user.set_password('admin') admin_user.set_role_by_role_name('Administrator') normal_user = User(email='*****@*****.**', name='用户', username='******') normal_user.set_password('user') ins_user = User(email='*****@*****.**', name='审核者一', username='******') ins_user.set_password('ins') admin_user.set_role_by_role_name('Inspector') mod_user = User(email='*****@*****.**', name='审核者二', username='******') mod_user.set_password('mod') admin_user.set_role_by_role_name('Moderator') db.session.add_all([admin_user, normal_user, ins_user, mod_user]) db.session.commit()
def login(): token = User.login(request.headers) if token is not None: return render_response(200, token) return render_response(401, {'message': 'Login unsuccessful.'})
def test_user_read(db_populate_users, users_in_db_getter): """Test that users are fetched correctly""" users = users_in_db_getter() user0 = User.find_by_id(users[0].id) assert user0 == users[0]
def test_user_create_errors(db_populate_users, users_in_db_getter): """Test that invalid users are not created""" users_before = users_in_db_getter() with pytest.raises(IntegrityError): duplicate_username = User(username=users_before[0].username, password_hash="passwordhash") duplicate_username.save() with pytest.raises(IntegrityError): missing_username = User(password_hash="passwordhash") missing_username.save() with pytest.raises(IntegrityError): missing_password_hash = User(username="******") missing_password_hash.save() users_after = users_in_db_getter() assert len(users_after) == len(users_before)