def social_login_callback(request, sitename): code = request.GET.get('code', None) if not code: return HttpResponseRedirect(SOCIAL_LOGIN_ERROR_REDIRECT_URL) socialsites = SocialSites(SOCIALOAUTH_SITES) try: site = socialsites.get_site_object_by_name(sitename) site.get_access_token(code) except(SocialSitesConfigError, SocialAPIError): return HttpResponseRedirect(SOCIAL_LOGIN_ERROR_REDIRECT_URL) try: user = SocialUser.objects.get(site_uid=site.uid, site_name=site.site_name) SiteUser.objects.filter(id=user.id).update(username=site.name, avatar_url=site.avatar) except SocialUser.DoesNotExist: user = SocialUser.objects.create( site_uid=site.uid, site_name=site.site_name, username=site.name, avatar_url=site.avatar ) # set uid in session, then this user will be auto login request.session['uid'] = user.user.id return HttpResponseRedirect(SOCIAL_LOGIN_DONE_REDIRECT_URL)
def social_login_callback(request, sitename): """第三方帐号OAuth认证登录,只有设置了USING_SOCIAL_LOGIN=True才会使用到此功能""" code = request.GET.get('code', None) if not code: return HttpResponseRedirect(SOCIAL_LOGIN_ERROR_REDIRECT_URL) socialsites = SocialSites(SOCIALOAUTH_SITES) try: site = socialsites.get_site_object_by_name(sitename) site.get_access_token(code) except(SocialSitesConfigError, SocialAPIError): return HttpResponseRedirect(SOCIAL_LOGIN_ERROR_REDIRECT_URL) # 首先根据site_name和site uid查找此用户是否已经在自身网站认证, # 如果查不到,表示这个用户第一次认证登陆,创建新用户记录 # 如果查到,就跟新其用户名和头像 try: user = SocialUser.objects.get(site_uid=site.uid, site_name=site.site_name) SiteUser.objects.filter(id=user.user.id).update(username=site.name, avatar_url=site.avatar) except SocialUser.DoesNotExist: user = SocialUser.objects.create( site_uid=site.uid, site_name=site.site_name, username=site.name, avatar_url=site.avatar ) # set uid in session, then this user will be auto login request.session['uid'] = user.user.id return HttpResponseRedirect(SOCIAL_LOGIN_DONE_REDIRECT_URL)
def login(request): site_object=[] socialsites = SocialSites(SOCIALOAUTH_SITES) for site_class in socialsites.list_sites_class(): _s = socialsites.get_site_object_by_class(site_class) site_object.append(_s) return render_to_response('oauth2/login.html', {'items':site_object,})
def slider_by_tag(request,tagname,page=1): '''Get all sliders in a tag. ''' if 'uid' in request.session: theSlider = Slider.objects.filter(tags__tag_name__exact=tagname).extra(select={ 'likes': 'SELECT COUNT(id) FROM users_siteuser_slider_like WHERE users_siteuser_slider_like.slider_id = slider_DB_slider.slider_id', 'collections': 'SELECT COUNT(id) FROM users_siteuser_slider_collection WHERE users_siteuser_slider_collection.slider_id = slider_DB_slider.slider_id', 'amILikeIt':'SELECT COUNT(id) FROM users_siteuser_slider_like WHERE users_siteuser_slider_like.slider_id = slider_DB_slider.slider_id and users_siteuser_slider_like.siteuser_id=%s' % (request.session['uid']), 'amICollectIt':'SELECT COUNT(id) FROM users_siteuser_slider_collection WHERE users_siteuser_slider_collection.slider_id = slider_DB_slider.slider_id and users_siteuser_slider_collection.siteuser_id=%s' % (request.session['uid']), },).order_by("-creation_date")[int(page) * 10 - 10:int(page) * 10] else: theSlider = Slider.objects.filter(tags__tag_name__exact=tagname).extra(select={ 'likes': 'SELECT COUNT(id) FROM users_siteuser_slider_like WHERE users_siteuser_slider_like.slider_id = slider_DB_slider.slider_id', 'collections': 'SELECT COUNT(id) FROM users_siteuser_slider_collection WHERE users_siteuser_slider_collection.slider_id = slider_DB_slider.slider_id', 'amILikeIt':'0', 'amICollectIt':'0', },).order_by("-creation_date")[int(page) * 10 - 10:int(page) * 10] if theSlider is None: return Http404() extra = {} extra["tagname"] = tagname extra["page"] = int(page) extra["slideCount"] = Slider.objects.filter(tags__tag_name__exact=tagname).count() extra["pageCount"] = int(math.ceil(extra["slideCount"] / 10.0))#取整 #extra["myIntrestingTag"]=InnerUser.objects.get() endxrange = extra["page"] / 10 * 10 + 10 if endxrange > extra["slideCount"] / 10 + 1: endxrange = extra["slideCount"] / 10 + 1 extra['loop_times'] = xrange(extra["page"] / 10 * 10 + 1,endxrange + 1) extra["isFavorite"] = getIsfavoriteTag(request,tagname) extra['favoriteCount'] = InnerUser.objects.filter(intersting_tags__tag_name__exact=tagname).count() #用户信息 if siteuser_settings.USING_SOCIAL_LOGIN:#允许使用社交网站登录 socialsites = SocialSites(settings.SOCIALOAUTH_SITES) info = {} if 'uid' in request.session: thisUser = SiteUser.objects.get(id=request.session['uid']) info['id'] = thisUser.id info['social'] = thisUser.is_social #Oauth user if siteuser_settings.USING_SOCIAL_LOGIN and info['social']: info['social'] = socialsites.get_site_object_by_name(thisUser.social_user.site_name).site_name_zh info['username'] = thisUser.username info['avatar'] = thisUser.avatar info['current'] = request.siteuser and request.siteuser.id == thisUser.id fanscound = UserFriends.objects.filter(target=thisUser.id).count() info['fansCount'] = fanscound if fanscound is None else 0 focusCount = UserFriends.objects.filter(source=thisUser.id).count() info['focusCount'] = focusCount if focusCount is None else 0 t = loader.get_template('slider_by_tag.html') c = RequestContext(request,{'theSlider':theSlider,'extra':extra,'users':info}) return HttpResponse(t.render(c))
def _social_sites(): def make_site(site_class): s = socialsites.get_site_object_by_class(site_class) return { 'site_name': s.site_name, 'site_name_zh': s.site_name_zh, 'authorize_url': s.authorize_url, } socialsites = SocialSites(SOCIALOAUTH_SITES) return [make_site(site_class) for site_class in socialsites.list_sites_class()]
def callback(request): code=request.GET('code') if not code: return HttpResponse(u'登陆失败!') socialsites=SocialSites(SOCIALOAUTH_SITES) s = socialsites.get_site_object_by_name(sitename) try: s.get_access_token(code) except SocialAPIError as e: return HttpResponse('<p>%s</p><p>%s</p><p>%s</p>' % (e.site_name,e.url,e.error_msg)) return render_to_response('oauth2/account.html',{'item':s,})
def parse_token_response(sitename, data): socialsites = SocialSites(SOCIALOAUTH_SITES) s = socialsites.get_site_object_by_name(sitename) try: s.parse_token_response(data) except SocialAPIError as e: current_app.logger.error( 'SocialAPIError. sitename: {}; url: {}; msg: {}'.format( e.site_name, e.url, e.error_msg)) return None, e.error_msg else: return s, ''
def on_get(self, req, resp, social): code = req.params.get('code') if not code: # error occurred challenges = ['Digest'] description = ('The provided auth token is not valid. ' 'Please request a new token and try again.') raise falcon.HTTPUnauthorized('Authentication required', description, challenges, href='http://docs.example.com/auth') socialsites = SocialSites(self.social_sites) s = socialsites.get_site_object_by_name(social) try: s.get_access_token(code) except SocialAPIError as e: challenges = ['Digest'] description = '{} {} {}'.format(e.site_name, e.url, e.error_msg) raise falcon.HTTPUnauthorized('Authentication required', description, challenges, href='http://docs.example.com/auth') # Ищем пользователя userSchema = UserSchema(many=False) user = Users.get_or_none(Users.uid == '{}'.format(s.uid), Users.social == social) if user is None: mock = { 'data': { 'type': 'user', 'attributes': { 'social': social, 'name': s.name, 'uid': '{}'.format(s.uid) } } } unresult = userSchema.load(mock, many=False) user = unresult.data try: with self.db.atomic(): user.save() except IntegrityError as e: raise falcon.HTTPBadRequest('User creation error', 'Cannot save user in database') # token = generate_user_token(user).decode() userDump = userSchema.dump(user) resp.context.update({'user': userDump.data}) resp.status = falcon.HTTP_OK
def get_oauth_token(sitename, code): if not code or code == 'authdeny': return None, 'No code' socialsites = SocialSites(SOCIALOAUTH_SITES) s = socialsites.get_site_object_by_name(sitename) try: s.get_access_token(code) except SocialAPIError as e: current_app.logger.error( 'SocialAPIError. sitename: {}; url: {}; msg: {}'.format( e.site_name, e.url, e.error_msg)) return None, e.error_msg else: return s, ''
def oauth(request, provider): code = request.GET.get('code') if not code: # 认证返回的params中没有code,肯定出错了 # 重定向到某处,再做处理 raise social_sites = SocialSites(settings.SOCIALOAUTH_SITES) s = social_sites.get_site_object_by_name(provider) # 用code去换取认证的access_token s.get_access_token(code) u = User.from_oauth(s.name, s.uid, s.access_token, s.avatar) login_user(request, u) return redirect('index')
def login_start_baidu(request): """ a method that loads config and redirect to Google """ site = SocialSites(SOCIALOAUTH_SITES).get_site_object_by_name('baidu') authorize_url = site.authorize_url return HttpResponsePermanentRedirect(authorize_url)
def home(request): if siteuser_settings.USING_SOCIAL_LOGIN: socialsites = SocialSites(settings.SOCIALOAUTH_SITES) def _make_user_info(u): info = {} info['id'] = u.id info['social'] = u.is_social if siteuser_settings.USING_SOCIAL_LOGIN and info['social']: info['social'] = socialsites.get_site_object_by_name(u.social_user.site_name).site_name_zh info['username'] = u.username info['avatar'] = u.avatar info['current'] = request.siteuser and request.siteuser.id == u.id return info all_users = SiteUser.objects.all() users = map(_make_user_info, all_users) return render_to_response( 'home.html', { 'users': users, }, context_instance = RequestContext(request) )
def login_3rd(request, site_name): socialsites = SocialSites(getSocialSite(request, site_name)) if site_name in socialsites._sites_name_list: _s = socialsites.get_site_object_by_name(site_name) if 'returnurl' in request.GET: returnurl = urlparse(request.GET['returnurl']) returnpath = returnurl.path returnhash = returnurl.fragment _s.REDIRECT_URI = u"%s?returnurl=%s" % (_s.REDIRECT_URI, returnpath) if returnhash is not None and returnhash != '': _s.REDIRECT_URI += u'&returnhash=%s' % (returnhash) url = _s.authorize_url return HttpResponseRedirect(url) else: raise Http404("Unknown login method '%s'." % site_name)
def login_complete_baidu(request): """ a method that get UserInfo from Baidu, log in or create a user, and finally return a token with which the user can log in to our server. """ code = request.GET.get("code") if not code: data = { "status": "error", "reason": "cannot find or create user, pls contact us", } return HttpResponse(json.dumps(data)) site = SocialSites(SOCIALOAUTH_SITES).get_site_object_by_name("baidu") try: site.get_access_token(code) except SocialAPIError as e: data = { "status": "error", "reason": e.error_msg, } return HttpResponse(json.dumps(data)) profile = dict() profile["username"] = site.name profile["uid"] = site.uid profile["given_name"] = "" profile["family_name"] = "" profile["email"] = "" (user, token) = _get_user_and_token(profile) if user: data = { "status": "success", "token": token.token, "uid": str(user.pk), "baiduName": profile["username"], } else: data = { "status": "error", "reason": "cannot find or create user, pls contact us", } return HttpResponse(json.dumps(data))
def login_complete_baidu(request): """ a method that get UserInfo from Baidu, log in or create a user, and finally return a token with which the user can log in to our server. """ code = request.GET.get('code') if not code: data = { 'status': 'error', 'reason': 'cannot find or create user, pls contact us', } return HttpResponse(json.dumps(data)) site = SocialSites(SOCIALOAUTH_SITES).get_site_object_by_name('baidu') try: site.get_access_token(code) except SocialAPIError as e: data = { 'status': 'error', 'reason': e.error_msg, } return HttpResponse(json.dumps(data)) profile = dict() profile['username'] = site.name profile['uid'] = site.uid profile['given_name'] = '' profile['family_name'] = '' profile['email'] = '' (user, token) = _get_user_and_token(profile) if user: data = { 'status': 'success', 'token': str(token), 'uid': user.pk, 'baiduName': profile['username'], } else: data = { 'status': 'error', 'reason': 'cannot find or create user, pls contact us', } return HttpResponse(json.dumps(data))
def oauth_links(): def _link(site_class): _s = socialsites.get_site_object_by_name(site_class) a_content = _s.site_name return (_s.authorize_url, a_content) socialsites = SocialSites(SOCIALOAUTH_SITES) links = map(_link, ['wechat', 'weibo', 'facebook']) return jsonify(message="OK", links = list(links))
def callback(sitename): code = request.GET.get('code') if not code: # error occurred redirect('/oautherror') socialsites = SocialSites(SOCIALOAUTH_SITES) s = socialsites.get_site_object_by_name(sitename) try: s.get_access_token(code) except SocialAPIError as e: # 这里可能会发生错误 print e.site_name # 哪个站点的OAuth2发生错误? print e.url # 请求的url print e.error_msg # 由站点返回的错误信息 / urllib2 的错误信息 raise # 到这里授权完毕,并且取到了用户信息,uid, name, avatar... storage = UserStorage() UID = storage.get_uid(s.site_name, s.uid) if not UID: # 此用户第一次登录,为其绑定一个自身网站的UID UID = storage.bind_new_user(s.site_name, s.uid) storage.set_user( UID, site_name = s.site_name, uid = s.uid, name = s.name, avatar = s.avatar ) session_id = request.get_cookie('session_id') if not session_id: session_id = Session.make_session_id(UID) session = Session() session.set(session_id, uid=UID) response.set_cookie('session_id', session_id) redirect('/')
def callback(sitename): code = request.GET.get('code') if not code: # error occurred redirect('/oautherror') socialsites = SocialSites(SOCIALOAUTH_SITES) s = socialsites.get_site_object_by_name(sitename) try: s.get_access_token(code) except SocialAPIError as e: # 这里可能会发生错误 print e.site_name # 哪个站点的OAuth2发生错误? print e.url # 请求的url print e.error_msg # 由站点返回的错误信息 / urllib2 的错误信息 raise # 到这里授权完毕,并且取到了用户信息,uid, name, avatar... storage = UserStorage() UID = storage.get_uid(s.site_name, s.uid) if not UID: # 此用户第一次登录,为其绑定一个自身网站的UID UID = storage.bind_new_user(s.site_name, s.uid) storage.set_user(UID, site_name=s.site_name, uid=s.uid, name=s.name, avatar=s.avatar) session_id = request.get_cookie('session_id') if not session_id: session_id = Session.make_session_id(UID) session = Session() session.set(session_id, uid=UID) response.set_cookie('session_id', session_id) redirect('/')
def qqlogin(request): # 构造url,直接打开 socialsites = SocialSites(SOCIALOAUTH_SITES) def _link(site_class): _s = socialsites.get_site_object_by_class(site_class) return _s.authorize_url link = map(_link, socialsites.list_sites_class()) # 获取到了url # 获取返回的code code = request.GET.get("code") if not code: return render_to_response("index.html", {"link": link[0]}, RequestContext(request)) s = socialsites.get_site_object_by_name("qq") s.get_access_token(code) # s.site_name s.uid s.name s.avatar sitename = s.site_name uid = s.uid name = s.name avatar = s.avatar # 根据昵称 ID 图标来添加新用户 # 判断获取的s的数据是否正确,如果正确,则添加新用户 try: user = User.objects.get(username=s.uid) # 只需要uid,便可以登录 # user = User.objects.create_user(username=s.uid) #只需要uid,便可以登录 except: user = User.objects.create_user(username=s.uid, password="******") # 只需要uid,便可以登录 user.save() person = Person(user=user, nick_name=s.name, photo=s.avatar) # 不再本地保存头像,保存url person.save() person = authenticate(username=s.uid, password="******") # login(user.username,user.password) # 用code换取token ,重定向到主页 if person is not None: login(request, person) # return HttpResponseRedirect('/') return blogall(request, loginflag=True)
def login(): def _link(site_class): _s = socialsites.get_site_object_by_class(site_class) if os.path.exists(os.path.join(IMAGE_PATH, _s.site_name + '.png')): a_content = '<img src="/static/images/%s.png" />' % _s.site_name else: a_content = '使用 %s 登录' % _s.site_name_zh return """<div style="margin: 20px;"> <a href="%s">%s</a> </div>""" % (_s.authorize_url, a_content) socialsites = SocialSites(SOCIALOAUTH_SITES) links = map(_link, socialsites.list_sites_class()) links = '\n'.join(links) html = """<!DOCTYPE html> <html> <body>%s</body> </html> """ % links return html
def portrait(request): #response for the social site user login socialsites = SocialSites(settings.SOCIALOAUTH_SITES) print 'portrait in' if request.GET.get('state', None) == 'socialoauth': print 'qq in' auth.logout(request) #logout first access_code = request.GET.get('code') qq_object = socialsites.get_site_object_by_name('qq') try: qq_object.get_access_token(access_code) fake_email = qq_object.uid + "@qq.com" try: #user exist User.objects.get(email=fake_email) except User.DoesNotExist: #user doesn't exist, need add it first social_user = User(name=qq_object.name, email=fake_email, head_portrait=qq_object.avatar, social_user_status=1, social_site_name=1, social_user_id=qq_object.uid) social_user.set_password(qq_object.uid) social_user.date = timezone.now() social_user.save() user = auth.authenticate(email=fake_email, password=qq_object.uid) request.user = user auth.login(request, user) return HttpResponseRedirect("/") except SocialAPIError as e: print e isMobile = dmb.process_request(request) if request.user.is_anonymous(): return comm.redirect_login_path(isMobile, request) result = {} if request.method == 'POST': usesr = request.user #remove the old portraint ''' pdb.set_trace() if 'media' in usesr.head_portrait.name[1:]: oldportraint = os.path.join(settings.MEDIA_ROOT, usesr.head_portrait.name[7:]) else: oldportraint = os.path.join(settings.MEDIA_ROOT, usesr.head_portrait.name[1:]) pdb.set_trace() if os.path.isfile(oldportraint): os.remove(oldportraint) #rename the fake portrait pdb.set_trace() if 'media' in usesr.fake_head_portrait.name[1:]: os.rename(os.path.join(settings.MEDIA_ROOT,usesr.fake_head_portrait.name[7:]), oldportraint) else: os.rename(os.path.join(settings.MEDIA_ROOT,usesr.fake_head_portrait.name[1:]), oldportraint) ''' usesr.head_portrait = usesr.fake_head_portrait usesr.is_head_portrait = True usesr.save() result['status'] = 'OK' result['msg'] = '头像上传成功...' return HttpResponse(json.dumps(result), content_type='application/json') else: form = UploadPortrainForm() form.fields['portrain'].label = '点击上传头像' admin_granted = has_admin_perm(request.user) context = { 'form': form.as_ul(), 'admin_granted': admin_granted, } if isMobile: return render(request, 'admin_user/m_change_portrait.html', context) else: return render(request, 'admin_user/change_portrait.html', context)
def defalut(request): '''tagCloud''' #统计表潜在每一篇文档中出现的次数 tags_with_slider = Tag.objects.all().annotate(counter=Count('Slider_Tags')) tagCloud = tags_with_slider.values('tag_name', 'counter').order_by('-counter')[:50]#group by #头条 sliderHeadlines = Slider.objects.filter(headline_date__isnull=False).order_by('-creation_date')[:10] #头条 recommends = Slider.objects.filter(recommended_date__isnull=False).order_by('-creation_date')[:20] #轮播 now = timezone.now() galleries=Slider_Gallery.objects.filter(gallery_date__gt=now).order_by('-gallery_date')[:5] #galleries = Slider_Gallery.objects.all().order_by('-gallery_date')[:5] #用户信息 if siteuser_settings.USING_SOCIAL_LOGIN:#允许使用社交网站登录 socialsites = SocialSites(settings.SOCIALOAUTH_SITES) #新注册用户 newUsers=SiteUser.objects.all().order_by('-date_joined')[:10] info = {} if 'uid' in request.session: thisUser = SiteUser.objects.get(id=request.session['uid']) info['id'] = thisUser.id info['social'] = thisUser.is_social if siteuser_settings.USING_SOCIAL_LOGIN and info['social']: info['social'] = socialsites.get_site_object_by_name(thisUser.social_user.site_name).site_name_zh info['username'] = thisUser.username info['avatar'] = thisUser.avatar info['current'] = request.siteuser and request.siteuser.id == thisUser.id if not thisUser.is_social: user = InnerUser.objects.get(user_id=thisUser.id) fanscound = UserFriends.objects.filter(target = user).count() info['fansCount'] = fanscound if fanscound is not None else 0 focusCount = UserFriends.objects.filter(source = user).count() info['focusCount'] = focusCount if focusCount is not None else 0 #关注的人的slider if thisUser.is_social: focuspeoples_sliders = Slider.objects.filter(author__in=SiteUser.objects.filter(id__in= map(getUserIdFromInnerUser,list(InnerUser.objects.filter(id__in= map(getTargetIdFromFriends,list(UserFriends.objects.filter(source = SocialUser.objects.get(user_id=thisUser.id))))))))).order_by('-creation_date')[:10] else: focuspeoples_sliders = Slider.objects.filter(author__in=SiteUser.objects.filter(id__in= map(getUserIdFromInnerUser,list(InnerUser.objects.filter(id__in= map(getTargetIdFromFriends,list(UserFriends.objects.filter(source = InnerUser.objects.get(user_id=thisUser.id))))))))).order_by('-creation_date')[:10] #return HttpResponse(Slider.objects.filter(author__in=SiteUser.objects.filter(id__in= # map(getUserIdFromInnerUser,list(InnerUser.objects.filter(id__in= # map(getTargetIdFromFriends,list(UserFriends.objects.filter(source = # InnerUser.objects.get(user_id=thisUser.id))))))))) # .query.__str__()) if not thisUser.is_social: mytags_sliders = Slider.objects.filter(tags__in=InnerUser.objects.get(user__id__exact=thisUser.id).intersting_tags.all()).distinct().order_by('-creation_date')[:10] else: mytags_sliders={} else: focuspeoples_sliders = None mytags_sliders={} #from siteuser.context_processors import social_sites #return render_to_response('default.html', # {'tagCloud':tagCloud,"headlines":headlines,'galleries':recommendHTML}, # context_instance=RequestContext(request, # processors=[social_sites])) '''导入公共配置social_sites,上面方法在django1.4需要手动引入social_sites,HttpResponse不需要''' t = loader.get_template('default.html') c = RequestContext(request,{'tagCloud':tagCloud,"headlines":sliderHeadlines,"recommends":recommends,'galleries':galleries,'focus_sliders':focuspeoples_sliders,'mytags_sliders':mytags_sliders,'user':request.siteuser,'userInfo': info,'newUsers':newUsers}) return HttpResponse(t.render(c))
from socialoauth import SocialSites SOCIALOAUTH_SITES = (('weibo', 'socialoauth.sites.weibo.Weibo', '新浪微博', { 'redirect_uri': 'http://zmrenwu.pythonanywhere.com', 'client_id': '3072222160', 'client_secret': '9b06ed28d7598a91ee72bc38e4f067b2', }), ) socialsites = SocialSites(SOCIALOAUTH_SITES) for s in socialsites.list_sites_class(): site = socialsites.get_site_object_by_class(s) authorize_url = site.authorize_url print(authorize_url) # site.get_access_token('453043b659879103c6886f7147fbea8c') # print(site.name) # print(site.avatar) # print(site.avatar_large)
""" # 以下是兼容python2和python3的导入 if str(sys.version[0]) == "3": from urllib.parse import urlencode, quote_plus from urllib.request import urlopen, Request from urllib.error import HTTPError, URLError else: from urllib import urlencode, quote_plus from urllib2 import urlopen, Request, HTTPError, URLError from socialoauth.exception import SocialAPIError, SocialSitesConfigError from socialoauth import SocialSites HTTP_TIMEOUT = 10 socialsites = SocialSites() if not socialsites._configed: raise SocialSitesConfigError("SocialSites not configed yet, Do it first!") def _http_error_handler(func): @wraps(func) def deco(self, *args, **kwargs): try: res = func(self, *args, **kwargs) except HTTPError as e: raise SocialAPIError(self.site_name, e.url, e.read()) except URLError as e: raise SocialAPIError(self.site_name, args[0], e.reason) error_key = getattr(self, 'RESPONSE_ERROR_KEY', None)
def callback(request, site_name): returnurl = '/' if 'returnurl' in request.GET: returnurl = request.GET.get('returnurl') if 'returnhash' in request.GET: returnurl += '#' + request.GET.get('returnhash') ''' user store and manage should be replaced by django.contib.auth (TBD) ''' code = request.GET.get('code') if not code: #error occurred return HttpResponseRedirect(reverse('oautherror')) socialsites = SocialSites(getSocialSite(request, site_name)) _s = socialsites.get_site_object_by_name(site_name) try: _s.get_access_token(code) except SocialAPIError as e: print e.site_name # the site_name which has error occurred print e.url # the url requested print e.error_msg # the error log returned from the site raise if _s.site_name != 'wechat': username = _s.uid[0:29] password = _s.site_name + _s.uid[30:] else: username = _s.uid password = _s.site_name + _s.uid user = auth.authenticate(username=username, password=password) if user is None: user = User.objects.create_user(username=username, password=password) user.site_name = _s.site_name user.save() user = auth.authenticate(username=username, password=(password)) if user.is_active == 0: return HttpResponseRedirect(returnurl) if _s.site_name != 'wechat': user.nickname = _s.name else: user.nickname = _s.name.encode('unicode_escape') # user.gender = (lambda x: 'm' if x else 'f')(_s.gender) user.avatar = _s.avatar user.access_token = _s.access_token user.expire_time = datetime.fromtimestamp( mktime(localtime()) + _s.expires_in) user.refresh_token = _s.refresh_token user.save() poolrooms = list(PoolroomUser.objects.filter(user=user)) if len(poolrooms) > 0: user.is_club_owner = True user.poolroom = poolrooms[0].poolroom else: user.poolroom = None auth.login(request, user) return HttpResponseRedirect(returnurl)
def __init__(self, db_manager, cfg): super(OAuthBaseResource, self).__init__(db_manager) # patch url self.social_sites = SocialSites(cfg.sites_list) self.base_url = cfg.base_url