def test_create_event(): from server.models.event import Event from server.models.user import User with client() as c: user1 = User.find(key='test') user2 = User.find(key='test2') create_event(c, user1, 'test event') resp = api_get(c, user1, '/api/events/') assert resp.status_code == 200, 'oops {}'.format(resp.data) data = ujson.loads(resp.data) assert data['objects'][0]['name'] == 'test event' assert data['objects'][0]['group'] == {'$ref': 'Group:1'} event_id = data['objects'][0]['id'] event = Event.find(event_id) assert user1.is_attending(event), 'user is attending the new event' assert 1 == Event.select().count() event_id = create_event(c, user1, 'test event 2') user1 = User.find(key='test') assert user1.get_attending_id() == event_id assert 2 == Event.select().count(), '2 events total now' count, page, results = Event.select().group(user1.group).execute() assert 1 == count, 'only 1 in the group though, since the other has no attendees now' assert results[0].name == 'test event 2'
def setUp(self): super().setUp() self.success_test_params_user = [{ KEY_INPUT: json.dumps({"token": "google_oauth_token"}), KEY_DATABASE: User(oauth_id="google", name="Test User", username="******", email="*****@*****.**") }, { KEY_INPUT: json.dumps({"token": "google_oauth_token"}), KEY_DATABASE: User(oauth_id="google", name="Test User", email="*****@*****.**") }, { KEY_INPUT: json.dumps({"token": "google_oauth_token"}), KEY_DATABASE: User(oauth_id="google", name="Other user", email="*****@*****.**") }] self.fail_test_params_user = [ { KEY_INPUT: json.dumps({"token": "google_oauth_token"}), KEY_EXPECTED: "Invalid Value", }, { KEY_INPUT: "{bad_json_string}", KEY_EXPECTED: "Malformed request", }, ]
def capture_interaction(user_id, with_user_id, t, action='view'): if not client: return logger.debug('capturing prediction event data between {} and {}'.format( user_id, with_user_id)) user = User.find(user_id) with_user = User.find(with_user_id) tz = timezone(with_user.group.timezone) event_time = t.replace(tzinfo=UTC).astimezone(tz) r = client.set_user( user_id, event_time=user.created.replace(tzinfo=UTC).astimezone(tz)) if r.status not in (200, 201): raise Exception('Error returned from prediction io') r = client.set_item( with_user_id, {'categories': [str(with_user.group_id)]}, event_time=with_user.created.replace(tzinfo=UTC).astimezone(tz)) if r.status not in (200, 201): raise Exception('Error returned from prediction io') r = client.record_user_action_on_item(action, user_id, with_user_id, event_time=event_time) if r.status not in (200, 201): raise Exception('Error returned from prediction io')
def notify_on_friend(user_id, friend_id, accepted): user = User.find(user_id) friend = User.find(friend_id) if not accepted: message_text = '{} wants to be your friend on Wigo'.format(user.full_name.encode('utf-8')) else: message_text = '{} accepted your friend request'.format(user.full_name.encode('utf-8')) notification = Notification({ 'user_id': friend_id, 'type': 'friend.request' if not accepted else 'friend.accept', 'from_user_id': user.id, 'navigate': '/users/{}'.format(user_id) if accepted else '/find/users/user/{}'.format(user_id), 'badge': 1, 'message': message_text }) if accepted: notification.save() send_notification_push.delay(notification.to_primitive()) else: __send_notification_push(notification) # for imported users from wigo1, send them a push saying their friend just joined wigo2 if friend.status == 'imported': notification = Notification({ 'user_id': friend_id, 'type': 'system', 'message': '{} added you to {} Wigo Summer friend list. Update Wigo now!'.format( user.full_name.encode('utf-8'), ('his' if user.gender == 'male' else 'her' if user.gender == 'female' else 'their')) }) __send_notification_push(notification, api_version_num=1)
def new_friend(user_id, friend_id): user = User.find(user_id) friend = User.find(friend_id) if not user.is_friend(friend): return min = epoch(datetime.utcnow() - timedelta(days=8)) # tells each friend about the event history of the other def capture_history(u, f): # capture each of the users posted photos with wigo_db.transaction(commit_on_select=False): for message in EventMessage.select().key(skey( u, 'event_messages')).min(min): if message.user and message.event: message.record_for_user(f) # capture the events being attended for event in Event.select().user(u).min(min): if u.is_attending(event) and f.can_see_event(event): event.add_to_user_attending(f, u) capture_history(user, friend) capture_history(friend, user)
def register(): data = request.get_json() new_user = User(**data) db.session.add(new_user) db.session.commit() return jsonify(new_user.to_dict()), 201
def create_user(_): """ Creates a new User. --- tags: - user summary: Create User requestBody: content: application/json: schema: $ref: '#/components/schemas/User' description: Created user object required: true responses: default: description: successful operation 400: description: email already exists """ data = request.get_json() if not data: raise BadRequest() data["password"] = bcrypt.generate_password_hash( data["password"], current_app.config.get("BCRYPT_LOG_ROUNDS")).decode() user = User(**data) user.save() res = {"status": "success", "message": "user was added!"} return res, 201
def test_decode_auth_token(self): user = User(username='******', email='*****@*****.**', password='******') auth_token = user.encode_auth_token(1) self.assertTrue(isinstance(auth_token, bytes)) self.assertTrue( User.decode_auth_token(auth_token.decode("utf-8")) == 1)
def renew_database(): from werkzeug.security import generate_password_hash, check_password_hash Chat.objects.delete() Message.objects.delete() User.objects.delete() user1 = User(name="user1", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() user2 = User(name="user2", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() user3 = User(name="user3", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() user4 = User(name="user4", email='*****@*****.**', password=generate_password_hash("test", method='sha256')).save() chat1 = ChatCreation.create_new(members=[user1, user2]) chat2 = ChatCreation.create_new(members=[user1, user3]) Message(text="Zprava user1", author=user1, chat=chat1).save() Message(text="Zprava user2", author=user2, chat=chat1).save() Message(text="Zprava user1", author=user1, chat=chat1).save() Message(text="Zprava user1 chat 2", author=user1, chat=chat2).save() Message(text="Zprava user2 chat2", author=user3, chat=chat2).save()
def test_thing(self): User(name="test1", email="*****@*****.**", password=os.urandom(16)).save() user = User.objects().first() self.assertEqual(user.name, 'test1') user = User.objects(name="test1").get() self.assertEqual(user.name, 'test1')
def post(self): form = UserCreateForm() if not form.validate_on_submit(): return form.errors, 422 # check invitation code if form.invite.data != app.config["INVITE_CODE"]: return "Wrong invitation code.", 410 # check if user already exists before trying to create user = User.query.filter_by(email=form.email.data).first() if user is not None: return "User already exists.", 401 # create user user = User(form.email.data, form.password.data) db.session.add(user) db.session.commit() serialized_user = UserSerializer(user).data # the first user created should have admin rights if user.id == 1: user.role = "admin" db.session.commit() # log user login_user(user, remember=True) # send confirmation email send_welcome_email(user.email) return serialized_user, 201
def create_conversations(): user1 = User.objects(name="test").first() user2 = User.objects(name="test2").first() try: ChatCreation.create_new(members=[user1, user2]) conv1 = Chat.objects(members=[user1, user2]).first() Message(text="Testovací zpráva autora test", author=user1, chat=conv1).save() Message(text="Testovací zpráva autora test3", author=user2, chat=conv1).save() Message(text="1. Testovací zpráva autora test", author=user1, chat=conv1).save() m1 = Message(text="3. Testovací zpráva autora test", author=user1, chat=conv1).save() conv1.update(last_message_date=m1.date_created) except Exception as e: print(str(e))
def admin_reset_user_pin(user: User): pin_reset_token = user.encode_single_use_JWS('R') user.save_pin_reset_token(pin_reset_token) user.failed_pin_attempts = 0 pin_reset_message = i18n_for(user, "general_sms.pin_reset") send_message(user.phone, pin_reset_message)
def post(self): form = UserCreateForm() if not form.validate_on_submit(): return form.errors, 422 # check invitation code if form.invite.data != app.config["INVITE_CODE"] : return "Wrong invitation code.", 410 # check if user already exists before trying to create user = User.query.filter_by(email=form.email.data).first() if user is not None: return "User already exists.", 401 # create user user = User(form.email.data, form.password.data) db.session.add(user) db.session.commit() serialized_user = UserSerializer(user).data # the first user created should have admin rights if user.id == 1: user.role = "admin" db.session.commit() # log user login_user(user, remember=True) # send confirmation email send_welcome_email(user.email) return serialized_user, 201
def test_private_event(): from server.models.event import Event, EventAttendee from server.models.user import User with client() as c: user1 = User.find(key='test') user2 = User.find(key='test2') make_friends(c, user1, user2) event_id = create_event(c, user1, 'test event 1', privacy='private') assert 1 == Event.select().count() assert 0 == Event.select().group(user1.group).count() assert 1 == Event.select().user(user1).count() assert 0 == Event.select().user(user2).count() event = Event.find(event_id) resp = api_post(c, user1, '/api/events/{}/invites'.format(event_id), {'invited_id': user2.id}) assert resp.status_code == 200, 'oops {}'.format(resp.data) assert 1 == Event.select().user(user2).count() count, page, results = EventAttendee.select().event(event).user( user2).execute() assert count == 1 assert results[0] == user1
def create_user(self, data=user): ''' Function that presists a User in the database for the test ''' user = User(email=data['email']) user.set_password('1234') db.session.add(user) db.session.flush()
def decorator(*args, **kwargs): auth_token = request.headers.get("Authorization") if not auth_token: raise Unauthorized username = User.decode_auth_token(auth_token) user = User.findOne(username=username) if not user: raise Unauthorized() return f(username, *args, **kwargs)
def get_client(email): user = User.query.filter_by(email=email).first() if user is None: user = User(None, email) else: user.sign_in() client = Client(user) if (add_to_db(client, others=[user], rollbackfunc=lambda:client.generate_uniques())): return client return None
async def create_new_user(user_input: UserInput): new_user = User(username=user_input.username, hashed_password=get_password_hash( user_input.plain_password)) new_user_dict = new_user.dict() user = await write_new_user_in_db(new_user_dict) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token(data={"sub": user["username"]}, expires_delta=access_token_expires) return {"access_token": access_token, "token_type": "bearer"}
def tell_friend_user_not_attending(user_id, event_id, friend_id): try: user = User.find(user_id) event = Event.find(event_id) friend = User.find(friend_id) except DoesNotExist: return if not user.is_attending(event): event.remove_from_user_attending(friend, user)
def register(): if current_user.is_authenticated: return redirect(url_for('home.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() return redirect(url_for('home.login')) return render_template('register.html', title='Register', form=form)
def user(session, request): user = User(username='******', email='*****@*****.**') user.set_password('password') session.add(user) session.commit() def teardown(): session.delete(user) session.commit() request.addfinalizer(teardown) return user
def create(user_id: int, first_name: str, last_name: str) -> dict: """ Create a user info entry """ try: user = UserInfo(user_id=user_id, first_name=first_name, last_name=last_name) user.save() user.flush() except IntegrityError: User.rollback() return None return user
def tell_friend_user_attending(user_id, event_id, friend_id, notify=True): try: user = User.find(user_id) event = Event.find(event_id) friend = User.find(friend_id) except DoesNotExist: return if user.is_attending(event): event.add_to_user_attending(friend, user) if notify: friend_attending.send(None, event=event, user=friend, friend=user)
def user_invited(event_id, inviter_id, invited_id): try: event = Event.find(event_id) inviter = User.find(inviter_id) invited = User.find(invited_id) except DoesNotExist: return # make sure i am seeing all my friends attending now for friend in invited.friends_iter(): if friend.is_attending(event): event.add_to_user_attending(invited, friend)
def new_sempo_admin_user(test_client, init_database, create_organisation): from server.models.user import User user = User() user.create_admin_auth(email='*****@*****.**', password='******', tier='sempoadmin') user.organisations.append(create_organisation) user.default_organisation = create_organisation db.session.add(user) # Commit so it gets an ID db.session.commit() return user
def test_user_model(session): user = User( username='******', email='*****@*****.**', ) user.set_password('password') session.add(user) session.commit() assert(user.id > 0) assert(user.check_password('password'))
def post(self): from server.models.user import User, db username = request.json.get('username') password = request.json.get('password') if username is None or password is None: return {"error": "Missing arguments"} if User.query.filter_by(username=username).first() is not None: return {"error": "Already existing user"} user = User(username=username) user.hash_password(password) db.session.add(user) db.session.commit() return {'username': user.username}
def post_chats_add(): title = request.get_json()['title'] members = request.get_json()['members'] cur_user = User.objects(id=current_user["id"]).first() chat_members = [] for member in members: user = User.objects(name=member["label"], email=member["value"]).first() if cur_user.id == user.id: return jsonify({ "success": False, "message": "It is not allowed to chat with yourself".format(member) }), 400 if user is None: return jsonify({ "success": False, "message": "User not exists {}".format(member) }), 200 chat_members.append(user) chat_members.append(cur_user) try: new_chat = ChatCreation.create_new(title=title, members=chat_members).save() except: return jsonify({ "success": False, "message": "Chat with same users already exist" }), 400 return jsonify({ "success": True, "message": "New chat created, title: {}, members: {}".format( new_chat.title, new_chat.members), "chat": { "members": ",".join([m.name for m in chat_members]), "title": new_chat.title, "id": str(new_chat.id) } }), 200
def sendgrid_hook(): data = request.get_data() or request.form.get('data') or '' if not data: abort(400, message='JSON post data invalid') try: data = ujson.loads(data) except ValueError: abort(400, message='JSON post data invalid') for record in data: event = record.get('event') user = None user_id = record.get('user_id') if user_id: try: user = User.find(user_id) except DoesNotExist: pass if not user: try: user = User.find(email=record.get('email')) except DoesNotExist: pass # only update the user if not validated already, since if they are validated # the email_validated_status will be set if user and not user.email_validated: event = record.get('event') existing_event = user.email_validated_status # make sure events progress forward, don't allow "delivered"->"processed" sg_evt_ord = [ 'processed', 'dropped', 'deferred', 'delivered', 'bounce', 'open', 'click', 'unsubscribe', 'spamreport' ] if event in sg_evt_ord and existing_event in sg_evt_ord and \ sg_evt_ord.index(existing_event) >= sg_evt_ord.index(event): continue logger.info('updating email validation status for user "%s", %s' % (user.email, event)) user.email_validated_status = event user.save() return jsonify(success=True)
def registration_view(request): """Registration view This function get email and password from json request, check if email isn't in db - add email and password into db, set status_id to 'Non_active', generate and send url-token to user email. """ json = request.json_body user_query = User.get_user_by_email(request, request.json['email']) nickname_query = User\ .get_user_by_nickname(request, request.json['nickname']) if user_query is None: if nickname_query is None: url_token_confirmation = generate_secret() if json['repeat_password'] == json['password']: User.add_user(request, email=request.json['email'], nickname=request.json['nickname'], password=pbkdf2_sha256.hash( request.json['password']), url_token=url_token_confirmation, status_id=UserStatus.get_user_by_status( request, status="Non_active").id, create_date=datetime.now()) mailer = request.mailer message = Message( subject="confirm email", sender="*****@*****.**", recipients=[json['email']], body='http://localhost:3000/#/email_confirm/{}'.format( url_token_confirmation)) mailer.send_immediately(message, fail_silently=False) return {"msg": "We sent token to your email address"} else: return { "msg": "Invalid password, please try again", "error": "password", } else: return { "msg": "Your nickname is taken, please choose another", "error": "nickname", } else: return { "msg": "Your email address is already registered", "error": "email", }
def post(self): args = self.reqparse.parse_args() user = User.authenticate(args) if user: login_user(user) return dict(user=user.name()), 200 return 'Invalid username or password', 400
def post(self): args = self.reqparse.parse_args() user = User.query.filter_by(username=args['username']).first() session.clear() if user: if User.verify_password(user, args['password']): session['user_id'] = user.id return {'user_id': user.id, 'message': 'Logged in successfully'}, 201 return 'Invalid username or password', 400
def register(): if request.method == 'POST': status,ret = User.register(request.form['email'],request.form['pw']) if status: session['user_id'] = ret.id return redirect(url_for('user.settings')) return render_template('register.html', email_error=ret) return render_template('register.html')
def register_view(self): form = RegistrationForm(request.form) if helpers.validate_form_on_submit(form): user = User() form.populate_obj(user) # we hash the users password to avoid saving it as plaintext in the db, # remove to use plain text: user.password = generate_password_hash(form.password.data) db.session.add(user) db.session.commit() login_user(user) return redirect(url_for('.index')) link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(MyAdminIndexView, self).index()
def test_authenticate_with_valid_params_returns_user(self): user = user_datastore.create_user( email='*****@*****.**', password=encrypt_password('example'), first_name='Colossus', last_name='Zadeh' ) db.session.commit() result = User.authenticate(dict( email='*****@*****.**', password='******' )) self.assertEquals(result, user)
def Auth(form): return User.login(form['email'],form['pw'])