def test_create_check_password_hash(self): self.assertRaises(TypeError, security.generate_password_hash, 'foo', 'bar') password = '******' hashval = security.generate_password_hash(password, 'sha1') self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, 'sha1', pepper='bar') self.assertTrue(security.check_password_hash(password, hashval, pepper='bar')) hashval = security.generate_password_hash(password, 'md5') self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, 'plain') self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, 'plain') self.assertFalse(security.check_password_hash(password, '')) hashval1 = security.hash_password(unicode(password), 'sha1', u'bar') hashval2 = security.hash_password(unicode(password), 'sha1', u'bar') self.assertTrue(hashval1 is not None) self.assertEqual(hashval1, hashval2) hashval1 = security.hash_password(unicode(password), 'md5', None) hashval2 = security.hash_password(unicode(password), 'md5', None) self.assertTrue(hashval1 is not None) self.assertEqual(hashval1, hashval2)
def test_create_check_password_hash(self): self.assertRaises(TypeError, security.generate_password_hash, 'foo', 'bar') password = '******' hashval = security.generate_password_hash(password, 'sha1') self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, 'sha1', pepper='bar') self.assertTrue( security.check_password_hash(password, hashval, pepper='bar')) hashval = security.generate_password_hash(password, 'md5') self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, 'plain') self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, 'plain') self.assertFalse(security.check_password_hash(password, '')) hashval1 = security.hash_password(unicode(password), 'sha1', u'bar') hashval2 = security.hash_password(unicode(password), 'sha1', u'bar') self.assertTrue(hashval1 is not None) self.assertEqual(hashval1, hashval2) hashval1 = security.hash_password(unicode(password), 'md5', None) hashval2 = security.hash_password(unicode(password), 'md5', None) self.assertTrue(hashval1 is not None) self.assertEqual(hashval1, hashval2)
def test_create_check_password_hash(self): self.assertRaises(TypeError, security.generate_password_hash, "foo", "bar") password = "******" hashval = security.generate_password_hash(password, "sha1") self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, "sha1", pepper="bar") self.assertTrue( security.check_password_hash(password, hashval, pepper="bar")) hashval = security.generate_password_hash(password, "md5") self.assertTrue(security.check_password_hash(password, hashval)) hashval = security.generate_password_hash(password, "plain") v = security.check_password_hash(password, hashval) self.assertTrue(v) hashval = security.generate_password_hash(password, "plain") self.assertFalse(security.check_password_hash(password, "")) hashval1 = security.hash_password(str(password), "sha1", "bar") hashval2 = security.hash_password(str(password), "sha1", "bar") self.assertTrue(hashval1 is not None) self.assertEqual(hashval1, hashval2) hashval1 = security.hash_password(str(password), "md5", None) hashval2 = security.hash_password(str(password), "md5", None) self.assertTrue(hashval1 is not None) self.assertEqual(hashval1, hashval2)
def badPassword(uph, praw): #logging.debug('uph = %s praw = %s', uph, praw) if uph.count('$') != 2: logging.warning('Checking creds - hashStr: "%s" has an invalid format.', uph) else: hash, method, salt = uph.split('$', 2) ph = security.hash_password ( praw , method , salt , pepper=None) #logging.debug('hash = %s', hash) #logging.debug(' ph = %s', ph) if sameStr (ph, hash): return False return True #recursive version of dict.update # import collections # def update(d, u): # for k, v in u.iteritems(): # if isinstance(v, collections.Mapping): # d[k] = update(d.get(k, {}), v) # elif isinstance(v, list) # append ? # else: # d[k] = u[k] # return d
def get(self, ngo_url): ngo = NgoEntity.get_by_id(ngo_url) if not ngo: self.abort(404) # if we have an form created for this ngo, return the url # if ngo.form_url: # self.redirect( str(ngo.form_url), abort=True ) # else, create a new one and upload to GCS for future use ngo_dict = { "name": ngo.name, "cif": ngo.cif, "account": ngo.account, "special_status": ngo.special_status } pdf = create_pdf({}, ngo_dict) # filename = "Formular 2% - {0}.pdf".format(ngo.name) filename = "Formular_donatie.pdf".format(ngo.name) ong_folder = security.hash_password(ngo.key.id(), "md5") path = "{0}/{1}/{2}".format(USER_UPLOADS_FOLDER, str(ong_folder), filename) file_url = CloudStorage.save_file(pdf, path) # close the file after it has been uploaded pdf.close() ngo.form_url = file_url ngo.put() self.redirect(str(ngo.form_url))
def create(cls, email, password): conflicts = User.fetchUser(email) if conflicts: return False newUser = User() newUser.email = email newUser.passwordSalt = security.generate_random_string(entropy=64) newUser.hashedPassword = security.hash_password(password, 'sha1', newUser.passwordSalt, passwordPepper) newUser.creationDate = datetime.datetime.now() return newUser.put()
def http_post(self, properties): email = properties.post["loginEmail"] password = password = security.hash_password(properties.post["loginPassword"], "sha1") logging.warning(password) user = db.GqlQuery("SELECT __key__ FROM User " + "WHERE email = :1 AND password = :2", email, password).get() if not user: return '{ "success": false, "error": "Invalid email or password." }' properties.session["user"] = user.id() return '{ "success": true, "target": "/" }'
def login(self): email = self.request.get('email') senha = hash_password(self.request.get('senha'), 'sha1') usuario = Usuario.query().filter(Usuario.email == email)\ .filter(Usuario.senha == senha).get() if usuario: self.usuario = usuario self.redirect(url['entrou']) else: self.redirecionar('/', [u'Login ou senha incorretos.'])
def post(self): post = self.request # we must use post.POST so we get the file files = post.POST.getall("files") if len(files) == 0: self.abort(400) file_urls = [] for a_file in files: # jump over files that are not images # https://docs.python.org/2/library/imghdr.html # if imghdr.what("", h=a_file.file.read()) is None if not a_file.type or a_file.type.split("/")[0] != "image": continue info(a_file.type) # if the image is uploaded by the admin # we don't have an user if self.user: folder = str(self.user.key.id()) else: folder = "admin" # the user's folder name, it's just his md5 hashed db id user_folder = security.hash_password(folder, "md5") # a way to create unique file names # get the local time in iso format # run that through SHA1 hash # output a hex string filename = "{0}/{1}/{2}".format(USER_UPLOADS_FOLDER, str(user_folder), sha1( datetime.now().isoformat() ).hexdigest()) file_url = CloudStorage.save_file(a_file, filename) if file_url: file_urls.append( file_url ) self.return_json({ "file_urls": file_urls })
def __basic_hash(password): return security.hash_password(password, method='sha1')
def post(self, ngo_url): post = self.request errors = { "fields": [], "server": False } self.ngo = NgoEntity.get_by_id(ngo_url) if self.ngo is None: self.error(404) return # if we have an ajax request, just return an answer self.is_ajax = self.request.get("ajax", False) def get_post_value(arg, add_to_error_list=True): value = post.get(arg) # if we received a value if value: # it should only contains alpha numeric, spaces and dash if re.match(r'^[\w\s.\-ăîâșț]+$', value, flags=re.I | re.UNICODE) is not None: # additional validation if arg == "cnp" and len(value) != 13: errors["fields"].append(arg) return "" return value # the email has the @ so the first regex will fail elif arg == 'email': # if we found a match if re.match(r'[^@]+@[^@]+\.[^@]+', value) is not None: return value errors["fields"].append(arg) return '' else: errors["fields"].append(arg) elif add_to_error_list: errors["fields"].append(arg) return "" donor_dict = {} # the donor's data donor_dict["first_name"] = get_post_value("nume").title() donor_dict["last_name"] = get_post_value("prenume").title() donor_dict["father"] = get_post_value("tatal").title() donor_dict["cnp"] = get_post_value("cnp", False) donor_dict["email"] = get_post_value("email").lower() donor_dict["tel"] = get_post_value("tel", False) donor_dict["street"] = get_post_value("strada").title() donor_dict["number"] = get_post_value("numar", False) # optional data donor_dict["bl"] = get_post_value("bloc", False) donor_dict["sc"] = get_post_value("scara", False) donor_dict["et"] = get_post_value("etaj", False) donor_dict["ap"] = get_post_value("ap", False) donor_dict["city"] = get_post_value("localitate").title() donor_dict["county"] = get_post_value("judet") # if he would like the ngo to see the donation donor_dict['anonymous'] = post.get('anonim') != 'on' # the ngo data ngo_data = { "name": self.ngo.name, "account": self.ngo.account.upper(), "cif": self.ngo.cif, "special_status": self.ngo.special_status } if len(errors["fields"]): self.return_error(errors) return captcha_response = submit(post.get(CAPTCHA_POST_PARAM), CAPTCHA_PRIVATE_KEY, self.request.remote_addr) # if the captcha is not valid return if not captcha_response.is_valid: errors["fields"].append("codul captcha") self.return_error(errors) return # the user's folder name, it's just his md5 hashed db id user_folder = security.hash_password('123', "md5") # a way to create unique file names # get the local time in iso format # run that through SHA1 hash # output a hex string filename = "{0}/{1}/{2}".format(USER_FORMS, str(user_folder), sha1( datetime.datetime.now().isoformat() ).hexdigest()) pdf = create_pdf(donor_dict, ngo_data) file_url = CloudStorage.save_file(pdf, filename) # close the file after it has been uploaded pdf.close() # create the donor and save it donor = Donor( first_name = donor_dict["first_name"], last_name = donor_dict["last_name"], city = donor_dict["city"], county = donor_dict["county"], email = donor_dict['email'], tel = donor_dict['tel'], anonymous = donor_dict['anonymous'], # make a request to get geo ip data for this user geoip = self.get_geoip_data(), ngo = self.ngo.key, pdf_url = file_url ) donor.put() # set the donor id in cookie self.session["donor_id"] = str(donor.key.id()) self.session["has_cnp"] = bool(donor_dict["cnp"]) # send and email to the donor with a link to the PDF file self.send_email("twopercent-form", donor) # if not an ajax request, redirect if self.is_ajax: self.response.set_status(200) response = { "url": self.uri_for("ngo-twopercent-success", ngo_url=ngo_url), "form_url": file_url } self.response.write(json.dumps(response)) else: self.redirect( self.uri_for("ngo-twopercent-success", ngo_url=ngo_url) )
def verify(self, password): hashedPassword = security.hash_password(password, 'sha1', self.passwordSalt, passwordPepper) return security.compare_hashes(hashedPassword, self.hashedPassword)
def http_post(self, properties, page): if page == "1": email = properties.post["registerEmail"] user = User(email=email) user.put() properties.session["user"] = user.key().id() return '{ "success": true, "target": "/register/2" }' elif page == "2": user = User.get_by_id(properties.session.get("user")) if user.email != properties.post["email"]: return '{ "success": false, "error": "Email address entered incorrectly" }' if len(properties.post["password"]) < 4: return '{ "success": false, "error": "Password must be at least 4 characters" }' user.password = security.hash_password(properties.post["password"], "sha1") user.firstName = properties.post["firstName"] user.lastName = properties.post["lastName"] user.address1 = properties.post["address1"] user.address2 = properties.post["address2"] user.zip = properties.post["zip"] user.state = properties.post["state"] user.put() return '{ "success": true, "target": "/register/3" }' elif page == "3": user = User.get_by_id(properties.session.get("user")) try: if properties.post["years"] != "": user.years = int(properties.post["years"]) except ValueError: return '{ "success"; false, "error": "Years must be valid number" }' user.has_served = "not_military" not in properties.post user.honorable_discharge = ( "honorable_discharge" in properties.post and properties.post["honorable_discharge"] == "yes" ) user.branch = properties.post["service_name"] user.duty_status = properties.post["duty_status"] user.occupations = properties.post["occupations"] user.deployments = properties.post["deployments"] user.highest_rank = properties.post["highest_rank"] user.put() return '{ "success": true, "target": "/register/4" }' elif page == "4": user = User.get_by_id(properties.session.get("user")) try: if properties.post["occupation1_time"] != "": user.occupation1Time = int(properties.post["occupation1_time"]) if properties.post["occupation2_time"] != "": user.occupation2Time = int(properties.post["occupation2_time"]) if properties.post["occupation3_time"] != "": user.occupation3Time = int(properties.post["occupation3_time"]) if properties.post["occupation4_time"] != "": user.occupation4Time = int(properties.post["occupation4_time"]) except ValueError: return '{ "success"; false, "error": "Years must be valid number" }' user.education = properties.post["education"] user.certifications = properties.post["certifications"] user.occupation1 = properties.post["occupation1"] user.occupation2 = properties.post["occupation2"] user.occupation3 = properties.post["occupation3"] user.occupation4 = properties.post["occupation4"] user.put() return '{ "success": true, "target": "/register/5" }' elif page == "5": return '{ "success": true, "target": "/" }'