Esempio n. 1
0
    def insert_mock_data(self):
        import csv
        from profile.models import Profile
        from audioanalysis.models import Audio
        from django.db import connection
        # from django.contrib.auth.models import User
        from profile import definitions
        import random
        import pycountry
        from faker import Faker
        from datetime import datetime
        from users.models import CustomUser as User



        #self.delete_all_users_except_admins()

        fake = Faker(['en_US']) 

        for i in range(0, 1000):
            first_name = fake.first_name()
            last_name = fake.last_name()
            
            # get first character of first name, full last name, 4 random numbers
            nums = ''.join([str(random.randint(0,9)) for p in range(0,4)])
            email = first_name[0][:1].lower()+last_name+nums+random.choice(self.email_prefix)

            # 1994-12-21
            birth_date = fake.date_of_birth(tzinfo=None, minimum_age=0, maximum_age=115).strftime('%Y-%m-%d')
            country = random.choice(list(pycountry.countries)).name
            # Create a user that will go in auth_user table
            user_one_to_one = self.create_random_user(email_from_profile_object=email)
            profile = Profile(user=user_one_to_one, first_name=first_name, last_name=last_name, email=email, birth_date=birth_date, country=country)
            #print(profile)
            profile.save()
            # connect audio file to user 
            audio_file = Audio(user=user_one_to_one, name=self.s3_urls[0].split("/")[-1], s3_url=self.s3_urls[0])
            audio_file.save()
            audio_file = Audio(user=user_one_to_one, name=self.s3_urls[1].split("/")[-1], s3_url=self.s3_urls[1])
            audio_file.save()

            print("Created user " + str(i))
        
        # Create admin users
        
        user = User.objects.create_superuser('lmp004', '*****@*****.**', 'password')
        profile = Profile(user=user, first_name='Logan', last_name="Phillips", email='*****@*****.**', birth_date='1996-04-24', country='America')
        # profile = Profile(user=user, first_name='Logan', last_name=None, email='*****@*****.**', birth_date=None, country=None)
        profile.save()
Esempio n. 2
0
def authorize(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            saved_row = form.save()
            profile = Profile(first_name=form.cleaned_data.get('first_name'),
                              last_name=form.cleaned_data.get('last_name'),
                              email=form.cleaned_data.get('email'),
                              phone=form.cleaned_data.get('phone'),
                              gender=form.cleaned_data.get('gender'),
                              is_veg='N',
                              is_smoke='N',
                              is_alcohol='N',
                              university='Dalhousie',
                              branch='CSE')
            values = profile.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            print(profile.user_id)
            return render_to_response('home.html',
                                      {'profile_user_id': profile.user_id},
                                      locals())
        else:
            return render(request, 'signup.html', {'form': form})
    else:
        form = RegisterForm()
        return render(request, 'signup.html', {'form': form})
Esempio n. 3
0
 def create(self, request, *args, **kwargs):
     nickname = request.data['nickname'] if False else ' '
     sex= request.data['sex'] if False else 1
     phone = request.data['phone'] if False else ' '
     data = {
         'email':request.data['email'],
         'username':request.data['username'],
         'password':request.data['password'],
         'nickname':nickname,
         'sex':sex,
         'phone':phone,
     }
     # 这里还要添加验证模型的东西
     user = User(email = data['email'],username = data['username'],password = data['password'],is_active = 0)
     try:
         user.save()
         profile = Profile(nickname=data['nickname'], sex=data['sex'], phone=data['phone'], user=user,user_id=user.id)
         profile.save()
         signals.user_registered.send(sender=self.__class__, user=user, request=self.request)
         if 1:
             self.send_activation_email(user)
         elif settings.get('SEND_CONFIRMATION_EMAIL'):
             self.send_confirmation_email(user)
         return Response({'status': 'User created success'},
                         status=status.HTTP_201_CREATED)
     except:
         return Response({'status': 'error'},
                         status=status.HTTP_400_BAD_REQUEST)
Esempio n. 4
0
def create_profile_data(strategy,
                        user,
                        response,
                        details,
                        is_new=False,
                        *args,
                        **kwargs):
    if is_new:
        if 'fullname' in details:
            full_name = details['fullname']
        else:
            full_name = user.username
        new_profile = Profile(user=user, name=full_name)
        new_profile.user_id = user.id
        new_profile.name = user.username
        new_profile.user.email = details[
            'email'] if 'email' in details else None

        url = 'https://graph.facebook.com/{0}/picture'.format(response['id'])
        try:
            img_content = request('GET', url, params={'type': 'large'})
            file_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
                'uploads', 'facebook', '{0}__social.jpg'.format(user.id))
            with open(file_path, 'wb+') as destination:
                img_file = ContentFile(img_content.content)
                for chunk in img_file.chunks():
                    destination.write(chunk)
            new_profile.photo = 'facebook/{0}__social.jpg'.format(user.id)
            new_profile.save()

            profile_settings = Settings.objects.get(profile_id=new_profile.id)
            profile_settings.email = details[
                'email'] if 'email' in details else None
            profile_settings.feed_radius = -1
            profile_settings.save()
            return
        except Exception as e:
            raise e
    elif user.date_joined >= (datetime.datetime.now(tz=pytz.utc) -
                              datetime.timedelta(hours=1)):
        existing_profile = Profile.objects.get(user_id=user.id)
        url = 'https://graph.facebook.com/{0}/picture'.format(response['id'])
        try:
            img_content = request('GET', url, params={'type': 'large'})
            file_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
                'uploads', 'facebook', '{0}__social.jpg'.format(user.id))
            with open(file_path, 'wb+') as destination:
                img_file = ContentFile(img_content.content)
                for chunk in img_file.chunks():
                    destination.write(chunk)
            existing_profile.photo = 'facebook/{0}__social.jpg'.format(user.id)
            existing_profile.save()
        except Exception as e:
            raise e
Esempio n. 5
0
def create_profile():
    data = request.get_json()
    new_profile = Profile(name=data['name'],
                          address=data['address'],
                          phone_number=data['phone_number'])

    db.session.add(new_profile)
    db.session.commit()

    return jsonify({'message': 'New profile created!'})
Esempio n. 6
0
    async def prepare_db_request(self, data: dict) -> dict:
        """
        Prepare request to db. Replace Profile.user_id to int32 value from db.
        Args:
            data: dict with user data for Profile object.

        Returns:  dict with user profile.

        """
        profile = Profile(**data)
        profile.user_id = await get_next_sequence_value(
            self.request.app['db'], "user_id")
        return profile.to_dict()
Esempio n. 7
0
def edit(request):
    try:
        profile = request.user.get_profile()
    except Profile.DoesNotExist:
        profile = Profile(user=request.user)
    if request.method == 'POST':
        form = ProfileForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse(edit) + '?saved')
    else:
        form = ProfileForm(instance=profile)

    return render_to_response('profile/edit.html',
                              {'form': form,
                               'saved': True if 'saved' in request.GET\
                                   else False},
                              context_instance = RequestContext(request))
Esempio n. 8
0
    def create_players(self, team,  name, coach, height, score=score):
        team_name = Team.objects.filter(name=team).first()
        player = Players.objects.filter(name=name, team=team_name).first()
        if not player:
            player = Players()

        player.team = team_name
        player.name = name
        player.score = score
        player.coach = coach
        player.height = height
        if coach is True:
            coach_exists = Players.objects.filter(team=team_name, is_coach=True).first()
            if coach_exists is not None:
                raise ValueError("Cannot have more than 1 coach in a team.")
            else:
                player.is_coach = coach
        player.save()
        Profile().add_user(player=player)
Esempio n. 9
0
    def create(self, validated_data):
        """
        Create and return a new User instance, given the validated data.
        """

        profile_data = validated_data.pop('profile')

        user = super(UserSerializer, self).create(validated_data)
        user.date_joined = datetime.today()
        user.set_password(validated_data['password'])
        user.save()

        profile = Profile(
            user=user,
            cba_username=profile_data.get('cba_username').strip(),
            cba_user_token=profile_data.get('cba_user_token').strip())
        profile.save()

        return user
Esempio n. 10
0
 def save(self, location, language):
     data = self.cleaned_data
     user = super(RegistrationForm, self).save(commit=False)
     user.last_login = timezone.now()
     user.email = data['email']
     user.first_name = data['first_name']
     # user.last_name = data['last_name']
     user.save()
     profile = Profile(user=user, name=data.get('name', data['username']))
     if not location.id:
         location.save()
     profile.location = location
     # profile.name = data['first_name'] + ' ' + data['last_name']
     profile.save()
     profile.settings.email = data['email']
     profile.settings.language = language
     profile.settings.feed_radius = -1
     profile.settings.save()
     return profile
Esempio n. 11
0
def complete_registration(request):
    if request.user.is_authenticated():
        return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
    try:
        identity_id = request.session.get('users_complete_reg_id', None)
        user_map = models.UserMap.objects.get(identity__id=identity_id)
    except models.UserMap.DoesNotExist:
        return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
    if not user_map.user.username:
        user_map.user.username = user_map.user.email.split('@')[0]
    user_map.user.save()
    profile = Profile(user=user_map.user, summa=0)
    profile.save()
    user_map.verified = True
    user_map.save()

    user = auth.authenticate(user_map=user_map)
    auth.login(request, user)

    messages.info(request, u'Добро пожаловать!')
    del request.session['users_complete_reg_id']
    return redirect('/')
Esempio n. 12
0
    async def post(self) -> Union[web.json_response, web.HTTPException]:
        """
        Take user credentials and check if user exist.
        If exist - return his profile in JSON. Else -> HTTPException
        Returns: User profile or Exception

        """
        request_data = await self.request.json()

        result = await self.find_user(request_data)

        if not result:
            raise web.HTTPNotFound(text="User not found")

        profile = Profile(**clean_data(result))

        if profile.check_password(request_data['password']):
            await profile.fetch_contacts(self.request.app['db'])

            return web.json_response(profile.to_dict(), status=200)

        raise web.HTTPNotAcceptable(text="Wrong password")
Esempio n. 13
0
def fb_registration_callback(request):
    """
    This view only gets hit by the facebook callback when a user registers.
    """
    signed_request = request.POST['signed_request']
    response = parse_signed_request(signed_request, settings.FACEBOOK_SECRET)
    data = response['registration']

    u = User(
        username=data['username'],
        email=data['email'],
        first_name=data['first_name'],
        last_name=data['last_name'],
    )

    d, m, y = data['birthday'].split('/')
    dob = datetime.datetime(year=y, month=m, date=d)

    p = Profile(
        user=u,
        dob=dob,
    )

    print response
Esempio n. 14
0
def login_on_activation(sender, user, request, **kwargs):
    profile = Profile(user=user, summa=0)
    profile.save()
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)
Esempio n. 15
0
def edit_about(userId):
    """ Profile post method to edit about """
    edit_about_form = EditAbout()

    if edit_about_form.validate_on_submit():
        birthday = edit_about_form.birthday.data
        political_spectrum = edit_about_form.political_spectrum.data
        political_party = edit_about_form.political_party.data
        favourite_news_websites = edit_about_form.favourite_news_websites.data
        allow_location_detection = edit_about_form.allow_location_detection.data

        profile = Profile.query.filter_by(user_id=userId).first()
        if profile:
            # update profile
            if profile.birthday != birthday:
                profile.birthday = birthday
                db.session.flush()

            if profile.political_spectrum != political_spectrum:
                profile.political_spectrum = political_spectrum
                db.session.flush()

            if profile.political_party != political_party:
                profile.political_party = political_party
                db.session.flush()

            if profile.favourite_news_websites != ",".join(
                    favourite_news_websites):
                profile.favourite_news_websites = ",".join(
                    favourite_news_websites)
                db.session.flush()

            if profile.allow_location_detection == True and allow_location_detection == 'no' or profile.allow_location_detection == False and allow_location_detection == 'yes':
                if allow_location_detection == 'yes':
                    profile.allow_location_detection = True
                else:
                    profile.allow_location_detection = False

                db.session.flush()
        else:
            # create new profile
            # convert allow_location_detection to bool
            allow_bool = None
            if allow_location_detection == 'yes':
                allow_bool = True
            else:
                allow_bool = False

            profile = Profile(userId, birthday, political_spectrum,
                              political_party, favourite_news_websites,
                              allow_bool, None, None, None)
            db.session.add(profile)
            db.session.flush()

        # if allow_location_detection, get location
        if profile.allow_location_detection == True:
            g = geocoder.ip('me')
            if profile.location != g.city + ", " + g.country or profile.lat != g.latlng[
                    0] or profile.lon != g.latlng[1]:
                # add location
                profile.lat = g.latlng[0]
                profile.lon = g.latlng[1]
                profile.location = g.city + ", " + g.country
                db.session.flush()

        db.session.commit()

    return redirect(url_for('about'))