Exemplo n.º 1
0
    def test_signup_page_flow(self):
        # Check that things are empty
        self.assertLength(0, Profile.all())

        # Sign up with the form
        response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
        self.assertRedirects(response, self.uri_for('dashboard', tour=''))

        # Check that we are actually logged in
        response = self.app.get(response.location)
        self.assertLoggedIn()

        # Check that one of everything was created
        self.assertLength(1, Profile.all())

        profile = Profile.all().get()

        # Check the basic data
        self.assertEqual(self.SIGNUP_DATA['email'], profile.email)
        self.assertEqual(self.SIGNUP_DATA['name'], profile.name)

        # Logout and log back in to test that the password works
        self.logout()
        response = self.login(self.SIGNUP_DATA['email'],
                              self.SIGNUP_DATA['password'])
        self.assertRedirects(response, self.uri_for('dashboard'))
Exemplo n.º 2
0
  def test_signup_sends_welcome_email(self):
    # Sign up successfully
    response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
    self.assertRedirects(response, self.uri_for('dashboard', tour=''))

    # Check that a profile was created
    profile = Profile.get_by_email(self.SIGNUP_DATA['email'])
    self.assertIsNotNone(profile)

    # Check that a mail-sending task is in the queue
    tasks = self.taskqueue_stub.GetTasks('mail')
    self.assertLength(1, tasks)

    # Run the task (it should be a deferred call) and check that an e-mail
    # is sent
    task, = tasks
    deferred.run(base64.b64decode(task['body']))
    messages = self.mail_stub.get_sent_messages()
    self.assertLength(1, messages)

    message, = messages
    self.assertEqual('"%s" <%s>' % (profile.name, profile.email), message.to)
    self.assertEqual('Welcome to Daily Meeting!', message.subject)
    self.assertEqual('"Daily Meeting" <*****@*****.**>',
                     message.sender)
    self.assertEqual('"Daily Meeting Support" <*****@*****.**>',
                     message.reply_to)
    activation_key = Profile.all().get().activation_key
    activation_url = self.uri_for('profile.activate', k=activation_key)
    self.assertIn(activation_url, message.body.decode())
    self.assertIn(activation_url, message.html.decode())
Exemplo n.º 3
0
    def get(self):
        user = self.get_current_user()
        created, profile = Profile.get_or_create_from_user(user)

        followers = Follow.who_subscribe_you(user)
        follower_profiles = []
        for f in followers:
            c, p = Profile.get_or_create_from_user(f.from_user)
            follower_profiles.append(p)
        followees = Follow.your_subscribers(user)
        followee_profiles = []
        for f in followees:
            c, p = Profile.get_or_create_from_user(f.to_user)
            followee_profiles.append(p)
        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        pagesize = settings.BLIP_PAGE_SIZE
        paginator = SimplePaginator(BlipLink.qs_for_user(user),
                                    page, pagesize)
        blips = each_profiles(paginator.object_list, field='author')
        is_self = True
        return self.render('home.html', locals())
Exemplo n.º 4
0
    def test_signup_sends_welcome_email(self):
        # Sign up successfully
        response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
        self.assertRedirects(response, self.uri_for('dashboard', tour=''))

        # Check that a profile was created
        profile = Profile.get_by_email(self.SIGNUP_DATA['email'])
        self.assertIsNotNone(profile)

        # Check that a mail-sending task is in the queue
        tasks = self.taskqueue_stub.GetTasks('mail')
        self.assertLength(1, tasks)

        # Run the task (it should be a deferred call) and check that an e-mail
        # is sent
        task, = tasks
        deferred.run(base64.b64decode(task['body']))
        messages = self.mail_stub.get_sent_messages()
        self.assertLength(1, messages)

        message, = messages
        self.assertEqual('"%s" <%s>' % (profile.name, profile.email),
                         message.to)
        self.assertEqual('Welcome to Daily Meeting!', message.subject)
        self.assertEqual('"Daily Meeting" <*****@*****.**>',
                         message.sender)
        self.assertEqual(
            '"Daily Meeting Support" <*****@*****.**>',
            message.reply_to)
        activation_key = Profile.all().get().activation_key
        activation_url = self.uri_for('profile.activate', k=activation_key)
        self.assertIn(activation_url, message.body.decode())
        self.assertIn(activation_url, message.html.decode())
Exemplo n.º 5
0
  def create_profile(cls, email=None, password=None, beta_tester=True,
                     is_admin=False, is_manager=False, is_editor=False,
                     activated=True, account=None):
    # TODO: Move this into a top level function (testing.create_profile)
    # Use defaults if anything here is missing.
    UserModel = cls.get_auth().store.user_model

    if not email:
      # Generate an e-mail that should be unique...
      email = '%s-%s' % (UserModel.query().count(), cls.DEFAULT_EMAIL)
    password = password or cls.DEFAULT_PASSWORD

    # Create the auth.user_model.
    ok, user = UserModel.create_user(email, password_raw=password)

    if not ok:
      raise Exception('Error creating auth.User: %s' % email)

    if not account:
      account = cls.create_account()

    # Create the profile.
    profile = Profile(name=cls.DEFAULT_PROFILE_NAME, is_admin=is_admin,
                      is_manager=is_manager, is_editor=is_editor,
                      email=email, beta_tester=beta_tester,
                      activated=activated, auth_user_id=user.key.id(),
                      timezone='UTC', parent=account)
    profile.put()

    # Return the profile (we can get everything else with that)
    return profile
Exemplo n.º 6
0
    def post(self):
        photo = str(self.request("photo"))
        user_name = self.request("user_name")
        first_name = self.request("first_name")
        last_name = self.request("last_name")
        twitter = self.requst("twitter")

        user = App.session.get('profile')

        if user:
            invalidFieldFlag = False
            if len(user_name.strip()) == 0:
                ProfileHandler.invalidUser_Name = True
                invalidFieldFlag = True
            if len(first_name.strip()) == 0:
                ProfileHandler.invalidFirst_Name = True
            if len(last_name.strip()) == 0:
                ProfileHandler.invalidLast_Name = True
            if not invalidFieldFlag:
                ProfileHandler.invalidUser_Name = ProfileHandler.invalidFirst_Name = ProfileHandler.invalidLast_Name = False

                user_id = user['user_id']
                new_profile = Profile(parent=App.DEFAULT_KEY)
                new_profile.user_name = user_name
                new_profile.first_name = first_name
                new_profile.last_name = last_name
                new_profile.photo = photo
                new_profile.photo_key = uuid.uuid4().hex
                new_profile.user_id = user_id

                new_profile.put()
            self.redirect("/#profiles")
        else:
            self.redirect("#login")
Exemplo n.º 7
0
    def get(self, blip_key=None):
        blip = Blip.get(blip_key)
        if blip is None:
            return self.error(404)
        login_user = self.get_current_user()
        if blip.meeting and not blip.meeting.has_member(login_user):
            return self.error(401)
        user = blip.user
        _, profile = Profile.get_or_create_from_user(user)

        is_self = user == login_user

        has_followed = False
        if not is_self:
            has_followed = Follow.gql('WHERE from_user = :1 AND to_user = :2',
                                      login_user, user).get() is not None            

        followers = Follow.who_subscribe_you(user)
        follower_profiles = []
        for f in followers:
            c, p = Profile.get_or_create_from_user(f.from_user)
            follower_profiles.append(p)
        followees = Follow.your_subscribers(user)
        followee_profiles = []
        for f in followees:
            c, p = Profile.get_or_create_from_user(f.to_user)
            followee_profiles.append(p)


        return self.render('blip_item.html', locals())
Exemplo n.º 8
0
    def get(self, artist_id):
        # artist_id may be a profile_unique_name or an application_user_id
        profile_obj = Profile.get_profile_by_profile_unique_name(artist_id)
        if profile_obj is not None:
            application_user_id = profile_obj.application_user_id
            user_obj = User.get_user_by_application_user_id(application_user_id)
            if user_obj is None:
                # TODO : All profiles should have a user associated with them. Log or handle the event where there is no User associated with a profile.
                # There is no user associated with the profile!
                pass
        else:
            user_obj = User.get_user_by_application_user_id(artist_id)
            if user_obj is not None:
                profile_obj = Profile.get_profile_by_application_user_id(user_obj.application_user_id)

        if user_obj is not None:
            self.template_values['user_exists'] = True
            self.template_values['artist_name'] = user_obj.first_name + ' ' + user_obj.last_name
            if profile_obj is not None:
                self.template_values['profile_unique_name'] = profile_obj.profile_unique_name
                if profile_obj.bio is not None and not re.match(r"^\s*$", profile_obj.bio):
                    self.template_values['profile_bio'] = profile_obj.bio
                if profile_obj.profile_picture is not None:
                    self.template_values['profile_picture'] = profile_obj.profile_picture
            art_objs = Art.get_art(user_obj.application_user_id)
            art_list = list()
            for art_obj in art_objs:
                art_list.append({'art_obj': art_obj})
            self.template_values['art_list'] = art_list
            self.template_values['artist_image_count'] = len(self.template_values['art_list'])
        else:
            self.template_values['user_exists'] = False

        template = self.get_template('templates/artist_content.html')
        self.response.write(template.render(self.template_values))
Exemplo n.º 9
0
def UploadImg():

    if request.method != 'POST':
        return jsonify({'response': {'msg': 'NOT POST'}}), 400
    if not request.files['profilePic']:
        return jsonify({'response': {'msg': 'No File Was Uploaded'}}), 400
    if not is_image(request.files['profilePic'].content_type):
        return jsonify({'response': {'msg': 'Bad File Type'}}), 400

    # user = kwargs['user']
    img = request.files['profilePic']
    FILE_NAME = img.filename
    BUCKET_NAME = "chef-booking"

    # S3 Connect
    s3 = boto3.resource('s3',
                        aws_access_key_id=S3_ACCESS_KEY_ID,
                        aws_secret_access_key=S3_ACCESS_SECRET_KEY,
                        config=Config(signature_version='s3v4'))

    # Image Uploaded
    s3.Bucket(BUCKET_NAME).put_object(Key='%s/%s' %
                                      ("*****@*****.**", FILE_NAME),
                                      Body=img,
                                      ACL='public-read')
    msg = 'File Was Uploaded Successfully.'

    #save url
    url = 'https://%s.s3.amazonaws.com/%s' % (BUCKET_NAME, FILE_NAME)

    Profile.update(1, **{'profile_image': url})

    return jsonify({'response': {'url': url, 'msg': msg}}), 200
Exemplo n.º 10
0
  def test_signup_page_flow(self):
    # Check that things are empty
    self.assertLength(0, Profile.all())

    # Sign up with the form
    response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
    self.assertRedirects(response, self.uri_for('dashboard', tour=''))

    # Check that we are actually logged in
    response = self.app.get(response.location)
    self.assertLoggedIn()

    # Check that one of everything was created
    self.assertLength(1, Profile.all())

    profile = Profile.all().get()

    # Check the basic data
    self.assertEqual(self.SIGNUP_DATA['email'], profile.email)
    self.assertEqual(self.SIGNUP_DATA['name'], profile.name)

    # Logout and log back in to test that the password works
    self.logout()
    response = self.login(self.SIGNUP_DATA['email'],
                          self.SIGNUP_DATA['password'])
    self.assertRedirects(response, self.uri_for('dashboard'))
Exemplo n.º 11
0
    def test_init_method(self):
        """
        tests the __init__ method for instantiating new objects
        both new and from kwargs
        __init__ method calls on inherited BaseModel with super()
        """
        # creates new instance of Profile
        new_obj1 = Profile()
        # tests that the new object is of type Profile
        self.assertIs(type(new_obj1), Profile)
        # adds all attributes for testing
        # (id should be set by primary key)
        # (created_at, updated_at should be set by datetime)
        new_obj1.name = "test_name"
        new_obj1.email = "*****@*****.**"
        new_obj1.password = "******"
        new_obj1.company_school_name = "123"
        new_obj1.about_me = "This is for testing purposes"
        new_obj1.linkedin = "https://www.linkedin.com/in/test"
        new_obj1.social_media = "Social media links would go here"
        # attributes_dict sets up dictionary of attribute names and types
        attributes_dict = {
            "id": str,
            "created_at": datetime,
            "updated_at": datetime,
            "name": str,
            "email": str,
            "password": str,
            "company_school_name": str,
            "about_me": str,
            "linkedin": str,
            "social_media": str
        }
        # loops through attributes_dict as subTests to check each attribute
        for attr, attr_type in attributes_dict.items():
            with self.subTest(attr=attr, attr_type=attr_type):
                # tests the expected attribute is in the object's dict
                self.assertIn(attr, new_obj1.__dict__)
                # tests the attribute is the expected type
                self.assertIs(type(new_obj1.__dict__[attr]), attr_type)
        # sets kwargs using object's dict and uses to create new object
        kwargs = new_obj1.__dict__
        new_obj2 = Profile(**kwargs)
        # tests that the new object is of type Profile
        self.assertIs(type(new_obj2), Profile)
        # loops through attributes_dict as subTests to check each attribute
        for attr, attr_type in attributes_dict.items():
            with self.subTest(attr=attr, attr_type=attr_type):
                # tests the expected attribute is in the object's dict
                self.assertIn(attr, new_obj2.__dict__)
                # tests the attribute is the expected type
                self.assertIs(type(new_obj2.__dict__[attr]), attr_type)
                # tests the value of name attribute matches the original object
                self.assertEqual(new_obj1.__dict__[attr],
                                 new_obj2.__dict__[attr])

        # tests that __class__ is not set in object 2
        self.assertNotIn('__class__', new_obj2.__dict__)
Exemplo n.º 12
0
    def test_signup_with_existing_email(self):
        response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
        self.assertRedirects(response)
        self.assertLength(1, Profile.all())

        response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
        self.assertOk(response)
        self.assertLength(1, Profile.all())

        email_field = response.pyquery('input#email')
        self.assertLength(1, email_field)
        self.assertNotEqual('', email_field.attr['data-error'])
Exemplo n.º 13
0
  def test_signup_with_existing_email(self):
    response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
    self.assertRedirects(response)
    self.assertLength(1, Profile.all())

    response = self.app.post(self.uri_for('signup'), self.SIGNUP_DATA)
    self.assertOk(response)
    self.assertLength(1, Profile.all())

    email_field = response.pyquery('input#email')
    self.assertLength(1, email_field)
    self.assertNotEqual('', email_field.attr['data-error'])
Exemplo n.º 14
0
def endpoint_create(data: dict, user: str) -> dict:
    if "name" not in data or "country" not in data:
        return invalid_request

    name: str = data["name"]
    country: str = data["country"]

    if Profile.exists(user):
        return profile_already_exists

    Profile.create(user, name, country)

    return success
Exemplo n.º 15
0
def run():
    print("---------------------------------------------------------------")
    print("Apply/Remove Vip Status on Profile")
    print("---------------------------------------------------------------")

    i = 1
    for profile in Profile.objects:
        print('{} - {}'.format(i, profile.get_name()))
        i += 1

    try:
        profile_id = int(
            input("Type the profile id you want to change status: "))
        profile = Profile.objects[profile_id - 1]

        if (type(profile) == Profile):
            new_profile = VipProfile(profile.get_name())
        else:
            new_profile = Profile(profile.get_name())

        new_profile.set_likes(profile.get_likes())
        new_profile.save()
        profile.delete()

    except:
        traceback.print_exc()
Exemplo n.º 16
0
    def test_forgot_password_post_sends_email(self):
        self.assertNotLoggedIn()
        profile = self.create_profile()
        response = self.app.get(self.uri_for('forgot-password'))
        form = response.forms['forgot-password']
        form['email'] = profile.email
        response = form.submit()

        # Check the task was put on the mail queue.
        tasks = self.taskqueue_stub.get_filtered_tasks(queue_names='mail')
        self.assertIn('mail', tasks[0].headers['X-AppEngine-QueueName'])
        task, = tasks
        deferred.run(task.payload)
        messages = self.mail_stub.get_sent_messages()
        self.assertLength(1, messages)
        message, = messages
        profile = Profile.get(profile.key())

        # Reload profile to get new activation key.
        self.assertEqual('"%s" <%s>' % (profile.name, profile.email),
                         message.to)
        self.assertEqual(constants.FULL_NO_REPLY_EMAIL, message.sender)
        self.assertEqual(constants.FULL_SUPPORT_EMAIL, message.reply_to)
        self.assertIn(profile.activation_key, message.body.decode())
        self.assertIn(profile.activation_key, message.html.decode())

        recover_uri = self.uri_for('forgot-password', k=profile.activation_key)
        self.assertIn(recover_uri, message.body.decode())
        self.assertIn(recover_uri, message.html.decode())
Exemplo n.º 17
0
 def test_forgot_password_post_only_has_homepage_login_form(self):
     params = {'email': '*****@*****.**'}
     self.assertIsNone(Profile.get_by_email(params['email']))
     response = self.app.post(self.uri_for('forgot-password'), params)
     self.assertOk(response)
     self.assertTemplateUsed('forgot_password.haml')
     self.assertLength(1, response.pyquery('form#login-form'))
Exemplo n.º 18
0
    def login(self):
        error = None

        if self.request.method == "POST":
            email = self.request.POST.get("email", "").strip()
            password = self.request.POST.get("password", "").strip()

            user = Profile.get_by_email(email)
            if not user:
                error = "User not found"
            else:
                try:
                    self.auth.get_user_by_password(email, password)
                except auth.InvalidPasswordError:
                    error = "Invalid password!"
                except auth.InvalidAuthIdError:
                    error = "Unknown e-mail address!"

                if not user.beta_tester:
                    self.session.add_flash(value="Please ensure you are cleared for beta testing.", level="error")
                    return self.redirect_to("login")

        if self.get_current_profile():
            redirect = self.request.get("redirect")
            return self.redirect(redirect or self.uri_for("home"))
        else:
            return self.render_to_response("login.haml", {"error": error})
Exemplo n.º 19
0
  def test_forgot_password_post_sends_email(self):
    self.assertNotLoggedIn()
    profile = self.create_profile()
    response = self.app.get(self.uri_for('forgot-password'))
    form = response.forms['forgot-password']
    form['email'] = profile.email
    response = form.submit()

    # Check the task was put on the mail queue.
    tasks = self.taskqueue_stub.get_filtered_tasks(queue_names='mail')
    self.assertIn('mail', tasks[0].headers['X-AppEngine-QueueName'])
    task, = tasks
    deferred.run(task.payload)
    messages = self.mail_stub.get_sent_messages()
    self.assertLength(1, messages)
    message, = messages
    profile = Profile.get(profile.key())

    # Reload profile to get new activation key.
    self.assertEqual('"%s" <%s>' % (profile.name, profile.email),
                     message.to)
    self.assertEqual(constants.FULL_NO_REPLY_EMAIL, message.sender)
    self.assertEqual(constants.FULL_SUPPORT_EMAIL, message.reply_to)
    self.assertIn(profile.activation_key, message.body.decode())
    self.assertIn(profile.activation_key, message.html.decode())

    recover_uri = self.uri_for('forgot-password', k=profile.activation_key)
    self.assertIn(recover_uri, message.body.decode())
    self.assertIn(recover_uri, message.html.decode())
Exemplo n.º 20
0
    def get_profile_data(username: str) -> Profile:
        # search user name
        result = ie.user(username)

        parsed_data = json.dumps(result, indent=4, sort_keys=True)
        test = json.loads(parsed_data)

        # displaying the data
        user_data = test[0]
        # print(user_data)

        profile = Profile(
            id=user_data["id"],
            full_name=user_data["full_name"],
            username=user_data["username"],
            biography=user_data["biography"],
            profile_pic_url=user_data["profile_pic_url"],
            amount_posts=user_data["edge_owner_to_timeline_media"]["count"],
            amount_followers=user_data["edge_followed_by"]["count"],
            amount_following=user_data["edge_follow"]["count"],
            external_url=user_data["external_url"],
            connected_fb_page=user_data["connected_fb_page"],
            is_joined_recently=user_data["is_joined_recently"],
            is_private=user_data["is_private"],
            is_verified=user_data["is_verified"],
            is_business_account=user_data["is_business_account"],
            business_email=user_data["business_email"],
            business_category_name=user_data["business_category_name"],
            category_enum=user_data["category_enum"])
        return profile
Exemplo n.º 21
0
def endpoint_get(data: dict, user: str) -> dict:
    profile: Profile = Profile.get(user)

    if profile is None:
        return invalid_user_uuid

    return profile.serialize
Exemplo n.º 22
0
 def test_forgot_password_post_only_has_homepage_login_form(self):
   params = {'email': '*****@*****.**'}
   self.assertIsNone(Profile.get_by_email(params['email']))
   response = self.app.post(self.uri_for('forgot-password'), params)
   self.assertOk(response)
   self.assertTemplateUsed('forgot_password.haml')
   self.assertLength(1, response.pyquery('form#login-form'))
Exemplo n.º 23
0
 def make_conference(self, conf_name, email):
     p_key = ndb.Key(Profile, email)
     profile = Profile(mainEmail=email, key=p_key).put()
     conf_id = Conference(name=conf_name,
                          organizerUserId=email,
                          parent=p_key).put().urlsafe()
     return conf_id, profile
Exemplo n.º 24
0
    def post(self):
        if request.form is None:
            return resp_data_invalid_err('Users', [])

        try:
            unique_guid = str(uuid.uuid4())
            initial_pwd = 'Rckb1000!'
            img_file = request.files['imageFile']
            if img_file:
                file_ext = img_file.filename.rsplit('.', 1)[1].lower()
                filename = '{}.{}'.format(unique_guid, file_ext)
                img_file.save(os.path.join(config.UPLOAD_DIR, filename))

            User(guid=unique_guid,
                 username=request.form['username'],
                 active=True if request.form['active'] == 'true' else False,
                 password=bcrypt.hashpw(initial_pwd.encode('utf-8'),
                                        bcrypt.gensalt()),
                 profile=Profile(name=request.form['profile.name'],
                                 cellPhone=request.form['profile.cellPhone'],
                                 avatar=filename),
                 roles=Roles(admin=True if request.form['role']
                             == 'administrator' else False,
                             superuser=True
                             if request.form['role'] == 'superuser' else False,
                             collaborator=True if request.form['role']
                             == 'collaborator' else False)).save()

            return resp_user_created('Users', request.form['username'])

        except NotUniqueError:
            return resp_not_unique_err('Users', 'usuário')

        except Exception as ex:  # pylint: disable=broad-except
            return resp_exception_err('Users', ex.__str__())
Exemplo n.º 25
0
    def login(self):
        error = None

        if self.request.method == 'POST':
            email = self.request.POST.get('email', '').strip()
            password = self.request.POST.get('password', '').strip()

            user = Profile.get_by_email(email)
            if not user:
                error = 'User not found'
            else:
                try:
                    self.auth.get_user_by_password(email, password)
                except auth.InvalidPasswordError:
                    error = 'Invalid password!'
                except auth.InvalidAuthIdError:
                    error = 'Unknown e-mail address!'

                if not user.beta_tester:
                    self.session.add_flash(
                        value='Please ensure you are cleared for beta testing.',
                        level='error')
                    return self.redirect_to('login')

        if self.get_current_profile():
            redirect = self.request.get('redirect')
            return self.redirect(redirect or self.uri_for('home'))
        else:
            return self.render_to_response('login.haml', {'error': error})
Exemplo n.º 26
0
def edit_profile(**kwargs):
    response_dict = {}
    request_dict = request.get_json()
    new_info = {}
    for field in Profile.get_fields():
        if request_dict.get(field, None) != None:
            new_info[field] = request_dict.get(field)
    try:
        Profile.update(user.profile.id, **new_info)
        response_dict['status'] = 200
        response_dict['message'] = "Successfully updated profile"
        return jsonify(response_dict), 200
    except AssertionError as e:
        response_dict['status'] = 400
        response_dict['message'] = "%s" % (e)
        return jsonify(response_dict), 400
Exemplo n.º 27
0
def find_network(network, user_id):
    result = {network: user_id}
    friends = handler[network](user_id)
    if network == 'vk':
        query = Q(vk__in=friends)
    elif network == 'instagram':
        query = Q(instagram__in=friends)
    elif network == 'twitter':
        query = Q(twitter__in=friends)
    else:
        return result
    data = {'vk': list(), 'instagram': list(), 'twitter': list()}
    for profile in Profile.objects(query):
        if network != 'vk' and profile.vk:
            for id in profile.vk:
                data['vk'].append(id)
        if network != 'instagram' and profile.instagram:
            for id in profile.instagram:
                data['instagram'].append(id)
        if network != 'twitter' and profile.twitter:
            for id in profile.twitter:
                data['twitter'].append(id)
    print("Profiles from database is finded")  # DEBUG
    friends = {'vk': list(), 'instagram': list(), 'twitter': list()}
    with ThreadPoolExecutor(max_workers=12) as executor:
        for key in data:
            for item in executor.map(lambda x: handler[key](x), data[key]):
                for uid in item:
                    friends[key].append(uid)
            print("Parsing complete " + key)
    print("Friend list is generated")  # DEBUG
    temp = {'vk': list(), 'instagram': list(), 'twitter': list()}
    for key in data:
        for id in data[key]:
            response = run([
                'dotnet', 'trainer/Bindex.Trainer.dll', network,
                str(user_id), key,
                str(id)
            ],
                           stdout=PIPE,
                           stderr=PIPE,
                           universal_newlines=True)
            #try:
            vector = [
                float(item) for item in response.stdout.strip().split(' ')
            ]
            with graph.as_default():
                factor = model.predict(np.array([vector]))[0][0]
            if factor >= 0.5:
                temp[key].append((id, factor))
            #except:
            #pass
    print("Neural network is used")  # DEBUG
    for key in temp:
        if not temp[key]:
            continue
        result[key] = int(max(temp[key], key=lambda x: x[1])[0])
    print("Profiles from other networks is finded")  # DEBUG
    return result
Exemplo n.º 28
0
 def test_delete_profile(self):
     """
     tests the storage.delete() method removes and commits obj to database
     for an object from the Profile class
     """
     # connect to MySQL database through MySQLdb and get initial count
     db = connect(host=ION_MYSQL_HOST,
                  user=ION_MYSQL_USER,
                  passwd=ION_MYSQL_PWD,
                  db=ION_MYSQL_DB)
     cur = db.cursor()
     cur.execute("""SELECT * FROM profiles""")
     objs_for_count1 = cur.fetchall()
     # creates new instance of Profile
     new_obj = Profile()
     # tests that the new object is of type Profile
     self.assertIs(type(new_obj), Profile)
     # adds all attributes required for testing
     # (id should be set by primary key)
     # (created_at, updated_at should be set by datetime)
     new_obj.name = "test_name"
     new_obj.email = "*****@*****.**"
     # save the object with BaseModel save method
     # save method calls storage.new() and storage.save()
     new_obj.save()
     # closes connection to database and restarts connection with MySQLdb
     cur.close()
     db.close()
     db = connect(host=ION_MYSQL_HOST,
                  user=ION_MYSQL_USER,
                  passwd=ION_MYSQL_PWD,
                  db=ION_MYSQL_DB)
     cur = db.cursor()
     cur.execute("""SELECT * FROM profiles""")
     objs_for_count2 = cur.fetchall()
     # tests that there is one more obj saved to profiles table in db
     self.assertEqual(len(objs_for_count1) + 1, len(objs_for_count2))
     # delete the object with BaseModel delete method
     # delete instance method calls storage.delete() and storage.save()
     new_obj.delete()
     # closes connection to database and restarts connection with MySQLdb
     cur.close()
     db.close()
     db = connect(host=ION_MYSQL_HOST,
                  user=ION_MYSQL_USER,
                  passwd=ION_MYSQL_PWD,
                  db=ION_MYSQL_DB)
     cur = db.cursor()
     cur.execute("""SELECT * FROM profiles""")
     objs_for_count3 = cur.fetchall()
     # tests that there is one less obj in profiles table in db
     self.assertEqual(len(objs_for_count2) - 1, len(objs_for_count3))
     self.assertEqual(len(objs_for_count1), len(objs_for_count3))
     # closes the connection
     cur.close()
     db.close()
Exemplo n.º 29
0
 def test_all_profiles_count(self):
     """
     tests all method retrieves all objects when class is Profile
     """
     # connect to MySQL database through MySQLdb and get initial count
     db = connect(host=ION_MYSQL_HOST,
                  user=ION_MYSQL_USER,
                  passwd=ION_MYSQL_PWD,
                  db=ION_MYSQL_DB)
     cur = db.cursor()
     cur.execute("""SELECT * FROM identities""")
     identity_objs = cur.fetchall()
     cur.execute("""SELECT * FROM profiles""")
     profile_objs = cur.fetchall()
     cur.execute("""SELECT * FROM skills""")
     skills_objs = cur.fetchall()
     total_count = len(identity_objs) + len(profile_objs) + len(skills_objs)
     total_profile_count = len(profile_objs)
     # call storage.all() method, both with and without class specified
     all_objs = storage.all()
     count1 = len(all_objs.keys())
     all_profile_objs = storage.all(Profile)
     profile_count1 = len(all_profile_objs.keys())
     # tests that counts from all method match current database
     self.assertEqual(total_count, count1)
     self.assertEqual(total_profile_count, profile_count1)
     # creates new Profile obj to test with
     new_obj = Profile()
     # adds all attributes required for testing
     # (id should be set by primary key)
     # (created_at, updated_at should be set by datetime)
     new_obj.name = "test_name"
     new_obj.email = "*****@*****.**"
     # saves new object to the database
     new_obj.save()
     # re-call storage.all() method
     all_objs = storage.all()
     count2 = len(all_objs.keys())
     all_profile_objs = storage.all(Profile)
     profile_count2 = len(all_profile_objs.keys())
     # tests that counts increased by 1
     self.assertEqual(count1 + 1, count2)
     self.assertEqual(profile_count1 + 1, profile_count2)
     # deletes new object from the database
     new_obj.delete()
     # re-call storage.all() method
     all_objs = storage.all()
     count3 = len(all_objs.keys())
     all_profile_objs = storage.all(Profile)
     profile_count3 = len(all_profile_objs.keys())
     # tests that count decreased by 1
     self.assertEqual(count2 - 1, count3)
     self.assertEqual(count1, count3)
     self.assertEqual(profile_count2 - 1, profile_count3)
     self.assertEqual(profile_count1, profile_count3)
Exemplo n.º 30
0
    def create(self):
        form = ProfileForm(self.request.POST)

        if self.request.method == 'POST' and form.validate():
            name = ' '.join([form.first_name.data, form.last_name.data])

            # Create the webapp2_extras.auth user.
            model = self.auth.store.user_model
            ok, user = model.create_user(form.data['email'],
                                         password_raw=form.data['password'])

            if not ok:
                self.session.add_flash(messages.EDITOR_CREATE_ERROR,
                                       level='error')
                return self.redirect_to('editors.list')

            # Create the profile.
            profile = Profile(name=name,
                              email=form.data['email'],
                              is_editor=True,
                              auth_user_id=user.key.id())
            profile.put()

            # Force reload of profile object
            Profile.get(profile.key())

            self.session.add_flash(messages.EDITOR_CREATE_SUCCESS)
            return self.redirect_to('editors.list')

        return self.render_to_response('editors/form.haml', {'form': form})
Exemplo n.º 31
0
 def test_all_profiles_dict(self):
     """
     tests return of all method when class is Profile
     """
     # connect to MySQL database through MySQLdb and get initial count
     db = connect(host=ION_MYSQL_HOST,
                  user=ION_MYSQL_USER,
                  passwd=ION_MYSQL_PWD,
                  db=ION_MYSQL_DB)
     cur = db.cursor()
     cur.execute("""SELECT * FROM profiles""")
     profile_objs = cur.fetchall()
     total_profile_count = len(profile_objs)
     # call storage.all() method
     all_profile_objs = storage.all(Profile)
     profile_count1 = len(all_profile_objs.keys())
     # tests that all method returns same count of Identity objects
     self.assertEqual(total_profile_count, profile_count1)
     # tests that all method returns dictionary
     self.assertIsInstance(all_profile_objs, dict)
     # creates new Profile obj to test with
     new_obj = Profile()
     # adds all attributes required for testing
     # (id should be set by primary key)
     # (created_at, updated_at should be set by datetime)
     new_obj.name = "test_name"
     new_obj.email = "*****@*****.**"
     # saves new object to the database
     new_obj.save()
     # re-call storage.all() method and test that count increased by 1
     all_profile_objs = storage.all(Profile)
     profile_count2 = len(all_profile_objs.keys())
     self.assertEqual(profile_count1 + 1, profile_count2)
     # tests that newly created obj is in dictionary with correct key
     self.assertIsInstance(storage.all(), dict)
     dict_key = "{}.{}".format("Profile", new_obj.id)
     self.assertIn(dict_key, storage.all())
     # get obj attributes from stroage.all() dictionary using obj id
     # test that retrieved attributes match expected values
     obj_class = storage.all().get("Profile.{}".format(
         new_obj.id)).__class__.__name__
     self.assertEqual("Profile", obj_class)
     obj_name = storage.all().get("Profile.{}".format(new_obj.id)).name
     self.assertEqual("test_name", obj_name)
     obj_email = storage.all().get("Profile.{}".format(new_obj.id)).email
     self.assertEqual("*****@*****.**", obj_email)
     # delete new object from the database
     new_obj.delete()
     # re-call storage.all() method and test that count decreased by 1
     all_profile_objs = storage.all(Profile)
     profile_count3 = len(all_profile_objs.keys())
     self.assertEqual(profile_count2 - 1, profile_count3)
     self.assertEqual(profile_count1, profile_count3)
     # tests that new object is no longer in return dictionary
     self.assertNotIn(dict_key, storage.all())
Exemplo n.º 32
0
  def delete(self, id):
    editor = Profile.get_by_id(int(id))
    if not editor or not editor.is_editor:
      self.session.add_flash(messages.EDITOR_NOT_FOUND, level='error')
      return self.redirect_to('editors.list')

    editor.delete()
    self.session.add_flash(messages.EDITOR_DELETE_SUCCESS)
    return self.redirect_to('editors.list')
Exemplo n.º 33
0
    def test_forgot_password_post_resets_activation_key(self):
        profile = self.create_profile()
        old_activation_key = profile.activation_key

        params = {'email': profile.email}
        response = self.app.post(self.uri_for('forgot-password'), params)
        self.assertOk(response)
        profile = Profile.get(profile.key())
        self.assertNotEqual(old_activation_key, profile.activation_key)
Exemplo n.º 34
0
 def verify_access(self, *args):
   user = users.GetCurrentUser()
   if user:
     profile = Profile.gql("WHERE user = :1", user)
     current_profile = profile.get()
     if role == current_profile.role:
       handler_method(self, *args)
       return
   self.response.out.write('<html><head></head><body>Access denied</body></html>')
Exemplo n.º 35
0
  def test_forgot_password_post_resets_activation_key(self):
    profile = self.create_profile()
    old_activation_key = profile.activation_key

    params = {'email': profile.email}
    response = self.app.post(self.uri_for('forgot-password'), params)
    self.assertOk(response)
    profile = Profile.get(profile.key())
    self.assertNotEqual(old_activation_key, profile.activation_key)
Exemplo n.º 36
0
 def post(self):
     user = self.get_current_user()
     created, profile = Profile.get_or_create_from_user(user)
     self.errors = []
     try:
         self.validate(profile)
     except Exception, e:
         self.errors = [str(e)]
         return self.get()
Exemplo n.º 37
0
    def delete(self, id):
        editor = Profile.get_by_id(int(id))
        if not editor or not editor.is_editor:
            self.session.add_flash(messages.EDITOR_NOT_FOUND, level='error')
            return self.redirect_to('editors.list')

        editor.delete()
        self.session.add_flash(messages.EDITOR_DELETE_SUCCESS)
        return self.redirect_to('editors.list')
Exemplo n.º 38
0
def signup():
    if request.method == "POST":
        request_dict = request.get_json()
        response_dict = {}
        user_info = {}
        name = request_dict['name']
        for field in User.get_fields():
            if field == "id":
                continue
            if field == "password_hash":
                user_info['password'] = request_dict['password']
                continue
            if request_dict.get(field, None) != None:
                user_info[field] = request_dict[field]
        try:
            user = User.create(**user_info)
            # New profile info
            placeholder_info = {
                'name': name,
                'is_chef': False,
                "about_me": "Not entered",
                "profile_image": "No image uploaded",
                "favourite_recipe": "None yet,",
                "favourite_cuisine": "None yet,",
                "location": "Unknown Location"
            }
            profile = Profile.create(**placeholder_info)
            user.assign_one_to_one("profile", profile)
            # Since we're sending all the information back
            # to the front end, use the user_info dict as a
            # response dictionary
            user_info = user.to_dict(excludes=['profile', 'password_hash'])
            user_info['profile_id'] = user.profile.id
            email = user.email
            access_token = create_access_token(identity=email)
            refresh_token = create_refresh_token(identity=email)
            session['user_id'] = user.id
            # Put all information in a non nested dictionary
            # which will make it easier to get info in the frontend
            response_dict['status'] = 201
            response_dict['message'] = "Successfully created account!"
            response_dict['login'] = True
            response_dict['user'] = user_info
            response_dict['user']['profile'] = profile.to_dict(
                excludes=['user_id', 'recipes', 'user'])
            response = make_response(response_dict)
            response.set_cookie("user_id", str(user.id))
            # Set JWT cookies
            set_access_cookies(response, access_token)
            set_refresh_cookies(response, refresh_token)
            return response, 200
        except AssertionError as e:
            User.do_rollback()
            response_dict['status'] = 401
            response_dict['message'] = "%s" % (e)
            # Validation problem
            return jsonify(response_dict), 401
Exemplo n.º 39
0
    def validate(self, email, password):
        if not email_pattern.match(email):
            raise Exception("Email format is not right")

        if not password or not email:
            raise Exception("Password and email cannot be empty")

        profile = Profile.gql('WHERE user_email=:1', email).get()
        if profile:
            raise Exception("This email is already occupied.")
Exemplo n.º 40
0
def create_profile():
    """
    create a new instance of Profile
    through POST request
    """
    # get JSON from POST request
    json = request.get_json(silent=True)
    # checks for missing attributes
    if json is None:
        abort(400, 'Not a JSON')
    if 'name' not in json:
        abort(400, 'Missing name attribute')
    if 'email' not in json:
        abort(400, 'Missing email attribute')
    # create new instance with **kwargs from json
    new_obj = Profile(**json)
    new_obj.save()
    # return json version of object's to_dict()
    return jsonify(new_obj.to_dict()), 201
Exemplo n.º 41
0
 def test_class_and_subclass(self):
     """
     tests that instances are of Profile class
     and are a subclass of BaseModel class
     """
     new_obj = Profile()
     # tests that the new instance is of type Profile
     self.assertIs(type(new_obj), Profile)
     # tests that the new instance is a subclass of BaseModel
     self.assertIsInstance(new_obj, BaseModel)
Exemplo n.º 42
0
	def get(self):
		user = users.get_current_user()
		if user:
		  profile = Profile.gql("WHERE user = :1", user).get()
		  if not profile:
		    self.redirect("/profiles/new")
		    return
		  self.redirect("/dashboard")
		else:
		  self.redirect(users.create_login_url(self.request.uri))
Exemplo n.º 43
0
  def get(self):	
	path = os.path.join(os.path.dirname(__file__),
	                    '../views/admin/index.html')
	
	template_values = {
		'name': self.__class__.__name__,
		'profiles': Profile.all(),
	}
	
	self.response.out.write(template.render(path, template_values))
Exemplo n.º 44
0
async def join_group(p: Profile, g: Group, sender: AbstractMessageSender):
    members = await g.get_members()

    await g.user_join(p.ident)
    await p.set_prop(PROFILE_GROUP_KEY, g.ident)

    tr = await p.get_translator()

    message = tr.myg_notification_joined_group(p.get_username())
    send_message_to_group_members(members, message, sender)
Exemplo n.º 45
0
    def get(self, artist_id):
        # artist_id may be a profile_unique_name or an application_user_id
        profile_obj = Profile.get_profile_by_profile_unique_name(artist_id)
        if profile_obj is not None:
            application_user_id = profile_obj.application_user_id
            user_obj = User.get_user_by_application_user_id(
                application_user_id)
            if user_obj is None:
                # TODO : All profiles should have a user associated with them. Log or handle the event where there is no User associated with a profile.
                # There is no user associated with the profile!
                pass
        else:
            user_obj = User.get_user_by_application_user_id(artist_id)
            if user_obj is not None:
                profile_obj = Profile.get_profile_by_application_user_id(
                    user_obj.application_user_id)

        if user_obj is not None:
            self.template_values['user_exists'] = True
            self.template_values[
                'artist_name'] = user_obj.first_name + ' ' + user_obj.last_name
            if profile_obj is not None:
                self.template_values[
                    'profile_unique_name'] = profile_obj.profile_unique_name
                if profile_obj.bio is not None and not re.match(
                        r"^\s*$", profile_obj.bio):
                    self.template_values['profile_bio'] = profile_obj.bio
                if profile_obj.profile_picture is not None:
                    self.template_values[
                        'profile_picture'] = profile_obj.profile_picture
            art_objs = Art.get_art(user_obj.application_user_id)
            art_list = list()
            for art_obj in art_objs:
                art_list.append({'art_obj': art_obj})
            self.template_values['art_list'] = art_list
            self.template_values['artist_image_count'] = len(
                self.template_values['art_list'])
        else:
            self.template_values['user_exists'] = False

        template = self.get_template('templates/artist_content.html')
        self.response.write(template.render(self.template_values))
Exemplo n.º 46
0
    def get(self, user_name=None):
        login_user = self.get_current_user()

        if user_name is None:
            return self.redirect('/signin')

        profile = Profile.gql('WHERE nickname=:1', user_name).get()
        if not profile or not profile.is_active:
            return self.error(404)
        user = profile.get_user()
        is_self = user == login_user

        has_followed = False
        if not is_self:
            has_followed = Follow.gql('WHERE from_user = :1 AND to_user = :2',
                                      login_user, user).get() is not None            

        followers = Follow.who_subscribe_you(user)
        follower_profiles = []
        for f in followers:
            c, p = Profile.get_or_create_from_user(f.from_user)
            follower_profiles.append(p)
        followees = Follow.your_subscribers(user)
        followee_profiles = []
        for f in followees:
            c, p = Profile.get_or_create_from_user(f.to_user)
            followee_profiles.append(p)

        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        has_followed = Follow.gql('WHERE from_user = :1 AND to_user =:2',
                                  login_user,
                                  user).get()
        pagesize = settings.BLIP_PAGE_SIZE
        paginator = SimplePaginator(Blip.qs_for_author(user),
                                    page, pagesize)

        blips = each_profiles(paginator.object_list)
        return self.render('user_page.html', locals())
Exemplo n.º 47
0
    def create_profile(cls,
                       email=None,
                       password=None,
                       beta_tester=True,
                       is_admin=False,
                       is_manager=False,
                       is_editor=False,
                       activated=True,
                       account=None):
        # TODO: Move this into a top level function (testing.create_profile)
        # Use defaults if anything here is missing.
        UserModel = cls.get_auth().store.user_model

        if not email:
            # Generate an e-mail that should be unique...
            email = '%s-%s' % (UserModel.query().count(), cls.DEFAULT_EMAIL)
        password = password or cls.DEFAULT_PASSWORD

        # Create the auth.user_model.
        ok, user = UserModel.create_user(email, password_raw=password)

        if not ok:
            raise Exception('Error creating auth.User: %s' % email)

        if not account:
            account = cls.create_account()

        # Create the profile.
        profile = Profile(name=cls.DEFAULT_PROFILE_NAME,
                          is_admin=is_admin,
                          is_manager=is_manager,
                          is_editor=is_editor,
                          email=email,
                          beta_tester=beta_tester,
                          activated=activated,
                          auth_user_id=user.key.id(),
                          timezone='UTC',
                          parent=account)
        profile.put()

        # Return the profile (we can get everything else with that)
        return profile
Exemplo n.º 48
0
    def get(self, meeting_key=None, user_name=None):
        login_user = self.get_current_user()
        m = Meeting.get(meeting_key)
        if m is None:
            return self.error(404)
        if m.creator != login_user:
            return self.error(401)

        profile = Profile.gql('WHERE nickname = :1', user_name).get()
        m.delete_member(profile.get_user())
        return self.redirect_back()
Exemplo n.º 49
0
async def leave_group(p: Profile, g: Group, sender: AbstractMessageSender):
    await g.user_leave(p.ident)
    await p.del_prop(PROFILE_GROUP_KEY)

    tr = await p.get_translator()

    members = await g.get_members()
    if members:
        message = tr.myg_notification_left_group(p.get_username())
        send_message_to_group_members(members, message, sender)
    else:
        await g.remove()
Exemplo n.º 50
0
  def create(self):
    form = ProfileForm(self.request.POST)

    if self.request.method == 'POST' and form.validate():
      name = ' '.join([form.first_name.data,
                       form.last_name.data])

      # Create the webapp2_extras.auth user.
      model = self.auth.store.user_model
      ok, user = model.create_user(form.data['email'],
                                   password_raw=form.data['password'])

      if not ok:
        self.session.add_flash(messages.EDITOR_CREATE_ERROR,
                               level='error')
        return self.redirect_to('editors.list')

      # Create the profile.
      profile = Profile(name=name,
                        email=form.data['email'],
                        is_editor=True,
                        auth_user_id=user.key.id())
      profile.put()

      # Force reload of profile object
      Profile.get(profile.key())

      self.session.add_flash(messages.EDITOR_CREATE_SUCCESS)
      return self.redirect_to('editors.list')

    return self.render_to_response('editors/form.haml', {'form': form})
Exemplo n.º 51
0
  def update(self, id):
    editor = Profile.get_by_id(int(id))
    if not editor or not editor.is_editor:
      self.session.add_flash(messages.EDITOR_NOT_FOUND, level='error')
      self.redirect_to('editors.list')

    form = ProfileUpdateForm(self.request.POST, obj=editor)
    form.user_id = editor.key().id()

    if self.request.method == 'GET':
      names = editor.name.split(' ')
      form.first_name.data = names[0]
      form.last_name.data = names[1]

    form.profile_id = editor.key().id()

    if self.request.method == 'POST' and form.validate():
      # Access to the user model is only needed in this section.
      user = editor.get_auth_user()
      editor.name = ' '.join([form.first_name.data, form.last_name.data])

      if form.email.data != editor.email:
        user.auth_ids.remove(editor.email)
        user.auth_ids.append(form.email.data)
        editor.email = form.email.data

      if form.password.data:
        user.password = security.generate_password_hash(form.password.data,
                                                        length=12)

      editor.put()
      user.put()

      # Force reload of profile object
      Profile.get(editor.key())
      self.session.add_flash(messages.EDITOR_UPDATE_SUCCESS)

      return self.redirect_to('editors.list')

    return self.render_to_response('editors/form.haml', {'form': form})
Exemplo n.º 52
0
  def activate(self):
    # k is used in emails
    # activation_key is the form name
    key = self.request.get('k')
    profile = Profile.get_by_activation_key(key)

    if not profile or profile.activated:
      self.session.add_flash(messages.PROFILE_ACTIVATION_NOT_FOUND,
                             level='error')
      self.redirect_to('home')

    form = ProfileActivationForm(self.request.POST, obj=profile)
    form.activation_key = key

    if self.request.method == 'POST' and form.validate():
      # Create the webapp2_extras.auth user.
      model = self.auth.store.user_model
      ok, user = model.create_user(profile.email,
                                   password_raw=form.data['password'])

      if not ok:
        self.session.add_flash(messages.PROFILE_ACTIVATION_ERROR,
                               level='error')
        return self.redirect_to('profile.activate', k=key)

      # Setup profile, create authentication token and activate
      profile.name = ' '.join([form.data['first_name'],
                               form.data['last_name']])

      # Set as activated (since they've confirmed their e-mail).
      profile.activated = True
      profile.activation_key = None
      profile.auth_user_id = user.key.id()
      profile.put()

      # Change the password for the auth_user.
      user = self.auth.store.user_model.get_by_id(profile.auth_user_id)
      user.password = security.generate_password_hash(form.data['password'],
                                                      length=12)
      user.put()

      # Log the user in.
      user_id = user.key.id()
      self.auth._user = None
      self.auth.get_user_by_token(user_id, user.create_auth_token(user_id))

      # Redirect to the dashboard.
      self.session.add_flash(messages.PROFILE_ACTIVATION_SUCCESS)
      return self.redirect_to('home')

    return self.render_to_response('activate.haml',
                                   {'profile': profile, 'form': form})
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # get Profile from datastore
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        # create new Profile if not there
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(),
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()

        return profile      # return Profile
Exemplo n.º 54
0
    def validate(self, profile):
        nickname = self.request.get('nickname', '').strip()
        if nickname:
            if Profile.gql('WHERE nickname=:1 AND __key__ != :2',
                           nickname,
                           profile.key()).get():
                raise Exception('Nickname already been taken')
        else:
            raise Exception('Nickname cannot be empty')

        fullname = self.request.get('fullname', '').strip()
        if not fullname:
            raise Exception('Full name cannot be empty')
Exemplo n.º 55
0
def getProfileFromUser(user):
    """
    Return user Profile from datastore, creating new one if non-existent.
    :param user: A current user object from API endpoint.
        Example: user = endpoints.get_current_user()
    :return: Profile object
    """
    user_id = getUserId(user)
    p_key = ndb.Key(Profile, user_id)
    profile = p_key.get()

    if not profile:
        profile = Profile(
            key=p_key,
            displayName=user.nickname(),
            mainEmail=user.email(),
            teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
        )
        profile.put()

    # return Profile
    return profile
Exemplo n.º 56
0
 def post(self):
     if not login_using_local():
         return self.error(404)
     email = self.request.get('email')
     password = self.request.get('password')
     continue_to = self.request.get('continue_to', '/')
     
     google_login_url = users.create_login_url(continue_to)
     errors = []
     local_user = UserAuth.gql('WHERE email=:1', email).get()
     if local_user and self.authenticate(local_user, password):
         login_user = local_user.get_user()
         profile = Profile.gql('WHERE user = :1', login_user).get()
         if not profile:
             created, profile = Profile.get_or_create_from_user(login_user)
             if created:
                 self.redirect('/profile/edit')
         return self.redirect(continue_to)
     else:
         errors.append('Login error, please relogin again')
     using_google = login_using_google()
     return self.render('signin.html', locals())
Exemplo n.º 57
0
  def signup(self):
    form = ProfileForm(self.request.POST)

    if self.request.method == 'POST' and form.validate():
      # Create the webapp2_extras.auth user.
      model = self.auth.store.user_model
      ok, user = model.create_user(form.data['email'],
                                   password_raw=form.data['password'])

      if not ok:
        self.session.add_flash(messages.ERROR_MESSAGE, level='error')
        return self.redirect_to('signup')

      # Ensure that we have a default account setup.
      default_account = Account.all().filter(
          'name = ', constants.PRODUCT_NAME).get()

      if not default_account:
        default_account = Account(name=constants.PRODUCT_NAME)
        default_account.put()

      # Create the profile.
      name = ' '.join([form.data['first_name'], form.data['last_name']])
      profile = Profile(parent=default_account,
                        name=name,
                        email=form.data['email'],
                        tel_number=form.data['tel_number'],
                        is_member=True,
                        auth_user_id=user.key.id())
      profile.put()

      # Automatically log the person in.
      user_id = user.key.id()
      self.auth.get_user_by_token(user_id, user.create_auth_token(user_id))

      self.session.add_flash(messages.PROFILE_CREATE_SUCCESS, level='info')
      return self.redirect_to('home')

    return self.render_to_response('signup.haml', {'form': form})
Exemplo n.º 58
0
 def post(self, meeting_key=None):
     login_user = self.get_current_user()
     m = Meeting.get(meeting_key)
     if m is None:
         return self.error(404)
     if m.creator != login_user:
         return self.error(401)
     
     user_name = self.request.get('user_name')
     profile = Profile.gql('WHERE nickname = :1', user_name).get()
     if profile:
         m.add_member(profile.get_user())
     return self.redirect_back()
Exemplo n.º 59
0
  def test_forgot_password_post_with_email_trailing_whitespace(self):
    profile = self.create_profile()
    params = {'email': profile.email + '   '}
    response = self.app.post(self.uri_for('forgot-password'), params)
    self.assertOk(response)

    tasks = self.taskqueue_stub.get_filtered_tasks(queue_names='mail')
    self.assertIn('mail', tasks[0].headers['X-AppEngine-QueueName'])
    task, = tasks
    deferred.run(task.payload)
    self.assertLength(1, self.mail_stub.get_sent_messages())
    message, = self.mail_stub.get_sent_messages()
    profile = Profile.get(profile.key())
    self.assertEqual('"%s" <%s>' % (profile.name, profile.email), message.to)
Exemplo n.º 60
0
    def get(self, meeting_key=None):
        from models.blip import Blip
        login_user = self.get_current_user()
        meeting = Meeting.get(meeting_key)
        if meeting is None or not meeting.is_active:
            return self.error(404)
        if not meeting.has_member(login_user):
            return self.error(401)
        c, p = Profile.get_or_create_from_user(meeting.creator)
        
        admin_profiles = [p]

        member_profiles = []
        members = meeting.members(include_creator=False)
        for u in members:
            c, p = Profile.get_or_create_from_user(u)
            member_profiles.append(p)

        followees = Follow.your_subscribers(login_user)
        followee_profiles = []
        for f in followees:
            if f.to_user not in members:
                c, p = Profile.get_or_create_from_user(f.to_user)
                followee_profiles.append(p)
            
        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        pagesize = settings.ROOM_PAGE_SIZE
        paginator = SimplePaginator(Blip.qs_for_meeting(meeting),
                                     page, pagesize)
        
        blips = each_profiles(paginator.object_list)
        return self.render('meeting_item.html', locals())