Пример #1
0
 def getPerson(question=None, nickname=None):
     person = None
     
     # check if person id stored in session
     # if so use to retrieve logged in user 
     session = gaesessions.get_current_session()
     person_id = session.pop("new_person_id") if session.has_key("new_person_id") else None
     if person_id:
         person = Person.get_by_id(person_id)
         # check if person id stored in session corresponds to inputs
         if not person:
             person = None
             helpers.log("WARNING: Person not found by id {0}".format(person_id))
         elif question and question != person.question:
             person = None
         elif nickname and nickname != person.nickname:
             person = None
     
     if not person:
         user = users.get_current_user()
         if question:
             if question.nicknameAuthentication:
                 # if no nickname provided, check session
                 if not nickname:
                     questionSessionValues = session.get(question.code)
                     nickname = questionSessionValues["nickname"] if questionSessionValues else None
                 if nickname:
                     person = Person.all().filter("question =", question).filter("nickname =", nickname).get()
             elif user is not None:
                 person = Person.all().filter("question =", question).filter("user ="******"question =", None).filter("user =", user).get()
     return person
Пример #2
0
    def post(self):
        person = self.initUserContext()
        client_id = self.request.get("client_id")
        title = self.request.get("title")
        questionText = self.request.get("question")
        nicknameAuthentication = self.request.get("nickname_authentication", "0") == "1"

        data = {}
        if not person:
            data["status"] = 0
            data["msg"] = "Please log in"

        elif len(title) < 5 or len(questionText) < 5:
            data["status"] = 0
            data["msg"] = "Title and question must must be at least 5 characters"

        else:
            question = Question.createQuestion(title, questionText, nicknameAuthentication)

            if not question:
                data["status"] = 0
                data["msg"] = "Error saving question"

            else:
                question_id = question.code
                session = gaesessions.get_current_session()
                session["new_question_key"] = question.key().id()

                data = {"status": 1, "question_id": question_id}
                # Update clients
                message = {"op": "newquestion"}
                send_message(client_id, question_id, message)  # Update other clients about this change

        self.writeResponseAsJson(data)
Пример #3
0
	def auth_check(self):
		user = users.get_current_user()
		
		#Check if the user is in @mekuido.info
		self.wr('emailDomain')
		if user:
			emailDomain = user.email().split("@")
			if emailDomain[1] == "mekuido.info":
				self.session = get_current_session()
				self.current_student_user = None
				self.current_account = None
				
				if self.session.has_key("current_account"):
					self.wr('Current: ' + str(self.session["current_account"]))
					self.current_account = self.session["current_account"]	
				else:
					self.current_account = MKAccount.all().filter('email = ',user.email()).get()
					self.wr( 'user email '+ str(user.email()))
					if not self.current_account:
						self.current_account = MKAccount()
						self.current_account.email = user.email()
						self.current_account.put()
					#Setting the session data
					self.session["current_account"] = self.current_account
					self.session["current_account"].put()
					time.sleep(1)
				self.flash_message = "HELO"
				self.render('index')
				return True
			else:
				self.redirect(users.create_logout_url('/admin/'))
				#self.redirect('/unlogFromGoogleAcount')
				
		else:
			self.redirect(users.create_login_url(self.request.uri))
Пример #4
0
    def get(self):
        nickname = self.request.get("nickname")
        page = self.request.get("page")
        questionId = self.request.get("question_id")
        question = Question.getQuestionById(questionId)

        # if question allows nickname authentication
        # store nickname in session if ok
        if question:
            person = Person.getPerson(question, nickname)
            if person and len(person.client_ids) > 0:
                if question.nicknameAuthentication:
                    self.redirectWithMsg(
                        "Someone is already logged in as " + nickname, "/loginpage?question_id=" + questionId
                    )
                else:
                    self.redirectWithMsg(str(person.user) + " is already logged in", dst="/")
                return

            if question.nicknameAuthentication and nickname:
                specialChars = set("$'\"*,")
                if any((c in specialChars) for c in nickname):
                    self.redirectWithMsg(
                        "Nickname can not contain " + "".join(specialChars), "/loginpage?question_id=" + questionId
                    )
                    return

                session = gaesessions.get_current_session()
                session[questionId] = {"nickname": nickname}

        person = self.initUserContext(create=True)
        url = str(page) if page else getPhaseUrl(person.question)
        self.redirect(url)
Пример #5
0
 def get(self):
     continue_url = self.request.get('continue', '/')
     session = gaesessions.get_current_session()
     if session.has_key('user_id'):
         session.terminate()
     self.redirect(continue_url)
     return
Пример #6
0
	def auth_check(self):
		user = users.get_current_user()
		
		#Check if the user is in @mekuido.info
		if user:
			emailDomain = user.email().split("@")
			if emailDomain[1] == "ataxic.org":
				self.session = get_current_session()
				self.current_account = None
				
				if self.session.has_key("current_account"):
					self.current_account = self.session["current_account"]	
				else:
					self.current_account = LLAccount.all().filter('email = ',user.email()).get()
					
					if not self.current_account:
						self.current_account = LLAccount()
						self.current_account.email = user.email()
						#self.current_account.put()
					#Setting the session data
					self.current_account.last_entrance = datetime.datetime.now()
					self.current_account.put()
					self.session["current_account"] = self.current_account
					#self.session["current_account"].put()
					time.sleep(1)
				return True
			else:
				self.redirect('/admin/unlog/')
				#self.redirect('/unlogFromGoogleAcount')
				
		else:
			self.redirect(users.create_login_url(self.request.uri))
Пример #7
0
    def auth_check(self):

        self.session = get_current_session()
        user = users.get_current_user()
        self.current_account = None

        if (user and self.session):
            if self.session.has_key("current_account"):
                self.current_account = self.session["current_account"]
            else:
                self.current_account = LLAccount.all().filter(
                    'email = ', user.email()).get()

                if not self.current_account:
                    self.current_account = LLAccount()
                    self.current_account.email = user.email()
                    #self.current_account.put()
                    #Setting the session data
                #self.current_account.is_administrator = users.is_current_user_admin()
                self.current_account.last_entrance = datetime.datetime.now()
                self.current_account.put()
                self.session["current_account"] = self.current_account

                time.sleep(1)

        else:
            self.login_url = users.create_login_url('/')

        return True
Пример #8
0
    def initUserContext(self, force_check=False, create=False):
        # Get the current browser session, if any
        # Otherwise, create one
        session = gaesessions.get_current_session()
        if session.sid is None:
            session.start()

        question_id = self.request.get("question_id")
        question = Question.getQuestionById(question_id)
        nickname = self.request.get("nickname")

        # if question allows nickname authentication
        # check if nickname stored in session, if not provided
        if question and question.nicknameAuthentication and not nickname:
            questionValues = session.get(question.code) if session.has_key(question.code) else None
            nickname = questionValues["nickname"] if questionValues else None

        # if requested, force check for authenticated user not affiliated with any specific question
        if force_check:
            question = None
            nickname = None

        person = Person.getPerson(question, nickname)
        user = users.get_current_user()

        # if no person found
        # create person if create is true, OR,
        # create person if question requires login authentication and person already logged in
        if not person and (create or (question and not question.nicknameAuthentication and user)):
            person = Person.createPerson(question, nickname)

        return person
Пример #9
0
    def auth_check(self):
        user = users.get_current_user()

        #Check if the user is in @mekuido.info
        if user:
            emailDomain = user.email().split("@")
            if emailDomain[1] == "ataxic.org":
                self.session = get_current_session()
                self.current_account = None

                if self.session.has_key("current_account"):
                    self.current_account = self.session["current_account"]
                else:
                    self.current_account = LLAccount.all().filter(
                        'email = ', user.email()).get()

                    if not self.current_account:
                        self.current_account = LLAccount()
                        self.current_account.email = user.email()
                        #self.current_account.put()
                    #Setting the session data
                    self.current_account.last_entrance = datetime.datetime.now(
                    )
                    self.current_account.put()
                    self.session["current_account"] = self.current_account
                    #self.session["current_account"].put()
                    time.sleep(1)
                return True
            else:
                self.redirect('/admin/unlog/')
                #self.redirect('/unlogFromGoogleAcount')

        else:
            self.redirect(users.create_login_url(self.request.uri))
Пример #10
0
	def auth_check(self):
		
		self.session = get_current_session()
		user = users.get_current_user()
		self.current_account = None
			
		if(user and self.session):
			if self.session.has_key("current_account"):
				self.current_account = self.session["current_account"]	
			else:
				self.current_account = LLAccount.all().filter('email = ',user.email()).get()
				
				if not self.current_account:
					self.current_account = LLAccount()
					self.current_account.email = user.email()
						#self.current_account.put()
					#Setting the session data
				#self.current_account.is_administrator = users.is_current_user_admin()
				self.current_account.last_entrance = datetime.datetime.now()
				self.current_account.put()
				self.session["current_account"] = self.current_account
				
				time.sleep(1)
		
		else:
			self.login_url = users.create_login_url('/')
		
		
		return True
Пример #11
0
def session_set(id, val, regen_id=False):
    from lib.gaesessions import get_current_session
    s = get_current_session()
    s[id] = val
    #Optionally regenerate the id for security
    if regen_id:
        s.regenerate_id()
Пример #12
0
def index_post():
  # new Data to GAE
  secret = 'the password is %s and the salt-of-this-secret'
  game_name = request.forms.get('game_name').strip().decode('utf-8')
  game_code = ''
  password = request.forms.get('game_password').strip()
  password_hashed = ((password == '') and [''] or [md5.new(secret % password).hexdigest()])[0]
  money = request.forms.get('coins').strip()
  nop = int(request.forms.get('number_of_player').strip())
  names = request.forms.getall('player_name')
  r = MonopolyRoom(game_name=game_name, password=password_hashed, number_of_player=nop)
  r.put()
  id = r.key().id()
  game_code = tiny_encode(id)
  r.game_code = game_code
  r.put()
  # Create room in Firebase
  fb = Firebase('https://summerwxy.firebaseio.com/monopoly/%s' % game_code)
  foo = {'nop': nop, 'player': {}, 'log': {}}
  for i in xrange(nop):
    foo['player'][i] = {'name': names[i], 'coins': money}
    foo['log'][i] = {'className': 'log999 log' + str(i), 'from': 999, 'to': i, 'coins': money}
  #var logClassName = _.template('log<\%=f%\> log<\%=t%\>');
  #           log.push({'className': logClassName({'f': from_id, 't': to_id}), 'from': from_id, 'to': to_id, 'coins': coins});
    
  fb.put(foo)
  # if create with password, login diretly
  if password_hashed:
    session = get_current_session()
    session['allow'] = game_code
  redirect('/monopoly/%s' % game_code)
Пример #13
0
    def get(self):
        person = self.initUserContext(force_check=True)
        questionObj = None

        # check if new_question_id stored in session
        # newly created questions may not be searchable immediately
        # but they should be retrievable with a key
        # would not be required if js did not immediately reload page
        # with question_id as url param (which forces new question search)
        session = gaesessions.get_current_session()
        question_id = session.pop("new_question_key") if session.has_key("new_question_key") else None
        if question_id:
            questionObj = Question.get_by_id(question_id)

        question_id = self.request.get("question_id")
        if question_id and not questionObj:
            questionObj = Question.getQuestionById(question_id)

        session = gaesessions.get_current_session()

        # check if user logged in
        if not person or not person.user:
            questionObj = None
            session["msg"] = "Please login"

        # check if valid question code
        elif question_id and not questionObj:
            session["msg"] = "Invalid question code"

        # check if question owned by logged in user
        elif questionObj and not Person.isAdmin(self) and questionObj.author != users.get_current_user():
            questionObj = None
            session["msg"] = "You do not have permission to edit this question"

        template_values = get_default_template_values(self, person, questionObj)
        if questionObj:
            template_values["num_notes_to_tag_per_person"] = questionObj.numNotesToTagPerPerson
            template_values["num_notes_to_compare_per_person"] = questionObj.numNotesToComparePerPerson
            template_values["num_notes_for_comparison"] = questionObj.numNotesForComparison
            template_values["num_ideas"] = Idea.getNumIdeas(questionObj)
            template_values["num_tags_by_cluster"] = questionObj.getNumTagsByCluster()
            template_values["num_tags_by_idea"] = questionObj.getNumTagsByIdea()
            template_values["num_similar_ideas"] = questionObj.getNumSimilarIdeas()
            template_values["num_clusters"] = Cluster.numClusters(questionObj)

        path = os.path.join(os.path.dirname(__file__), "../html/admin.html")
        self.response.out.write(template.render(path, template_values))
Пример #14
0
def choice_room(room):
  # if not exist redirect to room list
  q = MonopolyRoom.all()
  q.filter('game_code = ', room)
  result = q.get()
  if not result:
    redirect('/monopoly')
  # private game and not allowed goto login page
  session = get_current_session()
  if result.password and not room == session.get('allow', ''):  
    return dict(room=room, name=result.game_name, do='PASSWORD')
  else:
    return dict(room=room, name=result.game_name, do='ROLE')
Пример #15
0
 def createPerson(question=None, nickname=None):   
     person = Person()
     person.user = users.get_current_user() if not question or not question.nicknameAuthentication else None
     person.nickname = nickname if nickname else (Person.cleanNickname(person.user) if person.user else None)
     person.question = question
     person.put()
     
     # save to session since this person
     # may not be immediately retrievable from datastore
     session = gaesessions.get_current_session()
     session["new_person_id"] = person.key().id()
     
     return person
Пример #16
0
    def get(self, user=None):

        session = gaesessions.get_current_session()
        params = {
            'verifier': self.request.get("oauth_verifier"),
            'key': session.get('twitter_request_key'),
            'secret': session.get('twitter_request_secret')
        }
        response = user_component.twitter_user_settings(user=user,
                                                        params=params)
        response = simplejson.dumps(response)
        self.redirect("/settings?response=%s&is_popup=%s" % (response, True))
        return
Пример #17
0
	def auth_check(self):
		self.session = get_current_session()
		self.current_student_user = None
		self.current_account = None
		#google_app_user = users.get_current_user()
		if self.session.has_key("current_student_user") and self.session["current_student_user"] is not None and self.session["current_student_user"] != "":
			self.current_student_user = self.session["current_student_user"]
		elif self.session.has_key("current_account") and self.session["current_account"] is not None and self.session["current_account"].system_login is not None:
			self.current_account = self.session["current_account"]	
		else:
			#Not logged in
			self.redirect('/login')
			return
Пример #18
0
def get_default_template_values(requestHandler, person, question):
    """Return a dictionary of template values used for login template"""

    page = requestHandler.request.path
    requiresGoogleAuthentication = page == "/admin" or not question or not question.nicknameAuthentication

    # user already logged in
    if person:
        client_id, token = connect(person)
        # helpers.log("*** NEW CHANNEL CREATED ***")
        url_linktext = "Logout"
        url = users.create_logout_url("/logout") if person.user else "/logout"

    # no one logged in, and Google authentication required
    elif requiresGoogleAuthentication:
        url_linktext = "Login w/ Google Account"
        url = "/login?page=" + requestHandler.request.uri + ("&question_id=" + question.code if question else "")
        url = users.create_login_url(url)

    # no one logged in, and nickname authentication allowed
    else:
        url_linktext = "Login w/ Nickname"
        url = "/loginpage" + ("?question_id=" + question.code if question else "")

    session = gaesessions.get_current_session()
    msg = session.pop("msg") if session.has_key("msg") else ""

    template_values = {}
    template_values["logged_in"] = "true" if person else "false"
    template_values["url_linktext"] = url_linktext
    template_values["url"] = url
    template_values["msg"] = msg

    if person:
        template_values["client_id"] = client_id
        template_values["token"] = token
        # the displayed user login should be the nickname if on question page (e.g., url has question_id param)
        # and nickname authentication is allowed; otherwise the Google login should be displayed
        template_values["user_login"] = person.user if requiresGoogleAuthentication else person.nickname
        template_values["user_nickname"] = person.nickname
        googleUser = users.get_current_user()
        template_values["admin"] = Person.isAdmin(requestHandler) or (
            googleUser and (not question or question.author == googleUser)
        )

    if question:
        template_values["phase"] = question.phase
        template_values["title"] = question.title
        template_values["question"] = question.question

    return template_values
Пример #19
0
    def get(self):

        key, secret = oauthclient.retrieve_service_request_token(
            constants.TWITTER_REQUEST_TOKEN_URL,
            constants.TWITTER_CONSUMER_KEY, constants.TWITTER_CONSUMER_SECRET)
        session = gaesessions.get_current_session()
        session['twitter_request_key'] = key
        session['twitter_request_secret'] = secret
        logging.info(
            oauthclient.generate_authorize_url(
                constants.TWITTER_AUTHENTICATE_URL, key))
        self.redirect(
            oauthclient.generate_authorize_url(
                constants.TWITTER_AUTHENTICATE_URL, key))
Пример #20
0
def login_room(room):
  secret = 'the password is %s and the salt-of-this-secret'
  q = MonopolyRoom.all()
  q.filter('game_code = ', room)
  result = q.get()
  password = request.forms.get('password').strip()
  password = md5.new(secret % password).hexdigest()
  if result.password != password:
    # TODO: show password error message
    pass
  else:
    session = get_current_session()
    session['allow'] = room
  redirect('/monopoly/%s' % (room))
Пример #21
0
  def wrapper(self, *args, **kwargs):
    session = gaesessions.get_current_session()
    device_type = session['device_type']
    protocol = constants.DEFAULT_STREAMING_PROTOCOL
    if device_type == "ios":
      protocol = self.request.get("protocol", constants.APPLE_STREAMING_PROTOCOL)
    elif device_type == "android":
      protocol = self.request.get("protocol", constants.ANDROID_STREAMING_PROTOCOL)
    else:
      protocol = self.request.get("protocol", constants.DEFAULT_STREAMING_PROTOCOL)

    kwargs['protocol'] = protocol
    session['protocol'] = protocol
    session.save()
    
    return _call_method(self, method, *args, **kwargs)
Пример #22
0
def index():
  room = request.query.get('d')
  if room: 
    room = room.strip()
    q = MonopolyRoom.all()
    q.filter('game_code = ', room)
    result = q.get()
    if result:
      # delete from GAE
      result.delete()
      # delete from Firebase
      fb = Firebase('https://summerwxy.firebaseio.com/monopoly/%s' % room)
      fb.remove()
      redirect('/monopoly')
      return
  # show list
  session = get_current_session()
  allow = session.get('allow', '')
  q = MonopolyRoom.all()
  q.order('-created')
  data = []
  for r in q.run(limit=10):
    data.append({'game_name': r.game_name, 'game_code': r.game_code, 'number_of_player': r.number_of_player, 'status': not r.password and '公開' or (r.game_code == allow) and '私人(已進入)' or '私人'})
  return dict({'data': data})
Пример #23
0
def session_delete(id):
    from lib.gaesessions import get_current_session
    s = get_current_session()
    if id in s:
        del s[id]
Пример #24
0
 def __getSession__(self):
     return get_current_session()
Пример #25
0
def session_get(id, default=None):
    from lib.gaesessions import get_current_session
    return get_current_session().get(id, default)
Пример #26
0
 def __getSession__(self):
   return get_current_session()
Пример #27
0
 def GetUser(cls):
     s = get_current_session()
     if s and s.is_active():
         return s.get('user', default=None)
     else:
         return None
Пример #28
0
 def redirectWithMsg(self, msg=None, dst="/"):
     if msg is not None:
         session = gaesessions.get_current_session()
         session["msg"] = msg
     self.redirect(dst)
Пример #29
0
 def get(self):
     session = gaesessions.get_current_session()
     if session.is_active():
         session.terminate(True)
     self.redirect("/")
Пример #30
0
 def GetUser(cls):
     s = get_current_session()
     if s and s.is_active():
         return s.get('user', default=None)
     else:
         return None
Пример #31
0
 def initialize(self, request, response):
     super(BaseHandler, self).initialize(request, response)
     self.session = get_current_session()
     user_key = self.session.get('user_key')
     self.user = user_key and ndb.Key(urlsafe=user_key).get()
     self.school_key = self.user and self.user.key.parent()