OAuth for Flask

OAuth for Flask

3

Votes

""" Авторизация в Фласке посредством OAuth
"""

import json
from rauth import OAuth2Service
from flask import current_app, url_for, redirect, request


class OAuthSignIn(object):
    """ Общий класс с реализацией OAuth авторизации
    """

    providers = None

    def __init__(self, provider_name):
        self.provider_name = provider_name
        credentials = current_app.config["OAUTH_CREDENTIALS"][provider_name]
        self.consumer_id = credentials["id"]
        self.consumer_secret = credentials["secret"]

    def authorize(self):
        """ Заглушка которую переопределим в потомках
        """

    def callback(self):
        """ Заглушка которую переопределим в потомках
        """

    def get_callback_url(self):
        """ Возвращаем ссылку на callback функцию
        """

        return url_for(
            "users.oauth_callback", provider=self.provider_name, _external=True
        )

    @classmethod
    def get_provider(cls, provider_name):
        """ Выбор провайдера основываясь на существующих потомках

        Arguments:
            provider_name {[type]} -- Имя провайдера

        Returns:
            [type] -- Класс-потомок для нужного провайдера
        """

        if cls.providers is None:
            cls.providers = {}
            for provider_class in cls.__subclasses__():
                provider = provider_class()
                cls.providers[  # pylint: disable=E1137
                    provider.provider_name
                ] = provider # pylint: disable=C0303
        return cls.providers[provider_name]  # pylint: disable=E1136


class FacebookSignIn(OAuthSignIn):
    ''' OAuth аутентификация для Facebook
    '''

    def __init__(self):
        super(FacebookSignIn, self).__init__("facebook")


class TwitterSignIn(OAuthSignIn):
    ''' OAuth аутентификация для Twitter
    '''
    def __init__(self):
        super(TwitterSignIn, self).__init__("twitter")


class GoogleSignIn(OAuthSignIn):
    ''' OAuth аутентификация для Google
    '''
    def __init__(self):
        super(GoogleSignIn, self).__init__("google")
        self.service = OAuth2Service(
            name="google",
            client_id=self.consumer_id,
            client_secret=self.consumer_secret,
            access_token_url="https://accounts.google.com/o/oauth2/token",
            authorize_url="https://accounts.google.com/o/oauth2/auth",
            base_url=current_app.config["BASE_URI"],
        )

    def authorize(self):
        return redirect(
            self.service.get_authorize_url(
                scope="openid email profile",
                response_type="code",
                redirect_uri="http://127.0.0.1:5000/auth/callback/google",
            )
        )

    def callback(self):
        def decode_json(payload):
            return json.loads(payload.decode("utf-8"))

        if "code" not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
            data={
                "code": request.args["code"],
                "grant_type": "authorization_code",
                "redirect_uri": self.get_callback_url(),
            },
            decoder=decode_json,
        )
        profile = oauth_session.get(
            "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"
        ).json()
        return (profile["id"], profile["email"], profile["name"])

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote

Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

Advertise

DevOpsnipp.com © 2020

medium.png