Exemple #1
0
    def test_model(self):
        testProf1 = Profile(name="Test", username="******", password="******", \
                            lat=123, lng=123, school="school", \
                            courses="courses", preferences="preferences", \
                            interests="interests")
        testProf1.save()
        testProf2 = Profile(name="Test", username="******", password="******", \
                            lat=123, lng=123, school="school", \
                            courses="courses", preferences="preferences", \
                            interests="interests")
        testProf2.save()
        match = Match(user1=testProf1,
                      user2=testProf2,
                      score=100,
                      user1HasMatched=False,
                      user2HasMatched=False,
                      user1accepted=True,
                      user2accepted=True)
        match.save()
        msg = Message(sender=testProf1, matchID=match, message="message")
        msg.save()
        assert msg.__str__() == "message"
        assert msg.toJson()["sender"] == testProf1.id

        assert createMessage(testProf1.id, match.id, "Hello",
                             False)["id"] != -1
        assert createMessage(testProf1.id, match.id, "Hello", True)["id"] != -1
        assert createMessage(1000, match.id, "Hello", False)["id"] == -1

        assert messageLog(match.id) != None
Exemple #2
0
    def check_users(self):
        start_time = time.time()
        emails = []
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM smf_members;")
        rows = cursor.fetchall()
        for row in rows:
            try:
                user = User.objects.get(username=row[1])
            except User.DoesNotExist:
                try:
                    print "User %s does not exist. Creating" % row[1]
                    user = User.objects.create_user(row[1], row[12])
                    user.set_unusable_password()
                    user.save()

                    profile = Profile()
                    profile.user = user
                    profile.personal_text = row[13]
                    profile.location = row[18]
                    profile.old_user_id = row[0]
                    profile.website = row[17]
                    profile.title = row[32]
                    profile.save()
                except Exception, e:
                    print "Could not create user %s, %s" % (row[1], str(e))
Exemple #3
0
 def create(self, user_validate_data, profile_validate_data):
     user = self.model(**user_validate_data)
     profile = Profile(**profile_validate_data)
     profile.save()
     user.profile = profile
     user.save()
     return user
Exemple #4
0
def student_status_confirm(request):
    import urllib
    import simplejson as json
    from hashlib import md5

    import settings

    user = request.user
    if not user.is_authenticated():
        raise Http302('/login/')
    try:
        userprofile = user.get_profile()
    except:
        userprofile = Profile(user=user)
    login = request.POST.get('login', '')
    password = md5(request.POST.get('password',
                                    '').encode('utf-8')).hexdigest()
    params = "login=%s&password=%s" % (login.encode('utf-8'), password)
    result = urllib.urlopen(
        settings.EDUCON_URL,
        params).read() or u"Произошла досадная ошибка, попробуйте позже."
    try:
        userprofile.student_id = int(result)
        userprofile.save()
        return HttpResponse(u"Статус студента подтверждён, обновите профиль.",
                            mimetype="text/plain")
    except:
        return HttpResponse(content=result, mimetype="text/plain", status=500)
Exemple #5
0
def register(request):
    if request.method == "POST":
        try:
            user = User.objects.create_user(
                email=request.POST['email'],
                password=request.POST['password'],
            )
            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']
            user.save()
            profile = Profile()
            profile.user = user
            profile.save()
            is_employer = (request.POST['is_employer'] == '0')
            if (is_employer):
                company = Company()
                company.user = user
                company.save()

            return render(request, 'registration/edit.html',
                          {'is_company': is_employer})
        except:
            return render(request, 'registration/edit.html',
                          {'is_company': False})
    else:
        return render(request, 'registration/registration.html')
Exemple #6
0
 def test_to_string(self):
     testProf1 = Profile(name="Test", username="******", password="******", \
                         lat=123, lng=123, school="school", \
                         courses="courses", preferences="preferences", \
                         interests="interests")
     testProf1.save()
     testProf2 = Profile(name="Test", username="******", password="******", \
                         lat=123, lng=123, school="school", \
                         courses="courses", preferences="preferences", \
                         interests="interests")
     testProf2.save()
     match = Match(user1=testProf1,
                   user2=testProf2,
                   score=100,
                   user1HasMatched=False,
                   user2HasMatched=False,
                   user1accepted=True,
                   user2accepted=True)
     match.save()
     msg = Message(sender=testProf1, matchID=match, message="message")
     msg.save()
     assert msg.__str__() == "message"
Exemple #7
0
def email_confirm(request, user_id, code):
    user = User.objects.get(id=user_id)
    true_code = uuid5(UUID(settings.UUID_NAMESPACE_FOR_EMAIL_CONFIRM),
                      str(user.email))
    if str(true_code) == str(code):
        try:
            profile = user.get_profile()
        except:
            profile = Profile(user=user)
        profile.is_email_confirmed = True
        profile.save()
        return HttpResponse(u'Ваш email подтвержден')
    else:
        return HttpResponse(u'Код подтверждения не верен')
Exemple #8
0
def edit(request):
    from forms import ProfileForm
    context = {}
    user = request.user
    if not user.is_authenticated():
        raise Http302('/login/')
    try:
        profile = user.get_profile()
    except:
        profile = None
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user.last_name = data['last_name']
            user.first_name = data['first_name']

            drop_email = user.email != data['email']

            user.email = data['email']
            user.save()
            if data['middle_name'] or data['subscription']:
                if profile:
                    profile.middle_name = data['middle_name']
                    profile.subscription = data['subscription']
                else:
                    profile = Profile(user=user,
                                      middle_name=data['middle_name'],
                                      subscription=data['subscription'])

                if drop_email:
                    profile.is_email_confirmed = False

                profile.save()
            return u'Данные успешно сохранены'
        context['form'] = form
    else:
        data = {
            'last_name': user.last_name,
            'first_name': user.first_name,
            'email': user.email
        }
        if profile:
            data['middle_name'] = profile.middle_name
            data['subscription'] = profile.subscription
        context['form'] = ProfileForm(initial=data)
    context['profile'] = profile
    return template_loader.get_template("profile/edit.html").render(
        RequestContext(request, context))
Exemple #9
0
def user_save(sender, instance, created, signal, *args, **kwargs):
    if created:
        if instance.is_superuser or instance.is_staff:
            user_obj = User.objects.get(pk=instance.pk)
            profile_obj = Profile(user=user_obj, type='admin-person')
            profile_obj.save()
        else:
            user_obj = User.objects.get(pk=instance.pk)
            profile_obj = Profile(user=user_obj, type='employee-person')
            profile_obj.save()
    else:
        if instance.is_superuser or instance.is_staff:
            user_obj = User.objects.get(pk=instance.pk)
            profile_obj = Profile.objects.filter(user=user_obj).first()
            if profile_obj:
                employee_obj = Employee.objects.filter(
                    profile=profile_obj).first()
                if employee_obj:
                    instance.first_name = employee_obj.first_name
                    instance.last_name = employee_obj.last_name
                    # instance.first_name = employee_obj.e
                else:
                    profile_obj.type = 'admin-person'
                    profile_obj.save()
Exemple #10
0
    def convert_users(self):
        start_time = time.time()
        emails = []
        users = User.objects.values('email')
        for user in users:
            emails.append(user["email"])

        print emails

        cursor = connection.cursor()
        cursor.execute("SELECT * FROM smf_members;")
        rows = cursor.fetchall()

        for row in rows:
            old_id = row[0]
            username = row[1]
            date_registered = row[2]
            post_count = row[3]
            last_login = row[6]
            email = row[12]
            personal_text = row[13]
            gender = row[14]
            website = row[17]
            location = row[18]

            if email in emails:
                user = User.objects.get(email=row[12])
                profile, created = Profile.objects.get_or_create(user=user)
                if created:
                    profile.save()
            else:
                try:
                    user = User.objects.create_user(row[1], row[12])
                    user.set_unusable_password()
                    user.save()

                    profile = Profile()
                    profile.user = user
                    profile.personal_text = row[13]
                    profile.location = row[18]
                    profile.old_user_id = row[0]
                    profile.website = row[17]
                    profile.title = row[32]
                    profile.save()
                except Exception, e:
                    with open("conversion_errors.log", "a") as myfile:
                        myfile.write("%s \r\n %s\r\n\r\n" % (row[1], str(e)))
Exemple #11
0
def register(request):

    
    args={}
    args.update(csrf(request))

    if request.POST:
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        accountType = request.POST['accountType']

        user = User.objects.create_user(username=username,email=email,password=password)
        profile = Profile(user=user)

        if request.POST.get('ref') is not None:
            ref = request.POST['ref']
            userReferer = User.objects.get(username=ref)
            userRefererProfile = userReferer.profile
            userRefererProfile.members_referred+=1
            userRefererProfile.save()
        else:
            pass
        
        if accountType == 'influencer':
            profile.influencer = True
        elif accountType == 'brand':
            profile.brand = True

        profile.save()

        user = auth.authenticate(username=username,password=password)
        if user is not None:
            auth.login(request,user)
            return HttpResponseRedirect('/perkboard/')
        else:
            return HttpResponse('Wrong account details')

        return HttpResponseRedirect('/perkboard/')
    else:
          
        return HttpResponse('Something went wrong!')
Exemple #12
0
def save_profile(backend, user, response, *args, **kwargs):
    try:
        profile = user.profile
    except:
        profile = Profile(user_id=user.id)
    image_url = None
    print(response)
    if backend.name == 'twitter':
        image_url = response.get('profile_image_url_https',
                                 '').replace('_normal', '')
    elif backend.name == 'facebook':
        fb_id = response.get('id')
        if fb_id:
            image_url = 'https://graph.facebook.com/{}/picture?height=300&width=300'.format(
                fb_id)
    elif backend.name == 'google-oauth2':
        try:
            image_url = response['image']['url'].replace('sz=50', 'sz=300')
        except:
            pass
    if image_url:
        profile.social_photo_url = image_url
    profile.save()
Exemple #13
0
def set_initial_user_names(request, user, sociallogin=None, **kwargs):
    """
    sociallogin.account.provider  # e.g. 'twitter'
    sociallogin.account.get_avatar_url()
    sociallogin.account.get_profile_url()
    sociallogin.account.extra_data['screen_name']
    """

    profile = Profile()
    if sociallogin:
        if sociallogin.account.provider == 'facebook':
            profile.gender_type = sociallogin.account.extra_data['gender']
            #verified = sociallogin.account.extra_data['verified']

    #I want to get country and city of user from ip address.
    from ipware import get_client_ip
    client_ip, is_routable = get_client_ip(request)
    if client_ip is None:
        pass  # Unable to get the client's IP address
    else:
        # We got the client's IP address
        if is_routable:  # The client's IP address is publicly routable on the Internet
            import requests
            r = requests.get('http://usercountry.com/v1.0/json/' +
                             str(client_ip))
            result = r.json()
            if result['status'] == "success":
                profile.country = result['country']['alpha-2']
                profile.city = result['region']['city']
            else:  #result returns failure
                pass
        else:
            pass  # The client's IP address is private

    profile.user = user
    profile.save()