def authenticate_and_login(request, username, password): user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return json({'status': 'success', 'username': user.username}) else: return json({'status': 'failure'})
def test_json_handler(self): assert utils.json({"v": None}).find("null") != -1 assert utils.json({ "d": datetime.datetime(2014, 01, 01, 01, 01, 01) }).find("2014-01-01T01:01:01") != -1 assert utils.json({ "t": datetime.timedelta(days=1) }).find("00:00:00") != -1
def rsa_decrypt(): body = request.get_json() try: priv_key = int(body['key']['d']), int(body['key']['n']) except ValueError: return json(None, 'PrivateKey(d, n) should consist of two integers!') data = body['data'] return json({'decrypted': rsa.decrypt(priv_key, data)})
def food(fid): """ Palauttaa yksittäisen elintarvikkeen tiedot. """ food = scraper.get_food(fid) if not food: return json("fail", {"fid": "food not found"}) return json(data=food)
def get_rsa_keys(): body = request.get_json() try: public, private = rsa.generate_keypair(int(body['p']), int(body['q'])) except ValueError as error: return json(None, str(error)), 400 e, n = public d, n = private return json({'e': e, 'd': d, 'n': n})
def authenticate_and_login(request, username,password): user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return json({ 'status': 'success', 'username': user.username }) else: return json({'status': 'failure'})
def bites_by_date(date): """ Palauttaa kirjautuneen käyttäjän annokset valitulta päivältä. Parametrit: - date: päivämäärä muodossa YYYYmmdd """ try: date = datetime.strptime(date, DATEFORMAT) except ValueError: return json("fail", {"parameters": "invalid date parameter"}) return json(data=db.get_bites_by_user(g.user["_id"], date=date))
def search_foods(): """ Palauttaa elintarvikehaun tulokset annetulla hakusanalla. URL-parametrit: - q: hakusana """ query = request.args.get("q") if not query: return json("fail", {"q": "invalid query"}) results = scraper.search_foods(query) return json(data=results)
def buil_start_request(): data = {} action = "start" msg_type_ = "request" des = "" res_msg = buildMsg(data,action,msg_type_,des) return json(res_msg)
def _get_media_info(programID, mediaType, mediaID): response = json( URL_MEDIA_INFO.format(apiKey=API_KEY, programID=programID, mediaType=mediaType, mediaID=mediaID)) return response['media']
def delete_bite(bid): """ Poistaa kirjautuneelta käyttäjältä määrätyn annoksen. """ if request.method == DELETE: db.delete_bite(bid) return json()
def get_favs(): """ Palauttaa kirjautuneen käyttäjän suosikkielintarvikkeet. """ logging.error("get_favs") favs = db.get_favs_by_user(g.user["_id"]) return json(data=favs)
def search(search_term, limit=20): response = json( URL_SEARCH.format(apiKey=API_KEY, keyword=search_term, limit=limit)) programs = [ ProgramItem(programJson) for programJson in response['programs'] ] return programs
def get_channels(): """ :return: Returns list of all Channels :rtype : list of ChannelItem """ response = json(URL_CHANNEL_LIST.format(apiKey=API_KEY)) return [ChannelItem(channelJson) for channelJson in response['channels']]
def build_login_request(name ): data = Msg_Login(name) action = "login" msg_type_ = "request" des = "" res_msg = buildMsg(data,action,msg_type_,des) return json(res_msg)
def new_pet(request): if request.method == 'POST': form = DatingForm(request.POST) if form.is_valid(): pet = form.save() return json({'success': 'true', 'redirect_url': '/pets/pets/'}) raise Http404
def search_pet(request): if request.method == 'POST': form = SearchForm(request.POST) return json({ 'success': 'true', 'redirect_url': '/pets/pets/' }) raise Http404
def buil_verify_request(answer): data = {} action = "verify" msg_type_ = "request" des = "" data["user_answer"] = answer res_msg = buildMsg(data,action,msg_type_,des) return json(res_msg)
def add_or_delete_fav(fid): """ POST lisää kirjautuneelle käyttäjälle uuden suosikkielintarvikkeen. DELETE poistaa suosikkielintarvikkeen. """ if request.method == DELETE: db.delete_fav_from_user(g.user["_id"], fid) return json() food = scraper.get_food(fid) if not food: return json("fail", {"fid": "food not found"}) fav = {"fid": food["_id"], "name": food["name"]} db.add_fav_to_user(g.user["_id"], fav) return json()
def add_or_delete_recipe(rid): """ POST lisää kirjautuneelle käyttäjälle uuden suosikkireseptin. DELETE poistaa suosikkireseptin. """ if request.method == DELETE: db.delete_recipe_from_user(g.user["_id"], rid) return json() recipe = db.get_recipe(rid) if not recipe: return json("fail", {"rid": "recipe not found"}) recipe = {"rid": recipe["_id"], "name": recipe["name"]} db.add_fav_to_user(g.user["_id"], recipe) return json()
def get_data(): body = request.get_json() user = db.get(body['user'], {}) if not user.get('session_key') or key_expired(user.get('created_at')): return json(None, 'Session key has expired!'), 401 session_key = user['session_key'] with open(os.path.join(APP_STATIC, 'data.txt'), 'rb') as f: data = list(f.read()) encrypted_data = aes.encrypt(data, session_key) if __debug__: decrypted_data = aes.decrypt(encrypted_data, session_key) print('ENCRYPTION CORRECT:', bytes(decrypted_data).startswith(bytes(data))) return json({'encrypted': encrypted_data})
def build_suc_response(request_msg,data,des,): _msg_action = request_msg [msg_action] response_msg_data = data response_msg_action = _msg_action response_msg_type = 'response' response_msg_des = des response_msg_data['succeed'] = True res_msg = buildMsg(response_msg_data,response_msg_action,response_msg_type,response_msg_des) return json(res_msg)
def login(): body = request.get_json() user, password = body.get('user'), body.get('password') if not db.get(user, {}).get('password') == password: return json(None, 'Incorrect login or password!'), 401 try: pub_key = int(body['key']['e']), int(body['key']['n']) except ValueError: return json(None, 'PublicKey(e, n) should consist of two integers!'), 400 session_key = get_session_key(aes.KEY_LENGTH) encrypted_key = rsa.encrypt(pub_key, session_key) if __debug__: print('SESSION_KEY:', session_key) db[user]['session_key'] = session_key db[user]['created_at'] = time() return json({'sessionKey': encrypted_key})
def new_pet(request): if request.method == 'POST': form = DatingForm(request.POST) if form.is_valid(): pet = form.save() return json({ 'success': 'true', 'redirect_url': '/pets/pets/' }) raise Http404
def build_fail_response(request_msg,des): _msg_data = request_msg [msg_data] _msg_action = request_msg [msg_action] response_msg_data = _msg_data response_msg_action = _msg_action response_msg_type = 'response' response_msg_des = des response_msg_data['succeed'] = False res_msg = buildMsg(response_msg_data,response_msg_action,response_msg_type,response_msg_des) return json(res_msg)
def get_channel_programs(channelID): """ :param channelID: Channel ID :return: list of programs for th current Channel ID :rtype: list of ProgramItem """ response = json(URL_PROGRAMS_LIST.format(apiKey=API_KEY, channelID=channelID)) programs = [ProgramItem(programJson) for programJson in response['programs']] # Only return programs with one or more episodes/clips return filter(lambda x: (x.episodeCount + x.clipCount) > 0, programs)
def register(): """ Rekisteröi uuden käyttäjän. TODO """ username = request.form["username"] key = request.form["key"] # Validoidaan syötteet: if not username: return json("fail", {"username": "******"}) if not key or not (7 < len(key) < 500): return json("fail", {"key": "invalid key"}) existing_user = db.get_user(username) if existing_user: return json("fail", {"username": "******"}) uid = db.add_user(username, key) return json("success", {"id": str(uid)})
def days(): """ Palauttaa käyttäjän päivät annetulta väliltä. URL-parametrit: - start: inklusiivinen alkupäivämäärä (YYYYmmdd) - end: inklusiivinen loppupäivämäärä (YYYYmmdd) Paluuarvo on muotoa [{date, count, kcal, carbs, fat, protein}] """ start = request.args.get("start", None) end = request.args.get("end", None) try: if start: start = datetime.strptime(start, DATEFORMAT) if end: end = datetime.strptime(end, DATEFORMAT) except ValueError: return json("fail", {"parameters": "invalid date parameters"}) return json(data=db.get_days_by_user(g.user["_id"], start, end))
def new_question(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.questioner = request.user question.save() return json({ 'success': 'true', 'redirect_url': '/forum/questions/' + str(question.pk) }) raise Http404
def new_question(request): if request.method == 'POST': form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.questioner = request.user question.save() return json({ 'success': 'true', 'redirect_url': '/forum/questions/'+ str(question.pk) }) raise Http404
def goals(): """ Palauttaa/asettaa käyttäjän päivittäiset ravintoainetavoitteet. Jos tavoitteita ei ole asetettu, palautetaan tyhjä olio. POST-parametrit (kaikki pakollisia): - kcal: päivittäinen energiatavoite kilokaloreina - carbs: päivittäinen hiilihydraattitavoite grammoina - fat: päivittäinen rasvatavoite grammoina - protein: päivittäinen proteiinitavoite grammoina """ user = g.user if request.method == "GET": if not "goals" in user: return json("success", {}) return json("success", user["goals"]) # POST goals = {} try: for attr in ["kcal", "carbs", "fat", "protein"]: goals[attr] = int(request.form[attr]) except KeyError: return json("fail", {"missing parameter": attr}) except ValueError: return json("fail", {"invalid parameter": attr}) if db.set_user_goals(user["_id"], goals): return json("success") return json("error", "database update error")
def user(): """ Palauttaa käyttäjän tiedot. Paluuarvossa avaimina username, goals, favs, id. """ user = { "username": g.user["username"], "favs": g.user["favs"], "id": g.user["_id"], "goals": g.user["goals"] if "goals" in g.user else {} } return json("success", user)
def answer(request): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.answerer = request.user question_id = atoi(request.POST['question_id']) answer.question = Question.objects.get(id=question_id) answer.save() return json({ 'success' : True, 'redirect_url' : '/forum/questions/' + str(question_id) }) raise Http404
def get_channel_programs(channelID): """ :param channelID: Channel ID :return: list of programs for th current Channel ID :rtype: list of ProgramItem """ response = json( URL_PROGRAMS_LIST.format(apiKey=API_KEY, channelID=channelID)) programs = [ ProgramItem(programJson) for programJson in response['programs'] ] # Only return programs with one or more episodes/clips return filter(lambda x: (x.episodeCount + x.clipCount) > 0, programs)
def answer(request): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.answerer = request.user question_id = atoi(request.POST['question_id']) answer.question = Question.objects.get(id=question_id) answer.save() return json({ 'success': True, 'redirect_url': '/forum/questions/' + str(question_id) }) raise Http404
def get_animal_view_adoptable_js(dbo): """ Returns js that outputs adoptable animals into a host div """ js = utils.read_text_file("%s/static/js/animal_view_adoptable.js" % dbo.installpath) # inject adoptable animals, account and base url pc = PublishCriteria(configuration.publisher_presets(dbo)) js = js.replace("{TOKEN_ACCOUNT}", dbo.database) js = js.replace("{TOKEN_BASE_URL}", BASE_URL) js = js.replace( "\"{TOKEN_ADOPTABLES}\"", utils.json( get_animal_data(dbo, pc, include_additional_fields=True, strip_personal_data=True))) return js
def writeJavaScript(self, animals): # Remove original owner and other sensitive info from javascript database # before saving it for a in animals: for k in a.iterkeys(): if k.startswith("ORIGINALOWNER") or k.startswith("BROUGHTINBY") \ or k.startswith("RESERVEDOWNER") or k.startswith("CURRENTOWNER") \ or k == "DISPLAYLOCATION": a[k] = "" self.saveFile( os.path.join(self.publishDir, "db.js"), "publishDate='%s';animals=%s;" % (i18n.python2display(self.locale, i18n.now( self.dbo.timezone)), utils.json(animals))) if self.pc.uploadDirectly: self.log("Uploading javascript database...") self.upload("db.js") self.log("Uploaded javascript database.")
def update_xml(self): """ 将文件信息更新至xml配置文件 """ root_config = getLibXmlPath() #先检查一级xml配置文件是否有该文件对应库的信息 if not find_element(root_config, self.lib_name): insert_lib_node(root_config, self.lib_name) #在二级xml配置文件中插入信息 lib_config = getLibXmlPath(self.lib_name) if not os.path.exists(lib_config): open(lib_config, 'wb').close() create_empty_xml_file(lib_config, "root") log.debug("更新库%s的xml配置文件"%self.lib_name) node = create_single_element("node") for k, v in self.info.items(): sub_node = SubElement(node, k) sub_node.text = json(v) add_xml_element(lib_config, node)
def handler(post, path, remoteip, referer, querystring): """ Handles the various service method types. post: The GET/POST parameters path: The current system path/code.PATH remoteip: The IP of the caller referer: The referer HTTP header querystring: The complete querystring return value is a tuple containing MIME type, max-age, content """ # Get service parameters account = post["account"] username = post["username"] password = post["password"] method = post["method"] animalid = post.integer("animalid") formid = post.integer("formid") seq = post.integer("seq") title = post["title"] strip_personal = post.integer("sensitive") == 0 cache_key = querystring.replace(" ", "") # Do we have a cached response for these parameters? cached_response = get_cached_response(cache_key) if cached_response is not None: al.debug("cache hit for %s" % (cache_key), "service.handler") return cached_response # Are we dealing with multiple databases, but no account was specified? if account == "" and MULTIPLE_DATABASES: return ("text/plain", 0, 0, "ERROR: No database/alias specified") dbo = db.get_database(account) if dbo.database in ("FAIL", "DISABLED", "WRONGSERVER"): al.error( "auth failed - invalid smaccount %s from %s (%s)" % (account, remoteip, dbo.database), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid database (%s)" % dbo.database) # If the database has disabled the service API, stop now if not configuration.service_enabled(dbo): al.error("Service API is disabled (%s)" % method, "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Service API is disabled") # Do any database updates need doing in this db? dbo.installpath = path if dbupdate.check_for_updates(dbo): dbupdate.perform_updates(dbo) # Does the method require us to authenticate? If so, do it. user = None securitymap = "" if method in AUTH_METHODS: # If the database has authenticated service methods disabled, stop now if not configuration.service_auth_enabled(dbo): al.error("Service API for auth methods is disabled (%s)" % method, "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Service API for authenticated methods is disabled") user = users.authenticate(dbo, username, password) if user is None: al.error( "auth failed - %s/%s is not a valid username/password from %s" % (username, password, remoteip), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid username and password") securitymap = users.get_security_map(dbo, user["USERNAME"]) # Get the preferred locale and timezone for the site l = configuration.locale(dbo) dbo.locale = l dbo.timezone = configuration.timezone(dbo) al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title), "service.handler", dbo) if method == "animal_image": hotlink_protect("animal_image", referer) if utils.cint(animalid) == 0: al.error( "animal_image failed, %s is not an animalid" % str(animalid), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid animalid") else: mediadate, data = media.get_image_file_data( dbo, "animal", utils.cint(animalid), seq) if data == "NOPIC": mediadate, data = media.get_image_file_data(dbo, "nopic", 0) return set_cached_response(cache_key, "image/jpeg", 86400, 3600, data) elif method == "animal_thumbnail": if utils.cint(animalid) == 0: al.error( "animal_thumbnail failed, %s is not an animalid" % str(animalid), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid animalid") else: mediadate, data = media.get_image_file_data( dbo, "animalthumb", utils.cint(animalid), seq) if data == "NOPIC": mediadate, data = media.get_image_file_data(dbo, "nopic", 0) return set_cached_response(cache_key, "image/jpeg", 86400, 86400, data) elif method == "animal_view": if utils.cint(animalid) == 0: al.error( "animal_view failed, %s is not an animalid" % str(animalid), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid animalid") else: return set_cached_response( cache_key, "text/html", 86400, 120, publishers.html.get_animal_view(dbo, utils.cint(animalid))) elif method == "animal_view_adoptable_js": return set_cached_response( cache_key, "application/javascript", 10800, 600, publishers.html.get_animal_view_adoptable_js(dbo)) elif method == "animal_view_adoptable_html": return set_cached_response( cache_key, "text/html", 86400, 120, publishers.html.get_animal_view_adoptable_html(dbo)) elif method == "dbfs_image": hotlink_protect("dbfs_image", referer) return set_cached_response( cache_key, "image/jpeg", 86400, 86400, utils.iif(title.startswith("/"), dbfs.get_string_filepath(dbo, title), dbfs.get_string(dbo, title))) elif method == "extra_image": hotlink_protect("extra_image", referer) return set_cached_response(cache_key, "image/jpeg", 86400, 86400, dbfs.get_string(dbo, title, "/reports")) elif method == "json_adoptable_animal": if utils.cint(animalid) == 0: al.error( "json_adoptable_animal failed, %s is not an animalid" % str(animalid), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid animalid") else: users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = publishers.base.get_animal_data( dbo, None, utils.cint(animalid), include_additional_fields=True) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(rs)) elif method == "html_adoptable_animals": return set_cached_response(cache_key, "text/html", 10800, 1800, \ publishers.html.get_adoptable_animals(dbo, style=post["template"], \ speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"), locationid=post.integer("locationid"))) elif method == "html_adopted_animals": return set_cached_response(cache_key, "text/html", 10800, 1800, \ publishers.html.get_adopted_animals(dbo, daysadopted=post.integer("days"), style=post["template"], \ speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"))) elif method == "html_deceased_animals": return set_cached_response(cache_key, "text/html", 10800, 1800, \ publishers.html.get_deceased_animals(dbo, daysdeceased=post.integer("days"), style=post["template"], \ speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"))) elif method == "html_held_animals": return set_cached_response(cache_key, "text/html", 10800, 1800, \ publishers.html.get_held_animals(dbo, style=post["template"], \ speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"))) elif method == "json_adoptable_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = publishers.base.get_animal_data(dbo, None, include_additional_fields=True) if strip_personal: rs = strip_personal_data(rs) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(rs)) elif method == "jsonp_adoptable_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = publishers.base.get_animal_data(dbo, None, include_additional_fields=True) if strip_personal: rs = strip_personal_data(rs) return ("application/javascript", 0, 0, "%s(%s);" % (post["callback"], utils.json(rs))) elif method == "xml_adoptable_animal": if utils.cint(animalid) == 0: al.error( "xml_adoptable_animal failed, %s is not an animalid" % str(animalid), "service.handler", dbo) return ("text/plain", 0, 0, "ERROR: Invalid animalid") else: users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = publishers.base.get_animal_data( dbo, None, utils.cint(animalid), include_additional_fields=True) return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs)) elif method == "xml_adoptable_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = publishers.base.get_animal_data(dbo, None, include_additional_fields=True) if strip_personal: rs = strip_personal_data(rs) return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs)) elif method == "json_found_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_FOUND_ANIMAL) rs = lostfound.get_foundanimal_last_days(dbo) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(rs)) elif method == "jsonp_found_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_FOUND_ANIMAL) rs = lostfound.get_foundanimal_last_days(dbo) return ("application/javascript", 0, 0, "%s(%s);" % (post["callback"], utils.json(rs))) elif method == "xml_found_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_FOUND_ANIMAL) rs = lostfound.get_foundanimal_last_days(dbo) return set_cached_response(cache_key, "application/json", 3600, 3600, html.xml(rs)) elif method == "json_lost_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_LOST_ANIMAL) rs = lostfound.get_lostanimal_last_days(dbo) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(rs)) elif method == "jsonp_lost_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_LOST_ANIMAL) rs = lostfound.get_lostanimal_last_days(dbo) return ("application/javascript", 0, 0, "%s(%s);" % (post["callback"], utils.json(rs))) elif method == "xml_lost_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_LOST_ANIMAL) rs = lostfound.get_lostanimal_last_days(dbo) return set_cached_response(cache_key, "application/json", 3600, 3600, html.xml(rs)) elif method == "json_recent_adoptions": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = movement.get_recent_adoptions(dbo) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(rs)) elif method == "jsonp_recent_adoptions": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = movement.get_recent_adoptions(dbo) return ("application/javascript", 0, 0, "%s(%s);" % (post["callback"], utils.json(rs))) elif method == "xml_recent_adoptions": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) rs = movement.get_recent_adoptions(dbo) return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs)) elif method == "html_report": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_REPORT) crid = reports.get_id(dbo, title) p = reports.get_criteria_params(dbo, crid, post) rhtml = reports.execute(dbo, crid, username, p) return set_cached_response(cache_key, "text/html", 600, 600, rhtml) elif method == "csv_mail" or method == "csv_report": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_REPORT) crid = reports.get_id(dbo, title) p = reports.get_criteria_params(dbo, crid, post) rows, cols = reports.execute_query(dbo, crid, username, p) mcsv = utils.csv(l, rows, cols, True) return set_cached_response(cache_key, "text/csv", 600, 600, mcsv) elif method == "jsonp_recent_changes": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) sa = animal.get_recent_changes(dbo) return ("application/javascript", 0, 0, "%s(%s);" % (post["callback"], utils.json(sa))) elif method == "json_recent_changes": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) sa = animal.get_recent_changes(dbo) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(sa)) elif method == "xml_recent_changes": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) sa = animal.get_recent_changes(dbo) return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(sa)) elif method == "jsonp_shelter_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) sa = animal.get_shelter_animals(dbo) if strip_personal: sa = strip_personal_data(sa) return ("application/javascript", 0, 0, "%s(%s);" % (post["callback"], utils.json(sa))) elif method == "json_shelter_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) sa = animal.get_shelter_animals(dbo) if strip_personal: sa = strip_personal_data(sa) return set_cached_response(cache_key, "application/json", 3600, 3600, utils.json(sa)) elif method == "xml_shelter_animals": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) sa = animal.get_shelter_animals(dbo) if strip_personal: sa = strip_personal_data(sa) return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(sa)) elif method == "rss_timeline": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL) return set_cached_response(cache_key, "application/rss+xml", 3600, 3600, html.timeline_rss(dbo)) elif method == "upload_animal_image": users.check_permission_map(l, user["SUPERUSER"], securitymap, users.ADD_MEDIA) media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid), post) return ("text/plain", 0, 0, "OK") elif method == "online_form_html": if formid == 0: raise utils.ASMError( "method online_form_html requires a valid formid") return set_cached_response(cache_key, "text/html; charset=utf-8", 120, 120, onlineform.get_onlineform_html(dbo, formid)) elif method == "online_form_json": if formid == 0: raise utils.ASMError( "method online_form_json requires a valid formid") return set_cached_response(cache_key, "application/json; charset=utf-8", 30, 30, onlineform.get_onlineform_json(dbo, formid)) elif method == "online_form_post": flood_protect("online_form_post", remoteip, 15) onlineform.insert_onlineformincoming_from_form(dbo, post, remoteip) redirect = post["redirect"] if redirect == "": redirect = BASE_URL + "/static/pages/form_submitted.html" return ("redirect", 0, 0, redirect) elif method == "sign_document": if formid == 0: raise utils.ASMError( "method sign_document requires a valid formid") if post["sig"] == "": return set_cached_response(cache_key, "text/html", 2, 2, sign_document_page(dbo, formid)) else: media.sign_document(dbo, "service", formid, post["sig"], post["signdate"]) media.create_log(dbo, "service", formid, "ES02", _("Document signed", l)) return ("text/plain", 0, 0, "OK") else: al.error("invalid method '%s'" % method, "service.handler", dbo) raise utils.ASMError("Invalid method '%s'" % method)
def search(search_term, limit=20): response = json(URL_SEARCH.format(apiKey=API_KEY, keyword=search_term, limit=limit)) programs = [ProgramItem(programJson) for programJson in response['programs']] return programs
def get_media_stream_by_url(quality, url): match_obj = re.search(r'.*video\/(.*)\/.*', url, re.M | re.I) video_id = match_obj.group(1) streams = json(URL_MEDIA_STREAM_BY_VIDEO_ID.format(videoId=video_id)) return _get_matching_stream_quality(quality, streams)
def top_foods(): """ Palauttaa listassa 10 suosituinta elintarviketta. """ top_foods = db.get_top_foods(10) return json(data=top_foods)
def get_media_stream_by_media_id(quality, programID, mediaType, mediaID): mediaHash = _get_media_id_hash(programID, mediaType, mediaID) streams = json(URL_MEDIA_STREAM_BY_MEDIA_ID.format(mediaHash=mediaHash)) return _get_matching_stream_quality(quality, streams)
def get_login_status(request): if request.user.is_authenticated(): return json({'status':'authenticated'}) else: return json({'status' : 'not_authenticated'})
def _get_media_info(programID, mediaType, mediaID): response = json(URL_MEDIA_INFO.format(apiKey=API_KEY, programID=programID, mediaType=mediaType, mediaID=mediaID)) return response['media']
def search_pet(request): if request.method == 'POST': form = SearchForm(request.POST) return json({'success': 'true', 'redirect_url': '/pets/pets/'}) raise Http404
def get_program_media(programID, mediaType): response = json(URL_MEDIA_LIST.format(apiKey=API_KEY, programID=programID, mediaType=mediaType)) return [MediaItem(mediaJson) for mediaJson in response['media']]
def decorator(*args, **kwargs): logging.error("\nNEW REQUEST:") if not "Authorization" in request.headers: logging.error("Authorization header missing") return json("fail", {"authorization": "authorization header is required"}) # Poimitaan Authorization-headerin parametrit: auth_header = request.headers["Authorization"] auth_params = [param.split("=") for param in auth_header.split(",")] auth_dict = {k: v[1:-1] for k, v in auth_params} # Tarkastetaan timestamp: if time.time() - float(auth_dict["timestamp"]) > TIMESTAMP_LIMIT: logging.error("Old timestamp") return json("fail", {"timestamp": "old timestamp"}) # Etsitään käyttäjä tietokannasta: user = db.get_user(urllib.unquote(auth_dict["username"])) if not user: logging.error("User not found") return json("fail", {"username": "******"}) # Etsitään asiakassovellus tietokannasta: client = db.get_client(urllib.unquote(auth_dict["client"])) if not client: logging.error("Client not found") return json("fail", {"client": "client not found"}) # Poimitaan pyynnön data: method = request.method if method in ["GET", "DELETE"]: data_src = request.args else: data_src = request.form data = {escape(k): escape(v) for k, v in data_src.iteritems()} logging.error("DATA=" + str(data)) # Kerätään parametrit allekirjoitusta varten: params = { "username": auth_dict["username"], "client": auth_dict["client"], "timestamp": auth_dict["timestamp"], } signature_params = dict(params.items() + data.items()) # Kääritään parametrit yhteen merkkijonoon: root_url = request.url.split("?")[0] if not root_url.startswith("http://"): root_url = "http://" + root_url params_str = "&".join(["%s=%s" % (key, signature_params[key]) for key in sorted(signature_params)]) base_string = "&".join([method, escape(root_url), escape(params_str)]) logging.error("BASE_STR=" + base_string) # Luodaan allekirjoitus: signing_key = client["key"] + "&" + user["key"] hashed = hmac.new(signing_key.encode("utf-8"), base_string.encode("utf-8"), sha1) signature = escape(base64.b64encode(hashed.hexdigest())) # Tarkastetaan vastaako luotu allekirjoitus pyynnön allekirjoitusta: if signature != auth_dict["signature"]: logging.error("Incorrect signature, base_string=" + base_string) return json("fail", {"signature": "incorrect signature"}) # Allekirjoitus oikein -> autorisointi onnistui: logging.error("Auth success") g.user = user return f(*args, **kwargs)