def dist2db(dist): User.import_xml(dist) Keyword.importXml(dist) Question.import_file(dist) Answer.importXml_best(dist) for item in dist['nbestanswers']: Answer.importXml(dist, item)
def register(): # check if current user is already logged in if current_user.is_authenticated: return redirect(url_for('main.index')) form = RegistrationForm() # Action after received form data if form.validate_on_submit(): user = User(user_name=form.username.data, email=form.email.data, about_me=form.about_me.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() token = user.generate_token('confirm') send_email(user.email, 'Confirm Your Account', 'mail/confirm', user=user, token=token) # Login automatically login_user(user) flash(alerts['login_success']) return redirect(url_for('main.index')) return render_template('auth/register.html', form=form, title='Register')
def setUp(self): super().setUp() self.session.begin_nested() self.commentor = User(name="Commentor", email="*****@*****.**") self.author = User(name="Author", email="*****@*****.**") self.post = Post(title="Test Post", body="Test Post", user_id=self.author.id) self.answer = Answer(post_id=self.post.id, user_id=self.author.id) self.author.posts.append(self.post) self.author.answers.append(self.answer) self.post.answers.append(self.answer) self.session.add(self.commentor) self.session.add(self.author) self.session.add(self.post) self.session.add(self.answer) self.session.commit() with self.client as c: with c.session_transaction() as sess: set_session_user(self.commentor, current_session=sess) g.user = self.commentor
def setting(): """设置用户信息方法 """ g.user = user = User.is_login() form = SettingForm() u = User() if request.method == "POST": if not u.has_username(form.username.data) or session["username"] == form.username.data: """如果修改后的用户名不存在数据库或者和当前登录的用户名相同则更新数据库中对应的记录""" if form.username.data == "": flash(u"用户名不能为空", "error") return render_template("/user/setting.html", form=form, title=u"修改设置") if form.password.data == "": flash(u"密码不能为空", "error") return render_template("/user/setting.html", form=form, title=u"修改设置") if form.email.data == "": flash(u"邮箱不能为空", "error") return render_template("/user/setting.html", form=form, title=u"修改设置") if not u.edit(user, form.username.data, form.password.data, form.email.data): """写入数据库""" flash(u"修改失败", "error") return render_template("/user/setting.html", form=form, title=u"修改设置") user.dologin() flash(u"用户信息修改成功") return redirect(url_for("index")) else: flash(u"用户已存在", "warning") return render_template("/user/setting.html", form=form, title=u"修改设置") else: form.username = user.username form.password = user.password form.email = user.email return render_template("/user/setting.html", form=form, title=u"修改设置")
def test_request_reset_password(client, db): # Creates a new user TEST_RESET_USER = '******' TEST_RESET_PASSWORD = '******' new_user = User(username=TEST_RESET_USER) new_user.set_password(TEST_RESET_PASSWORD) db.session.add(new_user) db.session.commit() # Logs in to user and add an email address and log out login_response = login(client, TEST_RESET_USER, TEST_RESET_PASSWORD) assert login_response.status_code == 200 assert b'dashboard' in login_response.data MAIL_CREDS = get_server_mail_cred() TEST_EMAIL_ADDRESS = MAIL_CREDS[2] TEST_EMAIL_PASSWORD = MAIL_CREDS[3] response = add_mail(client, TEST_EMAIL_ADDRESS, TEST_EMAIL_PASSWORD) assert response.status_code == 200 assert get_email_address_by_address(TEST_EMAIL_ADDRESS) assert b'*****@*****.**' in response.data logout(client) reset_response = request_reset_password(client, db, TEST_RESET_USER\ , TEST_EMAIL_ADDRESS) # Assert redirected to update password page assert b'token' in reset_response.data # Assert token is generated assert get_user_by_name(TEST_RESET_USER).get_reset_token()
def test_user_verify_password_empty_string_argument(self): try: user = User("marcos", "*****@*****.**", "12345") user.verify_password("") self.fail("Exception was expected.") except: pass
def createdb(): Frame.create_table(fail_silently=True) Speech.create_table(fail_silently=True) Topic.create_table(fail_silently=True) SpeechTopic.create_table(fail_silently=True) User.create_table(fail_silently=True) db.database.execute_sql("ALTER TABLE speech_topic ADD CONSTRAINT speech_topic_unique UNIQUE(speech_id,topic_id);") populate_frames_dummy_data()
def __init__(self): """ Initialise class with configuration """ self.user = User() return None
def register(): data = request.get_json() user = User() user.email = data['email'] user.password = data['password'] db.session.add(user) db.session.commit() return jsonify(user.to_dict())
def logout(): form = SignupForm() if form.validate_on_submit(): user = User() form.populate_obj(user) user.ID = User.objects.count() + 1 user.save() return redirect('/login') return render_template('accounts/signup.html', form=form)
def test_admin_disable_user(driver): TEST_DISABLE_USER = '******' TEST_DISABLE_PASSWORD = '******' # Creation of dummy user new_user = User(username=TEST_DISABLE_USER) new_user.set_password(TEST_DISABLE_PASSWORD) db.session.add(new_user) db.session.commit() # Logs in to admin dashboard ADMIN_USER = '******' PASSWORD = '******' login(driver, ADMIN_USER, PASSWORD) # Search for newly created user for it's ID user_to_disable = db.session.query(User)\ .filter(User.username ==TEST_DISABLE_USER).first() user_to_disable_id = user_to_disable.get_id() # Clicks on 'Users' in admin navbar wait_user_btn = WebDriverWait(driver, 3) wait_user_btn.until(EC.visibility_of_element_located((By.XPATH\ , '//*[@id="admin-panel"]/a[2]'))) driver.find_element(By.XPATH, '//*[@id="admin-panel"]/a[2]').click() # Searches for edit (a pencil in 1st column) by href where it's url is href_link # and click to enter edit page for the particular user href_link = '//a[@href="{}"]'\ .format('/admin/user/edit/?id={}&url=%2Fadmin%2Fuser%2F&modal=True'\ .format(user_to_disable_id)) wait_user_entry = WebDriverWait(driver, 5) wait_user_entry.until(EC.visibility_of_element_located((By.XPATH, href_link))) driver.find_element(By.XPATH, href_link).click() # The sleep(2) is required otherwise wait_active_box does not work sleep(2) # Unchecks active checkbox wait_active_box = WebDriverWait(driver, 3) wait_active_box.until(EC.visibility_of_element_located((By.XPATH\ , '//*[@id="fa_modal_window"]/div/div/form/fieldset/div/div[5]/input'))) checkbox = driver.find_element_by_css_selector(".form-control-lg#is_active") driver.execute_script("arguments[0].click();", checkbox) # Clicks "Save" in edit page # The click here is done by send_keys(Keys.RETURN) simulating enter on the key # And the sleep(2) is required otherwise the click will NOT work sometimes sleep(2) wait_submit = WebDriverWait(driver, 3) wait_submit.until(EC.visibility_of_element_located((By.XPATH\ , '//*[@id="fa_modal_window"]/div/div/form/fieldset/div[2]/input'))) driver.find_element(By.XPATH\ , '//*[@id="fa_modal_window"]/div/div/form/fieldset/div[2]/input')\ .send_keys(Keys.RETURN)
def register(): """注册用户试图 """ form = RegisterForm(request.form) if request.method == "POST" and form.validate(): user = User(form.username.data, form.password.data, form.email.data) user.save(user) login_user(user, True, False) return redirect(url_for("index")) return render_template("/user/register.html", form=form)
def run(self): """Run the database seeds.""" User.create( { "name": "idmann509", "email": "*****@*****.**", "password": "******", "phone": "+123456789", } )
def createdb(): Frame.create_table(fail_silently=True) Speech.create_table(fail_silently=True) Topic.create_table(fail_silently=True) SpeechTopic.create_table(fail_silently=True) User.create_table(fail_silently=True) db.database.execute_sql( "ALTER TABLE speech_topic ADD CONSTRAINT speech_topic_unique UNIQUE(speech_id,topic_id);" ) populate_frames_dummy_data()
def create_user(): request_data = request.get_json() print(request_data) user = User(email=request_data['email'], username=request_data['username'], password=request_data['password']) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() return jsonify({'token': g.current_user.generate_auth_token( expiration=3600), 'expiration': 3600})
def DELETE(self): super(Login, self).check_login() if self.user_allowed: if User.logged_in_user is not None: User.logout() return json.dumps({"success": True}) return json.dumps({ "success": False, "message": "Aktion nicht erlaubt!" })
def request_loader(request): email = request.form.get('email') if not validate(email): return user = User(email) # DO NOT ever store passwords in plaintext and always compare password # hashes using constant-time comparison! user.authenticate(request.form['password']) return user
def setUp(self): super().setUp() user = User(username='******', email='*****@*****.**', password='******') user2 = User(username='******', email='*****@*****.**', password='******') self.db.session.add(user) self.db.session.add(user2) self.db.session.commit() self.userId = user.id self.username = user.username self.userEmail = user.email self.user2name = user2.username
def mutate(self, info, **kwargs): user = UserModel(**kwargs) try: user.save() except Exception as e: raise GraphQLError("Error creating User object.", e) else: ok = True message = "User have been created successfully" return RegisterUser(ok=ok, message=message)
def new_user(): the_form = UserForm() if the_form.validate_on_submit(): user = User(login=the_form.login.data, password=the_form.password.data, email=the_form.email.data) modules['db'].session.add(user) modules['db'].session.commit() flash('Ok, user '+user.login+' registered successfully! Confirmation email has been sent to '+user.email) token = user.generate_confirmation_token() send_email(user.email, "Account confirmation", 'auth/email/confirm', user=user, token=token) return redirect(url_for('.index')) return render_template('new_user.html', new_user_form=the_form)
def post(self): form = SignUpForm() if form.validate_on_submit(): user_name = request.form.get('user_name', None) email = request.form.get('email', None) password = request.form.get('password', None) repassword = request.form.get('repassword', None) if user_name is None: return (Response( render_template('SignUp.html', title="Sign Up", form=form, message='Please fill in the User Name'))) if email is None: return (Response( render_template('SignUp.html', title="Sign Up", form=form, message='Please fill in the Email'))) if password is None or repassword is None: return (Response( render_template('SignUp.html', title="Sign Up", form=form, message='Please fill in the Password'))) if password == repassword: userObj = User(user_name=user_name, password=password, email=email) if userObj.createUser(): return (Response( render_template('SignIn.html', title="Sign In", form=form, message='Please Login'))) else: return (Response( render_template('SignUp.html', title="Sign Up", form=form, message='Sign Up Error'))) else: return (Response( render_template('SignUp.html', title="Sign Up", form=form, message="Password didn't match")))
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() db.session.commit() Role.insert_roles() User.insert_root_admin() self.client = self.app.test_client()
def signup(name, email, password, profile_url): user = User.query.filter(User.email == func.lower(email)).first() if user: abort(404, message='Email already registerd !!!') user = User() user.name = name user.email = func.lower(email) user.password = password user.profile_url = profile_url db.session.add(user) db.session.commit() return {'success': True, 'message': 'Signup successful'}
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 __get_home_screen(self): user = self.get_user() users_list = [] # user's favourites favorites = Favorite.where_has('favorite', lambda q: q.where('user_id', '=', user.id)) \ .limit(Config.get('home_screen.favourite_limit')) \ .order_by('id', 'desc') \ .get() for fav in favorites: formatted_user = fav.favorite.format_list() formatted_user['last_message'] = {} formatted_user['favorite'] = True users_list.append(formatted_user) # last connections - last message to user or from user messages = Message.where({'id_from': user.id}) \ .or_where({'id_to_user': user.id}) \ .where_null('id_to_chat') \ .order_by('created_at', 'desc') \ .limit(Config.get('home_screen.last_connections_limit')) \ .get() for message in messages: if str(message.id_from) == str(user.id): tmp = user.format_list() last_message = message.format_last(user.id) last_message['message'] = self.__get_message(last_message) tmp['last_message'] = last_message tmp['favorite'] = False users_list.append(tmp) elif str(message.id_to_user) == str(user.id): message_user = User.where('id', message.id_from).first() if message_user is not None: tmp = message_user.format_list() last_message = message.format_last(message_user.id) last_message['message'] = self.__get_message(last_message) tmp['last_message'] = last_message tmp['favorite'] = False users_list.append(tmp) # users with birthday today birthday_day = datetime.datetime.now().strftime('%d') birthday_month = datetime.datetime.now().strftime('%m') users_with_birthday = User.where_raw( '(EXTRACT(MONTH FROM birthday) = ' + birthday_month + ' AND EXTRACT(DAY FROM birthday) = ' + birthday_day + ')') \ .limit(Config.get('home_screen.birthday_limit')) \ .get() for user_with_b in users_with_birthday: formatted_user = user_with_b.format_list() formatted_user['last_message'] = {} formatted_user['favorite'] = False users_list.append(formatted_user) return users_list
def save(data): username = data['username'] email = data['email'] if 'phone_region' not in data: phone_region = '+55' else: phone_region = data['phone_region'] if User.query.filter(or_(User.email == email, User.username == username)).first() is not None: return (jsonify({'message': 'User already exists'}), 400) user = User( username=username, email=email, company_id=data['company_id'], phone_number=data['phone_number'], phone_region=phone_region, role_id=data['role_id'], status=1, # ATIVO created_at=datetime.now(), updated_at=datetime.now()) user.hash_password(data['password']) if data['role_id'] == 1: # ADMIN company = Company.query.get(data['company_id']) company.admin_email = data['email'] db.session.add(company) db.session.add(user) db.session.commit() verify_password(user.username, data['password']) token = g.user.generate_auth_token(current_app.config['TOKEN_TTL']) response = flask.make_response( jsonify({ 'data': { 'id': user.id, 'username': user.username, 'company_id': user.company_id, 'email': user.email, 'phone_region': user.phone_region, 'phone_number': user.phone_number, 'status': user.status, 'role_id': user.role_id, 'created_at': format_datetime(user.created_at), 'updated_at': format_datetime(user.updated_at) } }), 201) response.headers["Content-Type"] = "application/json" response = setCookie(response, token) return response
def setUp(self): super().setUp() user1 = User(username='******', email='*****@*****.**', password='******') user2 = User(username='******', email='*****@*****.**', password='******') self.db.session.add(user1) self.db.session.add(user2) self.db.session.commit() post = Post(title="title", body="body", poster_id=user1.id) self.db.session.add(post) self.db.session.commit() self.user1Id = user1.id self.user2Id = user2.id self.postId = post.id
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, 'Confirm Your Account', 'auth/email/confirm', user=user, token=token) flash('A confirmation email has been sent to you by email.') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def api_login(): req_data = request.get_json() username = req_data.get("email_or_username") email = req_data.get("email_or_username") password = req_data.get("password") user = User(mongo.db, username=username, email=email, password=password) validCreds = user.verify() if not validCreds: return_data = dict(Messages.message_login_fail) resp = jsonify(return_data) resp.status_code = 200 return resp return sendToken(user, dict(Messages.message_login))
def index(): if g.user.role == ROLE['ADMIN']: return redirect(url_for('admin.index')) history = Score.query\ .filter_by(user_id=g.user.id)\ .order_by(Score.id.desc())\ .limit(20) data = { "online_num": User.online_users(), "total_num": User.total_users(), "average": Score.average(g.user.id), "history" : history, } return render_template("frontend/index.html", **data)
def invite_user(email, password): """ Creates new user (login=<email>) or updates its password """ form = ConsoleRegisterForm(email=email, password=password) if form.validate(): try: User.init(email, password, None, is_admin=True) print('Admin-user created (%s)') % email except Exception as e: print(e) else: print(form.errors)
def register(): logger.debug("Entering register function") if current_user.is_authenticated: logger.info("User is logged in, redirecting to dashboard") return redirect(url_for('dashboard')) form = RegistrationForm() if request.method == 'POST': logger.debug("Register form submitted") if form.validate_on_submit(): user_exist = get_user_by_name(form.username.data) if user_exist == None: new_user = User(username=form.username.data) new_user.set_password(form.password.data) new_user.set_last_logged_in(datetime.now()) db.session.add(new_user) db.session.commit() login_user(new_user) session["user_id"] = new_user.get_id() session["username"] = new_user.get_username() logger.debug("Successfully created user %s", new_user) return redirect(url_for('dashboard')) else: flash("Username already taken!") logger.error("Username already taken") logger.warning("Registration failed, user not registered") return redirect(url_for("register")) return render_template('register.html', form=form)
def PUT(self, benutzername, passwort): super(Login, self).check_login() if self.user_allowed: user = User.find({"benutzername": benutzername, "passwort": passwort}) if user is not None: User.login_user(benutzername) return json.dumps({'success': True, 'user': User.logged_in_user.data}) return json.dumps({'success': False, 'message': 'Benutzername oder Passwort falsch!'}) return json.dumps({ "success": False, "message": "Aktion nicht erlaubt!" })
def post(self): form = SignInForm() if form.validate_on_submit(): user_name = request.form.get('user_name', None) password = request.form.get('password', None) remember_me = request.form.get('remember_me', False) userObj = User(user_name) if userObj.verifyPassword(password): login_user(userObj, remember = remember_me) userObj.is_authenticated = True session['user_name'] = user_name return(redirect(url_for('indexpage'))) return(Response(render_template('SignIn.html', title="Sign In", form = form, message = 'Password Error')))
def get_json_shop(): data = request.get_json() code = data["code"] print(data) print(code) # 用code换取需要的access_token data2 = wx_login_auth_shop.get_access_token(code) # 调用上面方法,从返回的json数据里得到 对应数据 openid print(data2) from app.models.User import User if not User.objects(xcc_openid=data2.openid): user = User(xcc_openid=data2.openid) user.save() return jsonify(data2)
def register(): if current_user.is_authenticated: return redirect(url_for('userarea')) if request.method == 'GET': return render_template('register.html') form = RegisterForm(request.form) val_result = form.validate if val_result is not None: return render_template('register.html', err=val_result) user = User(form) user.password = hash.encrypt(user.password) user.birthday = datetime.strptime(user.birthday, '%d-%m-%Y') #for sqlite try: db.session.add(user) db.session.commit() except exc.IntegrityError as e: #the code below gives an error on sqlite #_, message = e.orig.args #db.session.rollback() #error_string = "Integrity error" #print(message) #if "Duplicate" in message and "email" in message: # error_string = "Duplicate Email" return render_template('register.html', err="Duplicate email") except Exception as e: error_string = "Unknown error" print(e) if type(e) is exc.OperationalError: error_string = "Can't connect to mysql server" db.session.rollback() return render_template('register.html', err=error_string) weightHist = WeightHist(user_id=user.user_id, datetime=datetime.now(), weight=user.weight, height=user.height) db.session.add(weightHist) try: db.session.add(weightHist) db.session.commit() except: db.session.rollback() pass login_user(user, remember=True) return redirect(url_for('userarea'))
def get_users(): """ 获取用户列表,分页返回 :return: json """ query_data = g.json_data start, pagesize = HttpHelper.get_page_info() if query_data: paginated_user = User.get_pagination_user(start, pagesize, **query_data) else: paginated_user = User.get_pagination_user(start, pagesize) return HttpHelper.normal_handler(pagination_to_dict(paginated_user))
def POST(self, benutzername, passwort): super(Registrieren, self).check_login() if self.user_allowed: user = User.find({"benutzername": benutzername}) if user is not None: return json.dumps({ "success": False, "message": "Benutzer ist schon vorhanden!" }) else: user = User() user.data["benutzername"] = benutzername user.data["passwort"] = passwort user.data["rolle"] = "besitzer" user.save() return json.dumps({ "success": True }) return json.dumps({ "success": False, "message": "Aktion nicht erlaubt!" })
def check_login(self): User.user_logged_in() RestAbstract.executed_class = self.__class__.__name__ RestAbstract.executed_method = inspect.stack()[1][3] if User.logged_in_user is None: allowed_actions = self.allowed_actions_gast elif User.logged_in_user.data["rolle"] == "besitzer": allowed_actions = self.allowed_actions_besitzer else: allowed_actions = None if allowed_actions is not None: called_action = RestAbstract.executed_class + '.' + RestAbstract.executed_method if called_action not in allowed_actions: self.user_allowed = False else: self.user_allowed = True else: self.user_allowed = True
def create_user(self, email, nickname, password): new_user = User() new_user.Email = email new_user.Nickname = nickname new_user.Password = password new_user.save() return new_user
def verify_password(email_or_token, password): if email_or_token == '': g.current_user = AnonymousUser() return True if password == '': 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 passwd(): form = PasswdForm() if form.validate_on_submit(): oldpassword = form.oldpassword.data newpassword = form.newpassword.data if g.user.check_password(oldpassword): g.user.password = User.create_password(newpassword) db.session.commit() flash(u'Password change succeed', 'success') return redirect(url_for(".index")) else: flash(u'Old Password is wrong', 'danger') form.password.data = '' return render_template("frontend/passwd.html", form = form)
def invite(invite_hash): print(request.form) if invite_hash: from app.models.Invite import Invite invite = Invite.query.filter_by(invite=invite_hash).filter_by(activated=False).first() if not invite: user = User.query.filter_by(email=invite.email).first() invite.update(activated=True) login_user(user) return redirect('/login') else: user = User.init(request.form['email'], invite=invite_hash, active=True) # return redirect(url_for('/admin', messages={"main":'Invite message to {0} successfully send'.format(user.email)})) return redirect(url_for('admin'))
def after_find(self): leiter = User.find({"id": self.data["leitungId"]}) if leiter is not None: self.data["leiter"] = leiter.data qualiergebnisse = Qualiergebnis.find({"rennId": self.data["id"]}) if qualiergebnisse is not None: self.data["quali_eingetragen"] = True else: self.data["quali_eingetragen"] = False rennergebnisse = Rennergebnis.find({"rennId": self.data["id"]}) if rennergebnisse is not None: self.data["rennen_eingetragen"] = True else: self.data["rennen_eingetragen"] = False
def login(): """登录用户视图 """ form = LoginForm(request.form) if form.validate_on_submit(): u = User.has_username(form.username.data) if not u: flash(u"无此用户", "warning") return render_template("/user/login.html", form=form, title=u"登录") if not u.is_correct_password(form.password.data): flash(u"密码错误", "error") return render_template("/user/login.html", form=form, title=u"登录") u.dologin() """如果输入的登录用户名和密码都正确则成功跳转到系统主页 """ flash(u" %s 登录成功" % form.username.data) return redirect(url_for("index")) return render_template("/user/login.html", form=form, title=u"登录")
def create_default_users(): """ Creates new default users """ # Create all tables db.create_all() users = [ ['*****@*****.**', 'qwe'], ['*****@*****.**', 'qwe'] ] for item in users: email = item[0] password = item[1] user = User.query.filter(User.email == email).first() if not user: user = User.init(email=email, password=password, active=True, is_admin=True) db.session.add(user) # Save to DB db.session.commit()
def add_user(): form = AddUserForm() if form.validate_on_submit(): user = User() user.email = form.email.data user.username = form.username.data user.password = form.password.data user.role_id = form.role.data user.created_on = datetime.utcnow() db.session.add(user) flash('"{0}" has been added'.format(user.username)) return redirect(url_for('.users')) return render_template('admin/users/add_user.html', form=form)
def validate_login(self, field): if User.objects(username = self.username.data): raise validators.ValidationError('Duplicate username')
def __init__(self): User.user_logged_in()
def test_password_verification(self): u = User(password='******') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog'))
def __init__(self): User.user_logged_in() ViewAbstract.executed_class = self.__class__.__name__
def get_user(self): return User.objects(username = self.username.data).first()
def load_user(userid): return User.objects(id = userid).first()