Beispiel #1
0
 def testAutoProfileCreate(self):
   ex_user = users.User('*****@*****.**')
   u = User(user = ex_user, username = '******')
   u.put()
   self.assert_(u.key())
   self.assertEqual(UserProfile.all().filter('user =', u).count(), 0)
   profile = u.get_profile()
   self.assertEquals(profile.user, u)
   self.assertEquals(profile.activity_count, 0)
Beispiel #2
0
def create_admin_user(request):
    user = User.get_by_key_name('admin')
    if not user :
        user = User(key_name='admin', username=settings.ADMIN_USERNAME,
            email=settings.DEFAULT_FROM_EMAIL, first_name=settings.ADMIN_FIRST_NAME, last_name=settings.ADMIN_LAST_NAME,
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password(settings.SECRET_KEY)
        user.put()
    return render_to_response(request, 'main.html')
Beispiel #3
0
def create_user(claimed_id, server_url):
    """Creates and returns a User model.
       
     Params:
       claimed_id: ?
       server_url: ?
  """
    user = User(claimed_id=claimed_id, server_url=server_url)
    user.put()
    return user
Beispiel #4
0
def create_admin_user(request):
    user = User.get_by_key_name('admin')
    if not user or not (user.is_active and user.is_staff and
            user.is_superuser and user.check_password('admin')):
        user = User(key_name='admin', username='******',
            email='admin@localhost', first_name='Boss', last_name='Admin',
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password('admin')
        user.put()
    return render_to_response(request, 'cook/admin_created.html')
Beispiel #5
0
def create_admin_user(request):
    user = User.get_by_key_name('admin')
    if not user or user.username != 'admin' or not (user.is_active and
            user.is_staff and user.is_superuser and
            user.check_password('admin')):
        user = User(key_name='admin', username='******',
            email='admin@localhost', first_name='Boss', last_name='Admin',
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password('admin')
        user.put()
    return render_to_response(request, 'myapp/admin_created.html')
Beispiel #6
0
def create_admin_user(request):
    user = User.get_by_key_name('admin')
    if not user or user.username != 'admin' or not (user.is_active and
            user.is_staff and user.is_superuser and
            user.check_password('admin')):
        user = User(key_name='admin', username='******',
            email='admin@localhost', first_name='Boss', last_name='Admin',
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password('admin')
        user.put()
    return HttpResponse("tamam")
Beispiel #7
0
  def testParseOfTcxWithErrors(self):
    testfile = open('gcycle/test/valid_multi_lap_with_short_lap.tcx').read()
    acts = pytcx.parse_tcx(testfile)
    act = acts[0]
    u = User(username = '******', user = users.User('*****@*****.**'))
    u.put()
    a = Activity._put_activity_record(act, u, 'tcx',
                                      'source, which is ignored')

    self.assert_(a)
    self.assertEqual(len(a.sourcedatafile_set.get().parse_errors), 1)
Beispiel #8
0
def create_admin_user(request):
    from django.contrib.auth.models import User
    user = User.get_by_key_name('admin')
    if not user or user.username != 'admin' or not (user.is_active and
            user.is_staff and user.is_superuser and
            user.check_password('admin')):
        user = User(key_name='admin', username='******',
            email='admin@localhost', first_name='Boss', last_name='Admin',
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password('admin')
        user.put()
    return HttpResponseRedirect('/')
def create_user(request):

    try:
        u = User.all().filter("username = "******"admin").fetch(1)[0]
    except IndexError:
        u = None

    if not u:
        u = User(username="******")
        u.set_password('password')
        u.put()

    return HttpResponse(u"Created")
Beispiel #10
0
def create_admin_user(request):
    """
        Создать администратора для админки джанги
            username: admin
            password: f558e93e820166e1d497ebe5d6a15f9f
            email: [email protected]
        Пароль md5 хэш от [email protected]
    """
    user = User.get_by_key_name('*****@*****.**')
    if not user or user.username != '*****@*****.**' or not (user.is_active and
            user.is_staff and user.is_superuser and
            user.check_password('admin')):
        user = User(key_name='*****@*****.**', username='******',
            email='*****@*****.**', first_name='*****@*****.**', last_name='*****@*****.**',
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password('f558e93e820166e1d497ebe5d6a15f9f')
        user.put()
    return _render_to_response(request, 'gallery/admin_created.html')
Beispiel #11
0
  def testValidPowerParse(self):
    testfile = open('gcycle/test/valid_activity_with_power.tcx').read()
    acts = pytcx.parse_tcx(testfile)
    self.assertEqual(len(acts), 1)
    activity = acts[0]
    self.assertEqual(activity['average_power'], 173)
    self.assertEqual(activity['maximum_power'], 794)
    u = User(username = '******', user = users.User('*****@*****.**'))
    u.put()

    a = Activity._put_activity_record(activity, u, 'tcx',
                                      'source, which is ignored')

    self.assertEqual(a.lap_set.count(), 2)
    laps = a.lap_set.fetch(2)
    self.assertEqual(laps[0].maximum_power, 585)
    self.assertEqual(laps[1].maximum_power, 794)
    self.assertEqual(laps[0].average_power, 322)
    self.assertEqual(laps[1].average_power, 162)
Beispiel #12
0
def create_admin_user(request):
    user = User.get_by_key_name("admin")
    if (
        not user
        or user.username != "admin"
        or not (user.is_active and user.is_staff and user.is_superuser and user.check_password("admin"))
    ):
        user = User(
            key_name="admin",
            username="******",
            email="admin@localhost",
            first_name="Boss",
            last_name="Admin",
            is_active=True,
            is_staff=True,
            is_superuser=True,
        )
        user.set_password("WsduhQODFNNCuweg3862geFGHoshi")
        user.put()
    return ragendja_render_to_response(request, "events/admin_created.html")
Beispiel #13
0
  def testValidParse(self):
    testfile = open('gcycle/test/valid_multi_lap.tcx').read()
    acts = pytcx.parse_tcx(testfile)
    self.assertEqual(len(acts), 1)
    act = acts[0]
    self.assertEqual(act['maximum_bpm'], 186)
    self.assertEqual(act['total_calories'], 6754.0)
    self.assertEqual(act['end_point'], '37.773787,-122.439899')
    self.assertEqual(act['average_bpm'], 136)
    self.assertEqual(act['average_cadence'], 80)
    self.assertAlmostEqual(act['average_speed'], 14.326339080604534, 2)
    self.assertEqual(act['maximum_bpm'], 186)
    self.assertEqual(act['maximum_cadence'], 81)
    self.assertAlmostEqual(act['maximum_speed'], 56.35, 2)
    self.assertEqual(len(act['laps']), 2)
    self.assertEqual(act['total_calories'], 6754.0)
    self.assertAlmostEqual(act['total_meters'], 78993.84, 2)
    self.assertEqual(act['total_time'], 26162)

    u = User(username = '******', user = users.User('*****@*****.**'))
    u.put()

    a = Activity._put_activity_record(act, u, 'tcx',
                                      'source, which is ignored')

    self.assert_(a)
    for l in act['laps']:
      lap = Lap(activity = a, **l)
      lap.put()

      self.assertEqual(len(lap.speed_list), len(lap.altitude_list))
      self.assertEqual(len(lap.speed_list), len(lap.cadence_list))
      self.assertEqual(len(lap.speed_list), len(lap.bpm_list))
      self.assertEqual(len(lap.speed_list), len(lap.timepoints))
      self.assertEqual(len(lap.speed_list), len(lap.geo_points))

      self.assertEqual(lap.total_ascent, 0)
      self.assertAlmostEqual(lap.total_descent, 9.1319, 2)

    self.assertEqual(a.total_ascent, 0)
    self.assertAlmostEqual(a.total_descent, 18.263, 2)
Beispiel #14
0
def register(request, page):
	payload = {}
	if request.method == 'POST': 
		f = RegisterForm(request.POST) 
		if request.POST.has_key('toc'):
			if f.is_valid(): 
				check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
				if check_captcha.is_valid:
					user = User(key_name="user%s" % f.data['username'], username=f.data['username'], email=f.data['email'])
					user.set_password(f.data['password'])
					user.is_active = True
					fb = Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_API_SECRET)
					user.email_hash = fb.hash_email(user.email)
					hashes = []
					hashes.append({"email_hash": user.email_hash})			
					user.put()
					user_info_response = fb.connect.registerUsers(hashes)
					#automatically login
					user = authenticate(username=f.data['username'],password=f.data['password'])
					if user is not None:
						if user.is_active:
							login(request, user)
					if request.session.test_cookie_worked():
						request.session.delete_test_cookie()	
					if request.GET.has_key("next"):	
						return HttpResponseRedirect(request.GET["next"]) 
					else:					
						return HttpResponseRedirect('/account/') 
				else:
					payload["captchaerror"] = True
		else:
			payload["tocerror"] = True
	else:
		f = RegisterForm()
	request.session.set_test_cookie()		
	payload["captchahtml"] = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
	payload["form"] = f
	if request.GET.has_key("next"):
		payload["next"] = request.GET["next"]
	return render("register.html", payload, request)
Beispiel #15
0
def create_admin_user(request):
    """
        Создать администратора для админки джанги
            username: admin
            password: f558e93e820166e1d497ebe5d6a15f9f
            email: [email protected]
        Пароль md5 хэш от [email protected]
    """
    user = User.get_by_key_name('*****@*****.**')
    if not user or user.username != '*****@*****.**' or not (
            user.is_active and user.is_staff and user.is_superuser
            and user.check_password('admin')):
        user = User(key_name='*****@*****.**',
                    username='******',
                    email='*****@*****.**',
                    first_name='*****@*****.**',
                    last_name='*****@*****.**',
                    is_active=True,
                    is_staff=True,
                    is_superuser=True)
        user.set_password('f558e93e820166e1d497ebe5d6a15f9f')
        user.put()
    return _render_to_response(request, 'gallery/admin_created.html')
Beispiel #16
0
# To create an admin user for local development
from django.contrib.auth.models import User

user = User.get_by_key_name('key_admin')
if not user or user.username != 'admin' or not (user.is_active and
  user.is_staff and user.is_superuser and user.check_password('admin')):
  user = User(key_name='key_admin', username='******', email='admin@localhost',
  first_name='Ping Pong', last_name='Admin', is_active=True, is_staff=True, 
  is_superuser=True)
  user.set_password('admin')
  user.put()

# To reset an account - deletes all games and teams and resets ranking points 
# and last movements for all players
from django.contrib.auth.models import User
from pingpong.models import Player, Team, Game

owner_key_name = '' # Set this to the key name (not the key itself) of the account owner
owner = User.get_by_key_name(owner_key_name)
if owner:
  # Find all players
  players = Player.gql("WHERE owner = :owner", owner=owner)
  for p in players:
    # Find all teams where p is player1 (no gql OR operator)
    teams = Team.gql("WHERE player1 = :player", player=p)
    for t in teams:
      # Delete all games in which t played
      games = Game.gql("WHERE team1 = :team", team=t)
      for g in games:
        g.delete()
Beispiel #17
0
 def testWorksWithRealUser(self):
   ex_user = users.User('*****@*****.**')
   u = User(user = ex_user, username = '******')
   u.put()
   self.assert_(u.key())
	def process_request(self, request):
		try:
			 # Set the facebook message to empty. This message can be used to dispaly info from the middleware on a Web page.
			request.facebook_message = None
	
			# Don't bother trying FB Connect login if the user is already logged in
			if not request.user.is_authenticated():
				# FB Connect will set a cookie with a key == FB App API Key if the user has been authenticated
				if API_KEY in request.COOKIES:
					fb = Facebook(API_KEY, API_SECRET)

					if(fb.validate_cookie_signature(request.COOKIES)):
				
						# If session hasn't expired
						if(datetime.fromtimestamp(float(request.COOKIES[API_KEY+'_expires'])) > datetime.now()):
			
							# Try to get Django account corresponding to friend
							# Authenticate then login (or display disabled error message)
							user = authenticate(facebook_id=request.COOKIES[API_KEY + '_user'])
							logging.info(user)
							if user is not None:
								if user.is_active:
									login(request, user)
									self.facebook_user_is_authenticated = True
								else:
									request.facebook_message = ACCOUNT_DISABLED_ERROR
									self.delete_fb_cookies = True
							else:
								django_user = User.get_by_key_name("userfb%s" % request.COOKIES[API_KEY + '_user'])
								if not django_user:
									# There is no Django account for this Facebook user.
									# Create one, then log the user in.
									fb.session_key = request.COOKIES[API_KEY + '_session_key']
									user_info_response = fb.users.getInfo([request.COOKIES[API_KEY + '_user']], ['first_name', 'last_name'])
							
									# Create user
									user = User(key_name="userfb%s" % request.COOKIES[API_KEY + '_user'], username = "******" % (user_info_response[0]['first_name'], user_info_response[0]['last_name']), 
												email= '*****@*****.**' % request.COOKIES[API_KEY + '_user'])
									user.set_password(md5.new(request.COOKIES[API_KEY + '_user'] + settings.SECRET_KEY).hexdigest())
									user.is_active = True
									user.facebook_id = int(request.COOKIES[API_KEY + '_user'])
									user.put()
							
									# Authenticate and log in (or display disabled error message)
									user = authenticate(username='******' % request.COOKIES[API_KEY + '_user'], 
											password=md5.new(request.COOKIES[API_KEY + '_user'] + settings.SECRET_KEY).hexdigest())
									logging.info("ROUND2")
									if user is not None:
										if user.is_active:
											login(request, user)
											self.facebook_user_is_authenticated = True
										else:
											request.facebook_message = ACCOUNT_DISABLED_ERROR
											self.delete_fb_cookies = True
									else:
										request.facebook_message = ACCOUNT_PROBLEM_ERROR
										self.delete_fb_cookies = True
								else:								
									request.facebook_message = ACCOUNT_PROBLEM_ERROR
									self.delete_fb_cookies = True
								
						# Cookie session expired
						else:
							logout(request)
							self.delete_fb_cookies = True
						
				   # Cookie values don't match hash
					else:
						logout(request)
						self.delete_fb_cookies = True
					
			# Logged in
			else:
				# If FB Connect user
				if API_KEY in request.COOKIES:
					# IP hash cookie set
					if 'fb_ip' in request.COOKIES:
					
						try:
							real_ip = request.META['HTTP_X_FORWARDED_FOR']
						except KeyError:
							real_ip = request.META['REMOTE_ADDR']
					
						# If IP hash cookie is NOT correct
						if request.COOKIES['fb_ip'] != md5.new(real_ip + API_SECRET + settings.SECRET_KEY).hexdigest():
							 logout(request)
							 self.delete_fb_cookies = True
					# FB Connect user without hash cookie set
					else:
						logout(request)
						self.delete_fb_cookies = True
				
		# Something else happened. Make sure user doesn't have site access until problem is fixed.
		except:
			request.facebook_message = PROBLEM_ERROR
			logout(request)
			self.delete_fb_cookies = True
Beispiel #19
0
    def create_inactive_user(self,
                             username,
                             password,
                             email,
                             domain_override="",
                             send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        
        To disable the email, call with ``send_email=False``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. It receives one context variable, ``site``, which
            is the currently-active
            ``django.contrib.sites.models.Site`` instance. Because it
            is used as the subject line of an email, this template's
            output **must** be only a single line of text; output
            longer than one line will be forcibly joined into only a
            single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email. It
            will receive three context variables: ``activation_key``
            will be the user's activation key (for use in constructing
            a URL to activate the account), ``expiration_days`` will
            be the number of days for which the key will be valid and
            ``site`` will be the currently-active
            ``django.contrib.sites.models.Site`` instance.

        To execute customized logic once the new ``User`` has been
        created, connect a function to the signal
        ``registration.signals.user_registered``; this signal will be
        sent (with the new ``User`` as the value of the keyword
        argument ``user``) after the ``User`` and
        ``RegistrationProfile`` have been created, and the email (if
        any) has been sent..
        
        """
        from registration.signals import user_registered
        # prepend "key_" to the key_name, because key_names can't start with numbers
        new_user = User(username=username,
                        key_name="key_" + username.lower(),
                        email=email,
                        is_active=False)
        new_user.set_password(password)
        new_user.put()

        registration_profile = self.create_profile(new_user)

        #        if send_email:
        #            from django.core.mail import send_mail
        #            current_site = domain_override
        ##            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())
        #
        #            message = render_to_string('registration/activation_email.txt',
        #                                       { 'activation_key': registration_profile.activation_key,
        #                                         'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
        #                                         'site': current_site })
        #
        #            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        """Отправка письма через google API"""
        if send_email:
            from google.appengine.api import mail
            current_site = domain_override

            message = mail.EmailMessage(
                sender="*****@*****.**",
                to=new_user.email,
                subject=render_to_string(
                    'registration/activation_email_subject.txt',
                    {'site': current_site}),
                body=render_to_string(
                    'registration/activation_email.txt', {
                        'activation_key': registration_profile.activation_key,
                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                        'site': current_site
                    }))
            message.send()

        user_registered.send(sender=self.model, user=new_user)
        return new_user
Beispiel #20
0
                 game_completed=False)
        g.put()

        print g

        #rotate the pairings
        pairings = rotate_pairings(pairings)
        #swap which is home and which is away
        h = not h
        a = not a

    #increment date
    current_week = current_week + datetime.timedelta(7)

print "DATA LOADED"
user = User.get_by_key_name('admin')
if not user or user.username != 'admin' or not (
        user.is_active and user.is_staff and user.is_superuser
        and user.check_password('admin')):
    user = User(key_name='admin',
                username='******',
                email='admin@localhost',
                first_name='Boss',
                last_name='Admin',
                is_active=True,
                is_staff=True,
                is_superuser=True)
    user.set_password('admin')
    user.put()
print "SUPERUSER ADMIN CREATED"
Beispiel #21
0
    def create_inactive_user(self, username, password, email, domain_override="", 
                             send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        
        To disable the email, call with ``send_email=False``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. It receives one context variable, ``site``, which
            is the currently-active
            ``django.contrib.sites.models.Site`` instance. Because it
            is used as the subject line of an email, this template's
            output **must** be only a single line of text; output
            longer than one line will be forcibly joined into only a
            single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email. It
            will receive three context variables: ``activation_key``
            will be the user's activation key (for use in constructing
            a URL to activate the account), ``expiration_days`` will
            be the number of days for which the key will be valid and
            ``site`` will be the currently-active
            ``django.contrib.sites.models.Site`` instance.

        To execute customized logic once the new ``User`` has been
        created, connect a function to the signal
        ``registration.signals.user_registered``; this signal will be
        sent (with the new ``User`` as the value of the keyword
        argument ``user``) after the ``User`` and
        ``RegistrationProfile`` have been created, and the email (if
        any) has been sent..
        
        """
        from registration.signals import user_registered
        # prepend "key_" to the key_name, because key_names can't start with numbers
        new_user = User(username=username, key_name="key_"+username.lower(),
            email=email, is_active=False)
        new_user.set_password(password)
        new_user.put()
        
        registration_profile = self.create_profile(new_user)
        
        if send_email:
            from django.core.mail import send_mail
            current_site = domain_override
#            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())
            
            message = render_to_string('registration/activation_email.txt',
                                       { 'activation_key': registration_profile.activation_key,
                                         'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                         'site': current_site })
            
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        user_registered.send(sender=self.model, user=new_user)
        return new_user
Beispiel #22
0
 def putActivity(self, activity_record):
   """Make sure app engine doesn't barf when putting activity_record."""
   user = User(username = '******', user = users.User('*****@*****.**'))
   user.put()
   return Activity._put_activity_record(activity_record, user, 'gpx',
                                        'source, which is ignored')
Beispiel #23
0
def create_default_facebook_profile(request):
    '''
    Called by both facebook_login (if connecting through the website) and synchronise_facebook_profile (if using facebook.require_add in events_fb)
    This is the place to send emails!
    '''

    #
    # Create User
    #
    new_user = User( username = str(uuid.uuid4())[:30] )

    # basic user created, now get some information about him
    fb_profile = request.facebook.users.getInfo([request.facebook.uid], ['first_name', 'last_name', 'pic_square', 'profile_url', 'current_location', 'email'])[0]

    new_user.first_name = fb_profile['first_name']
    new_user.last_name = fb_profile['last_name']
    new_user.email = fb_profile['email']

    new_user.put()

    #
    # Create Profile
    #
    try:
        zip = int(fb_profile['current_location']['zip'])
    except:
        zip = 0
        
    try:
        current_location_city = fb_profile['current_location']['city']
        current_location_state = fb_profile['current_location']['state']
        current_location_country = fb_profile['current_location']['country']
    except:
        current_location_city = None
        current_location_state = None
        current_location_country = None

    new_profile = FacebookProfile(
        user = new_user,
        uid = str(request.facebook.uid),
        pic_square = fb_profile['pic_square'],
        profile_url = fb_profile['profile_url'],
        current_location_city = current_location_city,
        current_location_state = current_location_state,
        current_location_country = current_location_country,
        current_location_zip = zip,
        site = Site.objects.get_current(),
        )

    new_profile.put()
    
    logging.debug("Created user: %s"%new_profile.user)

    if getattr(settings, 'SOCIAL_SEND_EMAIL_ON_NEW_PROFILE', False):
        if not new_user.email:
            logging.debug("Not sending email - user hasn't specified email")
        else:
            logging.debug("Sending email to: %s" % new_user.email)
            
            try:
                from django.core.mail import send_mail
                subject = render_to_string('socialregistration/new_profile_email_subject.txt',
                                               { 'site': new_profile.site })
                # Email subject *must not* contain newlines
                subject = ''.join(subject.splitlines())

                message = render_to_string('socialregistration/new_profile_email.txt',
                                           { 'user': new_user,
                                             'profile': new_profile })

                send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])

            except NotImplementedError:
                logging.error("Failed to send email to %s; subject: %s" %(new_user.email, subject))

    return new_profile