def get(self):
        apid = self.request.get("apid")
        email = self.request.get("email",'').lower()
        version = int(self.request.get("version", "0"))
        q = Token.query(Token.email == email)
        token = q.get()
        if token:
            token.apid = apid
            token.email = email
            token.version = version
        else:
            q = Token.query(Token.apid == apid)
            token = q.get()
            if token:
                token.apid = apid
                token.email = email
                token.version=version
            else:token = Token(apid=apid, email=email, version=version)
        token.put()

        cb = self.request.get('callback')
        self.response.headers['Content-Type'] = 'application/json'
        if cb:
            self.response.out.write(cb+'(' + json.dumps({}) +');')
        else:
            self.response.out.write(json.dumps({}))
    def regist_token(self, request):
        if Token.query(Token.token==request.token).fetch():
          return RegistTokenResult(result="DUP")

        token = Token(token=request.token, os='ios');
        token.put();

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
    def regist_token(self, request):
        if Token.query(Token.token == request.token).fetch():
            return RegistTokenResult(result="DUP")

        token = Token(token=request.token, os='ios')
        token.put()

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
    def regist_token(self, request):
        if Token.query(Token.token==request.token).fetch():
          return RegistTokenResult(result="DUP")

        token = urllib.unquote(request.token)
        token = Token(token=request.token, os=request.os, width=request.width, height=request.height);
        token.put();

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
    def regist_token(self, request):
        if Token.query(Token.token == request.token).fetch():
            return RegistTokenResult(result="DUP")

        token = urllib.unquote(request.token)
        token = Token(token=request.token,
                      os=request.os,
                      width=request.width,
                      height=request.height)
        token.put()

        push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)

        return RegistTokenResult(result="OK")
Beispiel #6
0
def fe_connect(request):
  """
  Do the OAuth dance for Fire Eagle!
  """
  CONSUMER_KEY = FE_CONSUMER_KEY
  CONSUMER_SECRET = FE_CONSUMER_SECRET
  CALLBACK_URL = FE_CALLBACK_URL
  fe = FireEagle( CONSUMER_KEY, CONSUMER_SECRET )
  request_token = fe.request_token( oauth_callback=CALLBACK_URL )
  if ( Token.gql( "WHERE user = :1", str(request.user) ).get() != None ):
      token = Token.gql( "WHERE user = :1", str(request.user) ).get()
  else:
    token = Token()
  token.user = str(request.user)
  token.fe_request_token = str(request_token)
  token.put()
  auth_url = fe.authorize( request_token, oauth_callback=CALLBACK_URL )
  return redirect( auth_url )
Beispiel #7
0
def fs_connect(request):
  """
  OAUTh dance for Foursquare
  """
  CONSUMER_KEY = FS_CONSUMER_KEY
  CONSUMER_SECRET = FS_CONSUMER_SECRET
  CALLBACK_URL = FS_CALLBACK_URL
  credentials = foursquare.OAuthCredentials(CONSUMER_KEY, CONSUMER_SECRET)
  fs = foursquare.Foursquare(credentials)
  request_token = fs.request_token( oauth_callback=CALLBACK_URL )
  if ( Token.gql( "WHERE user = :1", str(request.user) ).get() != None ):
      token = Token.gql( "WHERE user = :1", str(request.user) ).get()
  else:
    token = Token()
  token.user = str(request.user)
  token.fs_request_token = str(request_token)
  token.put()
  auth_url = fs.authorize( request_token, oauth_callback=CALLBACK_URL )
  return redirect( auth_url )
Beispiel #8
0
def save_token(token, request, *args, **kwargs):
    current_token = Token.query(Token.client_id == request.client.client_id,
                                Token.user == request.user).fetch(1)
    if current_token:
        logging.info('current token {}'.format(current_token))
        current_token[0].key.delete()
    expires_in = token.pop('expires_in')
    expires = datetime.utcnow() + timedelta(seconds=expires_in)
    token = Token(
        access_token=token['access_token'],
        refresh_token=token['refresh_token'],
        token_type=token['token_type'],
        scopes=str(token['scope']).split(),
        expires=expires,
        client_id=request.client.client_id,
        user=request.user,
    )
    token.put()
    return token
Beispiel #9
0
    def get(self, username=None, password=None):

        try:
            if (username is not None) and (password is not None):

                # Verification du user.
                user = User.query(
                    ndb.AND(User.str_username == username,
                            User.str_password == password)).get()

                if user is None:
                    self.error(404)
                    return

                # Voir s'il y a deja un token, si oui, on le recréé.
                token = Token.query(Token.key_user == user.key).get()

                if token is not None:
                    token.key.delete()

                token = Token(id=GetTimeInt(),
                              key_user=user.key,
                              b_valide=True)

                token.urlsafe_key = token.key.urlsafe()

                token.put()

                self.response.headers['Content-Type'] = ('text/plain')
                self.response.write(token.key.urlsafe())
                self.response.set_status(200)

        except (db.BadValueError, ValueError, KeyError):
            logging.error('%s', traceback.format_exc())
            self.error(400)

        except Exception:
            logging.error('%s', traceback.format_exc())
            self.error(500)
Beispiel #10
0
	def get(self, username=None, password=None):

		try:
			if (username is not None) and (password is not None):

				# Verification du user.
				user = User.query(ndb.AND(User.str_username==username,User.str_password==password)).get()

				if user is None:
					self.error(404)
					return

				# Voir s'il y a deja un token, si oui, on le recréé.
				token = Token.query(Token.key_user==user.key).get()

				if token is not None:
					token.key.delete()

				token = Token(id=GetTimeInt(),
					key_user=user.key,
					b_valide=True)

				token.urlsafe_key = token.key.urlsafe()

				token.put()

				self.response.headers['Content-Type'] = ('text/plain')
				self.response.write(token.key.urlsafe())
				self.response.set_status(200)

		except (db.BadValueError, ValueError, KeyError):
			logging.error('%s', traceback.format_exc())
			self.error(400)

		except Exception:
			logging.error('%s', traceback.format_exc())
			self.error(500)
Beispiel #11
0
    def post(self, code=None):
        response = RESPONSE.copy()
        if not code:
            desc = "There is/are missing parameters in the request."
            response["response"] = "MissingParameters"
            response["description"] = desc
            response["code"] = 463

        if "X-Signature" in self.request.headers:
            c_sig = self.request.headers['X-Signature']
            s_data = "&".join([
                "POST",
                urllib.quote(self.request.uri),
                urllib.quote(self.request.body)
            ])
            s_sig = generate_signature(LOGIN_KEY, s_data)
            logging.info("v: " + s_sig)
            if c_sig == s_sig:
                try:
                    body = json.loads(self.request.body)
                except:
                    desc = "The request body is not in a valid JSON format."
                    response["response"] = "InvalidJSONFormat"
                    response["description"] = desc
                    response["code"] = 406
                else:
                    if "nonce" in body and "timestamp" in body:
                        new = False
                        nn = Nonce.get_by_id(body["nonce"])
                        if nn:
                            expiry = datetime.datetime.now()
                            expiry = int(time.mktime(expiry.timetuple()))
                            expiry -= int(nn.timestamp)
                            expiry /= 60
                            expiry /= 60
                            if expiry <= 10:
                                new = True
                            else:
                                desc = "This request seems to be expired already"
                                response["response"] = "RequestExpired"
                                response["description"] = desc
                                response["code"] = 464
                        else:
                            n = Nonce(id=body["nonce"])
                            n.nonce = body["nonce"]
                            n.timestamp = int(body["timestamp"])
                            n.put()
                            new = True

                        if new:
                            logincode = LoginCode.get_by_id(str(code))
                            if logincode:
                                s = logincode.session.get()
                                if s.expires >= datetime.datetime.now():
                                    user = s.owner.get()
                                    if user:
                                        t_id = generate_uuid() + generate_uuid(
                                        )
                                        token = Token(id=t_id)
                                        token.token = t_id
                                        token.session = s.key
                                        token.token_type = "api"
                                        token.put()
                                        response = user.to_object(token=t_id)
                                        response["response"] = "Successful"
                                        response["expires"] = time.mktime(
                                            s.expires.timetuple())
                                        response["code"] = 200
                                    else:
                                        s.status = False
                                        s.put()
                                        response[
                                            "response"] = "UserUnavailable"
                                        response[
                                            "description"] = "This user seems to be unavailable"
                                        response["code"] = 404
                                else:
                                    response["response"] = "SessionExpired"
                                    response[
                                        "description"] = "This session seems to be expired already"
                                    response["code"] = 465
                            else:
                                response["response"] = "LoginCodeDoesNotExist"
                                response[
                                    "description"] = "This login code does not exist."
                                response["code"] = 404
                    else:
                        response["response"] = "MissingParameters"
                        response[
                            "description"] = "There is/are missing parameters in the request."
                        response["code"] = 463
            else:
                response["response"] = "InvalidSignature"
                response[
                    "description"] = "The request signature is invalid or has been tampered."
                response["code"] = 460
        else:
            response["response"] = "MissingParameters"
            response[
                "description"] = "There is/are missing parameters in the request."
            response["code"] = 463

        wrap_response(self, response)