2016-09-19 5 views
0

私はdjangoで新しく、私はユーザーとパスワードまたはFacebookにログインする必要があります。私はAPIエンドポイントのために休憩フレームワークを使用しています。 ¿どうやってできるの?django facebookとユーザーパスワード認証

は、私が試してみてください。

ジャンゴ休止フレームワーク - 社会のOAuth2が、私のニーズが最初に入力した後にユーザーからの追加情報を保存するので、私のために動作しません。私は2エンドポイント1は、ユーザとパスワードを送信し、別の送信Facebookの認証トークン

答えて

1

を持っている期待

はここでDjangoの残りFramework用のユーザログインのためのサンプルコードです:

class Login(APIView): 

    @csrf_exempt 
    def dispatch(self, *args, **kwargs): 
     return super(Login, self).dispatch(*args, **kwargs) 

    @staticmethod 
    def post(request): 
     request_data = JSONParser().parse(request) 

     if 'email' in request_data and 'password' in request_data: 
      try: 
       validate_email(request_data['email']) 
      except ValidationError: 
       return JsonResponse({'result': 'E-mail is invalid'}, status=400) 

      user = authenticate(email=request_data['email'], password=request_data['password']) 

      if user is not None: 
       if user.is_active: 
        try: 
         token = Token.objects.get(user=user) 
        except Token.DoesNotExist: 
         token = Token.objects.create(user=user) 

        return JsonResponse({'result': 'success', 'token': token.key, 'id': user.id}, status=200) 

      return JsonResponse({'result': 'E-mail or password is incorrect'}, status=400) 

     return JsonResponse({'result': 'E-mail or password is empty'}, status=400) 

ここではDjangoのためのFBのログインコードのサンプルです残りのフレームワーク(私のテストプロジェクトから):

class FbLogin(APIView): 
    authentication_classes = (authentication.TokenAuthentication,) 
    permission_classes = (permissions.AllowAny,) 

    @csrf_exempt 
    def dispatch(self, *args, **kwargs): 
     return super(FbLogin, self).dispatch(*args, **kwargs) 

    @staticmethod 
    def post(request): 
     request_data = JSONParser().parse(request) 

     if 'access_token' in request_data: 
      response = requests.get(
       url='https://graph.facebook.com/v2.5/me/', 
       params={ 
        'access_token': request_data['access_token'], 
        'fields': 'email,first_name,last_name', 
       }, 
      ) 

      json_response = json.loads(response.text) 

      if 'error' not in json_response: 
       response_photo = requests.get(
        url='https://graph.facebook.com/v2.5/%s/picture' % json_response['id'], 
        params={ 
         'redirect': 'false', 
         'type': 'large', 
        }, 
       ) 
       response_photo_json = json.loads(response_photo.text) 

       response_friends = requests.get(
        url='https://graph.facebook.com/v2.5/me/friends/', 
        params={ 
         'access_token': request_data['access_token'], 
         'limit': 300, 
        }, 
       ) 

       generated_password = get_random_string(10, 'abcdefghijklmnopqrstuvwxyz') 
       try: 
        json_response_email = json_response['email'] 
       except: 
        first_name = json_response['first_name'].lower() 
        last_name = json_response['last_name'].lower() 
        id = json_response['id'] 
        json_response_email = first_name + last_name + id + '@facebook.com' 
       try: 
        current_user = User.objects.get(email=json_response_email) 
        current_user.set_password(generated_password) 
        current_user.save() 
       except User.DoesNotExist: 
        new_user = User.objects.create_user(email=json_response_email, 
                 password=generated_password) 

        new_user.provider_id = json_response['id'] 
        new_user.provider_type = 'facebook' 

        if 'first_name' in json_response: 
         new_user.first_name = json_response['first_name'] 

        if 'last_name' in json_response: 
         new_user.last_name = json_response['last_name'] 

        new_user.save() 

        photo_name = urlparse(response_photo_json['data']['url']).path.split('/')[-1].split('?')[-1] 
        photo_content = urllib.request.urlretrieve(response_photo_json['data']['url']) 

        new_user.profile_photo.save(photo_name, File(open(photo_content[0], 'rb')), save=True) 
       user = authenticate(email=json_response_email, password=generated_password) 
       try: 
        token = Token.objects.get(user=user) 
       except Token.DoesNotExist: 
        token = Token.objects.create(user=user) 
       if user is not None: 
        if user.is_active: 
          fullname = json_response['first_name'] + ' ' + json_response['last_name'] 
          return JsonResponse({'result': 'success', 'token': token.key, 'name': fullname}, status=200) 

      return JsonResponse({'result': 'User access token is incorrect'}, status=400)