簡體   English   中英

Facebook登錄Django和網址重定向?

[英]Facebook login for Django and url redirection?

我已經實現了一個具有用戶登錄/注冊頁面的Django應用程序。 我想讓登錄我的應用程序的Facebook用戶ID也可以。 在這樣做時,我按照這個鏈接http://developers.facebook.com/docs/guides/web/#login 在該鏈接的幫助下,我現在也可以使用Facebook ID登錄。 點擊Facebook登錄按鈕,彈出facebook登錄頁面; 給用戶名n passw,讓它登錄facebook。 但登錄后,頁面也會重定向回我的主頁。 我需要將其重定向到其他URL,例如http:// localhost / login / 有人可以幫我解決這個問題。 我將粘貼用於django登錄的html部分。

HTML

<body>
     <div id="fb-root"></div>
      <script src="http://connect.facebook.net/en_US/all.js"></script>
      <script>
         FB.init({ 
            appId:'114322105313139', cookie:true,
            status:true, xfbml:true 
         });
      </script>


  <fb:login-button>Login with Facebook</fb:login-button>

</body>

settings.py

# Django settings for universityDB project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'student',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'qburst',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}


EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = '587'
EMAIL_HOST_USER = "rv@gmail.com" #create a gmail id
EMAIL_HOST_PASSWORD = "xxxx"#pwd for that id
EMAIL_USE_TLS = True 


FACEBOOK_CACHE_TIMEOUT=1800
FACEBOOK_APP_ID='xxx'
FACEBOOK_API_KEY='xxx'
FACEBOOK_SECRET_KEY='xxxx'
FACEBOOK_INTERNAL = 'TRUE'


# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'b_3=te)1b57mqsz^))jg95i%umw=*pug_i*8j!$6@y4(ie=8x$'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
     'django.middleware.csrf.CsrfResponseMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'facebook.djangofb.FacebookMiddleware',
    'facebookconnect.middleware.FacebookConnectMiddleware',
   # 'facebook.djangofb.FacebookMiddleware',
   # 'socialregistration.middleware.FacebookMiddleware' ,    

)


AUTHENTICATION_BACKENDS = (
    'facebookconnect.models.FacebookBackend',
    'social_auth.backends.facebook.FacebookBackend',
    'django.contrib.auth.backends.ModelBackend',
)



LOGIN_URL          = '/login-form/'
LOGIN_REDIRECT_URL = '/logged-in/'
LOGIN_ERROR_URL    = '/login-error/'

SOCIAL_AUTH_ERROR_KEY = 'social_errors'

SOCIAL_AUTH_COMPLETE_URL_NAME  = 'complete'
SOCIAL_AUTH_ASSOCIATE_URL_NAME = 'associate_complete'

SOCIAL_AUTH_DEFAULT_USERNAME = 'new_social_auth_user'

SOCIAL_AUTH_EXTRA_DATA = False

SOCIAL_AUTH_EXPIRATION = 'expires'

SOCIAL_AUTH_SESSION_EXPIRATION = False


DUMMY_FACEBOOK_INFO = {
    'uid':0,
    'name':'(Private)',
    'first_name':'(Private)',
    'pic_square_with_logo':'http://www.facebook.com/pics/t_silhouette.gif',
    'affiliations':None,
    'status':None,
    'proxied_email':None,
}

ROOT_URLCONF = 'universityDB.urls'

TEMPLATE_DIRS = (
    "/home/Desktop/universityDB/templates"             
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'universityDetails',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'captcha',
    'facebookconnect',
    'social_auth',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

該代碼看起來就像FB的HTML。 如果您需要更多幫助,您需要讓我們更好地了解您的Django Auth結構。

你前面還有很多步驟。 如果我是你,我會調查Django-SocialAuth以獲得輕松集成的體驗。

編輯:作為包含您的Settings.py的后續行動,假設您已經閱讀了Facebook身份驗證文檔以及SocialAuth README,您將需要為fb的身份驗證回調網址設置適當的控制器。

之后,將這些SocialAuth視圖掛鈎到您當前的身份驗證過程中:

def facebook_login(request):
    """
    Facebook login page
    """
    if request.REQUEST.get("device"):
        device = request.REQUEST.get("device")
    else:
        device = "user-agent"

    params = {}
    params["client_id"] = FACEBOOK_APP_ID
    params["redirect_uri"] = request.build_absolute_uri(reverse("socialauth_facebook_login_done"))

    url = "https://graph.facebook.com/oauth/authorize?"+urllib.urlencode(params)

    return HttpResponseRedirect(url)

def facebook_login_done(request):
    user = authenticate(request=request)

    if not user:
        request.COOKIES.pop(FACEBOOK_API_KEY + '_session_key', None)
        request.COOKIES.pop(FACEBOOK_API_KEY + '_user', None)

        # TODO: maybe the project has its own login page?
        logging.debug("SOCIALAUTH: Couldn't authenticate user with Django, redirecting to Login page")
        return HttpResponseRedirect(reverse('socialauth_login_page'))

    login(request, user)

    logging.debug("SOCIALAUTH: Successfully logged in with Facebook!")

    if request.GET.get('next'):
        return HttpResponseRedirect(request.GET.get('next'))
    else:
        return HttpResponseRedirect(LOGIN_REDIRECT_URL)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM