def account_result(request): type = request.GET.get('type') id = request.GET.get('id') user = get_object_or_404(get_user_model(), id=id) logger.info(type) if user.is_active: return HttpResponseRedirect('/') if type and type in ['register', 'validation']: if type == 'register': content = ''' 恭喜您注册成功,一封验证邮件已经发送到您 {email} 的邮箱,请验证您的邮箱后登录本站。 '''.format(email=user.email) title = '注册成功' else: c_sign = get_sha256(get_sha256(settings.SECRET_KEY + str(user.id))) sign = request.GET.get('sign') if sign != c_sign: return HttpResponseForbidden() user.is_active = True user.save() content = ''' 恭喜您已经成功的完成邮箱验证,您现在可以使用您的账号来登录本站。 ''' title = '验证成功' return render(request, 'account/result.html', { 'title': title, 'content': content }) else: return HttpResponseRedirect('/')
def fileupload(request): """ 该方法需自己写调用端来上传图片,该方法仅提供图床功能 :param request: :return: """ if request.method == 'POST': sign = request.GET.get('sign', None) if not sign: return HttpResponseForbidden() if not sign == get_sha256(get_sha256(settings.SECRET_KEY)): return HttpResponseForbidden() response = [] for filename in request.FILES: timestr = datetime.datetime.now().strftime('%Y/%m/%d') imgextensions = ['jpg', 'png', 'jpeg', 'bmp'] fname = u''.join(str(filename)) isimage = len([i for i in imgextensions if fname.find(i) >= 0]) > 0 blogsetting = get_blog_setting() basepath = r'{basedir}/{type}/{timestr}'.format( basedir=blogsetting.resource_path, type='files' if not isimage else 'image', timestr=timestr) if settings.TESTING: basepath = settings.BASE_DIR + '/uploads' url = 'https://resource.lylinux.net/{type}/{timestr}/{filename}'.format( type='files' if not isimage else 'image', timestr=timestr, filename=filename) if not os.path.exists(basepath): os.makedirs(basepath) savepath = os.path.normpath( os.path.join( basepath, f"{uuid.uuid4().hex}{os.path.splitext(filename)[-1]}")) if not savepath.startswith(basepath): return HttpResponse("only for post") with open(savepath, 'wb+') as wfile: for chunk in request.FILES[filename].chunks(): wfile.write(chunk) if isimage: from PIL import Image image = Image.open(savepath) image.save(savepath, quality=20, optimize=True) response.append(url) return HttpResponse(response) else: return HttpResponse("only for post")
def form_valid(self, form): email = form.cleaned_data['email'] oauthid = form.cleaned_data['oauthid'] oauthuser = get_object_or_404(OAuthUser, pk=oauthid) oauthuser.email = email oauthuser.save() sign = get_sha256(settings.SECRET_KEY + str(oauthuser.id) + settings.SECRET_KEY) site = get_current_site().domain if settings.DEBUG: site = '127.0.0.1:8000' path = reverse('oauth:email_confirm', kwargs={ 'id': oauthid, 'sign': sign }) url = "http://{site}{path}".format(site=site, path=path) content = """ <p>请点击下面链接绑定您的邮箱</p> <a href="{url}" rel="bookmark">{url}</a> 再次感谢您! <br /> 如果上面链接无法打开,请将此链接复制至浏览器。 {url} """.format(url=url) send_email(emailto=[ email, ], title='绑定您的电子邮箱', content=content) url = reverse('oauth:bindsuccess', kwargs={'oauthid': oauthid}) url = url + '?type=email' return HttpResponseRedirect(url)
def handler(self): info = self.message.content if self.userinfo.isAdmin and info.upper() == 'EXIT': self.userinfo = WxUserInfo() self.savesession() return "退出成功" if info.upper() == 'ADMIN': self.userinfo.isAdmin = True self.savesession() return "输入管理员密码" if self.userinfo.isAdmin and not self.userinfo.isPasswordSet: passwd = settings.WXADMIN if settings.TESTING: passwd = '123' if passwd.upper() == get_sha256(get_sha256(info)).upper(): self.userinfo.isPasswordSet = True self.savesession() return "验证通过,请输入命令或者要执行的命令代码:输入helpme获得帮助" else: if self.userinfo.Count >= 3: self.userinfo = WxUserInfo() self.savesession() return "超过验证次数" self.userinfo.Count += 1 self.savesession() return "验证失败,请重新输入管理员密码:" if self.userinfo.isAdmin and self.userinfo.isPasswordSet: if self.userinfo.Command != '' and info.upper() == 'Y': return cmdhandler.run(self.userinfo.Command) else: if info.upper() == 'HELPME': return cmdhandler.get_help() self.userinfo.Command = info self.savesession() return "确认执行: " + info + " 命令?" rsp = tuling.getdata(info) return rsp
def form_valid(self, form): if form.is_valid(): user = form.save(False) user.is_active = False user.source = 'Register' user.save(True) site = get_current_site().domain sign = get_sha256(get_sha256(settings.SECRET_KEY + str(user.id))) if settings.DEBUG: site = '127.0.0.1:8000' path = reverse('account:result') url = "http://{site}{path}?type=validation&id={id}&sign={sign}".format( site=site, path=path, id=user.id, sign=sign) content = """ <p>请点击下面链接验证您的邮箱</p> <a href="{url}" rel="bookmark">{url}</a> 再次感谢您! <br /> 如果上面链接无法打开,请将此链接复制至浏览器。 {url} """.format(url=url) send_email(emailto=[ user.email, ], title='验证您的电子邮箱', content=content) url = reverse('accounts:result') + \ '?type=register&id=' + str(user.id) return HttpResponseRedirect(url) else: return self.render_to_response({'form': form})
def test_image(self): import requests rsp = requests.get( 'https://www.python.org/static/img/[email protected]') imagepath = os.path.join(settings.BASE_DIR, 'python.png') with open(imagepath, 'wb') as file: file.write(rsp.content) rsp = self.client.post('/upload') self.assertEqual(rsp.status_code, 403) sign = get_sha256(get_sha256(settings.SECRET_KEY)) with open(imagepath, 'rb') as file: imgfile = SimpleUploadedFile('python.png', file.read(), content_type='image/jpg') form_data = {'python.png': imgfile} rsp = self.client.post('/upload?sign=' + sign, form_data, follow=True) self.assertEqual(rsp.status_code, 200) os.remove(imagepath) from djangoblog.utils import save_user_avatar, send_email send_email(['*****@*****.**'], 'testTitle', 'testContent') save_user_avatar( 'https://www.python.org/static/img/[email protected]')
def emailconfirm(request, id, sign): if not sign: return HttpResponseForbidden() if not get_sha256(settings.SECRET_KEY + str(id) + settings.SECRET_KEY).upper() == sign.upper(): return HttpResponseForbidden() oauthuser = get_object_or_404(OAuthUser, pk=id) with transaction.atomic(): if oauthuser.author: author = get_user_model().objects.get(pk=oauthuser.author_id) else: result = get_user_model().objects.get_or_create( email=oauthuser.email) author = result[0] if result[1]: author.source = 'emailconfirm' author.username = oauthuser.nikename.strip( ) if oauthuser.nikename.strip( ) else "djangoblog" + datetime.datetime.now().strftime( '%y%m%d%I%M%S') author.save() oauthuser.author = author oauthuser.save() oauth_user_login_signal.send(sender=emailconfirm.__class__, id=oauthuser.id) login(request, author) site = get_current_site().domain content = ''' <p>恭喜您,您已经成功绑定您的邮箱,您可以使用{type}来直接免密码登录本网站.欢迎您继续关注本站,地址是</p> <a href="{url}" rel="bookmark">{url}</a> 再次感谢您! <br /> 如果上面链接无法打开,请将此链接复制至浏览器。 {url} '''.format(type=oauthuser.type, url='http://' + site) send_email(emailto=[ oauthuser.email, ], title='恭喜您绑定成功!', content=content) url = reverse('oauth:bindsuccess', kwargs={'oauthid': id}) url = url + '?type=success' return HttpResponseRedirect(url)