class Auth(tornado.websocket.WebSocketHandler): code = Utils.generate_uuid() qrpic_time = Utils.epoch_before_sec(0) pic_path = None @staticmethod def generate_code(): return Auth.code @staticmethod def gen_pic_name(): return str(Auth.qrpic_time) + "_" + Auth.code + ".png"
def webhook(): """ Webhook :return: code 200 when ok """ data = request.get_json() log(data) if data['object'] == 'page': for entry in data['entry']: try: for messagingEvent in entry['messaging']: senderId = messagingEvent['sender']['id'] utilities = Utils(senderId, messagingEvent) utilities.process() except Exception as err: log(err) return "ok", 200
def test_process_Question(self): self.utilities.resetValues() someTextSent = "Vrai ou faux?" MESSAGING_EVENT_EXAMPLE = { "sender": { "id": "1" }, "recipient": { "id": "1" }, "timestamp": 1589741756249, "message": { "mid": "m_tNQZfCSPWbqdyv51mNsIHJ5LlpwnCaIRAbkiYStxbpo2G8q06-WX5lQ8OanDJnrFFQb50H0KPmqlksVml-ybQw", "text": someTextSent, }, } utilities = Utils(self.SENDER_ID, MESSAGING_EVENT_EXAMPLE) response = utilities.process() self.assertEqual("text_message", response["type"]) self.assertIn(response["message"], ["Vrai", "faux"])
def del_qr_cron(): try: time_before = Utils.epoch_before_sec(-300) # 删除5分钟前生成的qr code图像 pics_path = os.path.join(os.path.dirname(__file__), "../static/qrpic") for pic in os.listdir(pics_path): if len(pic) == 49: pic_create_time = pic.split("_")[0] if str(time_before) >= pic_create_time: pic_path = os.path.join(pics_path, pic) os.remove(pic_path) print("cron job delete qr pic") except OSError: print("delete qr qr pic error")
def post(self, par): email = self.get_argument("email", None) passwd = self.get_argument("md5_pass", None) if Utils.not_empty(par) and Utils.no_special_symbol( par) and email is not None and Utils.no_special_symbol( email) and passwd is not None and Utils.no_special_symbol( passwd): exist = [] find = [] try: sql = sa.select("1").select_from( modules.login).where(modules.login.c.id == str(par)) get_return = db.run_with_return(sql) exist.extend(get_return) except IOError: print("login token find error") if not find: try: sql = sa.select([ modules.authors.c.id, modules.authors.c.author, modules.authors.c.passwd ]).select_from(modules.authors).where( modules.authors.c.email == str(email)) get_return = db.run_with_return(sql) find.extend(get_return) except IOError: print("login check error") if find and find[0][2] == passwd: uid = find[0][0] sql = modules.login.insert().values( id=par, uid=uid, login_time=Utils.time_now()) try: db.run(sql) self.finish( "200") # 这里有一个坑,render和redirect不起作用,需要js callback except IOError: print("insert login log error")
def get(self): uid = self.get_argument("uid", None) token = self.get_argument("token", None) sql = sa.select([ modules.articles.c.id, modules.articles.c.title, modules.articles.c.publish_time ]).select_from(modules.articles).order_by( modules.articles.c.publish_time.desc()) list_article = db.run_with_return(sql) articles = [] for article in list_article: loop = modules.Articles(uuid=article[0], author_id=None, title=article[1], markdown=None, html=None, publish_time=article[2], update_time=None) articles.append(loop) if uid is None or token is None or len(uid) != 32 or len(token) != 32: self.render("index.html", articles=articles) else: sql = sa.select([modules.login.c.login_time]).select_from( modules.login).where(modules.login.c.id == str(token)) login_time = db.run_with_return(sql) sql1 = sa.select([modules.authors.c.author]).select_from( modules.authors).where(modules.authors.c.id == str(uid)) author = db.run_with_return(sql1) if not login_time or not author: self.write("token or user error") elif Utils.interval_sec(login_time[0][0]) >= 10: self.write("token lose efficacy") else: author = author[0][0] login_time = login_time[0][0] print(author, login_time) author_uid = author + "." + uid self.set_secure_cookie(name="author", value=author_uid, expires_days=1) self.render("index.html", articles=articles)
def get(self): article_id = self.get_argument("article_id", None) article = None tags = "" if article_id is None: self.render("editor.html", article=article, tags=tags) elif Utils.no_special_symbol(article_id) is False or len( article_id) != 32: self.write("404") else: get_return = [] sql = sa.select("*").select_from(modules.articles).where( modules.articles.c.id == str(article_id)) try: get_return = db.run_with_return(sql) except IOError: print("get article error") if get_return: article = modules.Articles(uuid=get_return[0][0], author_id=get_return[0][1], title=get_return[0][2], markdown=get_return[0][3], html=get_return[0][4], publish_time=get_return[0][5], update_time=get_return[0][6]) tags_sql = sa.select([modules.tags.c.tag_name]).select_from( modules.tags).where( modules.tags.c.article_id == article.id) get_tags = None try: get_tags = db.run_with_return(tags_sql) except IOError: print("get tags error") if get_tags: for tag in get_tags: tags = tags + tag[0] + "," self.render("editor.html", article=article, tags=tags) else: self.write("404")
class TestUtils(unittest.TestCase): """ Tests the Utils class """ SENDER_ID = "1" someTextSent = "Hey" MESSAGING_EVENT_EXAMPLE = { "sender": { "id": "1" }, "recipient": { "id": "1" }, "timestamp": 1589741756249, "message": { "mid": "m_tNQZfCSPWbqdyv51mNsIHJ5LlpwnCaIRAbkiYStxbpo2G8q06-WX5lQ8OanDJnrFFQb50H0KPmqlksVml-ybQw", "text": someTextSent, }, } utilities = Utils(SENDER_ID, MESSAGING_EVENT_EXAMPLE) def test_process_NewsType(self): self.utilities.resetValues() self.utilities.witCategories = {"newsType"} response = self.utilities.process() self.assertEqual("text_message", response["type"]) def test_process_Question(self): self.utilities.resetValues() someTextSent = "Vrai ou faux?" MESSAGING_EVENT_EXAMPLE = { "sender": { "id": "1" }, "recipient": { "id": "1" }, "timestamp": 1589741756249, "message": { "mid": "m_tNQZfCSPWbqdyv51mNsIHJ5LlpwnCaIRAbkiYStxbpo2G8q06-WX5lQ8OanDJnrFFQb50H0KPmqlksVml-ybQw", "text": someTextSent, }, } utilities = Utils(self.SENDER_ID, MESSAGING_EVENT_EXAMPLE) response = utilities.process() self.assertEqual("text_message", response["type"]) self.assertIn(response["message"], ["Vrai", "faux"]) def test_witCategories_NewsType(self): self.utilities.resetValues() self.utilities.messageFromUser = "******" self.utilities.setWitCategories() self.assertIn("newsType", self.utilities.witCategories) def test_witCategories_Question(self): deleteFromDB(self.SENDER_ID) self.utilities.resetValues() self.utilities.messageFromUser = "******" self.utilities.setWitCategories() self.assertIn("question", self.utilities.witCategories) def test_getMessageResponse_NewsType(self): deleteFromDB(self.SENDER_ID) self.utilities.resetValues() self.utilities.witCategories = {"newsType"} response = self.utilities.getMessageResponse() self.assertEqual("generic_message", response["type"]) def test_getMessageResponse_Location(self): deleteFromDB(self.SENDER_ID) self.utilities.resetValues() self.utilities.witCategories = {"location": "Canada"} response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) self.assertEqual( "Ton endroit préféré jusqu'à maintenant était inconnue, est-ce que tu veux le changer?", response["message"], ) def test_getMessageResponse_Favorite(self): deleteFromDB(self.SENDER_ID) self.utilities.resetValues() self.utilities.witCategories = { "favorite": "chien", "favoriteType": "animal" } response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) self.assertEqual( "Ok, donc je garde chien en note pour animal préféré(e)!", response["message"], ) def test_getMessageResponse_FavoriteFollowUp(self): deleteFromDB(self.SENDER_ID) self.utilities.resetValues() setInDB( self.SENDER_ID, { "question": "favorite", "type": "animal", "response": "chien" }, ) self.utilities.witCategories = {"response": "oui"} response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) self.assertEqual( "Ok, donc je garde chien en note pour animal préféré(e)!", response["message"], ) def test_getMessageResponse_Sing(self): deleteFromDB(self.SENDER_ID) self.utilities.resetValues() self.utilities.witCategories = { "rickSong": "We're no strangers to love" } response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) self.assertEqual( putNotesEmojisAround("You know the rules and so do I"), response["message"]) def test_getMessageResponse_ChoiceQuestions(self): self.utilities.resetValues() self.utilities.witCategories = {"question": ["Quelle", "?"]} response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) self.assertIn( response["message"], [ "Je dirais exactement comme la jument blanche de Napoléon", "La 4e à ta gauche", "Hmmm. Bonne question. Si j'avais le choix, je pense que je choisirais celle qui est la même que le " "fils unique de la fille unique de ma grand-mère", "La même que la patate à Mononc' Serge", ], ) def test_getMessageResponse_ToughQuestions(self): self.utilities.resetValues() self.utilities.witCategories = {"choice": ["no", "yes"]} response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) self.assertIn(response["message"], ["no", "yes", "Trop difficile comme choix, ça!"]) def test_getMessageResponse_Games(self): self.utilities.resetValues() self.utilities.witCategories = {"game": "tic-tac-toe"} response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) setInDB(self.SENDER_ID, {"state": None, "play": False, "game": None}) def test_getMessageResponse_GamesAcceptStart(self): self.utilities.resetValues() self.utilities.witCategories = {"response": "oui"} setInDB(self.SENDER_ID, {"state": {"game": "ticTacToe"}}) response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) setInDB(self.SENDER_ID, {"state": None, "play": False, "game": None}) def test_getMessageResponse_GamesAlreadyStarted(self): self.utilities.resetValues() self.utilities.witCategories = {"game": "tic-tac-toe"} setInDB(self.SENDER_ID, {"state": {"game": "ticTacToe"}}) response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) setInDB(self.SENDER_ID, {"state": None, "play": False, "game": None}) def test_getMessageResponse_WhatCanYouDo(self): self.utilities.resetValues() self.utilities.witCategories = { "whatCanYouDo": "faire", "question": "qu'est-ce que tu peux faire?", } response = self.utilities.getMessageResponse() self.assertEqual("text_message", response["type"]) def test_setMessageFromUser(self): self.utilities.resetValues() self.assertNotEqual("Hey", self.utilities.messageFromUser) self.utilities.setMessageFromUser() self.assertEqual("Hey", self.utilities.messageFromUser) def test_getEventType(self): self.utilities.resetValues() self.assertEqual("message", self.utilities.getEventType()) def test_getResponseToSend(self): self.utilities.resetValues() response = self.utilities.getResponseToSend("message") self.assertEqual("text_message", response["type"]) self.assertIsInstance(response["message"], str)
import jwt import datetime from application import app from flask import request, jsonify from application.utils import Utils from application.service import Service, FutsalExists import application.constants.errorconstants as ERROR_CONSTANTS service = Service() utils = Utils() @app.route('/', methods=['GET']) def home(): return jsonify({'message': 'hello'}) @app.route('/getusers', methods=['GET']) def getUsers(): try: encoded = request.headers['Authorization'].split(' ')[1] utils.checkTokenExpiry(encoded) return jsonify({'users': service.getUsers()}) except jwt.ExpiredSignature: return jsonify({'message': ERROR_CONSTANTS.TOKEN_EXPIRED}), 401 @app.route('/getfutsals', methods=['GET']) def getFutsals(): try: encoded = request.headers['Authorization'].split(' ')[1]
def get(self, par): par = str(par) if par is not None and Utils.no_special_symbol(par) and len(par) == 32: self.render("check.html", code=par) else: self.redirect("http://127.0.0.1:8000/")
import json from flask import Blueprint, Response, request from application.config import Config from application.logger import Logger from application.utils import Utils logger = Logger().get_logger() oauth = Blueprint( 'oauth', __name__, url_prefix='/api/oauth', ) CONFIG = Config() UTILS = Utils() @oauth.route('/lifecheck', methods=['GET']) @oauth.route('/lifecheck/', methods=['GET', 'POST']) def lifecheck(): app_name = CONFIG.app_name logging_json = {'app_name': app_name} logger.info(logging_json) return Response(headers=CONFIG.response_headers, response=json.dumps({ 'appName': app_name, 'stage': CONFIG.stage, 'path': 'api/oauth/lifecheck', 'status': 200 }))