def test_jumio_submit_with_error(self, mock_boto_utils): test_verification_id = "9f2c90119cb7424b8d69319ce211ddfc" verification_type = "JUMIO" username = "******" current_time = datetime.utcnow() verification_repository.add_item( VerificationModel(id=test_verification_id, verification_type=verification_type, entity_id=username, status="PENDING", requestee=username, created_at=current_time, updated_at=current_time)) jumio_repository.add_item( JumioVerificationModel( verification_id=test_verification_id, username=username, jumio_reference_id="123-13-13-134-1234", user_reference_id=sha1(username.encode("utf-8")).hexdigest(), redirect_url= "https://yourcompany.netverify.com/web/v4/app?locale=en-GB&authorizationToken=xxx", transaction_status="PENDING", verification_status="PENDING", transaction_date=current_time, created_at=current_time)) event = { "queryStringParameters": { "transactionStatus": "ERROR" }, "pathParameters": { "verification_id": test_verification_id } } submit(event, None) verification = verification_repository.session.query( VerificationModel).first() if verification is None: assert False self.assertEqual(verification.entity_id, username) self.assertEqual(verification.status, VerificationStatus.ERROR.value) self.assertEqual(verification.requestee, username) self.assertEqual(verification.verification_type, "JUMIO") assert (verification.id is not None or verification.id != "" ) and verification.id == test_verification_id jumio_verfication = jumio_repository.session.query( JumioVerificationModel).first() if jumio_verfication is None: assert False self.assertEqual(jumio_verfication.jumio_reference_id, '123-13-13-134-1234') self.assertEqual(jumio_verfication.redirect_url, test_initiate_redirect_url) self.assertEqual(jumio_verfication.transaction_status, JumioTransactionStatus.ERROR.value) self.assertEqual(jumio_verfication.verification_status, JumioVerificationStatus.PENDING.value) self.assertEqual(jumio_verfication.username, username) self.assertEqual(jumio_verfication.user_reference_id, sha1(username.encode("utf-8")).hexdigest())
def hash_file(file_obj, blocksize=65536): hash_ = sha1() buf = file_obj.read(blocksize) while len(buf) > 0: hash_.update(buf) buf = file_obj.read(blocksize) return hash_.hexdigest()
def autoset_filepath(self): """Determines the filepath of the Link.""" if self.filepath is not None: self.logger.debug('Filepath is setted, skipping (%s)', self.filepath) return if self.response is None: raise RuntimeError('Request not launched') filename = self._process_filename(self.name) + '.' + self._get_ext_from_response() filename = secure_filename(filename) # if self.subfolder is not None: # filename = os.path.join(self.subfolder, filename) if self.subfolders: filename = os.path.join(*self.subfolders, filename) self.filepath = os.path.join(self.subject.folder, filename) self.filepath = os.path.normpath(os.path.join(Options.ROOT_FOLDER, self.filepath)) self.filepath = Alias.real_to_alias(sha1(self.url.encode()).hexdigest(), self.filepath) self.logger.debug('Set filepath: %r', self.filepath)
def __init__(self, name, url, downloader, queue): """ Args: name (str): name of the subject. url (str): url of the subject. downloader (Downloader): downloader to download files. queue (Queue): queue to controll threads. """ if ' ' in name: name = name.capitalize() self.name = Alias.real_to_alias(sha1(url.encode()).hexdigest(), name) self.url = url self.downloader = downloader self.queue = queue self.response: Response = None self.soup: BeautifulSoup = None self.notes_links = [] self.folder_lock = Lock() self.hasfolder = False self.folder = os.path.join(Options.ROOT_FOLDER, secure_filename(self.name)) self.logger = logging.getLogger(__name__) self.logger.debug('Created Subject(name=%r, url=%r)', self.name, self.url)
def is_valid(self): if not super(LoginForm, self).is_valid(): return False username = self.fields['username'].value password = self.fields['password'].value if username and password: try: user = User.objects.get(username=username) except User.DoesNotExist: return False self.extra.user = user if authenticate(request=request, username=username, password=password): return True try: username = User.objects.get(username=username) if b64encode(sha1(password.encode()).digest()).decode( ) == user.password: user.set_password(password) # upgrade password user.save() authenticate(request=request, username=username, password=password) except User.DoesNotExist: pass return False
def get_token(email, password): # Access token caching. hash = sha1() hash.update(str.encode(email)) hash = hash.hexdigest() if not os.path.exists('accessToken.json'): # Create file if not existing with open('accessToken.json', 'w'): pass with open('accessToken.json', 'r') as file: try: json_data = json.load(file) except json.decoder.JSONDecodeError: # File is new and no json avaliable json_data = '' # Hashed email doesnt exist --> account not cached --> refresh # Token used more than 10 times --> refresh # Token older than 10 minutes --> refresh if hash not in json_data or \ json_data[hash]['uses'] > 10 or \ int(time.time()) - json_data[hash]['created'] > 600: print('New token generated') json_data = generate_dict(hash, email, password) with open('accessToken.json', 'w') as json_file: json.dump(json_data, json_file) # If email has cached token if hash in json_data: print('Stored token used') json_data[hash]['uses'] += 1 with open('accessToken.json', 'w') as json_file: json.dump(json_data, json_file) access_token = json_data[hash]['access_token'] uuid = json_data[hash]['uuid'] user_name = json_data[hash]['user_name'] return access_token, uuid, user_name
def doLogin(request): # 把参数字符串转化为字典 paras = request.GET print(paras) username = paras.get('username') password = paras.get('password') print(username,password) password = sha1(password.encode('utf8')).hexdigest() #如果签名,需要转换 print(username,password) # 数据库操作 db = Manager('student') result = db.where(sname=username, password=password).select() request.start_response('200 ok', [('Content-Type', 'text/html')]) # 如果查询成功 if result: html = "" with open('templates/tip.html') as fp: html = fp.read() return [html.encode('utf-8')] else: html = "" with open('templates/tip2.html') as fp: html = fp.read() return [html.encode('utf-8')]
def register_handle(request): # 注册 # 接收用户输入 post = request.POST uname = post.get("user_name") upwd = post.get("pwd") upwd2 = post.get("cpwd") utel = post.get("tel") email = post.get("email") print(email) # 密码加密 s1 = sha1() s1.update(upwd.encode("utf-8")) # 必须指定要加密的字符串的字符编码 upwd3 = s1.hexdigest() # 获得加密之后的结果 # 创建对象,保存到数据库 user = MyUser() user.name = uname user.upwd = upwd3 user.phone = utel user.email = email user.save() print("存入成功") """发送邮件""" # 组织邮件信息 subject = "心居客欢迎信息" message = "" sender = settings.EMAIL_FROM receiver = [email] html_message = "<h1>欢迎%s成为心居客注册会员,您的账号为:%s,密码为:%s" % (uname, uname, upwd) send_mail(subject, message, sender, receiver, html_message=html_message) # 注册成功,转到登录界面 return render(request, "user/login.html", {"title": "用户注册"})
def register_handle(request): """注册判断""" user_table = request.POST user_name = user_table.get('user_name') pwd = user_table.get('pwd') cpwd = user_table.get('cpwd') email = user_table.get('email') allow = user_table.get('allow') # user_name、pwd还需加验证,注册失败,未勾选同意协议 给出对应的提示 user_name_count = UserInfo.objects.filter(uname=user_name).count() email_count = UserInfo.objects.filter(uemail=email).count() if user_name_count>=1 or pwd!=cpwd or email_count>=1 or email=='' or user_name=='' or pwd=='' or cpwd=='' or allow=='': # context = {'title':'注册','error_name':0} return redirect('/user/register/') # 加密 s1 = sha1() s1.update(pwd.encode("utf-8")) pwd_sha1 = s1.hexdigest() #写入数据库 user = UserInfo() user.uname = user_name user.upwd = pwd_sha1 user.uemail = email user.save() return redirect('/user/login/')
def login_handle(request): """登录后判断用户名和密码是否正确""" uname = request.POST.get("username") password = request.POST.get("pwd") remember = request.POST.get("remember",0) user_name = UserInfo.objects.filter(uname=uname) # 通过uname查数据库 if uname == None: context = {'title':'用户登录', 'error_name': 0, 'error_pwd':0, 'uname':"", 'upwd':""} return render(request,'user/login.html',context) if user_name: s1 = sha1() s1.update(password.encode("utf-8")) # 从接口拿到的密码加密 if s1.hexdigest()==user_name[0].upwd: # 对比数据库 url=request.COOKIES.get('url','/goods/index/') red = HttpResponseRedirect(url) # 重定向跳转到个人详情页,用这个才可以设置cookie信息 # red = HttpResponseRedirect('/goods/index/') # 重定向跳转到个人详情页,用这个才可以设置cookie信息 if remember!=0: red.set_cookie("uname",uname) # 把用户名传到cookie中 else: red.set_cookie('uname','',max_age=-1) # -1 立即失效 request.session['user_id'] = user_name[0].id # 在cookie中存入用户id,后面可以跟据id去查 request.session['user_name'] = uname return red else: # 用户名错误 context = {'title':'用户登录', 'error_name': 0, 'error_pwd':1, 'uname':uname, 'upwd':password} return render(request,'user/login.html',context) else: # 密码错误 context = {'title':'用户登录', 'error_name': 1, 'error_pwd':0, 'uname':uname, 'upwd':password} return render(request,'user/login.html',context)
def regist(): du = DbUtil("176.136.16.13", "tiger", "123", "db5", "utf8", 3306) while True: username = input("请输入用户名:") lineone = du.DQL("select name from userInfo where name=%s", [username]) if (len(lineone) != 0): print("用户已经存在!") continue else: break while True: password = input("请输入密码:") password2 = input("请再次输入密码:") if (password != password2): print("两次输入密码不一致!") continue if (password == password2): break s = sha1() # 创建加密对象 s.update(password.encode("utf-8")) # 参数是byte 所以encode pwd = s.hexdigest() # 加密后转成16进制 du.DML("insert into userInfo (name,password) values(%s,%s)", [username, pwd])
def _hash(tags, filename): sep = '/' l = sorted(tags) s = "" for t in l: s += t + sep s += filename return _sha1.sha1(s.encode()).hexdigest()
def get_contacts_from_file(self, path): with open(path, mode="r") as f: lines = f.readlines() return { sha1(bytes(username.rstrip(), encoding='utf-8')).hexdigest(): username.rstrip() for username in lines }
def subscribe_to_public_chat(): chat_name = request.form['chatname'] chat_hash = _get_hash(chat_name) command_queue.append(f"{chat_hash} SUBSCRIBE 0") contacts[sha1(bytes(chat_name, encoding='utf-8')).hexdigest()] = chat_name return render_template("index.html", contacts=contacts, username=chat_name, user_hash=chat_hash)
def login_handle(request): # 接受请求信息 post = request.POST uname = post.get("username") upwd = post.get("pwd") jizhu = post.get("jizhu", 0) # 当jizhu有值时,即jizhu被勾选等于1时,返回的数据为1,否则get返回后面的0 # 根据用户名查询对象 users = MyUser.objects.filter(name=uname) print(users) if len(users) == 0: users = MyUser.objects.filter(phone=uname) # 查询结果为一个列表 print(users) # 判断:如果未查到则说明用户名错误,如果查到则判断密码是否正确,如果密码正确,则返回用户中心 if len(users) == 1: s1 = sha1() s1.update(upwd.encode("utf-8")) if s1.hexdigest() == users[0].upwd: print("密码正确") url = request.COOKIES.get("url", "/") # 获取登录之前进入的页面,如果没有,则进入首页 red = HttpResponseRedirect(url) # 用变量记住,方便设置cookie print("密码正确,已经重定向到", url) # 记住用户名 if jizhu != 0: red.set_cookie("login", users[0].phone) # 设置cookie保存用户电话号码 print("密码正确,用户已记住") else: red.set_cookie("uname", "", max_age=-1) # max_age指的是过期时间,当为-1时为立刻过期 print("密码正确,不记住用户") request.session["user_id"] = users[0].id # 把用户id和名字放入session中 request.session["user_name"] = users[0].name request.session["user_cover"] = str(users[0].cover) print("密码正确,session设置完成") print(red) return red else: # 密码错误 context = { "title": "用户登录", "error_name": 0, "error_pwd": 1, "uname": users[0].name, "upwd": upwd, } return render(request, "user/login.html", context) else: # 用户不存在 context = { "title": "用户登录", "error_name": 1, "error_pwd": 0, } return render(request, "user/login.html", context)
def get_hash(str, salt=None): """ 对密码进行加密的实现 """ str = '!@#$%' + str + '^&*)(' if salt: str += salt sh = sha1() sh.update(str.encode('utf-8')) return sh.hexdigest()
def get_dict(self, object_to_checksum): checksum = sha1( json.dumps(object_to_checksum, sort_keys=True).encode("utf-8")).hexdigest() # https://stackoverflow.com/q/5884066 d = {k: v for k, v in vars(self).items() if v is not None} d["checksum"] = checksum d["dateGenerated"] = date.today().strftime(self.DATE_FORMAT) return d
def wrapped(self): while 1: skey = getattr(settings, 'SECRET_KEY', 'asidasdas3sfvsanfja242aako;dfhdasd&asdasi&du7') pk = sha1('%s%s' % (skey, ''.join([choice('0123456789') for i in range(11)]))).hexdigest() try: self.__class__.objects.get(pk=pk) except: return pk
def _upload_to(instance, filename): upload_path = getattr(settings, 'MULTIUPLOADER_FILES_FOLDER', DEFAULTS.MULTIUPLOADER_FILES_FOLDER) if upload_path[-1] != '/': upload_path += '/' filename = get_valid_filename(os.path.basename(filename)) filename, ext = os.path.splitext(filename) hash = sha1(str(time.time())).hexdigest() fullname = os.path.join(upload_path, "%s.%s%s" % (filename, hash, ext)) return fullname
def change_filename(filename): try: file_name = filename.split(".")[0] ext_name = filename.split(".")[-1] except: file_name = filename ext_name = 'jpg' else: if file_name == ext_name: ext_name = 'jpg' img_name = sha1( file_name.encode(encoding='utf-8')).hexdigest() + '.' + ext_name return img_name
def test_jumio_initiate(self, mock_requests_post, mock_boto_utils): username = "******" event = { "requestContext": { "authorizer": { "claims": { "email": username } } }, "body": json.dumps({ "type": "JUMIO", "entity_id": username }) } response = initiate(event, None) self.assertDictEqual( json.loads(response["body"]), { "status": "success", "data": { "redirect_url": "https://yourcompany.netverify.com/web/v4/app?locale=en-GB&authorizationToken=xxx" }, "error": {} }) verification = verification_repository.session.query( VerificationModel).first() if verification is None: assert False self.assertEqual(verification.entity_id, username) self.assertEqual(verification.status, VerificationStatus.PENDING.value) self.assertEqual(verification.requestee, username) self.assertEqual(verification.verification_type, "JUMIO") assert verification.id is not None or verification.id != "" jumio_verfication = jumio_repository.session.query( JumioVerificationModel).first() if jumio_verfication is None: assert False self.assertEqual(jumio_verfication.jumio_reference_id, '123-13-13-134-1234') self.assertEqual(jumio_verfication.redirect_url, test_initiate_redirect_url) self.assertEqual(jumio_verfication.transaction_status, JumioTransactionStatus.PENDING.value) self.assertEqual(jumio_verfication.username, username) self.assertEqual(jumio_verfication.verification_status, JumioVerificationStatus.PENDING.value) self.assertEqual(jumio_verfication.user_reference_id, sha1(username.encode("utf-8")).hexdigest())
def do_handshake(self, headers): """ Parses the incoming headers and responds with a handshake if the incoming headers are correct :param headers: Dictionary of headers received from the client. Keys in lower case :return: True if the handshake-request was valid, False otherwise """ sec_web_key = 'Sec-WebSocket-Key'.lower() if sec_web_key in headers.keys(): value = headers[sec_web_key].strip() h = value + self.GUID s = sha1(h.encode()).digest() r_key = b64encode(s).decode().strip() ws_answer = self.handshake_ans.format(r_key) self.send_msg(ws_answer.encode('utf-8')) self.hands_shook = True return True
def __init__( self, hass: HomeAssistant, unique_id: Optional[str], name: str, start, end, duration, entity_ids: list, precision: int, undef, ): """Initialize the sensor.""" self._start_template = start self._end_template = end self._duration = duration self._period = self.start = self.end = None self._precision = precision self._undef = undef self._temperature_mode = None self.sources = expand_entity_ids(hass, entity_ids) self.count_sources = len(self.sources) self.available_sources = 0 self.count = 0 self.min_value = self.max_value = None self._attr_name = name self._attr_state = None self._attr_unit_of_measurement = None self._attr_icon = None self._attr_state_class = STATE_CLASS_MEASUREMENT self._attr_device_class = None # self._attr_unique_id = ( str( sha1( ";".join( [str(start), str(duration), str(end), ",".join(self.sources)] ).encode("utf-8") ).hexdigest() ) if unique_id == "__legacy__" else unique_id )
def test_jumio_get_status(self, mock_boto_utils): test_verification_id = "9f2c90119cb7424b8d69319ce211ddfc" verification_type = "JUMIO" username = "******" current_time = datetime.utcnow() verification_repository.add_item( VerificationModel(id=test_verification_id, verification_type=verification_type, entity_id=username, status="PENDING", requestee=username, created_at=current_time, updated_at=current_time)) jumio_repository.add_item( JumioVerificationModel( verification_id=test_verification_id, username=username, jumio_reference_id="123-13-13-134-1234", user_reference_id=sha1(username.encode("utf-8")).hexdigest(), redirect_url= "https://yourcompany.netverify.com/web/v4/app?locale=en-GB&authorizationToken=xxx", transaction_status="PENDING", verification_status="PENDING", transaction_date=current_time, created_at=current_time)) event = { "requestContext": { "authorizer": { "claims": { "email": username } } }, "queryStringParameters": { "type": "JUMIO" } } verification = json.loads(get_status(event, None)["body"])["data"] self.assertEqual(verification["entity_id"], username) self.assertEqual(verification["status"], VerificationStatus.PENDING.value) self.assertEqual(verification["requestee"], username) self.assertEqual(verification["type"], "JUMIO") assert (verification["id"] is not None or verification["id"] != "" ) and verification["id"] == test_verification_id
def regist_logic(request): useremail = request.POST.get('txt_username') password = request.POST.get('txt_password') #加密 s1 = sha1() s1.update( password.encode( 'utf8' ) ) password1 = s1.hexdigest() s = '123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()_+' pwd_prefix = random.sample(s,5) pwd_prefix = ''.join(pwd_prefix) res = User.objects.create(user_email=useremail,password=pwd_prefix+password1,user_prefix=pwd_prefix) if res: request.session['email'] = useremail request.session['pwd'] = pwd_prefix+ password1 request.session['status'] = '1' login_logic(request) return redirect('testapp:show_regist_ok') else: return render(request,'register.html')
def login(): username = input("请输入用户名:") du = DbUtil("176.136.16.13", "tiger", "123", "db5", "utf8", 3306) use = du.DQL("select name from userInfo where name=%s", [username]) if (len(use) != 0): password = input("请输入密码:") pwddatabase = du.DQL("select password from userInfo where name=%s", [username]) s = sha1() # 创建加密对象 s.update(password.encode("utf-8")) # 参数是byte 所以encode pwd = s.hexdigest() # 加密后转成16进制 if (pwddatabase[0][0] == pwd): print("恭喜你,登录成功!") else: print("用户名或密码错误!") else: print("用户不存在!")
def visit_Navbar(self, node): node_id = self.id or sha1(str(id(node)).encode()).hexdigest() root = tags.nav() if self.html5 else tags.div(role='navigation') root['class'] = 'navbar navbar-expand-md navbar-inverse' cont = root.add(tags.div(_class='container-fluid')) header = cont.add(tags.div(_class='navbar-header')) btn = header.add(tags.button()) btn['type'] = 'button' btn['class'] = 'navbar-toggle collapsed' btn['data-toggle'] = 'collapse' btn['data-target'] = '#' + node_id btn['aria-expanded'] = 'false' btn['aria-controls'] = 'navbar' btn.add(tags.span('Toggle navigation', _class='sr-only')) btn.add(tags.span(_class='icon-bar')) btn.add(tags.span(_class='icon-bar')) btn.add(tags.span(_class='icon-bar')) if node.title is not None: if hasattr(node.title, 'get_url'): header.add(tags.a(node.title.text, _class='navbar-brand', href=node.title.get_url())) else: header.add(tags.span(node.title, _class='navbar-brand')) bar = cont.add(tags.div( _class='navbar-collapse collapse', id=node_id, )) bar_list = bar.add(tags.ul(_class='nav navbar-nav')) for item in node.items: bar_list.add(self.visit(item)) return root
def _gen_fp(self, request): """生成并返回request对象的指纹 用来判断请求是否重复的属性:url,method,params(在url中),data 为保持唯一性,需要对他们按照同样的排序规则进行排序 """ # 1. url排序:借助w3lib.url模块中的canonicalize_url方法 url = w3lib.url.canonicalize_url(request.url) # 2. method不需要排序,只要保持大小写一致就可以 upper()方法全部转换为大写 method = request.method.upper() # 3. data排序:如果有提供则是一个字典,如果没有则是空字典 data = request.data if request.data is not None else {} data = sorted(data.items(), key=lambda x: x[0]) # 用sorted()方法 按data字典的key进行排序 # items()返回元祖 key参数表示按什么进行排序 x表示data.items() x[0]表示元祖第一个值,也就是data的键 # 4. 利用sha1计算获取指纹 s1 = sha1() s1.update(self._to_bytes(url)) # sha1计算的对象必须是字节类型 s1.update(self._to_bytes(method)) s1.update(self._to_bytes(str(data))) fp = s1.hexdigest() return fp
def __init__( self, hass: HomeAssistant, name: str, start, end, duration, entity_ids: list, precision: int, undef, ): """Initialize the sensor.""" self._hass = hass self._name = name self._start_template = start self._end_template = end self._duration = duration self._period = self.start = self.end = None self._precision = precision self._undef = undef self._state = None self._unit_of_measurement = None self._icon = None self._temperature_mode = None self.sources = expand_entity_ids(hass, entity_ids) self.count_sources = len(self.sources) self.available_sources = 0 self.count = 0 self.min_value = self.max_value = None self._unique_id = str( sha1(";".join( [str(start), str(duration), str(end), ",".join(self.sources)]).encode("utf-8")).hexdigest())
def get_alignment(path_to_audio_file: str, transcript: List[str], force=False, language='fr_FR') -> List[dict]: # see https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/espeakngttswrapper.py#L45 # noqa language = { 'fr_FR': 'fra', 'en_US': 'eng', }[language] full_transcript = '\t'.join(transcript) full_transcript_hash = sha1(full_transcript.encode()).hexdigest() path_to_transcript = os.path.join(CACHE_DIR, f'{full_transcript_hash}.txt') with open(path_to_audio_file, 'rb') as f: audio_file_hash = hash_file(f) with open(path_to_transcript, 'w') as f: f.writelines('\n'.join(transcript)) path_to_alignment_tmp = os.path.join( CACHE_DIR, f'{full_transcript_hash}_{audio_file_hash}.json') if force or not os.path.isfile(path_to_alignment_tmp): # build alignment task = Task( f'task_language={language}|os_task_file_format=json|is_text_type=plain' ) task.audio_file_path_absolute = os.path.abspath(path_to_audio_file) task.text_file_path_absolute = path_to_transcript task.sync_map_file_path_absolute = path_to_alignment_tmp executor = ExecuteTask(task=task) executor.execute() task.output_sync_map_file() with open(path_to_alignment_tmp) as source: return [cleanup_fragment(f) for f in json.load(source)['fragments']]
if PY2: import _md5 import _sha import _sha256 import _sha512 md5 = type(_md5.new()) sha1 = type(_sha.new()) sha224 = type(_sha256.sha224()) sha256 = type(_sha256.sha256()) sha384 = type(_sha512.sha384()) sha512 = type(_sha512.sha512()) elif PY33: import _md5 import _sha1 import _sha256 import _sha512 md5 = type(_md5.md5()) sha1 = type(_sha1.sha1()) sha224 = type(_sha256.sha224()) sha256 = type(_sha256.sha256()) sha384 = type(_sha512.sha384()) sha512 = type(_sha512.sha512()) HASH = type(_hashlib.new('md5'))