示例#1
0
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)
示例#2
0
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)
示例#3
0
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)
    )
示例#4
0
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))
示例#5
0
 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()]
示例#6
0
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, ''
示例#7
0
    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
示例#8
0
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, ''
示例#9
0
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)
示例#10
0
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))
示例#11
0
文件: index.py 项目: cash2one/hdj
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('/')
示例#12
0
文件: index.py 项目: cash2one/hdj
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
示例#13
0
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)
示例#14
0
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)
示例#15
0
 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
示例#16
0
"""
# 以下是兼容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)
示例#17
0
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)