Ejemplo n.º 1
0
def user_create(request):
    from hashlib import sha1

    ctx = {}
    username = request.REQUEST.get("username")
    password = request.REQUEST.get("password")
    signature = request.REQUEST.get("signature")
    email = request.REQUEST.get("email", "")
    m = sha1()
    m.update(":" + username + ":" + password + ":" + settings.SHARED_SECRET +
             ":")
    if m.hexdigest() != signature:
        ctx["ok"] = False
        return ctx

    (user, created) = User.objects.get_or_create(username=username)
    user.is_active = True
    user.email = email
    user.set_password(password)
    user.save()
    pro = UserProfile()
    pro.user = user
    pro.save()

    p = Polity.objects.get(id=1)
    p.members.add(user)

    ctx["ok"] = True
    ctx["username"] = user.username
    ctx["id"] = user.id
    return ctx
Ejemplo n.º 2
0
def hospital_registration(request):
    if request.POST is not None and request.POST != {}:
        data = request.POST
        if data['password'] != data['confirm_password']:
            messages.error(request, "passwords didn't match")
            return render(request, 'hospital_reg.html')

        usr_obj = User()

        usr_obj.email = data['hospital_email']

        usr_obj.username = data['hospital_name'].lower().replace(" ", "")
        usr_obj.set_password(data['password'])
        usr_obj.save()

        hos_profile = UserProfile()
        hos_profile.user = usr_obj
        hos_profile.hos_reg_id = data['hos_reg_id']
        hos_profile.hos_reg_date = data['hos_reg_date']
        hos_profile.hos_dir_name = data['hos_dir_name']
        hos_profile.ambulance_count = data['ambulance_count']
        hos_profile.is_hospital = True
        hos_profile.latitude = data["latitude"]
        hos_profile.longitude = data["longitude"]
        hos_profile.location_point = Point(float(data["longitude"]),
                                           float(data["latitude"]))

        hos_profile.address = data["formatted_address"]
        hos_profile.save()
        messages.success(request,
                         "Hospital Registration successfully completed")
    return render(request, 'hospital_reg.html')
Ejemplo n.º 3
0
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data.pop('user'),
                                        is_staff=True)
        _profile = UserProfile(**validated_data, user=user)
        _profile.save()

        return _profile
Ejemplo n.º 4
0
def myregister(request):
    form = UserRegisterForm()
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            email = form.cleaned_data.get('email')
            fname = form.cleaned_data.get('first_name')
            lname = form.cleaned_data.get('last_name')
            htmly = get_template('user/email.html')
            d = {'username': username}
            subject, from_email, to = 'Welcome', '*****@*****.**', email
            html_content = htmly.render(d)
            msg = EmailMultiAlternatives(subject, html_content, from_email,
                                         [to])
            msg.attach_alternative(html_content, 'text/html')
            msg.send()

            profile = UserProfile()
            profile.user = user
            profile.fname = fname
            profile.lname = lname
            profile.save()

            messages.success(request,
                             'Your Account has been successfully created!')
            return redirect('login')
    context = {'form': form}
    return render(request, 'user/signup.html', context)
Ejemplo n.º 5
0
    def post(self, request, *args, **kwargs):
        context = super(StaffFormView, self).get_context_data(**kwargs)
        context['departments'] = CompanyDepartments.objects.all()
        profile_form = UserProfileFrom(request.POST)
        form = UserCreateForm(request.POST)
        if form.is_valid() and profile_form.is_valid():
            new_user = form.save()
            new_user.email = request.POST.get('username')
            new_user.save()
            try:
                department_id = CompanyDepartments.objects.get(uuid=request.POST.get('department'))
            except CompanyDepartments.DoesNotExist:
                department_id = None

            user_profile = UserProfile(
                user_id=new_user,
                phone=request.POST.get('phone'),
                home_phone=request.POST.get('home_phone'),
                work_phone=request.POST.get('office_phone'),
                department=department_id,
                designation=request.POST.get('designation')
            )
            user_profile.save()

            return HttpResponseRedirect("/staff-list/")
        else:
            context['form'] = form
            context['profile_form'] = profile_form
            return render(request, self.template_name, context)
Ejemplo n.º 6
0
def user_create(request):
    from hashlib import sha1

    ctx = {}
    username = request.REQUEST.get("username")
    password = request.REQUEST.get("password")
    signature = request.REQUEST.get("signature")
    email = request.REQUEST.get("email", "")
    m = sha1()
    m.update(":" + username + ":" + password + ":" + settings.SHARED_SECRET + ":")
    if m.hexdigest() != signature:
        ctx["ok"] = False
        return ctx

    (user, created) = User.objects.get_or_create(username=username)
    user.is_active = True
    user.email = email
    user.set_password(password)
    user.save()
    pro = UserProfile()
    pro.user = user
    pro.save()

    p = Polity.objects.get(id=1)
    p.members.add(user)

    ctx["ok"] = True
    ctx["username"] = user.username
    ctx["id"] = user.id
    return ctx
Ejemplo n.º 7
0
    def authenticate(self, oauth_token=None):
        if oauth_token is None:
            return None
        user_info = None
        try:
            api = TroveAPI(settings.TROVE_APP_KEY, settings.TROVE_APP_SECRET, ["photos"], oauth_token)
            user_info = api.get_user_info()
        except:
            return None

        try:
            trove_profile = UserProfile.objects.get(trove_user_id=user_info["trove_internal_id"])
            return trove_profile.user
        except UserProfile.DoesNotExist:
            user = User()
            if user_info.has_key("trove_username"):
                user.username = user_info["trove_username"]
            else:
                user.username = user_info["trove_internal_id"]  # We use the trove internal id if there is no user name
            user.first_name = user_info["first_name"]
            user.last_name = user_info["last_name"]
            user.save()
            trove_profile = UserProfile()
            trove_profile.trove_user_id = user_info["trove_internal_id"]
            trove_profile.trove_access_token_key = oauth_token.key
            trove_profile.trove_access_token_secret = oauth_token.secret
            trove_profile.user = user
            trove_profile.save()
            return user
Ejemplo n.º 8
0
Archivo: models.py Proyecto: M15t/gxdy
    def create_inactive_user(self, username, email, password, 
                             first_name, 
                             last_name, 
                             career, favorite, gender, age, address, phone, city, state, country, zip,
                             send_email=True,
                             profile_callback=None ):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.

        By default, an activation email will be sent to the new
        user. To disable this, pass ``send_email=False``.
        
        """
        new_user = User.objects.create_user(username, email, password)
        new_user.email = email
        new_user.first_name = first_name
        new_user.last_name = last_name    
        new_user.is_active = False
        
        """
        set default user_group when registration
        """
        new_user.save()
        new_profile = UserProfile(user=new_user,                           
                            career=career,
                            gender=gender,
                            age=age,
                            address=address,
                            phone=phone,
                            city=city,
                            state=state,
                            country=country,
                            zip=zip
                            )
        new_profile.save()
     
        registration_profile = self.create_profile(new_user)
                   
        if send_email:
            from django.core.mail import send_mail
            current_site = Site.objects.get_current()
            
            subject = render_to_string('registration/activation_email_subject.txt',
                                       { 'site': current_site })
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines()) 
            
            fullname = new_user.last_name + " " + new_user.first_name          
            
            message = render_to_string('registration/activation_email.txt',
                                       { 'activation_key': registration_profile.activation_key,
                                         'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                         'site': current_site,
                                         'fullname': fullname,
                                         })
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        return new_user
Ejemplo n.º 9
0
def populate_users():
    print("Populating users...")

    users = [{
        "username": "******",
        "first_name": "",
        "last_name": "",
        "email": "",
        "password": make_password("admin"),
        "is_staff": True,
        "is_admin": True,
        "is_superuser": True
    }, {
        "username": "******",
        "first_name": "Bobby",
        "last_name": "Renson",
        "email": "*****@*****.**",
        "password": make_password("test"),
        "is_staff": False,
        "is_admin": False,
        "is_superuser": False
    }, {
        "username": "******",
        "first_name": "Meghan",
        "last_name": "Bright",
        "email": "*****@*****.**",
        "password": make_password("test"),
        "is_staff": False,
        "is_admin": False,
        "is_superuser": False
    }, {
        "username": "******",
        "first_name": "Victoire",
        "last_name": "Vert",
        "email": "*****@*****.**",
        "password": make_password("test"),
        "is_staff": False,
        "is_admin": False,
        "is_superuser": False
    }]

    for data in users:
        user, created = User.objects.get_or_create(username=data['username'])

        if created:
            user.first_name = data['first_name']
            user.last_name = data['last_name']
            user.email = data['email']
            user.password = data['password']
            user.is_staff = data['is_staff']
            user.is_admin = data['is_admin']
            user.is_superuser = data['is_superuser']
            user.save()

            profile = UserProfile(
                user=User.objects.get(username=data['username']),
                profile_pic="profile_images/" + data['username'].lower() +
                "-profile.jpg")
            profile.save()
Ejemplo n.º 10
0
    def save(self, commit=True):
        user = super(SgzUserCreationForm, self).save(commit=False)
        user.email = '{}@neverland.cc'.format(user.username)
        if commit:
            user.save()
            profile = UserProfile(user=user)
            profile.save()

        return user
Ejemplo n.º 11
0
def login(request,
          template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None,
          extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            # Make sure that profile exists
            try:
                UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                profile = UserProfile()
                profile.user = request.user
                profile.save()

            if hasattr(settings, 'SAML_1'):  # Is SAML 1.2 support enabled?
                if not request.user.userprofile.verified_ssn:
                    return HttpResponseRedirect(settings.SAML_1['URL'])

            if hasattr(settings, 'ICEPIRATE'):  # Is IcePirate support enabled?
                configure_external_member_db(request.user,
                                             create_if_missing=False)

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request,
                            template_name,
                            context,
                            current_app=current_app)
Ejemplo n.º 12
0
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.POST.get(redirect_field_name,
                                   request.GET.get(redirect_field_name, ''))

    if request.method == "POST":
        form = authentication_form(request, data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            # Make sure that profile exists
            try:
                UserProfile.objects.get(user=request.user)
            except UserProfile.DoesNotExist:
                profile = UserProfile()
                profile.user = request.user
                profile.save()

            request.session[LANGUAGE_SESSION_KEY] = request.user.userprofile.language

            if hasattr(settings, 'SAML_1'): # Is SAML 1.2 support enabled?
                if not request.user.userprofile.user_is_verified():
                    return HttpResponseRedirect(settings.SAML_1['URL'])

            if hasattr(settings, 'ICEPIRATE'): # Is IcePirate support enabled?
                configure_external_member_db(request.user, create_if_missing=False)

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)
    def create(self, validated_data):
        user_data = validated_data.pop('user')

        # create user profile
        user = User.objects.create_user(**user_data)

        # create user profile
        user_profile = UserProfile(**validated_data, user=user)
        user_profile.save()

        return user_profile
Ejemplo n.º 14
0
def create_profile(sender, **kw):
    if 'instance' not in kw or not kw.get('created', False):
        return
    instance = kw['instance']
    profile = UserProfile()
    profile.user = instance
    bc, im = create_barcode(u'USER-{0}'.format(instance.username[0]),
                            instance.id, instance.username)
    profile.barcode = bc
    content = ContentFile(im)
    profile._barcode.save('{0}.png'.format(bc), content)
    profile.save()
 def forwards(self, orm):
     "Whitelist any user who has whitelisted projects."
     for project in Project.objects.all():
         if project.whitelisted:
             # If user doesn't have a profile, create one
             try:
                 profile = project.user.get_profile()
             except ObjectDoesNotExist:
                 profile = UserProfile(user=project.user)
             # Whitelist the user's profile
             profile.whitelisted = True
             profile.save()
Ejemplo n.º 16
0
def user_registration(request):
    if request.POST is not None and request.POST != {}:

        data = request.POST
        # Validate password and return error
        if not request.user.is_authenticated:
            if data['password'] != data['confirm_password']:
                messages.error(request, "Passwords didn't match")
                return render(request, 'user_reg.html')

        user_obj = None
        if request.user.is_authenticated:
            user_obj = User.objects.get(id=request.user.id)
        else:
            user_obj = User()
        user_obj.email = data['email']
        user_obj.first_name = data['first_name']
        user_obj.last_name = data['last_name']
        username = user_obj.first_name
        if user_obj.last_name:
            username = username + user_obj.last_name
        user_obj.username = username.lower()
        if not request.user.is_authenticated:
            user_obj.set_password(data['password'])
        user_obj.save()

        user_profile = None
        if request.user.is_authenticated:
            # get_or_create is used while creating profile when user logged in via Google.
            user_profile, created = UserProfile.objects.get_or_create(
                user=request.user)
        else:
            user_profile = UserProfile()
            user_profile.user = user_obj
        user_profile.gender = data['gender']
        user_profile.dob = data['dob']
        user_profile.mobile_number = int(data['mobile'])
        if "alternate_mobile" in data and data[
                'alternate_mobile'] != "" and data[
                    'alternate_mobile'] is not None:
            user_profile.alternate_number = int(data['alternate_mobile'])
        user_profile.blood_group = data['blood_group']

        user_profile.address = data["formatted_address"]
        user_profile.save()

        if request.user.is_authenticated:
            messages.success(request, "User Updated.")
            return redirect('view_profile')
        messages.success(request, "User successfully created.")

    return render(request, 'user_reg.html')
Ejemplo n.º 17
0
    def create_user(self, is_active, device_id, email=None):
        consumer_id = generate_unique_customer_id()
        password = consumer_id + settings.PASSWORD_POSTFIX
        user_obj = User.objects.create(username=consumer_id)
        user_obj.set_password(password)
        user_obj.is_active = is_active
        if email:
            user_obj.email = email
        user_obj.save(using=settings.BRAND)
        bituser_obj = UserProfile(user=user_obj, device_id=device_id)

        bituser_obj.save()
        return {'bituser_obj': bituser_obj}
Ejemplo n.º 18
0
 def process_request(self, request):
     if request.user.is_authenticated():
         try:
             request.session['django_language'] = request.user.get_profile().language
         except AttributeError:
             # pass
             pro = UserProfile()
             pro.user = request.user
             pro.language = settings.LANGUAGE_CODE
             pro.save()
             request.session['django_language'] = pro.language
     else:
         request.session['django_language'] = "is"
Ejemplo n.º 19
0
def adduser(request, ssn=None, name=None, email=None, added=None, username=None):
    if ssn is None:
        assert(request.GET.get('key') == settings.ICEPIRATE['key'])

    # Parse args...
    ssn = ssn or request.GET.get('ssn')
    name = name or request.GET.get('name')
    email = email or request.GET.get('email')
    added = added or request.GET.get('added')
    username = username or request.GET.get('username')
    if added:
        added = datetime.strptime(added, '%Y-%m-%d %H:%M:%S')
    else:
        added = timezone.now()

    # Look up all the users that match
    users = []
    if ssn:
        users.extend(User.objects.filter(userprofile__verified_ssn=ssn))
    if username:
        users.extend(User.objects.filter(username=username))
    if email:
        users.extend(User.objects.filter(email=email))

    # Update or create user
    try:
        user = users[0]
        # Sanity checks...
        assert(len([u for u in users if u != user]) == 0)
        if user.userprofile.verified_ssn:
            assert(user.userprofile.verified_ssn == ssn)
        else:
            # User exist, is not verified! Just update SSN.
            user.userprofile.verified_ssn = ssn
            user.userprofile.save()
    except IndexError:
        # User does not exist. Create user, yay!
        if not username:
            username = _make_username(name, email)
        user = User(username=username, email=email)
        user.save()
        prof = UserProfile(user=user, verified_ssn=ssn, joined_org=added)
        prof.save()

    response_data = _icepirate_user_data(user)
    response_data.update({
        'reset_url': _password_reset_url(user),
        'success': True})

    return HttpResponse(
        json.dumps(response_data), content_type='application/json')
Ejemplo n.º 20
0
 def process_request(self, request):
     if request.user.is_authenticated():
         try:
             request.session['django_language'] = request.user.get_profile(
             ).language
         except AttributeError:
             # pass
             pro = UserProfile()
             pro.user = request.user
             pro.language = settings.LANGUAGE_CODE
             pro.save()
             request.session['django_language'] = pro.language
     else:
         request.session['django_language'] = "is"
Ejemplo n.º 21
0
def load_users(file):
    print '\nimporting users'
    for e in json.load(file):
        try:
            user = User.objects.filter(username=e['username']).get()
        except User.DoesNotExist:
            user = User.objects.create_user(e['username'], e['email'], 'asdfgh')
            user.save()
            
            profile = UserProfile(user=user)
            profile.save()
            
        print '.',
        sys.stdout.flush()
Ejemplo n.º 22
0
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            username = new_user.username
            email = new_user.email
            password = request.POST['password1']

            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt + email).hexdigest()
            key_expires = datetime.datetime.today() + datetime.timedelta(2)

            #Get user by username
            user = get_user_model().objects.get(username=username)

            # Create and save user profile
            new_profile = UserProfile(user=user,
                                      activation_key=activation_key,
                                      key_expires=key_expires)
            new_profile.save()

            # Send email with activation key
            email_subject = 'Account confirmation'
            email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
          48hours http://ivebeenfound-dev2.elasticbeanstalk.com/accounts/confirm/%s" % (
                username, activation_key)

            send_mail(email_subject,
                      email_body,
                      '*****@*****.**', [email],
                      fail_silently=False)

            context = RequestContext(request, {
                'request': request,
                'user': request.user,
                'email': email
            })

            return render_to_response('public/confirm_sent.html',
                                      context_instance=context)
        else:
            pass
    context = RequestContext(request, {
        'request': request,
        'user': request.user
    })
    return render_to_response('public/registration_form.html',
                              context_instance=context)
Ejemplo n.º 23
0
def signup(request):
    from forms import SignupForm

    if request.method == 'POST':
        # process signup form and create account
        form = SignupForm(request.POST)
        if form.is_valid():
            user = User()
            user.username = form.cleaned_data['username']
            user.set_password(form.cleaned_data['password1'])
            user.email = form.cleaned_data['email']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.is_active = True
            user.save()

            profile = UserProfile(paid_user=True, user=user)
            profile.save()

            # send a mail with registration details
            from django.template.loader import render_to_string
            from django.core.mail import EmailMessage

            email = EmailMessage('Welcome to Trackpattern',
                render_to_string('registration/welcome_mail.txt',
                        {'username': user.username,
                         'first_name': user.first_name}),
                from_email='*****@*****.**',
                to=[user.email])
            email.send()
            _out = {'username':user.username,'email':user.email,'first_name':user.first_name,'last_name':user.last_name,'Would you like to sign up to our mailing list to receive free information about analytics and data driven marketing?' : form.cleaned_data['question_1'],'ts':str(datetime.datetime.now())}
            emailtoadmin = EmailMessage('Trackpattern - New user has registered',body=json.dumps(_out),from_email="*****@*****.**",to=["*****@*****.**",'*****@*****.**'])
            emailtoadmin.send()
            #reset = True
#            return redirect(
#                'https://trackpattern.chargify.com/h/46549/subscriptions/new/?reference=%s&first_name=%s&last_name=%s&email=%s' % (
#                    user.id, user.first_name, user.last_name, user.email))

            login_user = authenticate(username=user.username, password=form.cleaned_data['password1'])
            auth_login(request, login_user)
            return redirect('/home/')

    else:
        form = SignupForm(initial={'question_1': True})
    return render_to_response('registration/signup.html',
            {'form': form, },
        context_instance=RequestContext(request))
Ejemplo n.º 24
0
    def form_valid(self, form):
        '''
        Creates a new user
        '''
        team = form.save()

        username = form.instance.name.lower().replace(' ', '')
        password = password_generator(8)
        user = User.objects.create_user(username=username, password=password)

        profile = UserProfile()
        profile.team = team
        profile.user = user
        profile.save()

        self.request.session['new_user'] = {'username': username, 'password': password}
        return super(TeamAddView, self).form_valid(form)
Ejemplo n.º 25
0
	def register(self, request, **cleaned_data):
		'''Register a new user, saving the User and UserProfile data.'''
		user = User()
		for field in user._meta.fields:
			if field.name in cleaned_data:
				setattr(user, field.name, cleaned_data[field.name])
		# the password has been validated by the form

		user.set_password(cleaned_data['password2'])
		user.save()

		profile = UserProfile(user=user)
		for field in profile._meta.fields:
			if field.name in cleaned_data:
				setattr(profile, field.name, cleaned_data[field.name])

		print "request data: image field"
		img_data = request.POST.get("image")
		# If none or len 0, means illegal image data
		if img_data == None or len(img_data) == 0:
			pass

		# Decode the image data
		img_data = base64.b64decode(img_data)
		filename = "%s.png" % uuid.uuid4()

		# XXX make the upload path a fixed setting in models, since it's
		# reference in three places
		upload_path = "data/avatars/%s/" % user.username
		upload_abs_path = os.path.join(settings.MEDIA_ROOT, upload_path)
		if not os.path.exists(upload_abs_path):
			os.makedirs(upload_abs_path)
		full_file_name = os.path.join(upload_abs_path, filename)

		with open(full_file_name, 'wb') as f:
			f.write(img_data)
			f.close()

		profile.image = full_file_name
		profile.save()

		new_user = authenticate(username=user.username, password=cleaned_data['password2'])
		login(request, new_user)
		signals.user_activated.send(sender=self.__class__, user=new_user, request=request)
		return new_user
Ejemplo n.º 26
0
    def register(self, request, **cleaned_data):
        """Register a new user, saving the User and UserProfile data."""
        user = User()
        for field in user._meta.fields:
            if field.name in cleaned_data:
                setattr(user, field.name, cleaned_data[field.name])
                # the password has been validated by the form

        user.set_password(cleaned_data["password2"])
        user.save()

        profile = UserProfile(user=user)
        for field in profile._meta.fields:
            if field.name in cleaned_data:
                setattr(profile, field.name, cleaned_data[field.name])

        print "request data: image field"
        img_data = request.POST.get("image")
        # If none or len 0, means illegal image data
        if img_data == None or len(img_data) == 0:
            pass

            # Decode the image data
        img_data = base64.b64decode(img_data)
        filename = "%s.png" % uuid.uuid4()

        # XXX make the upload path a fixed setting in models, since it's
        # reference in two places
        upload_path = "data/avatars/%s/" % user.username
        upload_abs_path = os.path.join(settings.MEDIA_ROOT, upload_path)
        if not os.path.exists(upload_abs_path):
            os.makedirs(upload_abs_path)
        full_file_name = os.path.join(upload_abs_path, filename)

        with open(full_file_name, "wb") as f:
            f.write(img_data)
            f.close()

        profile.image = full_file_name
        profile.save()

        new_user = authenticate(username=user.username, password=cleaned_data["password2"])
        login(request, new_user)
        signals.user_activated.send(sender=self.__class__, user=new_user, request=request)
        return new_user
Ejemplo n.º 27
0
def register(request):
  if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          new_user = form.save()
          username = new_user.username
          email = new_user.email
          password = request.POST['password1']
          

          salt = hashlib.sha1(str(random.random())).hexdigest()[:5]            
          activation_key = hashlib.sha1(salt+email).hexdigest()            
          key_expires = datetime.datetime.today() + datetime.timedelta(2)

          #Get user by username
          user=get_user_model().objects.get(username=username)

          # Create and save user profile                                                                                                                                  
          new_profile = UserProfile(user=user, activation_key=activation_key, 
              key_expires=key_expires)
          new_profile.save()

          # Send email with activation key
          email_subject = 'Account confirmation'
          email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
          48hours http://ivebeenfound-dev2.elasticbeanstalk.com/accounts/confirm/%s" % (username, activation_key)

          send_mail(email_subject, email_body, '*****@*****.**',
              [email], fail_silently=False)

          context = RequestContext(request,
                           {'request': request,
                            'user': request.user,
                            'email': email
                            })

          return render_to_response('public/confirm_sent.html', context_instance=context)
      else:
        pass
  context = RequestContext(request,
                           {'request': request,
                            'user': request.user
                            })
  return render_to_response('public/registration_form.html', context_instance=context)
Ejemplo n.º 28
0
 def save(self):
     user = User(
         username=self.validated_data['username'],
         first_name=self.validated_data['first_name'],
         last_name=self.validated_data['last_name'],
         email=self.validated_data['email'],
     )
     password = self.validated_data['password']
     password2 = self.validated_data['password2']
     if password != password2:
         raise serializers.ValidationError(
             {'password': '******'})
     user.set_password(password)
     userprofile = UserProfile(user=user,
                               user_description="Modifie ton profil",
                               city="Modifie ton profil")
     user.save()
     userprofile.save()
     return user
Ejemplo n.º 29
0
def protweet_registration(request):
	if request.method == "POST":
		form = ProTweetRegistrationForm(request.POST)
		msg = {'form': form}
		if form.is_valid():
			correct_data = form.cleaned_data
			#1. Creating the User
			try:
				user = User.objects.create_user (
					username = correct_data['tweet_handle'].lower(),
					first_name = correct_data['name'],
					last_name = 'none',
					email = correct_data['email']
				)
				
				user.set_password(correct_data['password'])
				user.save()
				
			except Exception, e:
				print 'Unable to Create User'
				print e
				return HttpResponseRedirect('/')
			
			#2. Initializing UserProfile
			try:
				user_profile = UserProfile(user = user)
				user_profile.save()
			except Exception, e:
				print 'Unable to Initialize UserProfile'
				print e
				#ToDo: Remove the previous failed user from db
				return HttpResponseRedirect('/')
				
			#3. Authentication User
			username = correct_data.get('tweet_handle')
			password = correct_data.get('password')
			
			user = authenticate(username = username, password = password)

			#5. Loggin in the user
			login(request, user)
			
			return HttpResponseRedirect('/home')
Ejemplo n.º 30
0
	def register(self, request, **cleaned_data):
		'''Register a new user, saving the User and UserProfile data.'''
		user = User()
		for field in user._meta.fields:
			if field.name in cleaned_data:
				setattr(user, field.name, cleaned_data[field.name])
		# the password has been validated by the form
		user.set_password(cleaned_data['password2'])
		user.save()

		profile = UserProfile(user=user)
		for field in profile._meta.fields:
			if field.name in cleaned_data:
				setattr(profile, field.name, cleaned_data[field.name])
		profile.save()

		new_user = authenticate(username=user.username, password=cleaned_data['password2'])
		login(request, new_user)
		signals.user_activated.send(sender=self.__class__, user=new_user, request=request)
		return new_user
Ejemplo n.º 31
0
class StatusProcessModelTest(TestCase):
    def setUp(self):
        self.user = UserProfile(email='*****@*****.**',
                                name='Test',
                                url='https://test.com/postback/',
                                password='******')
        self.user.save()

        self.obj = StatusProcess(user_profile=self.user,
                                 id_process='12345678901',
                                 status_process='Em análise')
        self.obj.save()

    def test_create(self):
        self.assertTrue(StatusProcess.objects.exists())
        self.assertTrue(UserProfile.objects.exists())

    def test_str(self):
        self.assertEqual('Em análise', str(self.obj))
        self.assertEqual('*****@*****.**', str(self.user))
Ejemplo n.º 32
0
	def register(self, request, **cleaned_data):
		'''Register a new user, saving the User and UserProfile data.'''
		user = User()
		for field in user._meta.fields:
			if field.name in cleaned_data:
				setattr(user, field.name, cleaned_data[field.name])
		# the password has been validated by the form
		user.set_password(cleaned_data['password2'])
		user.save()

		profile = UserProfile(user=user)
		for field in profile._meta.fields:
			if field.name in cleaned_data:
				setattr(profile, field.name, cleaned_data[field.name])
		profile.save()

		new_user = authenticate(username=user.username, password=cleaned_data['password2'])
		login(request, new_user)
		signals.user_activated.send(sender=self.__class__, user=new_user, request=request)
		return new_user
Ejemplo n.º 33
0
def subscribe(request):
    try:
        data = request.POST
        if request.method == 'POST':
            if not User.objects.filter(email=data['email']):
                user_obj = User(username=data['email'],
                                first_name=data['name'],
                                email=data['email'])
                user_obj.save()
                dob_tuple = (int(data['dob'].split('/')[1]),
                             int(data['dob'].split('/')[0]))
                dob = datetime.datetime.strptime(data['dob'], '%d/%m/%Y')
                zodiac = get_sign_from_date(dob_tuple)
                user_prof_obj = UserProfile(user=user_obj,
                                            zodiac=zodiac,
                                            dob=dob)
                user_prof_obj.save()

                today = time.strftime("%Y-%m-%d")
                zodiacs = Zodiac.objects.filter(date=today)
                prediction = 'None'
                if zodiacs:
                    predictions = zodiacs[0].zodiac.filter(
                        zodiac__iexact=zodiac)
                    if predictions:
                        prediction = predictions[0].prediction
                context = {
                    'zodiac': zodiac,
                    'prediction': prediction,
                    'today': datetime.datetime.now(),
                    'status': True
                }
            else:
                context = {'status': False}

            return render(request, 'core/success.html', context)
        else:
            return HttpResponseRedirect('/')
    except Exception as e:
        logger.error(traceback.format_exc())
        return HttpResponseRedirect('/')
Ejemplo n.º 34
0
    def register(self, request, **cleaned_data):
        '''Register a new user, saving the User and UserProfile data.'''
        # We can't use RegistrationManager.create_inactive_user()
        # because it doesn't play nice with saving other information
        # in the same transaction.
        user = User(is_active=False)
        for field in user._meta.fields:
            if field.name in cleaned_data:
                setattr(user, field.name, cleaned_data[field.name])
        user.save()

        profile = UserProfile(user=user)
        for field in profile._meta.fields:
            if field.name in cleaned_data:
                setattr(profile, field.name, cleaned_data[field.name])
        profile.save()

        registration_profile = RegistrationProfile.objects.create_profile(user)
        registration_profile.send_activation_email(Site.objects.get_current())

        signals.user_registered.send(sender=self.__class__, user=user, request=request)
Ejemplo n.º 35
0
def create_foursquare_user(foursquare_id, access_token):
    # Since we don't have a username, just generate one
    username = "******" + foursquare_id
    fake_email = username + "@example.com" # Don't know why we have to do this
    user = User.objects.create_user(username=username,email=fake_email,password=None)
    user.save()

    try:
        user_profile = UserProfile(
            user = user, 
            foursquare_id = foursquare_id, 
            foursquare_access_token = access_token)
        user_profile.save()
    except Exception:
        # If profile creation fails, clean up the user too
        user.delete()

        # Reraise exception
        raise

    return user
Ejemplo n.º 36
0
def subscribe(request):
    try:
        data = request.POST
        if request.method == 'POST':
            if not User.objects.filter(email=data['email']):
                user_obj = User(username=data['email'],
                                    first_name=data['name'],
                                    email=data['email'])
                user_obj.save()
                dob_tuple = (int(data['dob'].split('/')[1]),int(data['dob'].split('/')[0]))
                dob = datetime.datetime.strptime(data['dob'], '%d/%m/%Y')
                zodiac = get_sign_from_date(dob_tuple)
                user_prof_obj = UserProfile(user=user_obj,zodiac=zodiac,dob=dob)
                user_prof_obj.save()

                today = time.strftime("%Y-%m-%d")
                zodiacs = Zodiac.objects.filter(date=today)
                prediction = 'None'
                if zodiacs:
                    predictions =  zodiacs[0].zodiac.filter(zodiac__iexact=zodiac)
                    if predictions:
                        prediction = predictions[0].prediction
                context = {
                    'zodiac' : zodiac,
                    'prediction' : prediction,
                    'today' :datetime.datetime.now(),
                    'status' : True
                }
            else:
                context = {
                    'status' : False
                }

            return render(request,'core/success.html',context)
        else:
            return HttpResponseRedirect('/')
    except Exception as e:
        logger.error(traceback.format_exc())
        return HttpResponseRedirect('/')
Ejemplo n.º 37
0
def register(request):
    error_messages = list();
    if request.method == 'GET':
        return render(request,'index/signup.html',{'error_messages':error_messages})

    #email format verfication should be done in FE
    email = request.POST.get("email","").strip()
    passwd = request.POST.get("pass_confirmation", "").strip()
    passwd_confirm = request.POST.get("pass", "")
    name = request.POST.get("name", "").strip()

    if len(email)==0 or len(passwd)==0 or passwd != passwd_confirm:
        error_messages.append("Invalid email or password.")
        return render(request,'index/signup.html',{'error_messages':error_messages})

    try:
        validate_email(email)
    except ValidationError as e:
        error_messages.append("Invalid email.")
        return render(request,'index/signup.html',{'error_messages':error_messages})

    #first need to check whether email had been registered already or not
    if User.objects.filter(email=email).count() > 0:
        error_messages.append("User already exists.")
        return render(request,'index/signup.html',{'error_messages':error_messages})

    try:
        user = User.objects.create_user(username=email, email=email, password=passwd)
        user.save()
        profile = UserProfile(user=user, name=name)
        profile.save()
        user = authenticate(username=email,password=passwd)
        login(request,user)
        return redirect('/')
    except Exception,e:
        raise e
        error_messages.append("Cannot create user.");
        return render(request,'index/signup.html',{'error_messages':error_messages})
Ejemplo n.º 38
0
def account(request):
    user = request.user

    try:
        profile = UserProfile.objects.get(user=request.user)
    except:
        profile = UserProfile()
        profile.new(user, ip_address=get_remote_ip(request))
        profile.save()

    form = AccountForm({"phone": profile.phone, "email": user.email})
    error = ""

    if request.method == "POST":
        form = AccountForm(request.POST)
        if form.is_valid():
            # user.email = form.cleaned_data['email']
            user.save()
            profile.phone = form.cleaned_data["phone"]
            profile.save()
            return index(request, "Your account has successfully been edited.")
        else:
            error = form.errors
    return load_page(request, "account.html", {"form": form, "error": error})
Ejemplo n.º 39
0
def signup(request):
    from forms import SignupForm

    if request.method == 'POST':
        # process signup form and create account
        form = SignupForm(request.POST)
        if form.is_valid():
            user = User()
            user.username = form.cleaned_data['username']
            user.set_password(form.cleaned_data['password1'])
            user.email = form.cleaned_data['email']
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.is_active = True
            user.save()

            profile = UserProfile(paid_user=True, user=user)
            profile.save()

            # send a mail with registration details
            from django.template.loader import render_to_string
            from django.core.mail import EmailMessage

            email = EmailMessage('Welcome to Trackpattern',
                                 render_to_string(
                                     'registration/welcome_mail.txt', {
                                         'username': user.username,
                                         'first_name': user.first_name
                                     }),
                                 from_email='*****@*****.**',
                                 to=[user.email])
            email.send()
            _out = {
                'username':
                user.username,
                'email':
                user.email,
                'first_name':
                user.first_name,
                'last_name':
                user.last_name,
                'Would you like to sign up to our mailing list to receive free information about analytics and data driven marketing?':
                form.cleaned_data['question_1'],
                'ts':
                str(datetime.datetime.now())
            }
            emailtoadmin = EmailMessage(
                'Trackpattern - New user has registered',
                body=json.dumps(_out),
                from_email="*****@*****.**",
                to=["*****@*****.**", '*****@*****.**'])
            emailtoadmin.send()
            #reset = True
            #            return redirect(
            #                'https://trackpattern.chargify.com/h/46549/subscriptions/new/?reference=%s&first_name=%s&last_name=%s&email=%s' % (
            #                    user.id, user.first_name, user.last_name, user.email))

            login_user = authenticate(username=user.username,
                                      password=form.cleaned_data['password1'])
            auth_login(request, login_user)
            return redirect('/home/')

    else:
        form = SignupForm(initial={'question_1': True})
    return render_to_response('registration/signup.html', {
        'form': form,
    },
                              context_instance=RequestContext(request))