def client_loaded(app): with app.app_context(): client_loaded = app.test_client() db.create_all() password = generate_password_hash('Monday1') db.session.add( User(id=1, first_name='Test', last_name='User', email='*****@*****.**', password=password)) db.session.add( User(id=2, first_name='John', last_name='Smith', email='*****@*****.**', password=password)) db.session.commit() db.session.add( Character(id=1, name='Paladin', is_dead=False, user_id=1)) db.session.add(Character(id=2, name='Rogue', is_dead=False, user_id=1)) db.session.add( Character(id=3, name='Fighter', is_dead=False, user_id=2)) db.session.commit() data = dict(email='*****@*****.**', password='******', remember_me=False) client_loaded.post('/login', data=data) yield client_loaded db.drop_all()
def post(self): registerData = { 'username': request.json['username'], 'password': request.json['password'], 'email': request.json['email'] } user = User.objects(username=registerData['username']).first() userEmail = User.objects(email=registerData['email']).first() if user: return abort( 403, description='Użytkownik o podanej nazwie już istnieje!') elif userEmail: return abort( 403, description= 'Konto o podanym adresie email już istnieje! prosimy o podanie innego.' ) newUser = User(username=registerData['username'], password=bcrypt.generate_password_hash( registerData['password']), email=registerData['email']).save() token = generate_confirmation_token(newUser.email) send_email( newUser.email, 'Aktywacja Konta', render_template('auth/activate.html', confirm_url=url_for('auth.confirm_account', token=token, _external=True))) return jsonify( message= 'Twoje konto zostało pomyślnie utworzone! Na adres e-mail została wysłana wiadomość z linkiem aktywacyjnym - prosimy aktywować konto.' )
def test_incorrect_password_without_lowercase_letter(self): name= "USER" password = "******" user = User(name) error, goodPassword = user.check_password_strength_and_hash_if_ok(password) self.assertFalse(goodPassword) self.assertEqual(error, 'The password must include at least one lowercase letter')
def client(app): with app.app_context(): client = app.test_client() db.create_all() # Add Users password = generate_password_hash('Monday1') db.session.add( User(id=1, first_name='TestA', last_name='UserOne', email='*****@*****.**', password=password)) db.session.add( User(id=2, first_name='TestB', last_name='UserTwo', email='*****@*****.**', password=password)) db.session.commit() # Add some Characters db.session.add(Character(id=1, name='Paladin', is_dead=False)) db.session.add(Character(id=2, name='Rogue', is_dead=False)) db.session.add(Character(id=3, name='Fighter', is_dead=False)) db.session.commit() # Set the current Character db.session.add(Setting(key='current_character', value='2')) db.session.commit() yield client db.drop_all()
def add(): error = None if request.method == 'POST': uname = request.form.get("name") password = request.form.get("password") confirm = request.form.get("confirm") mail = request.form.get("mail") group = request.form.get("group") user = User(current_app) userdata = user.check(uname) if not uname or not mail or not password: return render_template("user/add.html", error=u"请填写所有选项") if password != confirm: return render_template("user/add.html", error=u"两次密码不匹配") if len(userdata) == 0: if password: #valide salt = createSalt() password = md5(md5(password).hexdigest() + salt).hexdigest() uid = user.add(username=uname, passwd=password, email=mail, permissions=group, salt=salt, createtime=int(time.time())) if uid > 0: return redirect(url_for('users.index')) else: error = u"添加失败" else: error = u"密码不能为空" else: error = u"用户已经存在" return render_template("user/add.html", error=error)
def test_incorrect_password_without_symbol(self): name= "USER" password = "******" user = User(name) error, goodPassword = user.check_password_strength_and_hash_if_ok(password) self.assertFalse(goodPassword) self.assertEqual(error, 'The password must include at least one symbol')
class UserModelTestCase(GenericModelTestCase): """ User Model TestCase """ cls = User fields = ['id', 'name', 'surname', 'weight', 'height', 'bmi'] def setUp(self): """SetUp""" self.user = User() def assert_bmi_health(self, bmi, expected): """ Asserts BMI health name""" self.user.bmi = MagicMock(return_value=bmi) assert self.user.bmi_health_name() == expected def test_bmi_health_name(self): """ tests for bmi_health_name method """ self.assert_bmi_health(-1, "") self.assert_bmi_health(0, "Underweight") self.assert_bmi_health(1, "Underweight") self.assert_bmi_health(18.5, "Underweight") self.assert_bmi_health(18.6, "Normal weight") self.assert_bmi_health(25.0, "Overweight") self.assert_bmi_health(30.0, "Obesity") def test_height_less_hundred(self): """ tests for height less then hundred if not raises ZeroDivisionError""" self.user.height = 99 self.user.weight = 50 self.user.name = "under hundred height" self.user.surname = "under fifty weight" self.assertEqual(self.user.bmi(), 51.02)
def test_user_password(self, testapp): """ Test password hashing and checking """ admin = User('admin', 'supersafepassword') assert admin.username == 'admin' assert admin.check_password('supersafepassword')
def login(request): reJson = json.loads(request.body) code = reJson['code'] url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' % ( appid, appsecret, code) re = requests.get(url) # result返回 session_key 和 openid reJson = json.loads(re.content.decode('utf-8')) print(re.content.decode('utf-8')) openid = reJson['openid'] logger.info("User: "******" login.") # 用户初次登入小程序即为其创建数据库记录 if not User.objects.filter(openid=openid): newUser = User(openid=openid) logger.info(openid + " create new user") newUser.save() # 加密openid token = createToken(openid) return HttpResponse(token)
def test_incorrect_password_too_long(self): name= "USER" password = "******"*50 user = User(name) error, goodPassword = user.check_password_strength_and_hash_if_ok(password) self.assertFalse(goodPassword) self.assertEqual(error, 'The password is too long')
def register(): if current_user.is_authenticated: return redirect(url_for('home.home_page')) form = RegistrationForm() if form.validate_on_submit(): user = User.objects(username=form.username.data).first() userEmail = User.objects(email=form.email.data).first() if user: flash('Podana nazwa użytkownika jest już zajęta!', 'danger') elif userEmail: return flash('Konto o podanym adresie email już istnieje! prosimy o podanie innego.', 'danger') newUser = User( username=form.username.data, email=form.email.data, password=bcrypt.generate_password_hash( form.password.data)).save() token = generate_confirmation_token(newUser.email) send_email( newUser.email, 'Aktywacja Konta', render_template( 'auth/activate.html', confirm_url=url_for( 'auth.confirm_account', token=token, _external=True))) flash('Twoje konto zostało pomyślnie utworzone! Na podany adres e-mail wyslaliśmy wiadomość z linkiem aktywacyjnym. Prosimy aktywować swoje konto aby mieć dostęp do pełnej wersji strony', 'success') return redirect(url_for('home.home_page')) return render_template('/auth/register.html', form=form)
def test_check_correct_password_and_verify_the_hash(self): name= "USER" password = "******" user = User(name) error, goodPassword = user.check_password_strength_and_hash_if_ok(password) self.assertTrue(goodPassword, error) password_verified = user.verify_password(password) self.assertTrue(password_verified, "The password could not be verified")
def create_fake_people(): user_group = 'alpha' for i in range(0, 100): name = 'fake_user_%s_%s' % (user_group, i) user = User(username=name, email='*****@*****.**'%(name), password='******') user.save() person = Person.objects.create_random(user) person.save()
def setUp(self): self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0) self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub(consistency_policy=self.policy) self.u1 = User.save(username1, email1, password1) self.u2 = User.save(username2, email2, password2)
def registration(): form = RegForm() if form.validate_on_submit(): password = sha256(form.password.data.encode()).hexdigest() user = User(form.login.data, password) user.save() return redirect('/') return render_template('registration.html', form=form)
def test(self): user = User() user.username = "******" password = "******" user.password = password db.session.add(user) db.session.commit() result = db.session.query(User).all()[0] self.assertTrue(result.verify_password(password))
def test_new_user(test_client, init_database): user = User(name='user004') user.password = '******' db.session.add(user) db.session.commit() assert user.password_hash != 'helloWorld' assert user.is_active is True assert user.is_superuser is False assert User.query.filter(User.name == 'user004').first() is not None
def registration(): form = RegForm() if form.validate_on_submit(): user = User(form.login.data, form.name.data) user.save(form.password.data) session["Login"] = user.login return redirect(url_for("main")) return render_template('registration.html', form=form, user=cur_user())
def validate(self): if not Form.validate(self): return False if self.firstname.data != User.make_valid_nickname(self.firstname.data): self.firstname.errors.append('This firstname has invalid characters. Please use letters, numbers, dots and underscores only.') return False if self.lastname.data != User.make_valid_nickname(self.lastname.data): self.lastname.errors.append('This lastname has invalid characters. Please use letters, numbers, dots and underscores only.') return False return True
def test_follow(self): u1 = User(nickname='john', email='*****@*****.**') u2 = User(nickname='susan', email= '*****@*****.**') db.session.add(u1) db.session.add(u2) db.session.commit() assert u1.unfollow(u2) is None u = u1.follow(u2) db.session.add(u) db.session.commit() assert u1.follow(u2) is None assert u1.is_following(u2) assert u1.followed.count() == 1 assert u1.followed.first().nickname == 'susan' assert u2.followers.count() == 1 assert u2.followers.first().nickname == 'john' u = u1.unfollow(u2) assert u is not None db.session.add(u) db.session.commit() assert u1.is_following(u2) is False assert u1.followed.count() == 0 assert u2.followers.count() == 0
def post(self): """ Users Method to create a new User --- tags: - Users parameters: - in: body name: body schema: id: UserToUpdate properties: name: type: string description: The User name default: "UserName" password: type: string description: The User password default: "P4$sw00rd!" responses: 201: description: The updated area schema: $ref: '#/definitions/Area' """ request_dict = request.get_json() if not request_dict: response = {'user': '******'} return response, status.HTTP_400_BAD_REQUEST errors = user_schema.validate(request_dict) if errors: return errors, status.HTTP_400_BAD_REQUEST name = request_dict['name'] existing_user = User.query.filter_by(name=name).first() if existing_user is not None: response = {'user': '******'} return response, status.HTTP_400_BAD_REQUEST try: user = User(name=name) error_message, password_ok = \ user.check_password_strength_and_hash_if_ok( request_dict['password']) if password_ok: user.add(user) query = User.query.get(user.id) result = user_schema.dump(query).data return result, status.HTTP_201_CREATED else: return {"error": error_message}, status.HTTP_400_BAD_REQUEST except SQLAlchemyError as e: db.session.rollback() resp = {"error": str(e)} return resp, status.HTTP_400_BAD_REQUEST
def comments_add(self, request): if request.apikey: self.apikey_model = ApiKeys.get_apikey_by_id(request.apikey) if self.apikey_model is None: return CommentsAddResponse(message="the API key provided is no longer valid") else: new_comment = Comments() self.user_model = User.get_user_by_id(self.apikey_model.user_id) self.model_current_posts = Connection.get_connections_by_user_id_status(self.user_model.key) new_comment.user_name = self.user_model.username new_comment.user_key = self.user_model.key self.apikey_model.total_calls += 1 self.apikey_model.put() else: return ConnectionAddResponse(message="you must provide an API key") self.header_dict = self.parse_header(self.request_state.headers._headers) # if len(Connection.get_connection_by_title(request.title)) > 0: # return CommentsAddResponse(message="title already exists %s" % request.title) if request.personthing_id: self.personthing_model = PeopleThing.get_person_by_id(request.personthing_id) new_comment.personthing_key = self.personthing_model.key new_comment.personthing_name = self.personthing_model.name if request.user_id: self.user_model = User.get_user_by_id(request.user_id) new_comment.user_key = self.user_model.key new_comment.user_name = self.user_model.name if request.connection_id: try: self.connection_model = Connection.get_connection_by_id(request.connection_id) new_comment.connection_key = self.connection_model.key new_comment.connection_title = self.connection_model.title except: return CommentsAddResponse(message="Connection ID not valid: %s" % request.connection_id) if request.media: new_comment.media = request.media new_comment.post_type = request.post_type new_comment.title = request.title new_comment.tags = request.tags new_comment.body = request.body new_comment.uastring = self.header_dict['user-agent'] new_comment.ip = self.request_state.remote_address new_blog_key = new_comment.put() return CommentsAddResponse(message="successfully added comment", comment_id = new_blog_key.id())
def index(): data = 0 sites = Site(current_app) site = sites.totalcount() seeds = Seed(current_app) seed = seeds.totalcount() users = User(current_app) uid = session['uid'] user = users.view(uid) lastlogin = user[0]["lastlogintime"] return render_template("index.html", site=site, seed=seed, data=data, lastlogin=lastlogin)
def setUp(self): app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( BASE_DIR, TEST_DB) self.app = app.test_client() db.create_all() self.user = User('TestUser') self.user.save('testpassword') self.video = Video('TestVideo') self.video.save(hash='Teststring', user=self.user)
def refresh(): """Function to refresh database """ db.drop_all() db.create_all() user = User('admin', 'admin', 'admin') user.role = 1 db.session.add(user) user = User('Guest', 'none', 'none') db.session.add(user) db.session.commit() exit()
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() # make sure you know what this does self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1) self.testbed.init_datastore_v3_stub(consistency_policy=self.policy) self.u1 = User.save(username1, email1, password1) self.u2 = User.save(username2, email2, password2) self.createNewSource() self.createNewCourses() self.courses = self.createNewAttempts()
def test_user(self): n = User.make_valid_nickname('John_123') assert n == 'John_123' n = User.make_valid_nickname('John_[123]\n') assert n == 'John_123' u = User(nickname='john', email='*****@*****.**') db.session.add(u) db.session.commit() assert u.is_authenticated is True assert u.is_active is True assert u.is_anonimous is False assert u.id == int(u.get_id())
def register(): if current_user.is_authenticated: return redirect(url_for('main.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!') send_activation_email(user) flash('Wysłano maila!') return redirect(url_for('auth.login')) return render_template('auth/register.html', title='Register', form=form)
def reg(): """ Отвечает за вывод страницы регистрации и регистрацию :return: Страница регистрации """ form = RegForm() if form.validate_on_submit(): user = User(form.login_reg.data) user.save(form.password_reg.data) session["Login"] = user.login return redirect(url_for("main")) return render_template('reg.html', form=form, user=cur_user())
def test_make_unique_nickname(self): u = User(nickname='john', email='*****@*****.**') db.session.add(u) db.session.commit() nickname = User.make_unique_nickname('john') assert nickname != 'john' u = User(nickname=nickname, email='*****@*****.**') db.session.add(u) db.session.commit() nickname2 = User.make_unique_nickname('john') assert nickname2 != 'john' assert nickname2 != nickname
def create_user(email, name, password): user = User(email=email, name=name, pwdhash=generate_password_hash(password), is_active=True) db.session.add(user) db.session.commit()
def post(self): if not session.get('status'): return {'result': {'status_code': 401}} args = self.parser.parse_args() key_username = args.username key_password = args.password key_xingming = args.xingming key_phone = args.phone key_email = args.email key_remark = args.remark if session['username'] != 'root': return {'result': {'status_code': 202}} user_query = User.query.filter(User.username == key_username).first() if user_query: # 用户名存在 addlog(session.get('username'), session.get('login_ip'), f'新增用户[{key_username}]失败,原因:用户已存在') return {'result': {'status_code': 201}} user1 = User(username=key_username, password=key_password, name=key_xingming, phone=key_phone, email=key_email, remark=key_remark) DB.session.add(user1) try: DB.session.commit() except Exception as e: logger.log('ALERT', f'用户新增接口SQL错误:{e}') DB.session.rollback() return {'result': {'status_code': 500}} addlog(session.get('username'), session.get('login_ip'), f'新增用户[{key_username}]成功') return {'result': {'status_code': 200}}
def testDeleteWithoutOwner(self): c, msg = User.add_new_conversation(self.u1.username, self.u2.username, title_plain_text, content_plain_text) m = Conversation.add_new_message(self.u2.username, content_plain_text2, conv_key=c.key) Conversation.add_new_message(self.u1.username, content_plain_text, conv_key=c.key) # c.put() self.assertEqual(len(c.messages_list), 3, "Length of messages list != 3") Conversation.delete_message(self.u2.username, c.key.id(), m.key.id()) self.assertEqual(len(c.messages_list), 3, "Length of messages list != 3 after deletion") deleted = m.key.get() self.assertIsNotNone(deleted, "Message is None") self.assertEqual(deleted.deleted_for, self.u2.username, "Deleted for is incorrect") for k in c.messages_list: msg = k.get() if k != deleted.key: self.assertIsNone(msg.deleted_for, "deleted_for was not None for a message other than deleted")
def createRandomUser(code=None, name=None): if code is None: code = generateRandomCode() if name is None: name = _generateRandomName(10) user = User( code = code, name = name, cha = random.randrange(1, 8), con = random.randrange(1, 8), dex = random.randrange(1, 8), int = random.randrange(1, 8), str = random.randrange(1, 8), wis = random.randrange(1, 8), role = random.randrange(7)) user.save()
def forget_password(): if current_user.is_authenticated: return redirect(url_for('home.home_page')) else: form = ResetPasswordForm() if form.validate_on_submit(): user = User.objects(email=form.email.data).first() if user.last_change + timedelta(minutes=30) <= datetime.now(): if user: token = generate_confirmation_token(user.email) send_email( user.email, 'Zmiana hasła', render_template( 'auth/activate.html', confirm_url=url_for( 'auth.reset_password', token=token, _external=True))) flash( 'Na podany adres email zostały wysłane dalesze instrukcje dotyczące zmiany hasła!', 'success') else: flash( 'Do podanego adresu email nie zostało przypisane żadne konto!', 'danger') else: flash( 'Hasło można zresetować po upływie 30minut od ostatniej zmiany!', 'warning') return render_template('/auth/forgetPassword.html', form=form)
def reset_password(token): if current_user.is_authenticated: return redirect(url_for('home.home_page')) form = ResetPasswordChangeForm() if form.validate_on_submit(): try: email = confirm_token(token) except BaseException: flash( 'Link resetujący hasło wygasł, lub jest nieprawidłowy!', 'danger') user = User.objects(email=email).first_or_404() if user.last_change + timedelta(minutes=30) <= datetime.now(): user.update(password=bcrypt.generate_password_hash(form.password.data)) user.update(last_password_change=datetime.now()) flash( 'Twoje hasło zostało pomyślnie zresetowane!, teraz możesz się zalogować.', 'success') return redirect(url_for('auth.login')) else: flash( 'Hasło można zresetować po upływie 30minut od ostatniej zmiany!', 'warning') return redirect(url_for('home.home_page')) return render_template('/auth/resetPassword.html', form=form)
def comments_list(self, request): filter_dict = {} self.curs = Cursor(urlsafe=request.cursor) #If the user does not specify the limit of results, use 20 if not request.limit: request.limit = 20 if request.created: filter_dict['created'] = request.created if request.updated: filter_dict['updated'] = request.updated if request.tags: filter_dict['tags'] = request.connection_stage if request.title: filter_dict['title'] = request.title if request.user_id: filter_dict['user_key'] = User.get_user_by_id(request.user_id).key if request.personthing_id: filter_dict['personthing_key'] = PeopleThing.get_person_by_id(request.personthing_id).key if request.connection_id: filter_dict['connection_key'] = Connection.get_connection_by_id(request.connection_id).key self.all_comments, next_curs, more_results = Comments.get_comments(self.curs, request.limit, filter_dict) comments = [comment.to_comment_message() for comment in self.all_comments] if more_results is True: self.cursor=next_curs.urlsafe() else: self.cursor="No More Results" return CommentsListResponse(comments=comments, cursor = self.cursor, num_of_results = len(self.all_comments))
def post(self): user = UserModel.objects(username='******').first() if not request.json: return abort( 403, description= 'Brakujące argumenty, prosze wypełnić wszystkie pola.') kidData = [ request.json['name'], request.json['age'], request.json['height'], request.json['favorite_colour'], request.json['shoe_size'] ] for k in kidData: if not k: return abort( 403, description= 'Brakujące argumenty, prosze wypełnić wszystkie pola.') if not kidData[1].isdigit() or not kidData[2].isdigit( ) or not kidData[4].isdigit(): return jsonify( message='Podane wartości muszą być typu liczbowego!') user.kids.append( Kid(name=kidData[0], age=kidData[1], height=kidData[2], favorite_colour=kidData[3], shoe_size=kidData[4])) user.save() return jsonify(message='Dziecko zostało dodane pomyślnie')
def signup_post(): form = SignupForm() if form.validate_on_submit(): new_user = User(first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data, password=generate_password_hash(form.password.data, method='sha256')) # check if the user exists user = User.query.filter_by(email=new_user.email).first() if user: # user exists, go back to signup flash('email already exists', 'warning') return redirect(url_for('auth_bp.signup')) # User doesn't exist add them, then to login form db.session.add(new_user) db.session.commit() flash('User added, please login', 'success') return redirect(url_for('auth_bp.login')) else: # Invalid form, back to signup return redirect(url_for('auth_bp.signup'))
def populate_db(db): role_admin, role_user = db_create(db) user1, user2 = [ User(nickname=name, email="*****@*****.**" % name, pwdhash=name, roles=[role_user], activation_key="") for name in ["user1", "user2"] ] db.session.add(user1) db.session.add(user2) db.session.commit() for user in (user1, user2): for feed_name in ['feed1', 'feed2', 'feed3']: feed = Feed(link=feed_name, user_id=user.id, title="%r %r" % (user.nickname, feed_name)) db.session.add(feed) db.session.commit() for article in ['article1', 'article2', 'article3']: entry = "%s %s %s" % (user.nickname, feed.title, article) article = Article(entry_id=entry, link=article, feed_id=feed.id, user_id=user.id, title=entry, content=article) db.session.add(article) db.session.commit() db.session.commit()
def create_user(): '''Inserts a test user that has an active habit to the db''' db.session.add( User(username='******', password=generate_password_hash('test_password', method='sha256'))) db.session.commit()
def login(self, request): """Exposes an API endpoint to query for an upload URL. Args: Returns: """ salt=config.get('salt') aes_key=config.get('aes_key') if not request.username: LoginResponse(message="Provide a username") username = request.username.lower() # try: if utils.is_email_valid(username): user = User.get_by_email(username) if user: auth_id = user.auth_ids[0] else: raise InvalidAuthIdError else: auth_id = "own:%s" % username user = User.get_by_auth_id(auth_id) password = request.password.strip() remember_me=False # Password to SHA512 password = utils.hashing(password, salt) # Try to login user with password # Raises InvalidAuthIdError if user is not found # Raises InvalidPasswordError if provided password # doesn't match with specified user user = User.get_by_auth_id(auth_id) if not user: raise endpoints.BadRequestException('Password/Username Do Not Match') if not security.check_password_hash(password, user.password): raise endpoints.BadRequestException('Password/Username Do Not Match') else: self.user_apikey = ApiKeys.get_apikey_by_user_id(user.key.id()).key.id() return LoginResponse(apikey=self.user_apikey)
def validate(self): validated = super(EditUserForm, self).validate() if self.name.data != User.make_valid_name(self.name.data): self.name.errors.append( 'This name has invalid characters. ' 'Please use letters, numbers, dots and underscores only.') validated = False return validated
def validate(self): validated = super(SignupForm, self).validate() if self.nickname.data != User.make_valid_nickname(self.nickname.data): self.nickname.errors.append(lazy_gettext( 'This nickname has invalid characters. ' 'Please use letters, numbers, dots and underscores only.')) validated = False return validated
def testCreateConversation(self): c, msg = User.add_new_conversation(self.u1.username, self.u2.username, title_plain_text, content_plain_text) conv = c.key.get() self.assertEqual(conv.title, title_plain_text, 'new conversation title') self.assertEqual(conv.messages[0].content, content_plain_text, 'new conversation message')
def register_user(): i = ctx.request.input(name='', email='', password='') name = i.name.strip() email = i.email.strip().lower() password = i.password if not name: raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not password or not _RE_MD5.match(password): raise APIValueError('password') user = User.find_first('where email=?', email) if user: raise APIError('register:failed', 'email', 'Email is already in use.') user = User(name=name, email=email, password=password, image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email).hexdigest()) user.insert() cookie = make_signed_cookie(user.id, user.password, None) ctx.response.set_cookie(_COOKIE_NAME, cookie) return user
def connection_update(self, request): # Create New Connection DB Instance self.header_dict = self.parse_header(self.request_state.headers._headers) if request.apikey: self.apikey_model = ApiKeys.get_apikey_by_id(request.apikey) if self.apikey_model is None: return ConnectionUpdateResponse(message="the API key provided is no longer valid") else: self.update_connection_model = Connection.get_connection_by_id(request.connection_id) self.user_model = User.get_user_by_id(self.apikey_model.user_id) self.update_connection_model.user_name = self.user_model.name self.update_connection_model.user_key = self.user_model.key self.apikey_model.total_calls += 1 self.apikey_model.put() else: return ConnectionAddResponse(message="you must provide an API key") if self.update_connection_model is None: return ConnectionUpdateResponse(message="ID not found: %s" % request.connection_id) if request.personthing_id: request.personthing_name = self.personthing_model.name self.update_connection_model.personthing_key = self.personthing_model.key if request.media: self.update_connection_model.media = request.media if request.type is not None: self.update_connection_model.type = request.type if request.title is not None: self.update_connection_model.title = request.title if request.summary is not None: self.update_connection_model.summary = request.summary if request.body is not None: self.update_connection_model.body = request.body if request.primary_media is not None: self.update_connection_model.primary_media = request.primary_media if request.connection_stage is not None: self.update_connection_model.connection_stage = request.connection_stage if request.personthing_name is not None: self.update_connection_model.personthing_name = request.personthing_name if request.request_reason is not None: self.update_connection_model.request_reason = request.request_reason if request.private_location is not None: self.update_connection_model.private_loc = request.private_location if request.personalized_message is not None: self.update_connection_model.personalized_message = request.personalized_message self.update_connection_model.uastring = self.header_dict['user-agent'] self.update_connection_model.ip = self.request_state.remote_address update_connection_key = self.update_connection_model.put() return ConnectionUpdateResponse(message="successfully updated connection", update_connection_id = update_connection_key.id())
def validate(self): validated = super(CreateUserForm, self).validate() if self.name.data != User.make_valid_name(self.name.data): self.name.errors.append( 'This name has invalid characters. ' 'Please use letters, numbers, dots and underscores only.') validated = False user = User.query.filter(User.email==self.email.data).first() if user: self.email.errors.append('This email is already used.') validated = False return validated
def validate(self): ucontr = UserController() validated = super().validate() if ucontr.read(nickname=self.nickname.data).count(): self.nickname.errors.append('Nickname already taken') validated = False if self.nickname.data != User.make_valid_nickname(self.nickname.data): self.nickname.errors.append(lazy_gettext( 'This nickname has invalid characters. ' 'Please use letters, numbers, dots and underscores only.')) validated = False return validated
def create_user(self, user=None): """ Create or Update User """ if user: user.h_id = self.data['_id'] else: user = User(name=slugify(self.data.get('name')), email=self.data.get('email'), pwdhash=generate_password_hash( generate_random_password(8)), h_id=self.data.get('_id'), is_active=True) flash('Your account has been created. ', 'success') if self.user_profile: user.image = self.user_profile.get('image') user.organization = self.user_profile.get('organization') db.session.add(user) db.session.commit() return user
def login(): error = None if request.method == 'POST': user = User(current_app) username = request.form['name'] password = request.form['password'] userdata = user.check(username) if len(userdata) > 0: userdata = userdata[0] salt = userdata["salt"] password = md5(md5(password).hexdigest() + salt).hexdigest() if userdata["passwd"] == password: session['uid'] = userdata["uid"] session['username'] = userdata["username"] user.edit(uid=userdata["uid"], lastlogintime=int(time.time())) return redirect(url_for('home.index')) else: error = u'用户名或者密码错误' else: error = u'没有找到此用户' error = (request.args.get("error") is not None) and request.args.get("error") or error return render_template('login.html', error=error)
def search_add(self, request): # Create New Connection DB Instance self.header_dict = self.parse_header(self.request_state.headers._headers) index = search.Index(name="alcindex_01") try: self.user_key = User.get_user_by_id(request.user_id) except: return SearchAddResponse(message="user_id is a required field") search_document_dictionary = {} if request.user_id: self.user_model = User.get_user_by_id(request.user_id) if self.user_model is not None: search_document_dictionary['user_name'] = self.user_model.name else: return SearchAddResponse(message="provided user id did not match") else: search_document_dictionary['user_name'] = None if request.personthing_id: self.personthing_model = PeopleThing.get_person_by_id(request.personthing_id) search_document_dictionary['personthing_name'] = self.personthing_model.name else: search_document_dictionary['personthing_name'] = None search_document_dictionary['type'] = request.type search_document_dictionary['title'] = request.title search_document_dictionary['blog_title'] = request.blog_title search_document_dictionary['summary'] = request.summary search_document_dictionary['tags'] = request.tags search_document_dictionary['latitude'] = request.latitude search_document_dictionary['longitude'] = request.longitude search_document_dictionary['body'] = request.body new_search_doc_id = self.search_doc_create(search_document_dictionary, index) return SearchAddResponse(message="successfully added connection", new_search_id = new_search_doc_id[0].id)
def validate(self): validated = super(ProfileForm, self).validate() if self.password.data != self.password_conf.data: message = lazy_gettext("Passwords aren't the same.") self.password.errors.append(message) self.password_conf.errors.append(message) validated = False if self.nickname.data != User.make_valid_nickname(self.nickname.data): self.nickname.errors.append(lazy_gettext('This nickname has ' 'invalid characters. Please use letters, numbers, dots and' ' underscores only.')) validated = False return validated
def signup(): """ Signup page. """ if int(os.environ.get("SELF_REGISTRATION", 0)) != 1: flash(gettext("Self-registration is disabled."), 'warning') return redirect(url_for('home')) if g.user is not None and g.user.is_authenticated: return redirect(url_for('home')) form = SignupForm() if form.validate_on_submit(): role_user = Role.query.filter(Role.name == "user").first() user = User(nickname=form.nickname.data, email=form.email.data, pwdhash=generate_password_hash(form.password.data)) user.roles = [role_user] db.session.add(user) try: db.session.commit() except IntegrityError: flash(gettext('Email already used.'), 'warning') return render_template('signup.html', form=form) # Send the confirmation email try: notifications.new_account_notification(user) except Exception as error: flash(gettext('Problem while sending activation email: %(error)s', error=error), 'danger') return redirect(url_for('home')) flash(gettext('Your account has been created. ' 'Check your mail to confirm it.'), 'success') return redirect(url_for('home')) return render_template('signup.html', form=form)
def createUser(request): if request.method != 'POST': raise Exception('Cannot GET {0}'.format(request.path)) print >> sys.stderr, request.POST code = generateRandomCode() user = User( code = code, name = '', cha = request.POST['cha'], con = request.POST['con'], dex = request.POST['dex'], int = request.POST['int'], str = request.POST['str'], wis = request.POST['wis'], role = request.POST['role']) user.save() response = { 'success': True, 'id': user.id } return HttpResponse(json.dumps(response), content_type='application/json')
def index(page=1): user = User(current_app) filte = None if request.method == "POST": error = None action = request.form.get("do") if action == "delete": uids = request.form.getlist("uid[]") if len(uids) > 0: for uid in uids: if uid: user.remove(uid) return redirect(url_for('users.index')) else: error = "请选择要删除的数据" return error if request.args.get("keywords"): filte = "username='******'" users = user.list(page, PER_PAGE, filte) if not users and page != 1: abort(404) count = user.totalcount() pagination = Pagination(page, PER_PAGE, count) return render_template("user/list.html", pagination=pagination, users=users)
def authenticate(): i = ctx.request.input(remember='') email = i.email.strip().lower() password = i.password remember = i.remember user = User.find_first('where email=?', email) if user is None: raise APIError('auth:failed', 'email', 'Invalid email.') elif user.password != password: raise APIError('auth:failed', 'password', 'Invalid password.') max_age = 604800 if remember == 'true' else None cookie = make_signed_cookie(user.id, user.password, max_age) ctx.response.set_cookie(_COOKIE_NAME, cookie, max_age=max_age) user.password = '******' return user
def signup(): """ Signup page. """ form = SignupForm() if form.validate_on_submit(): role_user = Role.query.filter(Role.name == "user").first() user = User(firstname=form.firstname.data, lastname=form.lastname.data, email=form.email.data, pwdhash=generate_password_hash(form.password.data)) user.roles = [role_user] db.session.add(user) try: db.session.commit() except IntegrityError: flash('Email already used.', 'warning') return render_template('signup.html', form=form) flash('Your account has been created. You can now sign in.', 'success') return redirect(url_for('login')) return render_template('signup.html', form=form)
def parse_signed_cookie(cookie_str): try: L = cookie_str.split('-') if len(L) != 3: return None id, expires, md5 = L if int(expires) < time.time(): return None user = User.get(id) if user is None: return None if md5 != hashlib.md5('%s-%s-%s-%s' % (id, user.password, expires, _COOKIE_KEY)).hexdigest(): return None return user except: return None