Example #1
0
    def post(self, request):
        email = request.DATA['email']
        username = request.DATA['username']
        password = request.DATA['password']

        pre_existing = Player.objects.filter(Q(username__iexact=username) | Q(email__iexact=email))
        if ' ' in username:
            return Response([{'type': 'danger', 'msg': 'Yeah soo.. no spaces in username please. Gracias Amigo.'}], status=status.HTTP_403_FORBIDDEN)
        if username == '' or email == '' or password == '':
            return Response([{'type': 'danger', 'msg': 'All Fields are required buddy'}], status=status.HTTP_403_FORBIDDEN)
        if len(pre_existing) is not 0:
            return Response([{'type': 'danger', 'msg': 'username/email already exists.'}], status=status.HTTP_403_FORBIDDEN)
        else:
            player = Player()
            player.email = email
            player.username = username
            player.is_active = True
            player.set_password(password)
            player.save()
            authed = authenticate(username=username, password=password)
            login(request, authed)

            serialized = PlayerSerializer(player)

            return Response(serialized.data, status=status.HTTP_201_CREATED)
Example #2
0
 def upload_players(self):
   players = []
   new_player_count = len(self.form.new_player)
   logger.info('No of New players %s' % new_player_count) 
   sport = self.request.get('sport')
   
   for x in xrange(new_player_count):
     player_obj = Player()
     player_obj.name = self.form.new_player.__getitem__(x).data['name']
     player_obj.email = self.form.new_player.__getitem__(x).data['email']
     #player_obj.phone = self.form.new_player.__getitem__(x).data['phone']
     player_obj.sport = sport
     
     logger.info('New Player Data: ' + str(player_obj))
     if player_obj.email != '':
       player_exist = self.playerDao.query_by_email(player_obj.email)
       logger.info('Exist Player Data: ' + str(player_exist))
       if player_exist is None:
         key = self.playerDao.persist(player_obj, self.user_info)
         players.append(key)
         logger.info('Add New Player %s' % player_obj.name)
       else:
         players.append(player_exist.key)
         logger.info('Skipped Already Exist of Player %s' % player_obj.name)
     else:
       logger.info('Skipped Empty Player Data')
   return players
Example #3
0
 def form_to_dao_player(self, alias_name, **update):
     try:
         player = Player()
         player.name = update['name']
         player.email = update['email']
         player.phone = update['phone']
         player.sport = update['sport']
     except StandardError as e:
         logger.error('Error occured, %s, for %s:%s' %
                      (str(e), type, update['name']))
         raise
     return player
Example #4
0
def register():
    if request.method == "POST":
        email = request.form['email']
        username = request.form['username']
        if len(session.query(Player).filter(Player.username == username).all()) < 1:
            password = generate_password_hash(request.form['password'], method='pbkdf2:sha1', salt_length=8)
            player = Player()
            player.email = email
            player.username = username
            player.password = password
            player.authenticated = True
            session.add(player)
            session.commit()
            login_user(player)
            flash('Account created and logged in.', 'success')
            return redirect(url_for('game_page'))
        else:
            flash('That username is taken.', 'error')
            return redirect(url_for('register'))
    return render_template('register.html')
Example #5
0
 def form_to_dao(self, player_id):
   player = None
   if player_id is not None  and len(player_id) > 1:
     player = self.playerDao.get_record(long(player_id))
   else:
     player = Player()
   player.name = self.form.name.data
   player.email = self.form.email.data
   #player.phone = self.form.phone.data
   player.sport = self.form.sport.data
   sel_team = self.request.get_all('team')
   logger.debug('sel_team:  ' + str(sel_team))
   if len(sel_team) > 0:        
     teams = []        
     teams_count = len(sel_team)
     logger.debug('Teams Count: ' + str(teams_count))
     for x in xrange(teams_count):
       teams.append(self.teamDao.get_record(sel_team[x]).key)
     logger.debug('Teams ' + str(teams))        
     player.teams = teams
   return player
Example #6
0
    def post(self, request):
        email = request.DATA['email']
        username = request.DATA['username']
        password = request.DATA['password']

        pre_existing = Player.objects.filter(
            Q(username__iexact=username) | Q(email__iexact=email))
        if ' ' in username:
            return Response([{
                'type':
                'danger',
                'msg':
                'Yeah soo.. no spaces in username please. Gracias Amigo.'
            }],
                            status=status.HTTP_403_FORBIDDEN)
        if username == '' or email == '' or password == '':
            return Response([{
                'type': 'danger',
                'msg': 'All Fields are required buddy'
            }],
                            status=status.HTTP_403_FORBIDDEN)
        if len(pre_existing) is not 0:
            return Response([{
                'type': 'danger',
                'msg': 'username/email already exists.'
            }],
                            status=status.HTTP_403_FORBIDDEN)
        else:
            player = Player()
            player.email = email
            player.username = username
            player.is_active = True
            player.set_password(password)
            player.save()
            authed = authenticate(username=username, password=password)
            login(request, authed)

            serialized = PlayerSerializer(player)

            return Response(serialized.data, status=status.HTTP_201_CREATED)
Example #7
0
def handle_post(request):
    if request.method == "POST":
        #Loads json received from POST
        received_json_data = json.loads(request.body)

        #Check if we got player data
        if 'player' in received_json_data or received_json_data['player']['social_id'] is not None or received_json_data['player']['email'] is not None or received_json_data['player']['puzzle_data'] is not None:
            inputid = received_json_data['player']['social_id']

            #See if player data already exist in database
            if len(Player.objects.filter(social_id=inputid))<1:

                #New Player
                p = Player()
                p.email = received_json_data['player']['email']
                p.social_id = received_json_data['player']['social_id']
                p.name = received_json_data['player']['name']
                p.save()

                playerPuzzleData = received_json_data['player']['puzzle_data']

                #Create puzzle data
                for i in range(len(playerPuzzleData['puzzles'])):

                    pdata = PuzzleData()
                    pdata.puzzles = playerPuzzleData['puzzles'][i]
                    pdata.scores=playerPuzzleData['scores'][i]
                    pdata.stars=playerPuzzleData['stars'][i]
                    pdata.save()
                    p.puzzle_data.add(pdata)

                p.save()
                data = serializers.serialize("python", p.puzzle_data.all())
                data = [d['fields'] for d in data]
                data = json.dumps(data)
                data = {'player': data}
                data = {'message': data}
                
                return render(request, "update.html", data)
            else:

                #Not a new player so have to see if we need to update scores and stars
                #I'll assume that players have unique social ids
                p = Player.objects.get(social_id=received_json_data['player']['social_id'])

                inputplayerPuzzleData = received_json_data['player']['puzzle_data']

                mylevels = {}
                #Create a list of levels and data pairs
                for currentlevel in p.puzzle_data.all():
                    mylevels[currentlevel.puzzles]=currentlevel

                #Check through each puzzle and update if needed
                for i in range(len(inputplayerPuzzleData['puzzles'])):
                    findlevel = inputplayerPuzzleData['puzzles'][i]

                    if findlevel not in mylevels:
                        #New puzzle level to add to puzzle data

                        pdata = PuzzleData()
                        pdata.puzzles = inputplayerPuzzleData['puzzles'][i]
                        pdata.scores=inputplayerPuzzleData['scores'][i]
                        pdata.stars=inputplayerPuzzleData['stars'][i]
                        pdata.save()
                        p.puzzle_data.add(pdata)

                    else:
                        #Puzzle data already exists, check if scores or stars is greater value

                        storedlevel = mylevels[findlevel]
                        if inputplayerPuzzleData['scores'][i] > storedlevel.scores:
                            storedlevel.scores = inputplayerPuzzleData['scores'][i]
                        if inputplayerPuzzleData['stars'][i] > storedlevel.stars:
                            storedlevel.stars = inputplayerPuzzleData['stars'][i]
                        storedlevel.save()

                p.save()

                #serialize puzzle data and return player's data in JSON

                data = serializers.serialize("python", p.puzzle_data.all())
                data = [d['fields'] for d in data]
                data = json.dumps(data)
                data = {'player': data}
                data = {'message': data}

                return render(request, "update.html", data)

        else:
            mymessage = {'message':"Did not find player data in JSON or badly formed JSON"}
            return render(request, "summary.html", mymessage)

    else:
        #Was not post request
        mymessage = {'message':"Did not make a POST request"}
        return render(request, "summary.html", mymessage)
Example #8
0
    def post(self):

        isAdmin = login.isAdmin()
        isPlayer = login.isPlayer()
        user = users.get_current_user()

        if not isAdmin and not isPlayer:
            self.response.set_status(500, message='You must log in')
            self.response.out.write('You must log in')
            return

        # get player data
        logging.info(self.request.body)
        try:
            player_data = json.loads(self.request.body)
        except ValueError:
            player_data = self.request
        logging.info(player_data)

        if player_data and player_data.get('id'):
            id = int(player_data.get('id'))
            db_player = Player.get_by_id(id)
        elif player_data.get('name'):
            db_player = Player(name=player_data['name'])
        else:
            self.response.set_status(500, message='You have not specified an id or a name')
            self.response.out.write('You have not specified an id or a name')
            return

        if not isAdmin and db_player.email != user.email():
            logging.info(db_player.email)
            logging.info(user.email())
            self.response.set_status(500, message='You are not authorized')
            self.response.out.write('You are not authorized')
            return

        # edit player in db
        if db_player:

            status = player_data.get('status') or 'waiting'
            # check if status is valid
            n_presents = Player.all().filter('status =', 'present').count()
            if db_player.status != 'present' and status == 'present' and n_presents >= 10:
                logging.info(user.nickname() + ' (' + user.email() +
                             ') tried to set status to \'' + status +
                             '\' but it was full')
                self.response.set_status(500, message='La lista e\' piena')
                self.response.out.write('La lista e\' piena')
                return

            db_player.status = status

            if isAdmin:
                isStarred = player_data.get('isStarred') == 'True' or False
                db_player.isStarred = isStarred
                db_player.name = player_data.get('name')
                if player_data.get('email'):
                    db_player.email = player_data.get('email')

            db_player.put()

            #send message to clients
            result = playerToJSON(db_player, isAdmin)
            sendMessage(result)
            self.response.out.write(result)

        else:
            self.response.out.write('emptyName')