Beispiel #1
0
	def clean(self, value):
		super(UserField, self).clean(value)
		user = User.get_by_key_name("user%s" % value)
		if user:
			raise forms.ValidationError("Someone is already using this username. Please pick an other.")
		else:
			return value
Beispiel #2
0
 def clean_username(self):
     """
     Validate that the username is alphanumeric and is not already
     in use.
     """
     user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
     if user:
         raise forms.ValidationError(__(u'This username is already taken. Please choose another.'))
     return self.cleaned_data['username']
Beispiel #3
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='admin',
            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 #4
0
def set_user_org(username, org):
#  userobj = User.objects.get(username__exact=username)
  # HACK(dan): This gets the user object, but it's probably not the right way.
  userobj = User.get_by_key_name('key_' + username)
  if userobj:
    userobj.organization = org
    userobj.save()
    logging.info("Set %s organization to %s" % (username, org))
  else:
    logging.warning("No such user %s" % username)
Beispiel #5
0
def set_password(username, password):
#  userobj = User.objects.get(username__exact=username)
  # HACK(dan): This gets the user object, but it's probably not the right way.
  userobj = User.get_by_key_name('key_' + username)
  if userobj:
    userobj.set_password(password)
    userobj.save()
    logging.info("Set password for %s" % username)
  else:
    logging.warning("No such user %s" % username)
Beispiel #6
0
def index(request):
		#user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
		username = request.user.username
		user = User.get_by_key_name("key_"+username.lower())
		if user and user.is_active:
			last_scrape = user.nike_last_scrape
		else:
			last_scrape = None
		return object_list(request, Run.all().filter('user =', user).order('-run_time'),
		                   extra_context={'last_scrape':last_scrape})
Beispiel #7
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='admin',
            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 #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='admin',
            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('/')
Beispiel #9
0
def create_admin_user(request):
    """
        Создать администратора для админки джанги
            username: admin
            password: f558e93e820166e1d497ebe5d6a15f9f
            email: adm.shotscreens@gmail.com
        Пароль md5 хэш от adm.shotscreens@gmail.com
    """
    user = User.get_by_key_name('adm.shotscreens@gmail.com')
    if not user or user.username != 'adm.shotscreens@gmail.com' or not (user.is_active and
            user.is_staff and user.is_superuser and
            user.check_password('admin')):
        user = User(key_name='adm.shotscreens@gmail.com', username='adm.shotscreens@gmail.com',
            email='adm.shotscreens@gmail.com', first_name='adm.shotscreens@gmail.com', last_name='adm.shotscreens@gmail.com',
            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 #10
0
    def _createEvent(self, result, checksum, url):
        REQUIRED_PARAMETERS = ['dates', 'name', 'name_long', 'venue', 'times', 'to register', 'cost']
        for p in REQUIRED_PARAMETERS:
            if not (result.has_key(p) and result[p] != ''):
                return None

        if not STANDALONE:
            admin_user = User.get_by_key_name('admin')
            if not admin_user:
                raise "Missing admin user"
            country = Country.get_by_key_name('GB')

            site = Site.objects.get_current()
            gmaps = GoogleMaps(api_key = settings.GOOGLE_MAPS_API_KEY,
                               referrer_url = site.domain)
            address = "%s, %s, GB" % (result['venue'], result['name'])
            try:
                lat, lng = gmaps.address_to_latlng(address)
            except GoogleMapsError:
                lat, lng = gmaps.address_to_latlng('GB')

            new_event = Event(active = False,
                              moderated = False,
                              name = str(result['name_long']),
                              creator = admin_user,
                              type = 22,
                              location = db.GeoPt(lat, lng),
                              country = country,
                              region = None,
                              address = str(result['venue']),
                              description = str(result),
                              free = False,
                              fees = str(result['cost']),
                              date_start = datetime.datetime.today(),
                              date_end = datetime.datetime.today(),
                              recurrent = False,
                              featured_priority = 0,
                              source_url = url,
                              source_checksum = checksum)
            return new_event
        else:
            print result, '\n'
            return None
Beispiel #11
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="admin",
            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")
	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 = "%s %s" % (user_info_response[0]['first_name'], user_info_response[0]['last_name']), 
												email= '%s@connect.facebook.com' % 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='%s@connect.facebook.com' % 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 #13
0
 def get_user(self, user_id):
     return User.get_by_key_name(user_id)
Beispiel #14
0
 def authenticate(self, username=None, password=None):
     user = User.get_by_key_name(username)
     if user and user.check_password(password):
         return user
Beispiel #15
0
def get_nike_plus_data(request):


	# TODO: protect against the case where a user_id hasn't been set. force this to be set upon registration?
	# TODO: Only set new last_scrape_time if the scrape is successful
	
	username = request.user.username
	user = User.get_by_key_name("key_"+username.lower())
	
	if user and user.is_active:
		last_scrape_time = user.nike_last_scrape
		userId = user.nike_user_id
	else:
		last_scrape_time = None
		
	if not last_scrape_time:
		last_scrape_time = datetime.datetime(1970, 1, 1) # Set it to an arbitrary early date
				
	#response = urllib2.urlopen('http://nikeplus.nike.com/nikeplus/v1/services/widget/get_public_run_list.jsp?userID=%s' % userId).read()
	#response = urlfetch.fetch('https://secure-nikerunning.nike.com/nikeplus/v1/services/app/run_list.jsp')
	#response = urlfetch.fetch('http://nikerunning.nike.com/nikeplus/v2/services/app/run_list.jsp?userID=%s&startIndex=0&endIndex=5' % userId)
	
	# don't specify startIndex and endIndex in the URL i.e. get all runs
	response = urlfetch.fetch('http://nikerunning.nike.com/nikeplus/v2/services/app/run_list.jsp?userID=%s' % userId)
	import logging
	logging.debug(response.content)		
	
	dom = minidom.parseString(response.content)
	
	run_ids_and_times = []
	# N.B. in the following code I replaced 'startTime' with 'syncTime' - this makes sense
	
	# AUG 14TH 2010 - NOTE - THIS IS PROBABLY REALLY INEFFICIENT!!!
	# WOULD BE BETTER TO LIMIT THE AMOUNT OF RUNS I GET IN THE REQUEST (i.e. use startIndex/endIndex)
	# THIS LIMIT NEEDS TO BE BASED ON nike_last_scrape
	#
	# IDEA: START AT END OF XML FILE AND MOVE BACKWARDS, CHECKING THE syncTime value until
	# it becomes earlier than nike_last_scrape 
	for run in dom.getElementsByTagName('run'):
		run_id = run.getAttribute('id')
		
		sync_time = run.getElementsByTagName('syncTime')[0]
		sync_time = sync_time.toxml()
		sync_time = sync_time.replace('<syncTime>', '') # Get rid of the opening syncTime tag
		sync_time = sync_time.split('+')[0] # Strip off the time zone stuff and closing tag
		sync_time = datetime.datetime.strptime(sync_time, '%Y-%m-%dT%H:%M:%S')
		
		run_ids_and_times.append((run_id, sync_time))
		##run = Run(run_id=run_id, run_time=run_time)
		##run.put()
		
	# Only keep the runs which have been synced after the last_scrape_time
	run_ids_and_times = [(run_id, t) for (run_id, t) in run_ids_and_times if t > last_scrape_time]

	# Set last scrape time to now
	# TODO - uncomment the following line
	#user.nike_last_scrape = datetime.datetime.now()
	user.put()
	
	# No new runs so just return
	# TODO: Give the user some feedback e.g. a message saying 'No new runs'
	if len(run_ids_and_times) == 0:
		return HttpResponseRedirect('/runs/')
		
	cookie = Cookie.SimpleCookie()
	cookie.load(response.headers.get('set-cookie', ''))
	cookie['plusid'] = user.nike_user_id +"&nikerunning.nike.com"
	headers = {
				'Host' : 'runlogger.appspot.com',
				'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)',
				'Cookie' : _makeCookieHeader(cookie)
			  }
	
	# Save the new run(s)
	for run in dom.getElementsByTagName('run'):
		for (run_id, t) in run_ids_and_times:
			if run.getAttribute('id') == run_id:
				
				# Get the time the run started
				run_time = run.getElementsByTagName('startTime')[0]
				run_time = run_time.toxml()
				run_time = run_time.replace('<startTime>', '') # Get rid of the opening startTime tag
				run_time = run_time.split('+')[0] # Strip off the time zone stuff and closing tag
				run_time = datetime.datetime.strptime(run_time, '%Y-%m-%dT%H:%M:%S')
				
				distance = run.getElementsByTagName('distance')[0]
				distance = distance.toxml()
				distance = distance.replace('<distance>', '')
				distance = distance.replace('</distance>', '')
				
				dist_len = len('%.2f' % float(distance)) # Length of distance string when truncated to 2 D.P.
				distance = float(distance[:dist_len])
				
				duration = run.getElementsByTagName('duration')[0]
				duration = duration.toxml()
				duration = duration.replace('<duration>', '')
				duration = duration.replace('</duration>', '')
				# TODO - TEST OUT THIS CODE WITH RUNS OVER AN HOUR LONG - WILL IT WORK?
				duration = float(duration)/1000/60 # Convert duration in ms to minutes
				decimal_part_of_mins, mins = math.modf(duration)
				gt_1hour = False
				if mins >= 60:
					gt_1hour = True
					mins_when_duration_gt_1hour, hours = math.modf(mins/60)
					mins = mins_when_duration_gt_1hour * 60
					
				secs = decimal_part_of_mins * 60
				
				if gt_1hour:
					duration_pretty = '%s:%s:%02d' % (int(hours), int(round(mins)), int(round(secs)))
				else:
					duration_pretty = '%s:%02d' % (int(mins), int(round(secs)))
				
				# Get GPX data
				# TODO - don't hardcode the run ID!
				response = urlfetch.fetch('https://secure-nikerunning.nike.com/nikeplus/v2/services/app/get_gps_detail.jsp?_plus=true&id=%s&format=json' % run_id, headers=headers)
				
				logging.debug('gpx data is:')
				logging.debug(response.content)			
				new_run = Run(user=user, run_id=run_id, run_time=run_time, distance=distance, 
								duration=duration, duration_pretty=duration_pretty, gpx_data=unicode(response.content))
				new_run.put()
	
	return HttpResponseRedirect('/runs/')
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='admin', 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()