Example #1
0
def authorize():
    if request.method == "GET":
        print "123445566"
        context_id = None
        # scopes requesting resource accesses
        resource_scopes = []
        for scope in request.args["scope"].split(" "):
            if scope.startswith("launch:"):
                _, context_id = scope.rsplit(":", 1)
            elif scope.startswith("patient/") or scope.startswith("user/"):
                resource_scopes.append(scope)
        if context_id is None:
            # create launch context for app launched outside of EHR env
            # TODO clean this up
            return redirect(
                "%s?%s" % (url_for("auth.create_context"), urlencode({"auth_req": json.dumps(request.args)}))
            )
        assert request.args["response_type"] == "code"
        # find app requested this authorization
        app = App.query.filter_by(
            client_id=request.args["client_id"], redirect_uri=request.args["redirect_uri"]
        ).first()
        assert app is not None
        client = Client(
            authorizer=request.session.user,
            app=app,
            state=request.args.get("state"),
            scope=request.args["scope"],
            context_id=context_id,
        )
        db.session.add(client)
        ctx = Context.query.get(context_id)
        # id of patient selected in launch time, could be none
        pid = json.loads(ctx.context).get("Patient")
        # parse requested scopes
        scopes = [OAuthScope(scp_str, pid) for scp_str in resource_scopes]
        readable_accesses = map(OAuthScope.to_readable, scopes)
        # we grant access despite user's reaction so that we don't have to keep tract of requested scope
        # security is being taken care of by marking the authorized client as un authorized
        for scope in scopes:
            scope.get_access_from_user(request.session.user, client)
        db.session.commit()
        return render_template(
            "authorization.html", appname=app.name, accesses=readable_accesses, auth_code=client.code
        )
    else:
        client = Client.query.filter_by(code=request.form["auth_code"]).first()
        assert client is not None
        app = App.query.filter_by(client_id=client.client_id).first()
        redirect_uri = app.redirect_uri
        if request.form["authorize"] == "yes":
            # authorize the client and redirect
            client.authorized = True
            db.session.commit()
            redirect_args = {"code": request.form["auth_code"]}
            if client.state is not None:
                redirect_args["state"] = client.state
        else:
            redirect_args = {"error": "Authorization declined"}
        return redirect("%s?%s" % (redirect_uri, urlencode(redirect_args)))
 def register(self):
     if request.method == u'POST':
         client_key = self.generate_client_key()
         secret = self.generate_client_secret()
         # TODO: input sanitisation?
         name = request.form.get(u"name")
         description = request.form.get(u"description")
         callback = request.form.get(u"callback")
         pubkey = request.form.get(u"pubkey")
         # TODO: redirect?
         # TODO: pubkey upload
         # TODO: csrf
         info = {
             u"client_key": client_key,
             u"name": name,
             u"description": description,
             u"secret": secret,
             u"pubkey": pubkey
         }
         client = Client(**info)
         client.callbacks.append(Callback(callback))
         client.resource_owner = g.user
         db_session.add(client)
         db_session.commit()
         return render_template(u"client.html", **info)
     else:
         clients = g.user.clients
         return render_template(u"register.html", clients=clients)
Example #3
0
 def delete_client(self, cmd, anon_ch):
     valid, msg, owner = self.check_del_params(cmd)
     if not valid:
         anon_ch.put({'status': 'error',
                      'message': 'Invalid parameters sent: {}'.format(msg)})
         return None
     try:
         _, ag = self.get_agave(cmd['tenant'], owner)
     except ClientException as e:
         anon_ch.put({'status': 'error',
                      'message': 'Could not generate an Agave client: {}'.format(e)})
         return None
     # remove the client from APIM
     try:
         ag.clients.delete(clientName=cmd['worker_id'])
     except Exception as e:
         anon_ch.put({'status': 'error',
                     'message': 'Not able to delete client from APIM. Exception: {}'.format(e)})
         return None
     # remove the client from the abaco db
     try:
         Client.delete_client(tenant=cmd['tenant'], client_key=cmd['client_id'])
     except Exception as e:
         anon_ch.put({'status': 'error',
                     'message': 'Not able to delete client from abaco db. Exception: {}'.format(e)})
         return None
     anon_ch.put({'status': 'ok',
                  'message': 'Client deleted.'})
 def register(self):
     if request.method == u'POST':
         client_key = self.generate_client_key()
         secret = self.generate_client_secret()
         # TODO: input sanitisation?
         name = request.form.get(u"name")
         description = request.form.get(u"description")
         callback = request.form.get(u"callback")
         pubkey = request.form.get(u"pubkey")
         # TODO: redirect?
         # TODO: pubkey upload
         # TODO: csrf
         info = {
             u"client_key": client_key,
             u"name": name,
             u"description": description,
             u"secret": secret,
             u"pubkey": pubkey
         }
         client = Client(**info)
         client['callbacks'].append(callback)
         client['resource_owner_id'] = g.user['_id']
         client_id = Client.insert(client)
         g.user.client_ids.append(client_id)
         User.get_collection().save(g.user)
         return render_template(u"client.html", **info)
     else:
         clients = Client.get_collection().find({'_id': {'$in': 
             [ObjectId(oid) for oid in g.user.client_ids]}})
         return render_template(u"register.html", clients=clients)
Example #5
0
 def create(self, validated_data):
     client = Client(
         name=validated_data['name'],
         alias=validated_data['name'].lower(),
         active=validated_data['active']
     )
     client.save()
     return client
Example #6
0
 def test_one_report(self):
   client = Client(product=ProductData.killerapp_obj, cookie='123')
   client.put()
   report = Report(product=ProductData.killerapp_obj, client=client, status=REPORT_NEW, remote_ip='127.0.0.1', data='[]')
   report.put()
 
   response = self.get('/status/')
   assert 'Queued Reports: 1' in str(response)
Example #7
0
def management():
    """ This endpoint is for vieweing and adding users and clients. """
    if request.method == 'POST' and request.form['submit'] == 'Add User':
        User.save(request.form['username'], request.form['password'])
    if request.method == 'POST' and request.form['submit'] == 'Add Client':
        Client.generate()
    return render_template('management.html', users=User.all(),
                           clients=Client.all())
Example #8
0
def authorize():
    if request.method == 'GET':
        context_id = None
        # scopes requesting resource accesses
        resource_scopes = [] 
        for scope in request.args['scope'].split(' '):
            if scope.startswith('launch:'):
                _, context_id = scope.rsplit(':', 1)
            elif scope.startswith('patient/') or scope.startswith('user/'):
                resource_scopes.append(scope)
        if context_id is None:
            # create launch context for app launched outside of EHR env
            # TODO clean this up
            return redirect('%s?%s'% (url_for('auth.create_context'), urlencode({'auth_req': json.dumps(request.args)})))
        assert request.args['response_type'] == 'code'
        # find app requested this authorization
        app = App.query.filter_by(
                client_id=request.args['client_id'],
                redirect_uri=request.args['redirect_uri']).first()
        assert app is not None
        client = Client(authorizer=request.session.user,
                        app=app,
                        state=request.args.get('state'),
                        scope=request.args['scope'],
                        context_id=context_id)
        db.session.add(client)
        ctx = Context.query.get(context_id)
        # id of patient selected in launch time, could be none
        pid = json.loads(ctx.context).get('Patient')
        # parse requested scopes
        scopes = [OAuthScope(scp_str, pid) for scp_str in resource_scopes]
        readable_accesses = map(OAuthScope.to_readable, scopes)  
        # we grant access despite user's reaction so that we don't have to keep tract of requested scope
        # security is being taken care of by marking the authorized client as un authorized
        for scope in scopes:
            scope.get_access_from_user(request.session.user, client)
        db.session.commit()
        return render_template('authorization.html',
                    appname=app.name,
                    accesses=readable_accesses,
                    auth_code=client.code)
    else:
        client = Client.query.filter_by(code=request.form['auth_code']).first()
        assert client is not None
        app = App.query.filter_by(client_id=client.client_id).first()
        redirect_uri = app.redirect_uri
        if request.form['authorize'] == 'yes':
            # authorize the client and redirect
            client.authorized = True 
            db.session.commit()
            redirect_args = {'code': request.form['auth_code']}
            if client.state is not None:
                redirect_args['state'] = client.state
        else:
            redirect_args = {'error': 'Authorization declined'}
        return redirect('%s?%s'% (redirect_uri, urlencode(redirect_args))) 
Example #9
0
def client():
    item = Client(
            client_id=gen_salt(40),
            client_secret=gen_salt(50),
            _redirect_uris='/',
            is_confidential=True
    )
    db.session.add(item)
    db.session.commit()
    return make_response(json.dumps(item.dict()), 200)
Example #10
0
    def test_parse_client(self):

        response = '''
            {"response":[{"id":"107111","name":"Ford","day_limit":170,"all_limit":3000}]}
            '''
        account = AccountFactory(remote_id=1)
        instance = Client(account=account, fetched=datetime.now())
        instance.parse(json.loads(response)['response'][0])
        instance.save(commit_remote=False)

        self.assertEqual(instance.account, account)
        self.assertEqual(instance.remote_id, 107111)
        self.assertEqual(instance.name, 'Ford')
        self.assertEqual(instance.day_limit, 170)
        self.assertEqual(instance.all_limit, 3000)
Example #11
0
def clients_add(request):
    if request.method == "POST":
        add_form = ClientAddForm(request.POST)
        if add_form.is_valid():
            new_cl = Client(
                name=add_form.cleaned_data["name"],
                address=add_form.cleaned_data["address"],
                zip_code=add_form.cleaned_data["zip_code"],
                country=add_form.cleaned_data["country"],
            )
            new_cl.save()
            return HttpResponseRedirect("/clients/")
    else:
        add_form = ClientAddForm()
    return render_to_response("storage/clients_add.html", {"form": add_form}, context_instance=RequestContext(request))
Example #12
0
def createUser(request):
    _udid = request.GET['udid']
    _tokenId = request.GET['tokenId']
    _bundleId = request.GET['bundleId']
    userId = ""
    try : 
        user = Client.objects.get(udid =_udid)
        user.tokenId = _tokenId
        user.bundleId = _bundleId
        userId = user.id
        user.save()
    except :
        add_to_db = Client(udid=_udid,tokenId=_tokenId,bundleId=_bundleId)
        add_to_db.save()
        userId= add_to_db.id
    return JSONResponse({'userId':userId})
Example #13
0
def announce(request):
    
    try:
        params = torUtils.getParams(request.get_full_path()) # <-- Add this to models
        ih = params[u'info_hash'][0]
        
        # Match params to grab a specific torrent
        t = Torrent.getTorrent(info_hash=ih)
        
        # Check whether this is a new or returning client
        c = t.getPeer(ip=request.META["REMOTE_ADDR"])
        if c.size == 0:
            c = Client.create(n = params['name'], i = request.META["REMOTE_ADDR"], p = params['port'], ih = params[u'info_hash'][0])
        else:
            # Parse old client
            c = c[0]
        c.update(params["event"])

    except Exception as e:
        print "Torrent not found; ", e
    #     return HttpResponse("Newp!")
    # Match client against list of known users
    # -- Seeding:
    # -- Leeching:
    # -- Loading:
    # -- Inactive:
    # If no announce, double-check peer connections, and send a new list
    return HttpResponse("Fixthis")
 def get_client_secret(self, client_key):
         client = Client.find_one({'client_key':client_key})
         
         if client:
             return client.get('secret')
         else:
             return None
 def get_rsa_key(self, client_key):
         client = Client.find_one({'client_key':client_key})
         
         if client:
             return client.get('pubkey')
         else:
             return None
Example #16
0
    def register(self):
        """Registers a new client (app)."""
        if request.method == u'POST':
            client_key = self.generate_client_key()
            secret = self.generate_client_secret()

            name = request.form.get(u"name")
            description = request.form.get(u"description")
            callback = request.form.get(u"callback")
            pubkey = request.form.get(u"pubkey")

            # Validoitaan syötteet:
            params = [name, description, callback, pubkey]
            if any(not param for param in params):
                flash("Please fill all fields.")
                return redirect(url_for("register"))

            for param in params:
                if len(param) < 5:
                    flash("Input too short: " + param)
                    return redirect(url_for("register"))
                if len(param) > 60:
                    flash("Input too long: ")
                    return redirect(url_for("register"))

            if not callback.startswith("http://"):
                flash("Invalid callback url: " + callback)
                return redirect(url_for("register"))

            info = {
                u"client_key": client_key,
                u"name": name,
                u"description": description,
                u"secret": secret,
                u"pubkey": pubkey
            }
            cb = Callback(callback=callback)
            cb_key = cb.put()
            client = Client(**info)
            client.callbacks.append(cb_key)
            client.resource_owner = g.user.key
            client.put()
            return render_template(u"client.html", **info)
        else:
            clients = Client.query(Client.resource_owner == g.user.key)
            return render_template(u"register.html", clients=clients)
Example #17
0
 def get_realm(self, client_key, request_token):
     client = Client.find_one({'client_key':client_key})
     
     if client:
         return RequestToken.find_one(
             {'token':request_token, 'client_id': client['_id']})['realm']
     else:
         return None
Example #18
0
 def start_oauth2_dance(self):
     login_hint = ''
     scope = ''
     client = Client.get_by_id(1)
     if not client:
         # If client does not exist then create an empty one
         client = Client(id=1)
         client.installer_user = users.get_current_user().email()
         client.put()
     # Get the login hint from configuration
     approval_prompt = 'auto' if client.refresh_token else 'force'
     scope = constants.OAUTH2_SCOPE
     redirect_uri = helpers.url_for('oauth.oauth_callback',
                                    _external=True)
     oauth_helper = OAuthDanceHelper(redirect_uri, approval_prompt, scope)
     url = oauth_helper.step1_get_authorize_url()
     #TODO: Add a random token to avoid forgery
     return redirect(url)
Example #19
0
def date(request):
    if request.method == 'POST':
        if request.is_ajax():
            name = request.POST.get('name')
            phone = request.POST.get('phone')
            email = request.POST.get('email')
            d = request.POST.get('date')
            t = request.POST.get('time')
            dd = datetime.date.fromtimestamp(int(d)/1000.0)

            bookedHour = int(t[16:18])
            bookedMin = int(t[19:21])
            bookedTime = datetime.time(bookedHour, bookedMin)
            dateTime = Client(name = name, phone = phone, email = email, date = dd, time=bookedTime)
            dateTime.save()
            return render(request, 'date2.html')

    return render(request,'date2.html')
 def save_request_token(self, client_key, request_token, callback,
         realm=None, secret=None):
     client = Client.find_one({'client_key':client_key})
     
     if client:
         token = RequestToken(
             request_token, callback, secret=secret, realm=realm)
         token.client_id = client['_id']
     
         RequestToken.insert(token)
Example #21
0
    def validate_access_token(self, client_key, resource_owner_key):

        token = None
        client = Client.find_one({'client_key':client_key})
    
        if client:
            token = AccessToken.find_one(
                {'token':resource_owner_key, 'client_id': client['_id']})
        
        return token != None
Example #22
0
	def get(self, request):
		data = json.loads(list(request.GET)[0].replace('\'', ''))
		register_output = { 'code': -1 }
		u = authenticate(username=data['name_surname'], password=data['pass'])
		if u is not None:
		 	register_output['code'] = 1
			return JsonResponse(register_output)
		else:
			u = User()
			u.email = data['email']
			u.username = data['name_surname']
			u.set_password(data['pass'])
			register_output['code'] = 0 
			u.save()
			client = Client(client_id=data['client_id'])
			client.save()
			qccess_token = create_token(u, client)
			register_output.update({'token' : access_token.token})
			return JsonResponse(register_output)
Example #23
0
    def validate_access_token(self, client_key, resource_owner_key):
        token = None
        client = Client.query(Client.client_key == client_key).get()

        if client:
            token = AccessToken.query(
                AccessToken.client == client.key,
                AccessToken.token == resource_owner_key).get()

        return token is not None
 def get_realm(self, client_key, request_token):
     client = Client.find_one({'client_key':client_key})
     
     if client:
         token = RequestToken.find_one(
             {'token':request_token, 'client_id': client['_id']})
         
         if token:
             return token.get('realm')
             
     return None
Example #25
0
def login(request):
	print 'blarg'
	if request.method == 'POST':
		print 'passed check 1'
		if request.POST.__contains__('user') and request.POST.__contains__('sessionid'):
			print 'passed if'
			hash = hashlib.md5(request.POST.__getitem__('sessionid')).hexdigest()
			print 'got hash'
			client = Client(user=request.POST.__getitem__('user'), sessionid=str(request.POST.__getitem__('sessionid')), md5=hash)
			print 'made client'
			
			print 'saved user'
			client.save()
			print 'saved client'
			return HttpResponse(hash)
			
		else:
			return HttpResponse('Invalid Request')
	if request.method == 'GET':
		return HttpResponse('ERROR')
Example #26
0
	def get(self, request):
		data = json.loads(list(request.GET)[0].replace('\'', ''))
		print data 
		user = authenticate(username=data['name_surname'], password=data['pass'])
		login_output = { 'code': -1}
		if user is not None:
			login_output['code'] = 0
			login(request, user)
			client = Client.objects.filter(client_id=data['client_id']).first()
			if client == None:
				client = Client(client_id=data['client_id'])
				client.save()
			access_token = AccessToken.objects.filter(client=client, user=user).first()
			if access_token == None:
				access_token = create_token(user, client)
			login_output.update({'token':access_token.token})
			return JsonResponse(login_output)
		else:
			login_output['code'] = 2
			return JsonResponse(login_output)
Example #27
0
 def validate_verifier(self, client_key, resource_owner_key, verifier):
     token = None
     client = Client.find_one({'client_key':client_key})
 
     if client:
         token = RequestToken.find_one(
             {'token':resource_owner_key,
              'client_id': client['_id'], 
              'verifier':verifier})
     
     return token != None
Example #28
0
 def save_request_token(self, client_key, request_token, callback,
         realm=None, secret=None):
     client = Client.find_one({'client_key':client_key})
     
     if client:
         token = RequestToken.find_or_create(realm = realm,
             user_id = current_user.get_id(), client_id = client['_id'])
         token.token = request_token
         token.callback = callback
         token.secret = secret        
         token.save()
def start_oauth2_dance():
    login_hint = ""
    scope = ""
    client = Client.get_by_id(1)
    if not client:
        # If client does not exist then create an empty one
        client = Client(id=1)
        client.put()
    # Get the login hint from configuration

    # approval_prompt = 'auto' if client.reseller_refresh_token else 'force'
    # Always force to be sure to get valid refresh token
    approval_prompt = "force"
    login_hint = get_setting("OAUTH2_RESELLER_DOMAIN_USER")
    scope = get_setting("OAUTH2_SCOPE")
    redirect_uri = helpers.url_for("oauth_callback", _external=True)
    oauth_helper = OAuthDanceHelper(scope=scope, redirect_uri=redirect_uri, approval_prompt=approval_prompt)
    url = oauth_helper.step1_get_authorize_url()
    # TODO: Add a random token to avoid forgery
    return redirect("%s&login_hint=%s" % (url, login_hint))
Example #30
0
    def validate_verifier(self, client_key, resource_owner_key, verifier):
        token = None
        client = Client.query(Client.client_key == client_key).get()

        if client:
            token = RequestToken.query(
                RequestToken.client == client.key,
                RequestToken.token == resource_owner_key,
                RequestToken.verifier == verifier).get()

        return token is not None
Example #31
0
 def post(self):
     parsed_args = parser_client.parse_args()
     client_name = parsed_args['client_name']
     if not client_name:
         return 418
     else:
         client = Client(name=client_name)
         try:
             session.add(client)
             session.commit()
         except:
             session.rollback()
     return client, 201
Example #32
0
    def get_realm(self, client_key, request_token):
        client = Client.find_one({'client_key': client_key})

        if client:
            token = RequestToken.find_one({
                'token': request_token,
                'client_id': client['_id']
            })

            if token:
                return token.get('realm')

        return None
Example #33
0
    def get_access_token_secret(self, client_key, resource_owner_key):
        client = Client.find_one({'client_key': client_key})

        if client:
            token = AccessToken.find_one({
                'token': resource_owner_key,
                'client_id': client['_id']
            })

            if token:
                return token.get('secret')

        return None
Example #34
0
	def update_client(self, client):
		count = 0
		newClient = False

		clientObj = Client.get_by_id(client.auth.email) 

		if (  clientObj is None ):
			newClient = True
			for c in client.child_list:
				d = datetime.datetime.now()
				next_month = datetime.datetime(d.year, d.month+1, 1)
				next_month_string =  next_month.isoformat() + '.0000'
				pay = Payment()
				pay.start_date = datetime.datetime.strptime(next_month_string, "%Y-%m-%dT%H:%M:%S.%f")
				pay.end_date = datetime.datetime.strptime(next_month_string, "%Y-%m-%dT%H:%M:%S.%f")
				pay.pay_date = datetime.datetime.strptime(next_month_string, "%Y-%m-%dT%H:%M:%S.%f")
				c.payment = pay.put()
				

		client.key = ndb.Key(Client, client.auth.email)	
		client.email = client.auth.email

		for c in client.child_list:			
		 	KindergartenKey =  ndb.Key(Kindergarten, c.kindergarten_id)
		 	c.kindergarten_key = KindergartenKey
		 	c.parent_id = client.email 
		 	#c.put()
		 	kindergarten = Kindergarten.get_by_id(c.kindergarten_id)
		 	for kc in kindergarten.child_list:
		 	 	if ( client.email  == kc.parent_id ):
		 	 		kindergarten.child_list.remove(kc)


		client.put()



		for c in client.child_list:
			count = count +1			
			kindergarten = Kindergarten.get_by_id(c.kindergarten_id)
			# c.client_email =  client.auth.email
			# c.put()

			kindergarten.child_list.append(c)

			if ( count == len( client.child_list) ):				
				kindergarten.put()



		return client
Example #35
0
    def setUpClass(cls):
        engine = create_engine(
            'mysql+mysqlconnector://iteatest:iteatest@localhost/iteatest')
        session_class = sessionmaker(bind=engine)
        session = session_class()

        app.session = session

        Base.metadata.create_all(engine)

        with open('department.csv', 'r') as c_file:
            reader = csv.reader(c_file)
            for n, row in enumerate(reader):
                if n == 0:
                    pass
                else:
                    department = Department(id=row[0],
                                            city=row[1],
                                            count_of_workers=row[2])
                    session.add(department)

        with open('client.csv', 'r') as c_file:
            reader = csv.reader(c_file)
            for n, row in enumerate(reader):
                if n == 0:
                    pass
                else:
                    client = Client(id=row[0],
                                    first_name=row[1],
                                    last_name=row[2],
                                    education=row[3],
                                    passport=row[4],
                                    city=row[5],
                                    age=row[6],
                                    department_id=row[7])
                    session.add(client)

        with open('application.csv', 'r') as c_file:
            reader = csv.reader(c_file)
            for n, row in enumerate(reader):
                if n == 0:
                    pass

                else:
                    application = Application(suma=row[1],
                                              credit_state=row[2],
                                              currency=row[3],
                                              client_id=row[4])
                    session.add(application)

        session.commit()
Example #36
0
    def register(self):
        if request.method == u'POST':
            client_key = self.generate_client_key()
            secret = self.generate_client_secret()
            # TODO: input sanitisation?
            name = request.form.get(u"name")
            description = request.form.get(u"description")
            callback = request.form.get(u"callback")
            pubkey = request.form.get(u"pubkey")
            # TODO: redirect?
            # TODO: pubkey upload
            # TODO: csrf
            info = {
                u"client_key": client_key,
                u"name": name,
                u"description": description,
                u"secret": secret,
                u"pubkey": pubkey
            }
            client = Client(**info)
            client['callbacks'].append(callback)
            client['user_id'] = g.user.get_id()
            client_id = client.insert()

            if not 'client_ids' in g.user:
                g.user.client_ids = []

            g.user.client_ids.append(client_id)
            g.user.save()

            return render_template(u"client.html", **info)
        else:
            clients = Client.get_collection().find(
                {'_id': {
                    '$in': [ObjectId(oid) for oid in g.user.client_ids]
                }})

            return render_template(u"register.html", clients=clients)
Example #37
0
def add_client():
    name=request.args.get('name')
    money=request.args.get('money')
    try:
        client=Client(
            name=name,
            money=money
        )
        db.session.add(client)
        db.session.commit()
        my_logger.debug('Clint added with id={}'.format(client.id))
        return "Client added with id={}".format(client.id)
    except Exception as e:
	    return(str(e))
Example #38
0
    def post(self):
        client_id = self.request.get_range("client_id") or int(
            self.request.headers.get('Client-Id') or 0)
        client = Client.get(client_id)
        auth_code = self.request.get("auth_code")

        try:
            client.paypal_refresh_token = paypal.get_refresh_token(auth_code)
        except paypal_exceptions.BadRequest:
            self.abort(400)
        else:
            client.put()
            user_data = paypal.get_user_info(client.paypal_refresh_token)
            self.render_json({'user': user_data})
Example #39
0
    def create_client(jwt):
        data = request.get_json()
        name = data.get('name')
        country = data.get('country')
        email = data.get('email')

        if not name or not country or not email:
            abort(412)
            return jsonify({
                'success': False,
                'message': 'required fields expected'
            }), 412
        else:
            try:
                client = Client(name=name, country=country, email=email)
                client.insert()
                return jsonify({
                    'success': True,
                    'email': email,
                    'message': 'client created'
                })
            except AssertionError as e:
                abort(422)
Example #40
0
    def post(self):
        order_id = self.request.get('orderId')

        result = alfa_bank.check_extended_status(config.ALFA_LOGIN,
                                                 config.ALFA_PASSWORD,
                                                 order_id)['alfa_response']
        alfa_response = {}

        if 'errorCode' in result:
            alfa_response['ErrorCode'] = result['errorCode']
            alfa_response['errorCode'] = result['errorCode']
            if alfa_response['ErrorCode'] == '0':
                if result.get('actionCode') != 0:
                    alfa_response['ErrorCode'] = '1'
                    alfa_response['errorCode'] = '1'

        if 'orderStatus' in result:
            alfa_response['OrderStatus'] = result['orderStatus']
            alfa_response['orderStatus'] = result['orderStatus']

        if result.get('cardAuthInfo'):
            if result['cardAuthInfo'].get('pan'):
                alfa_response['Pan'] = result['cardAuthInfo']['pan']
                alfa_response['pan'] = result['cardAuthInfo']['pan']
            if result['cardAuthInfo'].get('expiration'):
                alfa_response['expiration'] = result['cardAuthInfo'][
                    'expiration']

        if 'orderNumber' in result:
            alfa_response['OrderNumber'] = result['orderNumber']
            alfa_response['orderNumber'] = result['orderNumber']

        alfa_response['bindingId'] = None
        if result.get('bindingInfo'):
            if result['bindingInfo'].get('bindingId'):
                alfa_response['bindingId'] = result['bindingInfo']['bindingId']

        binding = CardBindingPayment.get_by_id(order_id)
        if alfa_response['OrderStatus'] == 1:
            binding.success = True
            client = Client.get(binding.client_id)
            client.tied_card = True
            client.put()
        else:
            binding.success = False
            binding.error = result.get('actionCode')
            binding.error_description = result.get('actionCodeDescription')
        binding.put()

        self.render_json(alfa_response)
Example #41
0
 def post(self):
     client_id = int(self.request.headers.get('Client-Id') or 0)
     if not client_id:
         self.abort(400)
     client = Client.get(client_id)
     if not client:
         self.abort(400)
     push = GeoPush.query(
         GeoPush.client == client.key,
         GeoPush.status == STATUS_AVAILABLE).order(-GeoPush.created).get()
     if not push:
         push = GeoPush(client=client.key)
         push.put()
     self.render_json({'success': True})
Example #42
0
def convert(experiment, client_id,
    kpi=None,
    datetime=None,
    redis=None):
    """"""
    exp = Experiment.find(experiment, redis=redis)#查找实验,得到实验对象

    if cfg.get('enabled', True):#判断是否为启用状态
        client = Client(client_id, redis=redis)#创建client对象
        alt = exp.convert(client, dt=datetime, kpi=kpi)#调用exp对象的convert方法
    else:
        alt = exp.control

    return alt
Example #43
0
def convert(experiment, client_id,
    kpi=None,
    datetime=None,
    redis=None):

    exp = Experiment.find(experiment, redis=redis)

    if cfg.get('enabled', True):
        client = Client(client_id, redis=redis)
        alt = exp.convert(client, dt=datetime, kpi=kpi)
    else:
        alt = exp.control

    return alt
Example #44
0
    def validate_request_token(self, client_key, resource_owner_key):
        token = None
        if client_key:
            client = Client.query(Client.client_key == client_key).get()

            if client:
                token = RequestToken.query(
                    RequestToken.token == resource_owner_key,
                    RequestToken.client == client.key).get()
        else:
            token = RequestToken.query(
                RequestToken.token == resource_owner_key).get()

        return token is not None
Example #45
0
def signupClient():
    if request.method == "POST":
        new_client = json.loads(request.data)
        password = request.json.get('password', None)
        email = request.json.get('email', None)
        hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

        client = Client(
            name=new_client["name"], 
            email=new_client["email"], 
            password=hashed,
            role=new_client["role"]
        )

        db.session.add(client)
        db.session.commit()
        return jsonify(client.serialize()), 200

    if request.method == "GET":
        client_signup = Client.query.all()

        all_client_signup = list(map(lambda client: client.serialize(), client_signup))
        return jsonify(all_client_signup), 200
Example #46
0
        def create_client():
            try:
                client = Client.create(name=name_entry.get(),
                                       identity_card=pre_id.get() + "-" +
                                       identity_entry.get(),
                                       phone_number=phone_entry.get())
                new_client_window.destroy()
                self.update_client_frame(client)

            except IntegrityError:
                error_message = "Ya existe un cliente con esta cédula o rif."
                messagebox.showerror("Error",
                                     error_message,
                                     parent=new_client_window)
Example #47
0
    def validate_redirect_uri(self, client_key, redirect_uri=None):
        try:
            cbs = Client.query(Client.client_key == client_key).get().callbacks
            if redirect_uri in (x.callback for x in ndb.get_multi(cbs)):
                return True

            elif len(cbs) == 1 and redirect_uri is None:
                return True

            else:
                return False

        except AttributeError:  # Clientiä ei löytynyt
            return False
Example #48
0
def protest_approval(warning_id):
    """
    The '/protest_approval/<warning_id>' route directs a superuser to approve a protest against a warning
    with the id of [warning_id].
    """
    if session['type_of_user'] == 'user':
        return redirect(url_for('dashboard'))
    if session['type_of_user'] == 'applicant':
        return redirect(url_for('dashboard_applicant'))

    warning_id = int(warning_id)
    info = SystemWarning.get_warning_info(warning_id)
    username = info['warned_user']
    type_of_user = User.get_user_info(username)['type_of_user']
    avg_rating = 0
    if type_of_user == 'client':
        avg_rating = Client.get_info(username)['avg_rating']
    elif type_of_user == 'developer':
        avg_rating = Developer.get_info(username)['avg_rating']

    form = ProtestApprovalForm()

    if request.method == 'GET':
        return render_template("protestApproval.html",
                               warning_id=warning_id,
                               info=info,
                               form=form,
                               avg_rating=avg_rating)
    if request.method == 'POST':
        if form.validate():
            if form.decision.data == 'remove':
                SystemWarning.remove_warning(warning_id)
                Notification(
                    username, session['username'],
                    'Your protest for warning#' + str(warning_id) +
                    ' was approved. Your warning has been deleted.')
            else:
                SystemWarning.keep_warning(warning_id)
                Notification(
                    username, session['username'],
                    'Your protest for warning#' + str(warning_id) +
                    ' was not approved. Your warning remains.')
            return redirect(url_for('dashboard_superuser'))
        else:
            return render_template("protestApproval.html",
                                   warning_id=warning_id,
                                   info=info,
                                   form=form,
                                   avg_rating=avg_rating)
Example #49
0
def client_experiments(api_key,
                       client_id,
                       kpi=None,
                       redis=None,
                       exclude_paused=True,
                       exclude_archived=True):
    client = Client(client_id, redis=redis)
    alternatives = []
    running_experiments = Experiment.all(api_key,
                                         redis=redis,
                                         exclude_paused=exclude_paused,
                                         exclude_archived=exclude_archived)
    for experiment in running_experiments:
        alternatives.append(experiment.get_alternative(client))
    return alternatives
Example #50
0
def handle_client():
    """
    Create client and retrieve all clients
    """

    # *******************   POST REQUEST    *******************
    if request.method == 'POST':
        body = request.get_json()

        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        if 'name' not in body:
            raise APIException('You need to specify the name', status_code=400)
        if 'email' not in body:
            raise APIException('You need to specify the email',
                               status_code=400)
        if 'password' not in body:
            raise APIException('You need to specify the password',
                               status_code=400)

        client1 = Client(name=body['name'],
                         email=body['email'],
                         password=body['password'])
        db.session.add(client1)
        db.session.commit()
        return jsonify(client1.serialize()), 200

# *******************   GET REQUEST    *******************
    if request.method == 'GET':
        all_clients = Client.query.all()
        all_clients = list(map(lambda x: x.serialize(), all_clients))
        return jsonify(all_clients), 200

    return "Invalid Method", 404
Example #51
0
 def get(self):
     client_id = self.request.get_range('client_id') or int(
         self.request.headers.get('Client-Id') or 0)
     client = Client.get(client_id)
     if not client:
         self.abort(400)
     history = Order.get(client)
     sorted_history = sorted(history,
                             key=lambda order: order.delivery_time,
                             reverse=True)
     order_dicts = [
         order.history_dict() for order in sorted_history
         if order.status != CREATING_ORDER
     ]
     self.render_json({'orders': order_dicts})
Example #52
0
def setClientData(email, nom, prénom, sex, balance, incomes, expenses):
    new_client = Client(Email=email,
                        Name=nom,
                        LastName=prénom,
                        Sex=sex,
                        CurrentBalance=balance,
                        Incomes=balance,
                        Expenses=expenses)
    if new_client:
        db.session.add(new_client)
        db.session.commit()
        time.sleep(1)

    db.session.commit()
    return new_client
Example #53
0
 def delete_client(self, cmd, anon_ch):
     """Main function to process a `delete` command message."""
     valid, msg, owner = self.check_del_params(cmd)
     if not valid:
         anon_ch.put({
             'status': 'error',
             'message': 'Invalid parameters sent: {}'.format(msg)
         })
         return None
     try:
         _, ag = self.get_agave(cmd['tenant'], owner)
     except ClientException as e:
         m = 'Could not generate an Agave client: {}'.format(e)
         logger.error(m)
         anon_ch.put({'status': 'error', 'message': m})
         return None
     # remove the client from APIM
     try:
         ag.clients.delete(clientName=cmd['worker_id'])
     except Exception as e:
         m = 'Not able to delete client from APIM. Exception: {}'.format(e)
         logger.error(m)
         anon_ch.put({'status': 'error', 'message': m})
         return None
     # remove the client from the abaco db
     try:
         Client.delete_client(tenant=cmd['tenant'],
                              client_key=cmd['client_id'])
     except Exception as e:
         m = 'Not able to delete client from abaco db. Exception: {}'.format(
             e)
         logger.error(m)
         anon_ch.put({'status': 'error', 'message': m})
         return None
     logger.info("client deleted successfully.")
     anon_ch.put({'status': 'ok', 'message': 'Client deleted.'})
Example #54
0
    def save_request_token(self,
                           client_key,
                           request_token,
                           callback,
                           realm=None,
                           secret=None):
        client = Client.query(Client.client_key == client_key).get()

        if client:
            token = RequestToken(token=request_token,
                                 callback=callback,
                                 secret=secret,
                                 realm=realm,
                                 client=client.key)
            token.put()
Example #55
0
File: client.py Project: WLSF/chat
def main_loop(ip, port):
    try:
        print('Write your first message: ')
        while 1:
            client = Client(ip, port)
            client.connect()
            msg = input()
            client.send_message(msg)
    except:
        pass
Example #56
0
def _order_data(order, lite, venue_cache):
    venue = _get_venue(order.venue_id, venue_cache)
    tz_offset = venue.timezone_offset if venue else 3  # TODO: Moscow time is hardcoded in case venue is not found
    venue_title = venue.title if venue else order.venue_id
    dct = {
        "order_id":
        order.key.id(),
        "comment":
        order.comment if order.comment else '',
        "return_comment":
        order.return_comment if order.return_comment else '',
        "status":
        STATUS_MAP[order.status],
        "date":
        (order.date_created + timedelta(hours=tz_offset)).strftime("%d.%m.%Y"),
        "created_time":
        (order.date_created + timedelta(hours=tz_offset)).strftime("%H:%M:%S"),
        "delivery_time": (order.delivery_time +
                          timedelta(hours=tz_offset)).strftime("%H:%M:%S"),
        "payment_type":
        PAYMENT_TYPE_MAP[order.payment_type_id],
        "menu_sum":
        sum(d.price / 100.0 for d in order.item_details),
        "sum_after_promos":
        order.total_sum - order.delivery_sum,
        "sum_after_delivery":
        order.total_sum,
        "sum_after_wallet":
        order.total_sum - order.wallet_payment,
        "venue_revenue":
        sum(d.revenue for d in order.item_details),
        "venue":
        venue_title,
        "delivery_type":
        order.delivery_type
    }
    if lite:
        dct["client"] = {"id": order.client_id}
    else:
        dct['items'] = order.grouped_item_dict(order.item_details)
        client = Client.get(order.client_id)
        dct["client"] = {
            "id": client.key.id(),
            "name": client.name,
            "surname": client.surname,
            "phone": client.tel
        }
    return dct
Example #57
0
    def on_participate(self, request):
        opts = {}
        alts = request.args.getlist('alternatives')
        experiment_name = request.args.get('experiment')
        force = request.args.get('force')
        client_id = request.args.get('client_id')
        distribution = request.args.get('traffic_dist')

        if client_id is None or experiment_name is None or alts is None:
            return json_error({'message': 'missing arguments'}, request, 400)

        if distribution:
            opts['distribution'] = distribution

        try:
            experiment = Experiment.find_or_create(experiment_name, alts,
                                                   self.redis, opts)
        except ValueError as e:
            return json_error({'message': str(e)}, request, 400)

        alternative = None
        if force and force in alts:
            alternative = force
        elif not cfg.get('enabled', True):
            alternative = alts[0]
        elif experiment.winner is not None:
            alternative = experiment.winner
        elif should_exclude_visitor(request):
            alternative = alts[0]
        else:
            dt = None
            if request.args.get("datetime"):
                dt = dateutil.parser.parse(request.args.get("datetime"))
            client = Client(client_id, self.redis)
            alternative = experiment.get_alternative(client, dt=dt).name

        resp = {
            'alternative': {
                'name': alternative
            },
            'experiment': {
                'name': experiment.name,
            },
            'client_id': client_id,
            'status': 'ok'
        }

        return json_success(resp, request)
Example #58
0
def fixtures_load():
    User.query.delete()

    users = [
        {
            'full_name': 'Максим Скочинский',
            'email': '*****@*****.**',
            'role': User.ROLE_MANAGER,
            'username': '******',
            'password': '******'
        },
        {
            'full_name': 'Максим Скочинский',
            'email': '*****@*****.**',
            'role': User.ROLE_ADMINISTRATOR,
            'username': '******',
            'password': '******'
        },

    ]

    for user in users:
        manager = User()
        manager.full_name = user.get('full_name')
        manager.email = user.get('email')
        manager.role = user.get('role')
        manager.username = user.get('username')
        manager.set_password(user.get('password'))
        manager.generate_token()
        db.session.add(manager)

        for i in range(10):
            client = Client()
            client.full_name = fake.name()
            client.user = manager
            client.organization_name = fake.company()
            client.address = fake.address()
            client.phone_number = fake.phone_number()
            db.session.add(client)

            meeting = Meeting()
            meeting.user = manager
            meeting.client = client
            meeting.datetime = datetime.today() - timedelta(minutes=30)
            meeting.goal = 'Договор'
            meeting.address = client.address
            db.session.add(meeting)

    db.session.commit()
    pass
Example #59
0
def update(ctx, client_uid):
    """Updates a single client"""
    client_service = ClientService(ctx.obj['clients_table'])

    client = [
        client for client in client_service.list_clients()
        if client['uid'] == client_uid
    ]

    if client:
        client = _update_client_flow(Client(**client[0]))
        client_service.update_client(client)

        click.echo('Client updated')
    else:
        click.echo('Client not found')
Example #60
0
def test_seed_client_saves_clients_to_db(initialize_db):
    """
    Tests that `seed_client` function stores clients in the db.

    Args:
        initialize_db (None): initializes the database and drops tables when
            test function finishes.
    """
    seed_client()

    clients = Client.get_all()

    assert clients[0].username == 'Client A'
    assert clients[1].username == 'Client B'
    assert clients[2].username == 'Client C'
    assert len(clients) == 3