def changeStatus(id_report,status): if status not in [1,2,3,4]: return make_response(jsonify( { 'error': 'Unknown status' } ), 400) rm = ReportModel() um = UserModel() # get the current report report_prev = rm.getReport(id_report) #get user of report user = um.getUser(idUser=report_prev["id_user"]) # get the previous report again with the current language report_prev = rm.getReport(id_report,user["language"]) # change the status rm.changeStatus(id_report,status) report = rm.getReport(id_report,user["language"]) #send the email body = tr("Report status changed email",user["language"]) body = body % ( report_prev["status_str"].decode("utf-8"), report["status_str"].decode("utf-8"),app.config["cdnUrl"] + "#?c=Report/detail/"+str(id_report)) utils.sendEmail([report["user_email"]],tr("Report status change subject",user["language"]), body) if report_prev["id_report_status"] == 1 and (status==2 or status==4): # send email to manager mpa mm = MPASModel() for lang in app.config["languages"]: emails = map(lambda x: x["email"],mm.getMPAManagersEmailLanguage(report["id_mpa"] ,lang)) if len(emails)>0: body = tr("New report added MPA",lang) body = body % ( report["mpa"], app.config["cdnUrl"] + "#?c=Report/detail/"+str(id_report)) utils.sendEmail(emails,tr("New report added in %s [MPA]",lang) % report["mpa"], body) return jsonify( {"result" : "done" })
def get_user(id_user): #check lang parameter exist if "language" not in request.args: return make_response(jsonify( { "error": "Mandatory language param missing" } ), 400) language = request.args['language'] # check if it's a valid order if language not in app.config["languages"]: return make_response(jsonify( { 'error': 'Unknown language value' } ), 400) um = UserModel() u = um.getUser(idUser=id_user,lang=language) return jsonify( { "id" : u["id"], "name": u["name"], "surname": u["surname"], "email" : u["email"], "username": u["username"], "profile": u["profile"], "country": u["country"], "id_country": u["id_country"], "sex": u["sex"], "city": u["city"], "biography": base.utils.htmlspecialchars(u["biography"]), "gravatar": utils.getGravatar(u["email"]), } )
def post(self): data = UserResource.parser.parse_args() if (UserModel.find_by_username(data['username'])): return {"message": "usuário já existe"}, 400 user = UserModel(**data) user.save_to_db() return {"message": "User created successfully."}, 201
def check_username(username): um = UserModel() nUsers = um.nUsersWithUsername(username) if nUsers==0: return jsonify({"available": True}) else: # return user json return jsonify({"available": False})
def check_email(email): um = UserModel() nUsers = um.nUsersWithEmail(email) if nUsers==0: return jsonify({"available": True}) else: # return user json return jsonify({"available": False})
class UserService(BaseService): def __init__(self, db, cursor): self.userModel = UserModel(db, cursor) def findUser(self, phone, passwd): return self.userModel.findOneByPhoneAndPasswd(phone, passwd) def findUserByOpenid(self, openid): return self.userModel.findUserByOpenid(openid) def findUserByUserid(self, openid): return self.userModel.findUserByUserid(openid) def insertUserWxInfo(self, userInfo): return self.userModel.insertUserWxInfo(userInfo)
def on_message(self, message): print(self.namespace, str(message)) if message['data'] == 'backgroud': self.__sio.start_background_task(target=self.__background_thread) emit('reply', {'data': 'backgroud function will be trigger an event'}) # 当前所在房间号 # print(self.rooms(sid)) # 当前namespace # print(self.namespace) else: if self.namespace == u'/buyGrab': try: import json requsetData = json.loads(message['data']) except: pass else: neededArgs = { 'uid': None, 'auid': None, 'grabid': None, 'num': None, 'sp': None, } for key, val in neededArgs.items(): val = requsetData.get(key) if val is None: emit( 'reply', { 'code': 400, 'message': 'Lack Of Param Or Invalid[%s]' % (key), 'data': {} }) return neededArgs[key] = val from model.UserModel import UserModel import random dbModel = UserModel() data = dbModel.User(random.choice(range(1, 90000))) message['data'] = data session['receive_count'] = session.get('receive_count', 0) + 1 emit('reply', { 'data': message['data'], 'count': session['receive_count'] })
def confirm_email(): # check params if "email" not in request.form or "secret" not in request.form: return make_response(jsonify( { "error": "Mandatory param missing" } ), 400) email = request.form["email"] secret = request.form["secret"] encrypt = hashlib.md5(utils.encrypt(email.encode("UTF-8"))).hexdigest() if secret == encrypt: um = UserModel() user = um.getUser(email) um.editUser({"status" : base.USER_ST_ACTIVE},user["id"]) return jsonify({"confirmed": True}) else: return jsonify({"confirmed": False})
def change_password(): # check params if "password" not in request.form or "current_password" not in request.form : return make_response(jsonify( { "error": "Mandatory param missing" } ), 400) password = hashlib.md5(request.form["password"]).hexdigest() current_password = hashlib.md5(request.form["current_password"]).hexdigest() um = UserModel() user = um.getUserLogin(session["email"]) if user["passwd"] == current_password: um.editUser({"passwd" : password },user["id"]) return jsonify({"done": True}) else: # this sleep is done to simulate a sending to mislead hackers time.sleep(1) return jsonify({"done": False})
def deleteReport(id_report): rm = ReportModel() um = UserModel() images = rm.getReportImages(id_report) r = rm.getReport(id_report, "en") #get user of report user = um.getUser(idUser=r["id_user"]) # get the report again with the user language r = rm.getReport(id_report,user["language"]) # remove thumbnail try: fdest = os.path.join(app.config["cdnReportImagePath"], str(id_report) +"_120_120"+ r["thumb_ext"]) if os.path.isfile(fdest): os.unlink(fdest) except Exception, e: pass
def reset_password(): # check params if "email" not in request.form or "secret" not in request.form or "password" not in request.form: return make_response(jsonify( { "error": "Mandatory param missing" } ), 400) email = request.form["email"] secret = request.form["secret"] encrypt = hashlib.md5(utils.encrypt(email.encode("UTF-8"))).hexdigest() if secret == encrypt: um = UserModel() user = um.getUser(email=email) if user: um.editUser({"passwd" : hashlib.md5(request.form["password"]).hexdigest() },user["id"]) else: # this sleep is done to simulate a sending to mislead hackers time.sleep(1) # done is returned always to lose hackers return jsonify({"done": True})
def remember_password(): # check params if "email" not in request.form or "id_country" not in request.form: return make_response(jsonify( { "error": "Mandatory param missing" } ), 400) email = request.form["email"] id_country = request.form["id_country"] um = UserModel() u = um.getUser(email=email) if u and u["id_country"] == id_country: encrypt = hashlib.md5(utils.encrypt(u["email"].encode("UTF-8"))).hexdigest() body = tr("Reset password email",u["language"]) % (app.config["cdnUrl"] + "/#?c=User/resetPassword/" + u["email"] + "/" + encrypt) utils.sendEmail([u["email"]],tr("MedMIS - Reset password",u["language"]),body) else: # this sleep is done to simulate a sending to mislead hackers time.sleep(3) # done is returned always to confuse hackers return jsonify({"done": True})
def edit_user(id_user): u = {}; u["username"] = request.form["username"] u["email"] = request.form["email"] u["name"] = request.form["name"] u["surname"] = request.form["surname"] u["sex"] = request.form["sex"] u["city"] = request.form["city"] u["id_country"] = request.form["id_country"] u["biography"] = request.form["biography"] u["language"] = request.form["language"] u["phone"] = request.form["phone"] u["institution"] = request.form["institution"] um = UserModel() um.editUser(u,id_user) resp = make_response(jsonify(u), 200) resp.set_cookie('language', u["language"]) return resp
def on_message(self, sid, message): print(self.namespace) if self.namespace == u'/buyGrab': try: requsetData = json.loads(message['data']) except: pass else: neededArgs = { 'uid': None, 'auid': None, 'grabid': None, 'num': None, 'sp': None, } for key, val in neededArgs.items(): val = requsetData.get(key) if val is None: self.emit('reply', {'code':400, 'message': 'Lack Of Param Or Invalid[%s]' % (key), 'data':{}}) return neededArgs[key] = val from model.UserModel import UserModel dbmodel = UserModel(app) data = dbmodel.buy_grab(neededArgs) print(data) else: print('message ', message) if message['data'] == 'backgroud': sio.start_background_task(self.__background_thread) self.emit('reply', {'data': 'backgroud function will be trigger an event'}) # 当前所在房间号 # print(self.rooms(sid)) # 当前namespace # print(self.namespace) else: self.emit('reply', {'data': message['data']}, room = sid)
def get(self): data = PostModel.objects.aggregate(*[ { '$lookup':{ 'from': UserModel._get_collection_name(), 'localField':'author', 'foreignField':'_id', 'as':'User' } } ]) # for i in data: # print(i) schema = PostSchema(many=True) # s = schema.dump(data).data # print(list(data._CommandCursor__data)) # return {} # return loads(dumps(data)) '''Embedded document test''' # c1 = CommentsModel(content="123") # c2 = CommentsModel(content="213") # for i in PostModel.objects(): # i.comments = [c1, c2] # i.save() return schema.dump(data).data '''Dynamic document, dict field, list field test ''' # Page(t="1230", dd={'1':1,'2':2}).save() # for p in Page.objects: # p.abc = [{"anc":'jshjkasd', "jsdbasjkd":122312153}, {"anc":'jshjkasd', "jsdbasjkd":122312153}] # = datetime.datetime.now() # print(p.d) # p.save() # return loads(Page.objects.to_json())
def hello(): from model.UserModel import UserModel dbmodel = UserModel(app) data = dbmodel.user_list() return jsonify({'code': 200, 'message': '', 'data': data})
def authenticate(username, password): user = UserModel.find_by_username(username) if user and user.password == password: return user
def __init__(self, db, cursor): self.userModel = UserModel(db, cursor)
def upload(): contributor = request.form.get('contributor', False) print request.form r = {} r["id_species"] = request.form["id_species"] r["y"] = request.form["lat"] r["x"] = request.form["lng"] r["lower_depth"] = request.form.get("lower_depth", None) if r['lower_depth'] == '': r['lower_depth'] = None r["upper_depth"] = request.form.get("upper_depth", None) if r['upper_depth'] == '': r['upper_depth'] = None r["id_mpa"] = request.form.get("id_mpa", None) if r['id_mpa'] == '0': r['id_mpa'] = None date = request.form["date"] r["date"] = datetime.strptime(date + " 00:00:00","%d/%m/%Y %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S") comment = request.form.get("comment", '') r['author'] = request.form.get('author', None) if contributor: r["id_report_status"] = 4 # Auto-publish else: r["id_report_status"] = 1 r["id_user"] = session['id_user'] city = request.form.get("city",None) r["city"] = None if city=="" else city abundance = request.form.get("abundance",None) r["abundance"] = None if abundance=="" else abundance habitats = request.form.getlist("habitats",None) r["date_creation"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S"); images = request.form.getlist("images") print images if images: filename, fileExtension = os.path.splitext(images[0]) r["thumb_ext"] = fileExtension rm = ReportModel() id_report = rm.insertReport(r) if comment != "": c = { "comment" :comment, "date": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), "id_report": id_report, "id_user" : session["id_user"] } ReportModel().newComment(c) if images: fdest = os.path.join(app.config["cdnReportImagePath"], str(id_report) +"_120_120"+ fileExtension) fsrc = os.path.join(app.config["tmpFolder"], images[0]) cmd = "%s %s -auto-orient -thumbnail %dx%d^ -gravity center -extent %dx%d %s" % (app.config["convertBin"],fsrc,120,120,120,120,fdest) os.system(cmd) for img in images: filename, fileExtension = os.path.splitext(img) imgdb = { "id_report": id_report, "ext": fileExtension }; id_image = rm.insertImage(imgdb) # target image on jpg fdest = os.path.join(app.config["cdnReportImagePath"], str(id_image) +"_2400_2400.jpg") fsrc = os.path.join(app.config["tmpFolder"], img) cmd = "%s %s -quality 60 -resize %dx%d\> %s" % (app.config["convertBin"],fsrc,2400,2400,fdest) os.system(cmd) fdest = os.path.join(app.config["cdnReportImagePath"], str(id_image) +"_original"+ fileExtension) cmd = "mv %s %s" % (fsrc,fdest) os.system(cmd) ##add habitat types rh = [] for i in habitats: rh.append({ "id_habitat_type" : i, "id_report" : id_report }); ReportModel().insertReportHabitats(rh) #send mail to admin um = UserModel() if not contributor: for lang in app.config["languages"]: emails = map(lambda x: x["email"],um.getAdminEmailLanguage(lang)) if len(emails)>0: body = tr("New report added email",lang) body = body % (app.config["cdnUrl"] + "?c=User/loginRequest/Report??detail??"+str(id_report)) subject = tr("New MedMIS report submitted",lang) utils.sendEmail(emails,subject, body) return jsonify( {"id_report" : id_report })
def __init__(self, request=None): self.db = DatabaseService() self.transaction_service = DatabaseStatement() self.tk = TokenService() dto = DTO_Parser(request).get_DTO() action = dto.action if (action == 'login'): model = UserModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'logout'): model = UserModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'product_history'): model = ProductModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'transaction'): model = ProductModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'products'): model = ProductModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'product_by_id'): model = ProductModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'registration'): model = UserModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'user_information'): model = UserModel(self.transaction_service, self.db, dto, self.tk) elif (action == 'user'): model = UserModel(self.transaction_service, self.db, dto, self.tk) else: self.response = "ERROR_BAD_REQUEST" dto = model.get_response() self.response = dto.get_response() return
def upload(): validation = { "id_species" : [ ['is_required', { 'required': tr("###Species is required","en") }], ['is_integer'], ], "lat": [['is_required'],['is_number']], "lng": [['is_required'],['is_number']], "lower_depth": [['is_required'],['is_number']], "upper_depth": [['is_required'],['is_number']], "id_mpa": [['is_required'],['has_length',5,10]], "date": [['is_required'],['is_date',"%d/%m/%Y"]], "comment" : [['has_length',0,1000]], "city" : [['has_length',3,255]] } messages = base.utils.form_validation(request.form,validation) # If can haz messages, throw a big exception if len(messages): return make_response(jsonify( { "error": messages } ), 400) # let's read habitat types habitats = request.form.getlist("habitats",None) images = request.form.getlist("images") if not images or len(images)==0: return make_response(jsonify( { "error": tr("###There is no image") } ), 400) u = UserModel().getUser(email=auth.username) r = {} r["id_species"] = request.form["id_species"] r["y"] = request.form["lat"] r["x"] = request.form["lng"] r["lower_depth"] = request.form["lower_depth"] r["upper_depth"] = request.form["upper_depth"] r["id_mpa"] = request.form["id_mpa"] date = request.form["date"] r["date"] = datetime.strptime(date + " 00:00:00","%d/%m/%Y %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S") comment = request.form.get("comment",None) r["id_report_status"] = 1; r["id_user"] = u["id"] city = request.form.get("city",None) r["city"] = None if city=="" else city abundance = request.form.get("abundance",None) r["abundance"] = None if abundance=="" else abundance r["thumb_ext"] = ".jpg" r["date_creation"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S"); rm = ReportModel() id_report = rm.insertReport(r) if comment and comment != "": c = { "comment" :comment, "date": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), "id_report": id_report, "id_user" : u["id"] } ReportModel().newComment(c) createThumbnail = True for img in images: imgdb = { "id_report": id_report, "ext": ".jpg" } id_image = rm.insertImage(imgdb) imgbuffer = base64.b64decode(img) fsrc = os.path.join(app.config["cdnReportImagePath"], str(id_image) +"_original.jpg") wfile = open(fsrc, "w") wfile.write(imgbuffer) wfile.close() # create thumbnail if createThumbnail: createThumbnail = False fdest = os.path.join(app.config["cdnReportImagePath"], str(id_report) +"_120_120.jpg") cmd = "%s %s -auto-orient -thumbnail %dx%d^ -gravity center -extent %dx%d %s" % (app.config["convertBin"],fsrc,120,120,120,120,fdest) os.system(cmd) fdest = os.path.join(app.config["cdnReportImagePath"], str(id_image) +"_2400_2400.jpg") cmd = "cp %s %s " % (fsrc,fdest) os.system(cmd) ##add habitat types rh = [] for i in habitats: rh.append({ "id_habitat_type" : i, "id_report" : id_report }); ReportModel().insertReportHabitats(rh) #send mail to admin um = UserModel() for lang in app.config["languages"]: emails = map(lambda x: x["email"],um.getAdminEmailLanguage(lang)) if len(emails)>0: body = tr("New report added email",lang) body = body % (app.config["cdnUrl"] + "#?c=User/loginRequest/Report??detail??"+str(id_report)) utils.sendEmail(emails,tr("New MedMIS report submitted",lang), body) return jsonify( {"id_report" : id_report})