---路由---
urlparttens = []
---引入---
from .models import OAthQQUser
from django.auth import User
from oauth.constants import OPENID_EXPIRES
from meiduo_mall.utils import meiduo_signatrue
---定义视图---
class OAthQQOpenid(View):
def get(self,request):
# 获取AC和跳转路由
code = request.GET.get('code')
state = request.GET.get('state', '/')
# 传入参数
oauthqq = OAuthQQ(
settings.QQ_CLIENT_ID,
settings.QQ_CLIENT_SECRET,
settings.QQ_REDIRECT_URL,
state,
)
# 获取AT
token = oauthqq.get_acess_token(code)
# 获取openid
openid =oauthqq.get_open_id(token)
# 判定授权
try:
qquser = OAthQQUser.objects.get(openid=openid)
# 首次,将openid放入<hidden>,并加密
except:
json_str = meiduo_signatrue.dumps({"openid":openid},
constants.OPENID_EXPIRES)
context = {
'token': json_str
}
return render(request, 'oauth_callback.html', context)
# 获取用户,保持登录
else:
user = qquser.user
login(request, user)
response = redirect('/')
response.set_cookie('username', user.username)
return response
## 绑定页绑定首次授权用户
from import
---继续定义post请求---
def post(self, request):
# 获取填写信息
access_token = request.POST.get('access_token')
mobile = request.POST.get('mobile')
pwd = request.POST.get('pwd')
sms_code = request.POST.get('sms_code')
state = request.GET.get('state')
# 解密openid
openid_dict = meiduo_signature.loads(acess_token, contants.OPENID_EXPRIS)
# 取值
openid = openid_dict.get('openid')
# 判定id
if openid is None:
return HttpResponseForbidden('授权过期')
# 判定用户,若无则新建
try:
user = User.objects.get(mobile=mobile)
except:
user = User.objects.create_user(mobile,password=pwd,mobile=mobile)
else:
if not user.check_password(pwd):
return HttpResponseForbidden('密码错误')
# 新建qq对象
OAuthQQuser.objects.create(
user = user,
openid = openid,
)
# 保持会话
login(request,user)
response = redirect(state)
response.set_cookie('username', user.username)
return response |
|