def post(self): """ Register a user. Args: self Returns: A 201 status code user created. Raises: 401 error when invalid credentials given """ # parse incoming request data parser = reqparse.RequestParser() parser.add_argument('username') parser.add_argument('password') args = parser.parse_args() username = args['username'] password = args['password'] users_schema.validate(args) user = User(username) user.hash_password(password) user.add(user) results = items_schema.dump(user).data return results, 201
def create(): "Fill database with test data" user = User(user_name="admin", password="******") user.save() videos = [('http://www.youtube.com/watch?v=uLPW9qx8hj4', 'NAME1', 'имя1'), ('http://www.youtube.com/watch?v=oKv7AXSAUt0', 'NAME2', 'имя2'), ('http://www.youtube.com/watch?v=r-zKMsj5rio', 'NAME3', 'имя3'), ('http://www.youtube.com/watch?v=1hAWr6c9wV4', 'NAME4', 'имя4'), ('http://www.youtube.com/watch?v=XG--kTbq4ww', 'NAME5', 'имя5'), ('http://www.youtube.com/watch?v=z4Yek65lC-0', 'NAME6', 'имя6')] for url,name,name_ru in videos: video = Video(url=url, name=name) video.save() MainPage(text="MAINPAGE",text_ru="МАЙНПАГЕ").save() news = [["The PSI'14 is open. Congratulations to the Conference participants and organizers! See some photographs taken at the opening.", u"Поздарвляем всех участников и организаторов! Несколько фоток уже выложено!"], ["The Programme of Workshop on Science Intensive Applied Software is available in PDF (in Russian).", u"Программа конференции уже доступна на русском языке"], ["The Programme of Workshop 'Educational Informatics' is available in PDF.", u"Программа конференции уже доступна в PDF"], ["Registration for the conference begins at 8.00 am June 24 at New Peterhof Hotel.", u"Регестрация на конференцию начинается в 8.00 24 июня"]] for n in news: newsItem = NewsItem(content=n[0], content_ru=n[1]) newsItem.save() dates = [["abstract submission", u"прием докладов"], ["submission deadline", u"прием докладов закончен"], ["notification of acceptance", u"рассылка приглашений"], ["camera ready papers for pre-proceedings", u"что-то там готово для обработки"], ["the conference dates", u"план конференции"], ["camera ready papers due", u"что то там заканчивается"]] for d in dates: date = ImportantDate(description=d[0], description_ru=d[1]) date.save()
def delete(): "Delete all data from database" Page.drop_collection() User.drop_collection() Video.drop_collection() NewsItem.drop_collection() ImportantDate.drop_collection()
def form_verified(self): if User.user_login(self.user_name, self.user_password): user = User.get_user_by_name(self.user_name) self.login(user) self.redirect('/blog/welcome') else: error_message = "User does not exist. Please signup." self.render("signup.html", error_message=error_message)
def setUp(self): """Set up the test client.""" self.app = app.test_client() db.create_all() user = User("testuser") user.hash_password("testpassword") db.session.add(user) db.session.commit()
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) send_email(current_app.config['FLASKY_ADMIN'], 'New Registered User', 'auth/email/new_user', user=user) 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 verify_password(token, password): """ Verifies if token is valid Args: token: The token generated password: (optional) The users password Returns: True if user exists and token is valid False if user is nonexistent or token is invalid """ token = request.headers.get('Authorization') if token is None: return False # first try to authenticate by token user = User.verify_auth_token(token) g.user = user if not user: # try to authenticate with username / password user = User.query.filter_by(username=token).first() if not user or not user.verify_password(password): return False return True
def form_verified(self): """Called when form is verified.""" # Make sure user doesn't already exist user = User.get_user_by_name(self.user_name) if user: message = "That user already exists." self.render('signup.html', error_username=message) else: # Create user object in database user = User.register( self.user_name, self.user_password, self.user_email) user.put() # Log the user in and redirect to welcome page self.login(user) self.redirect('/blog/welcome')
def inner(*args, **kw): all_tokens = User.token_dict() token = request.args.get('token') if not token: return make_error(403, "Acess forbidden") if restrict and not any(all_tokens.get(user)== token for user in restrict): return make_error(403, "Acess forbidden") if not any(all_tokens[user] for user in all_tokens): return make_error(403, "Acess forbidden") return f(*args, **kw)
def test_gravatar(self): u = User(email='*****@*****.**', password='******') with self.app.test_request_context('/'): gravatar = u.gravatar() gravatar_256 = u.gravatar(size=256) gravatar_pg = u.gravatar(rating='pg') gravatar_retro = u.gravatar(default='retro') self.assertTrue('https://secure.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6' in gravatar) self.assertTrue('s=256' in gravatar_256) self.assertTrue('r=pg' in gravatar_pg) self.assertTrue('d=retro' in gravatar_retro)
def signup(): # POST를 이용해 db에 값 저장. SQLAlchemy ORM 쿼리 사용. if request.method == 'POST': try: new_user = User( id=request.form['id'], password=bcrypt.generate_password_hash( request.form['password']).decode('utf-8'), # 비밀번호를 암호화 하여 저장, UTF-8 디코딩 필수 name=request.form['name'], email=request.form['email']) db.session.add(new_user) db.session.commit() flash("회원가입에 성공하셧습니다.") return render_template('login/login.html') except: flash("동일한 아이디는 사용할 수 없습니다.") return render_template('login/signup.html') return render_template('login/signup.html')
def setUp(self): super(TestApi, self).setUp() self.payload = { "optimize": ["clicks", "engagements", "conversions"], "stats": [ { "date": str(datetime.date.today() - datetime.timedelta(days=1)), "ad_id": "1234", "cost": 1000, "impressions": 1000, "engagements": 100, "clicks": 10, "conversions": 1, } ], } db.session.add(User(name='Test', api_key='valid_key')) db.session.commit()
def setUpClass(cls): # start Chrome options = webdriver.ChromeOptions() options.add_argument('headless') try: cls.client = webdriver.Chrome(chrome_options=options) 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() fake.users(10) fake.posts(10) # add an administrator user admin_role = Role.query.filter_by(name='Administrator').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 cls.server_thread = threading.Thread(target=cls.app.run, kwargs={'debug': False}) cls.server_thread.start() # give the server a second to ensure it is up time.sleep(1)
def create_user(): """ User route. User creation, verification and data enrichment. Reads from the body. Requires: first_name last_name email password """ data = request.get_json() # verify address try: verify = hunter.email_verifier(data['email']) if verify.get('status') != 'valid': return jsonify({'message': 'Email address isn\'t verified'}), 400 except: return jsonify({'message': 'Unable to verify the address'}), 500 # try: # create user account hashed_password = generate_password_hash(str(data['password']), method='sha256') new_user = User(email=data['email'], first_name=data['first_name'], last_name=data['last_name'], password=hashed_password) db.session.add(new_user) # try data enrichment try: enrich = clearbit.Enrichment.find(email=new_user.email, stream=True) enriched = Enriched(data=enrich, user=new_user) db.session.add(enriched) except: print(f'Couln\'t enrich user {new_user.email}') pass db.session.commit() return jsonify({'message': f'User {new_user.email} created'}), 201
def register(): if session.get('logged_in'): return render_template('home.html') if request.method == 'GET': return render_template('register.html') if request.method == 'POST': try: # Add the user to db # TODO: Encrypt the password db.session.add( User(username=request.form['username'], password=request.form['password'])) db.session.commit() return redirect(url_for('login')) except: return render_template('index.html', message="User Already Exists")
def register(): if current_user.is_authenticated: return redirect(url_for('home')) form = RegistrationForm() if form.validate_on_submit(): # generando um senha segura 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() # f-string, o que define uma variável para conter numa string flash('Account created has created. You are now able to log in', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def create_user(self, user_create: UserCreate): new_user = User(first_name=user_create.first_name, last_name=user_create.last_name, is_active=True, email=user_create.email, hashed_password=get_password_hash( user_create.password), city=user_create.city, state=user_create.state, address=user_create.address, phone_number=user_create.phone_number, document_number=user_create.document_number, birth_date=user_create.birth_date, shirt_size=user_create.shirt_size, gender=user_create.gender) self.db.add(new_user) self.db.flush() self.db.refresh(new_user) return new_user
def post(self): """ 登录,获取用户信息以及生成token :return: """ data = request.json username = data.get('username') password = data.get('password') user = User.query.filter(User.username == username).first() if User.verify_password(user, password): # 生成token token = user.generate_auth_token() return jsonify(code=Ret.SUCCESS, msg="登录成功", data={ 'token': token.decode('utf-8'), 'name': user.username }) else: return jsonify(code=Ret.FAILURE, msg="密码错误")
def login(): form = LoginForm() if form.validate_on_submit(): user = User.login_check(request.form.get('user_name'), request.form.get('user_password')) if user: login_user(user) user.last_seen = datetime.now() try: db.session.add(user) db.session.commit() except: flash("The Database error!") return redirect('/login') flash('Your name: ' + request.form.get('user_name')) return redirect(url_for("index")) else: flash('Login failed, username or password error!') return redirect('/login') return render_template('login.html', form=form)
def register(): temp_userdetails = '' form = RegistrationForm() if form.validate_on_submit(): flash("Account created for {}!".format(form.username.data), 'success') temp_userdetails = form.username.data user = User(FirstName=form.FirstName.data, LastName=form.LastName.data, username=form.username.data, email=form.email.data, password=bcrypt.generate_password_hash( form.password.data).decode('utf-8')) db.session.add(user) db.session.commit() return redirect(url_for('login')) return render_template('register.html', title='Register', form=form, userdetails=temp_userdetails)
def register(): """ Handle requests to the /register route Add an user to the database through the registration form """ form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data, password=form.password.data) # add user to the database db.session.add(user) db.session.commit() flash('You have successfully Create a user! You may now login.') # redirect to the login page return redirect(url_for('view.dashboard')) # load registration template return render_template('registration.html', form=form, title='Register')
def new_users(): if session.get('logged_in'): return redirect(url_for('index_dashboard')) form = UserForm(request.form) if request.method == 'POST': if form.validate(): user_exists = User.query.filter(User.name == form.name.data).first() if not user_exists: email_exists = User.query.filter(User.email == form.email.data).first() if not email_exists: user = User(form) db.session.add(user) db.session.commit() flash('Usuário registrado', 'success') return redirect(url_for('index_users')) else: flash('Email já existe', 'danger') else: flash('Usuario já existe', 'danger') else: flash('Erro ao registrar usuário', 'danger') return render_template('users/new.html', form=form)
def create_regist_user(form): session = DBConnetor.db() try: user = User(name=form.data["name"], pwd=generate_password_hash(form.data["pwd"]), email=form.data["email"], phone=form.data["phone"], sex=None, xingzuo=None, face=None, info=None, createdAt=Database.datenow(), updatedAt=Database.datenow()) session.add(user) except: session.rollback() else: session.commit() finally: session.close() return True
def update_profile(): isPassenger() user = current_user if not User.is_passenger(user): return redirect('/logout') else: form = ProfileForm() imageForm = UploadProfileImageForm() if request.method == "POST": if form.validate_on_submit(): update_user = User.query.filter_by(id=user.id).first() update_user.name = form.name.data update_user.surname = form.surname.data update_user.country = form.country.data update_user.email = form.email.data try: db.session.add(update_user) db.session.commit() flash('Profile Updated', 'success') return redirect("/passenger/updateprofile") except Exception as e: # return 'Profile not updated '+str(e) flash( 'Error occurred in updating the profile, please try again.', 'danger') return redirect("/passenger/updateprofile") else: return render_template('driver_profile_update.html', form=form, imageForm=imageForm, user=user) else: form.email.data = user.email form.name.data = user.name form.surname.data = user.surname form.country.data = user.country return render_template('passenger_profile_update.html', form=form, imageForm=imageForm, user=user)
def register(): if request.method == 'GET': return render_template('register.html') else: mobile = request.form.get('mobile') username = request.form.get('username') password1 = request.form.get('password1') password2 = request.form.get('password2') # 验证手机号码是否已经注册 user = User.query.filter(User.mobile == mobile).first() if user: return u"当前手机号码已经被注册" else: # 两次密码是否相等 if password1 != password2: return u"两次密码不相同,请核对后再填写" else: user = User(mobile=mobile, username=username, password=password1) db.session.add(user) db.session.commit() return redirect(url_for('login'))
def new_user(): uniqname = request.form.get('uniqname') print(uniqname) if not uniqname: abort(404) user = User.query.filter_by(uniqname=uniqname).first() if user: session['user_id'] = user.user_id session['curr_q_id'] = 0 return redirect(url_for('show_question',id=str(session['curr_q_id']))) new_user = User(uniqname=uniqname) db.session.add(new_user) db.session.commit() db.session.refresh(new_user) # 1. generate the questions # 2. for each questions, add to use_question table without best and worst option question = get_questions() for i in question: user_id = new_user.user_id question_id = i['question_id'] best_option = None worst_option = None new_answer = User_Question(user_id=user_id, question_id=question_id, best_option=best_option, worst_option=worst_option) db.session.add(new_answer) db.session.commit() session['user_id'] = new_user.user_id session['annotate'] = 0 return redirect(url_for('show_question',id=str(0)))
def post(self): """External user login This method allows an external handshake of a user to the LDAP database Returns ------- """ args = user_login_parser.parse_args() username = args.username password = args.password if LOGIN_METHOD != "None": try: result = User.try_login(username, password) if not result: return None except ldap.INVALID_CREDENTIALS, e: print e return None user = User.query.filter_by(username=result['uid'][0]).first()
def update_user(): name = request.form['username'] email = request.form['email'] optIn = request.form['optIn'] # print(optIn) matchingUser = mongo_user_dao.findAllMatchingEmail(email) if (isinstance(matchingUser[0], Admin)): user = Admin(Id=matchingUser[0].Id, name=name, email=email, optIn=optIn, listOfItemIds=matchingUser[0].listOfItemIds) mongo_user_dao.update(user) return jsonify(user.toDict()), 200 else: user = User(Id=matchingUser[0].Id, name=name, email=email, optIn=optIn, listOfItemIds=matchingUser[0].listOfItemIds) mongo_user_dao.update(user) return jsonify(user.toDict()), 200
def reset_token(token): # verificar se eles estão logados if current_user.is_authenticated: return redirect(url_for('main.home')) user = User.verify_reset_token(token) if not user: flash('That is an invalid or expired token', 'warning') return redirect(url_for('users.reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): # generando um senha segura hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() # f-string, o que define uma variável para conter numa string flash('You password has been update. You are now able to log in', 'success') return redirect(url_for('users.login')) return render_template('reset_token.html', title='Reset Password', form=form)
def post(self): """Create a user record on a signup""" email = api.payload["email"] password = api.payload["password"] test = User.query.filter_by(email=email).first() if test: return {"message": "The email already is registered"}, 409 else: password = api.payload["password"] first_name = api.payload["firstName"] last_name = api.payload["lastName"] phoneNumber = api.payload["phoneNumber"] user = User( first_name=first_name, last_name=last_name, email=email, password=password, phone_number=phoneNumber, ) db.session.add(user) db.session.commit() return {"message": "successfully created user."}, 201
def reg(): if request.method == "GET": session["num1"] = random.randint(0, 9) session["num2"] = random.randint(0, 9) return render_template("user/reg.html") elif request.method == "POST": localtime = time.asctime(time.localtime(time.time())) create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 注册的时间 email = request.form.get("email") username = request.form.get("username") password = request.form.get("pass") repass = request.form.get("repass") vercode = request.form.get("vercode") ss = session.get("num1") + session.get("num2") print(email, username, password, repass, vercode) print(ss, '-----人类验证码') # 查询用户注册的邮箱是否存在 user = db.session.query(User).filter(User.email == email).first() if user: return "用户名存在" # 数据库添加 if int(vercode) == int(ss): user = User() if user: # 用户注册成功 user.email = email user.user_name = username user.password_hash = password user.create_time = create_time db.session.add(user) db.session.commit() # 2 重定向到index return redirect("/login") return "Aa" return "验证码错误"
def test_is_registered_with_broker(): user = User(mqtt_creds=MQTTUser()) assert user.is_registered_with_broker user = User() assert not user.is_registered_with_broker
def get_users(): # users = User.query.all().to_dict() data = User.to_collection_dict(User.query.all, 'api.get_users') return (jsonify(data))
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_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_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_follows(self): u1 = User(email='*****@*****.**', password='******') u2 = User(email='*****@*****.**', password='******') db.session.add(u1) db.session.add(u2) db.session.commit() self.assertFalse(u1.is_following(u2)) self.assertFalse(u1.is_followed_by(u2)) timestamp_before = datetime.utcnow() u1.follow(u2) db.session.add(u1) db.session.commit() timestamp_after = datetime.utcnow() self.assertTrue(u1.is_following(u2)) self.assertFalse(u1.is_followed_by(u2)) self.assertTrue(u2.is_followed_by(u1)) self.assertTrue(u1.followed.count() == 2) self.assertTrue(u2.followers.count() == 2) f = u1.followed.all()[-1] self.assertTrue(f.followed == u2) self.assertTrue(timestamp_before <= f.timestamp <= timestamp_after) f = u2.followers.all()[-1] self.assertTrue(f.follower == u1) u1.unfollow(u2) db.session.add(u1) db.session.commit() self.assertTrue(u1.followed.count() == 1) self.assertTrue(u2.followers.count() == 1) self.assertTrue(Follow.query.count() == 2) u2.follow(u1) db.session.add(u1) db.session.add(u2) db.session.commit() db.session.delete(u2) db.session.commit() self.assertTrue(Follow.query.count() == 1)
def initialize(self, *a, **kw): """Reads if there is any cookies and sets a global user object.""" webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie('user_id') self.user = uid and User.get_user_by_id(int(uid))