def emailverifyhash(hashvalue): getuserdata = User.find_one({"emailhash" : hashvalue, "emailverified" :False}, {"_id" :0}) if getuserdata is not None: User.update({"emailhash" : hashvalue} ,{"$set" :{"emailverified" :True, "updateddatetime" : datetime.now()}}) return render_template("sample.html") else: return jsonify({"status" :200 ,"message" :"Email already Verified."})
def change_password(): try: userid = int(request.json['userid']) token = request.json['token'] password = request.json['password'] userdata = User.find_one({ "userid": userid, "active": True }, {"_id": 0}) if userdata is not None: salt = userdata['salt'] if request.json['password'].strip() != "": password = hashlib.md5( request.json['password'].strip()).hexdigest() + salt User.update({"userid": userid}, {"$set": {"password": password}}) return jsonify({ "status": 200, "message": "Password Successfully changed." }) else: return jsonify({"status": 202, "message": "No user is found."}) except Exception as e: return jsonify({"status": 500, "message": e.message})
def forgotpasswordhash(hashvalue): userid = "" token = "" getuserdata = list( User.find( { "$and": [{ "forgotpasswordJSON.forgotpasswordhash": hashvalue }, { "forgotpasswordJSON.forgotpassworduseddatetime": -1 }] }, {"_id": 0})) if len(getuserdata) == 1: for userdata in getuserdata: forgotpassworduseddatetime = datetime.now() User.update( { "userid": userdata['userid'], "forgotpasswordJSON.forgotpasswordhash": hashvalue }, { "$set": { "forgotpasswordJSON.$.forgotpassworduseddatetime": forgotpassworduseddatetime } }) userid = userdata['userid'] token = userdata['token'] return render_template("front_saveonjobs/forgot_password.html", userid=userid, token=token) else: return jsonify({"status": 200, "message": "URL not found."})
def bank_update(): try: userid = int(request.json['userid']) user_details = User.find_one({"userid": userid}, {"_id": 0}) bank_details = [] if user_details: User.update({"userid": userid}, {"$set": { "paypal_id": request.json['paypal_id'] }}) bank_details = User.find_one({"userid": userid}, { "_id": 0, "paypal_id": 1 }) return make_response( jsonify({ "status": 402, "message": "User not Connected", "bank_details": bank_details }), 200) except Exception as e: return make_response( jsonify({ "status": 500, "message": "Something went wrong, Please try again!" }), 500)
def signout_mobile(): userid = request.json['userid'] session.clear() User.update({"userid": userid}, {"$set" :{"device_token": "", "version": "", "os": ""}}) return 'success'
def reportuser(): userid = int(request.json['userid']) token = request.json['token'] touserid = int(request.json['touserid']) userreportedJSON = [] if (userid != None) and (token != None) and (touserid != None): userData = User.find_one({"userid": touserid}, {"_id": 0}) if userData is not None: userreportedJSON = userreportedJSON + userData['reportedJSON'] newReportedJSON = { "reportid": CommonUtils.generateRandomNo(Report, "reportid"), "byuserid": userid, "reportresolved": False, "reporteddatetime": datetime.now(), "reportresolveddatetime": -1, "active": True } userreportedJSON.append(newReportedJSON) User.update({"userid": touserid}, {"$set": { "reportedJSON": userreportedJSON }}) return jsonify({ "status": 200, "message": "Successfully Report Created." }) else: return jsonify({"status": 400, "message": "No data Recevied"})
def verify_email(): #Check authentications keys userid = int(request.json['userid']) token = request.json['token'] email = request.json['email'] findUser = User.find_one({"userid" : userid, "token": token, "email":request.json['email'], "active":True}) if findUser is not None: emailhash = CommonUtils.getHashValue() result = User.update({ "userid" : userid, "token": token, "email":request.json['email']},{"$set":{ "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL)+"emailverify/"+str(emailhash) subject = "Your SAVEonJOBS.comAccount Email Verification" msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email]) msg.html = render_template('/emailTemplates/email_verification_template.html', name= findUser['firstname'], resetLink= reset_password_link ,email=email) mail.send(msg) EmailTracks.insert({"emailtrackid":CommonUtils.generateRandomNo(EmailTracks,"emailtrackid"),"userid":userid , "email":request.json['email'] , "subject":subject ,"emailtext":msg.html ,"createdatetime":datetime.now(),"updatedatetime":datetime.now()}) return jsonify({'status':200 , 'message' : 'Send Successfully.'}) else: return jsonify({'status':201 , 'message' : "Email doesn't match."}) #Check authentications keys userid = int(request.json['userid']) token = request.json['token'] email = request.json['email'] findUser = User.find_one({"userid" : userid, "token": token, "email":request.json['email'], "active":True}) if findUser is not None: emailhash = CommonUtils.getHashValue() result = User.update({ "userid" : userid, "token": token, "email":request.json['email']},{"$set":{ "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL)+"emailverify__"+str(emailhash) subject = "Your jobwork Account Email Verification" msg = Message(subject, sender=("Jobwork", "*****@*****.**"), recipients=[email]) msg.html = render_template('/emailTemplates/email_verification_template.html', name= findUser['firstname'], resetLink= reset_password_link ,email=email) mail.send(msg) EmailTracks.insert({"emailtrackid":CommonUtils.generateRandomNo(EmailTracks,"emailtrackid"),"userid":userid , "email":request.json['email'] , "subject":subject ,"emailtext":msg.html ,"createdatetime":datetime.now(),"updatedatetime":datetime.now()}) return jsonify({'status':200 , 'message' : 'Send Successfully.'}) else: return jsonify({'status':201 , 'message' : "Email doesn't match."})
def save_token(): userid = int(request.json['userid']) token = request.json['token'] devicetoken = request.json['devicetoken'] version = request.json['version'] os = request.json['os'] User.update( {"userid": userid}, {"$set": { "device_token": devicetoken, "version": version, "os": os }}) return jsonify({"status": 200, "message": "Successfully updated."})
def verify_mobile_otp(): userid = int(request.json['userid']) token = request.json['token'] findUser = User.find_one({ "userid": userid, "token": token, "mobile": str(request.json['mobile']), "mobileotp": int(request.json['mobileotp']), "isdcode": int(request.json['isdcode']), "mobileverified": False, "active": True }) if findUser is not None: result = User.update( { "userid": userid, "token": token, "mobile": str(request.json['mobile']) }, {"$set": { "mobileverified": True, "proJSON.mobileverified": True }}) sendText = "Your Mobile Number is registered to SAVEonJOBS." full_mobile_number = "+" + str(request.json['isdcode']) + str( request.json['mobile']) message = msgclient.messages.create(body=sendText, to=full_mobile_number, from_=Constants.MSG_SEND_FROM) print(message.sid) MessageTracks.insert({ "messagetrackid": CommonUtils.generateRandomNo(MessageTracks, "messagetrackid"), "userid": userid, "mobile": full_mobile_number, "messagetext": sendText, "messagesid": message.sid, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) userdata = list(User.find({"userid": userid}, {"_id": 0})) return jsonify({ 'status': 200, 'message': 'Verify Successfully.', "userdata": userdata }) else: return jsonify({ 'status': 201, 'message': "OTP and Mobile Number doesn't match." })
def emailverifyhash(hashvalue): getuserdata = User.find_one( { "emailhash": hashvalue, "emailverified": False }, {"_id": 0}) if getuserdata is not None: User.update({"emailhash": hashvalue}, { "$set": { "emailverified": True, "updateddatetime": datetime.now() } }) # userid = getuserdata['userid'] # token = getuserdata['token'] return render_template("front_saveonjobs/email_verify.html") else: return jsonify({"status": 200, "message": "Email already Verified."})
def user_forgotpassword_email(): try: email = request.json['email'] if email is not None: getuserdata = User.find_one({"email": email, "active": True}, {"_id": 0}) # data = user.find_one({"$or" : {"email" : email},{"mobile" : mobile}}) addforgotpasswordJSON = [] if getuserdata is not None: oldJSON = getuserdata['forgotpasswordJSON'] forgotpassworduseddatetime = -1 forgopassworddatetime = datetime.now() forgotpasswordhash = CommonUtils.getHashValue() addforgotpasswordJSON = addforgotpasswordJSON + oldJSON addforgotpasswordJSON.append({"forgopassworddatetime": forgopassworddatetime, "forgotpasswordhash": forgotpasswordhash, "forgotpassworduseddatetime": forgotpassworduseddatetime }) User.update({"email": email}, {"$set": {"forgotpasswordJSON": addforgotpasswordJSON}}) reset_password_link = str(URL) + "forgotpassword__" + str(forgotpasswordhash) subject = "Your SAVEonJOBS Password" msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email]) msg.html = render_template('/emailTemplates/Reset_password_template.html', name=getuserdata['firstname'], resetLink=reset_password_link) mail.send(msg) EmailTracks.insert( {"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": getuserdata['userid'], "email": email, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) return jsonify({"status": 200, "message": "Successfully mail sent."}) else: return jsonify({"status": 200, "message": "No data."}) else: return jsonify({"status": 200, "message": "email not found."}) except Exception as e: print(e) return jsonify({"status": 500, "message": "error"})
def reportData(): try: by_userid = request.json['userid'] to_userid = request.json['to_userid'] token = request.json['token'] reporteddatetime = datetime.now() reportresolved = False reportresolveddatetime = datetime.now() temp = [] temp.append({"by_userid": by_userid}) temp.append({"reportresolved": reportresolved}) temp.append({"reporteddatetime": reporteddatetime}) temp.append({"reportresolveddatetime": reportresolveddatetime}) User.update({"userid": to_userid}, {"$set": {"reportedJSON": temp}}) return jsonify({ "status": 200, "message": "Successfully Report Created." }) except Exception as e: return jsonify({"status": 500, "message": e.message})
def register(): try: firstname = request.json['fname'] lastname = request.json['lname'] email = request.json['email'] regtype = int(request.json['regtype']) mobile = request.json['mobile'] cityid = request.json['city'] skill = request.json['skill'] stateid = request.json['state'] countryid = request.json['country'] picurl = request.json['picurl'] gender = request.json['gender'] locationid = request.json['locationid'] if locationid != "": locationid = int(locationid) if picurl == '': picurl = "default-image.jpg" ''' if city!="": citylist=db.city.find_one({"city":city},{"_id":0,"cityid":1}) cityid=citylist['cityid'] else: cityid="" if state!="": statelist=db.state.find_one({"state":state},{"_id":0,"stateid":1}) stateid=statelist['stateid'] else: stateid="" if country!="": countrylist=db.country.find_one({"country":country},{"_id":0,"countryid":1}) countryid=countrylist['countryid'] else: countryid="" ''' addressJSON = { "address1": request.json['address1'], "address2": request.json['address2'], "city": cityid, "state": stateid, "country": countryid, "pincode": request.json['pincode'] } salt = CommonUtils.generateRandomName() emailhash = CommonUtils.getHashValue() token = CommonUtils.generateRandomName() if regtype == 0: password = request.json['password'] password = CommonUtils.password_hash(password, salt) sociallogin = False emailverified = False fbid = "" fbaccesstoken = "" registeredfrom = "jobwork" else: password = "" sociallogin = True emailverified = True fbid = request.json['fbid'] fbaccesstoken = request.json['fbaccesstoken'] if regtype == 1: registeredfrom = "facebook" elif regtype == 2: registeredfrom = "gmail" #return jsonify({"ok":1}) userdata = list(User.find({"email": email}, {"_id": 0})) if User.count({"email": email}) == 0: userid = CommonUtils.generateRandomNo(User, "userid") User.insert({ "userid": userid, "signupJSON": "", "email": email, "emailverified": emailverified, "emailhash": emailhash, "mobile": mobile, "mobileverified": False, "mobileotp": "", "isdcode": None, "fbid": fbid, "fbaccesstoken": fbaccesstoken, "password": password, "salt": salt, "token": token, "firstname": firstname, "lastname": lastname, "isadmin": False, "createddatetime": datetime.now(), "updateddatetime": datetime.now(), "addressJSON": addressJSON, "paymentdetailsJSON": [], "skillsJSON": skill, "languagesJSON": [], "educationCSV": [], "workplaceCSV": [], "certificateJSON": [], "proJSON": [], "forgotpasswordJSON": [], "gender": gender, "dob": "", "locationid": locationid, "aboutme": "", "picurl": picurl, "reportedJSON": [], "notificationJSON": [], "socaillogin": sociallogin, "facebookpicurl": "", "active": True, "paypal_id": "", "registeredfrom": registeredfrom }) if regtype != 0: response = userDataResponse(email) # user = list(User.find({"email": email}, {"_id": 0})) return jsonify({ "status": 200, "response": response, "message": "", "error": False, "registedfrom": registeredfrom }) else: emailhash = CommonUtils.getHashValue() result = User.update( { "userid": userid, "token": token, "email": request.json['email'] }, {"$set": { "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL) + "emailverify/" + str( emailhash) subject = "Your jobwork.io Account Email Verification" msg = Message(subject, sender=("JobWork", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/email_verification_template.html', name=firstname, resetLink=reset_password_link, email=email) mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid, "email": request.json['email'], "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({ "status": 200, "response": {}, "message": "verification mail sent", "error": True, "registedfrom": registeredfrom }) elif userdata[0]['emailverified'] == False: emailhash = CommonUtils.getHashValue() userid = CommonUtils.generateRandomNo(User, "userid") db.user.remove({"email": email}) User.insert({ "userid": userid, "signupJSON": "", "email": email, "emailverified": emailverified, "emailhash": emailhash, "mobile": mobile, "mobileverified": False, "mobileotp": "", "isdcode": None, "fbid": fbid, "fbaccesstoken": fbaccesstoken, "password": password, "salt": salt, "token": token, "firstname": firstname, "lastname": lastname, "isadmin": False, "createddatetime": datetime.now(), "updateddatetime": datetime.now(), "addressJSON": addressJSON, "paymentdetailsJSON": [], "skillsJSON": skill, "languagesJSON": [], "educationCSV": [], "workplaceCSV": [], "certificateJSON": [], "proJSON": [], "forgotpasswordJSON": [], "gender": gender, "dob": "", "locationid": locationid, "aboutme": "", "picurl": picurl, "reportedJSON": [], "notificationJSON": [], "socaillogin": sociallogin, "facebookpicurl": "", "active": True, "paypal_id": "", "registeredfrom": registeredfrom }) if regtype != 0: response = userDataResponse(email) return jsonify({ "status": 200, "response": response, "message": "existed now updated", "error": False, "registedfrom": registeredfrom }) else: emailhash = CommonUtils.getHashValue() result = User.update( { "userid": userid, "token": token, "email": request.json['email'] }, {"$set": { "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL) + "emailverify/" + str( emailhash) subject = "Your jobwork.io Account Email Verification" msg = Message(subject, sender=("JobWork", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/email_verification_template.html', name=firstname, resetLink=reset_password_link, email=email) mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid, "email": request.json['email'], "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({ "status": 200, "response": {}, "message": "mail id exist but not verified yet verification mail sent", "error": True, "registedfrom": registeredfrom }) elif regtype != 0: verify = False user = list(User.find({"email": email}, {"_id": 0})) if regtype == 1 and user[0]['registeredfrom'] == "facebook": verify = True elif regtype == 2 and user[0]['registeredfrom'] == "gmail": verify = True else: message = "account already registered from " + user[0][ 'registeredfrom'] return jsonify({ "status": 200, "messsage": message, "registedfrom": user[0]['registeredfrom'], "response": {}, "error": True }) #user = list(User.find({"email": email}, {"_id": 0})) if verify == True: #print(userdata[0]['cityname'][0]) response = userDataResponse(email) print((response)) return jsonify({ "status": 200, "response": response, "message": "", "error": False, "registedfrom": user[0]['registeredfrom'] }) else: return jsonify({ "status": 200, "messsage": "email id already used", "response": {}, "error": True, "registedfrom": userdata[0]['registeredfrom'] }) except Exception as e: return json.dumps(e, indent=4, default=json_util.default)
def user_forgotpassword_set(): try: email = request.json['email'] if request.json is not None: if request.json['hashData'] != "" and request.json[ 'email'] != "" and request.json['password'] != "": getuserdata = User.find_one \ ({"forgotpasswordJSON.forgotpasswordhash" : request.json['hashData'] ,"email" :request.json['email']}, {"_id" :0}) if getuserdata is not None: salt = getuserdata['salt'] if request.json['password'].strip() != "": password = hashlib.md5(request.json['password'].strip( )).hexdigest() + salt User.update( { "userid": getuserdata['userid'], "email": request.json['email'] }, {"$set": { "password": password }}) subject = "Your SAVEonJOBS password has changed" msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/password_changed.html', name=getuserdata['firstname'] + " " + getuserdata['lastname']) Mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo( EmailTracks, "emailtrackid"), "userid": getuserdata['userid'], "email": email, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({ "status": 200, "message": "Password Successfully changed." }) else: return jsonify({ "status": 402, "message": "No user is found." }) else: return jsonify({"status": 402, "message": "Data is empty."}) else: return jsonify({"status": 402, "message": "No Data."}) except Exception as e: return jsonify({"status": 500, "message": e.message})
def user_update(): try: userid = int(request.json['userid']) token = request.json['token'] location = request.json['location'] if location != "": location = int(location) find_user = User.find_one({"userid": userid, "active": True}) if find_user is not None: skills = request.json['skills'] print(skills) print(type(skills)) if request.json['dob'] != "": birth = request.json['dob'] print(birth) format = '%d-%m-%Y' dob = datetime.datetime.strptime(birth, format) else: dob = "" if request.json['city'] != "": citydetail = CityCollections.find_one( {"cityid": int(request.json['city'])}, {"_id": 0}) addressJSON = { "address1": request.json['address1'], "address2": request.json['address2'], "city": int(request.json['city']), "state": citydetail['stateid'], "country": citydetail['countryid'], "pincode": request.json['pincode'] } else: addressJSON = { "address1": request.json['address1'], "address2": request.json['address2'], "city": "", "state": "", "country": "", "pincode": request.json['pincode'] } if request.json['isdcode'] != "" and request.json[ 'isdcode'] is not None: isdcode = int(request.json['isdcode']) else: isdcode = "" # locationData = location.find_one({"cityid" : int(request.json['city'])},{"_id":0,"locationid":1}) # skillsJSON = [] # for skillDataJSON in skills: # stringData = '.*'+skillDataJSON+'.*' # skillsData = skills.find_one({"skillname" : { "$regex" : skillDataJSON, "$options" : 'i' }},{"_id":0,"skillid":1,"skillname":1}) # if skillsData is not None: # for skillsCollections in skillsData : # skillDict = {"skillid" : skillsCollections['skillid'], # "skillname" : skillsCollections['skillname']} # skillsJSON.append(skillDict) randomNameForFile = "" # if request.json['imageFlag']: # randomNameForFile = "image_"+str(int(time.time()))+".jpg" # fh = open("static/images/profile/"+randomNameForFile, "wb") # fh.write(request.json['picurl'].decode('base64')) # fh.close() # languagesJSON = request.json['languagesJSON'] # educationCSV = request.json['educationCSV'] # workplaceCSV = request.json['workplaceCSV'] # certificateJSON = request.json['certificateJSON'] # reportedJSON = list(report.find({ "userid" : userid, "token" : token }, {"_id":0})) if find_user['mobile'] != str(request.json['mobile']): User.update({"userid": userid}, { "$set": { "signupJSON.mobile": str(request.json['mobile']), "mobile": str(request.json['mobile']), "mobileverified": False, "proJSON.mobileverified": False } }) if find_user['email'] != str(request.json['email']): User.update({"userid": userid}, { "$set": { "signupJSON.email": str(request.json['email']), "email": str(request.json['email']), "emailverified": False } }) result = User.update({"userid": userid}, { "$set": { "firstname": request.json['firstname'], "lastname": request.json['lastname'], "aboutme": request.json['aboutme'], "languagesJSON": [], "educationCSV": [], "workplaceCSV": [], "updateddatetime": datetime.datetime.now(), "isdcode": isdcode, "addressJSON": addressJSON, "skillsJSON": skills, "gender": request.json['gender'], "dob": dob, "locationid": location } }) userdata_array = list( User.find({ "userid": userid, "active": True }, {"_id": 0})) resultArray = {} responseArr = [] if len(userdata_array) > 0: for collectionInfo in userdata_array: # cityname = citycollections.find_one({"cityid":collectionInfo['addressJSON']['city']},{"_id":0}) # allCityData = list(CityCollections.find({}, {"_id": 0, "cityid": 1, "city": 1})) # allcity = [] # if len(allCityData) > 0: # for getAllCityData in allCityData: # allcity.append({"cityid" : getAllCityData['cityid'], "city" : getAllCityData['city']}) location_name = "" if collectionInfo['addressJSON']['city'] != "": citynamedata = CityCollections.find_one( {"cityid": collectionInfo['addressJSON']['city']}, {"_id": 0}) city_name = citynamedata['city'] countrynamedata = CountryCollections.find_one( { "countryid": collectionInfo['addressJSON']['country'] }, {"_id": 0}) country_name = countrynamedata['country'] else: city_name = "" country_name = "" if collectionInfo['locationid'] != "": location_name_data = Locations.find_one( {"locationid": int(collectionInfo['locationid'])}, { "_id": 0, "locationname": 1, "under": 1 }) if location_name_data is not None: if location_name_data['under'] != "": location_name = str( location_name_data['under']) + " - " + str( location_name_data['locationname']) else: location_name = str( location_name_data['locationname']) else: location_name = "" skill_data = collectionInfo['skillsJSON'] skillNameData = [] if len(skill_data) > 0: for skillDataCollections in skill_data: skillNameData.append( skillDataCollections['skillname']) rating = 0 # Rating Initially 0 userReview = list( JobReviews.find( { "touserid": collectionInfo['userid'], "active": True }, { "_id": 0, "rating": 1 })) if len(userReview) > 0: totalUserReview = len(userReview) if userReview is not None: for userRating in userReview: rating = rating + userRating['rating'] tatalRating = int(rating / totalUserReview) else: tatalRating = 0 allCityData = list( CityCollections.find({}, { "_id": 0, "cityid": 1, "city": 1 })) picurlPath = Constants.PROFIL_PIC_STATIC_PATH + collectionInfo[ 'picurl'] portfolioData = list( UserPortfolio.find({ "userid": userid, "active": True, }, {"_id": 0})) documentsPath = Constants.URL + Constants.DOC_PATH portfolioDataPath = Constants.URL + Constants.PORTFOLIO_PATH updateJSON = { "cityname": city_name, "locationName": location_name, "countryname": country_name, "allcity": allCityData, "skillName": skillNameData, "portfolioData": portfolioData, "picurlPath": picurlPath, "userrating": tatalRating, "documentsPath": documentsPath, "portfolioDataPath": portfolioDataPath } collectionInfo.update(updateJSON) responseArr.append(collectionInfo) resultArray['data'] = responseArr else: resultArray['data'] = responseArr return make_response( jsonify({ 'status': 200, 'message': 'Successfull Updated', 'userid': userid, 'token': token, 'updateData': responseArr }), 200) else: return make_response( jsonify({ 'status': 402, 'message': 'No User Found.', 'userid': userid, 'token': token, 'updateData': [] }), 400) except Exception as e: CommonUtils.print_exception() return make_response(jsonify({"status": 500, "message": str(e)}), 500)
def user_update_image(): try: userid = int(request.form['userid']) token = request.form['token'] secdatetime = datetime.utcnow() - timedelta(minutes=1) createdatetimeinseconds = calendar.timegm(secdatetime.utctimetuple()) findUser = User.find_one({ "userid": userid, "token": token, "active": True }) certificateJSON = findUser['certificateJSON'] if findUser is not None: print(request.form['type']) # Profile Pic Upload if request.form['type'] == "profileimage": file = request.files['myimage'] fileNameContain = str(userid) + str( findUser['salt']) + "profile_" + str( createdatetimeinseconds) if file and allowed_file_image(file.filename): print(file.filename) filename = secure_filename(file.filename) ext = file.filename.rsplit('.', 1)[1] filename = fileNameContain + "." + ext file.save( os.path.join(jw_upload.config['UPLOAD_FOLDER_PROFILE'], filename)) User.update({ 'userid': userid, 'token': token }, {"$set": { 'picurl': filename }}) profilePic = URL + imagePath + filename message = { 'status': 200, 'message': 'Image successfully uploaded', "profilePic": profilePic } # Police Documents Upload if request.form['type'] == "police": file = request.files['myimage'] fileNameContain = str(userid) + str( findUser['salt']) + "police_" + str( createdatetimeinseconds) if file and (allowed_file_image(file.filename) or allowed_file_doc_pdf(file.filename)): filename = secure_filename(file.filename) ext = file.filename.rsplit('.', 1)[1] filename = fileNameContain + "." + ext file.save( os.path.join(jw_upload.config['UPLOAD_FOLDER_DOC'], filename)) proDocuments = URL + Constants.DOC_PATH + filename certificateJSONDATA = { "type": ext, "certificateid": CommonUtils.generateRandomNo(Certificate, "certificateid"), "certificateimageurl": filename, "certificatestatus": "pending", "certificatecaption": request.form['certificatecaption'], "ispoliceverification": True } certificateJSON.append(certificateJSONDATA) User.update({ 'userid': userid, 'token': token }, {"$set": { 'certificateJSON': certificateJSON }}) message = { 'status': 200, 'message': 'Image successfully uploaded', "certificateJSON": certificateJSON } # Pro Documents Uploads if request.form['type'] == "certificateimage": file = request.files['myimage'] fileNameContain = str(userid) + str( findUser['salt']) + "pro_docs_" + str( createdatetimeinseconds) if file and (allowed_file_image(file.filename) or allowed_file_doc_pdf(file.filename)): filename = secure_filename(file.filename) ext = file.filename.rsplit('.', 1)[1] filename = fileNameContain + "." + ext file.save( os.path.join(jw_upload.config['UPLOAD_FOLDER_DOC'], filename)) proDocuments = URL + Constants.DOC_PATH certificateJSONDATA = { "type": ext, "certificateid": CommonUtils.generateRandomNo(Certificate, "certificateid"), "certificateimageurl": filename, "certificatestatus": "pending", "certificatecaption": request.form['certificatecaption'], "ispoliceverification": False } certificateJSON.append(certificateJSONDATA) User.update({ 'userid': userid, 'token': token }, {"$set": { 'certificateJSON': certificateJSON }}) message = { 'status': 200, 'message': 'Image successfully uploaded', "certificateJSON": certificateJSON } # Portfolio Images Uploads if request.form['type'] == "portfolioimage": file = request.files['myimage'] fileNameContain = str(userid) + str( findUser['salt']) + "portfolio_" + str( createdatetimeinseconds) if file and allowed_file_image(file.filename): filename = secure_filename(file.filename) ext = file.filename.rsplit('.', 1)[1] filename = fileNameContain + "." + ext file.save( os.path.join( jw_upload.config['UPLOAD_FOLDER_PORTFOLIO'], filename)) portfolioDataPath = URL + Constants.PORTFOLIO_PATH UserPortfolio.insert({ "portfolioid": CommonUtils.generateRandomNo(UserPortfolio, "portfolioid"), "portfolioimage": filename, "userid": userid, "active": True, "createddatetime": datetime.now(), "updatedatetime": datetime.now() }) portfolioData = list( UserPortfolio.find({ "userid": userid, "active": True, }, {"_id": 0})) message = { 'status': 200, 'message': 'Image successfully uploaded', "portfolioData": portfolioData, "portfolioDataPath": portfolioDataPath } User.update({ "userid": userid, "token": token, "active": True }, {"$set": { "updateddatetime": datetime.now() }}) return jsonify(message) else: return jsonify({"status": 402, "message": "No User found."}) except Exception as e: return jsonify({"status": 500, "message": e.message})