コード例 #1
0
ファイル: views.py プロジェクト: tomreeveclark/MarkerBot
def callback_handling():

    code = request.args.get(CODE_KEY)
    get_token = GetToken(AUTH0_DOMAIN)
    auth0_users = Users(AUTH0_DOMAIN)
    token = get_token.authorization_code(AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET,
                                         code, AUTH0_CALLBACK_URL)
    user_info = auth0_users.userinfo(token['access_token'])
    session[PROFILE_KEY] = json.loads(user_info)
    # return user_info
    # extract data to register user on DB in order top track question set progress
    first_name = session['profile']['given_name']
    surname = session['profile']['family_name']
    try:
        email = session['profile']['email']
    except Exception as e:
        # log exception arup waad has email in nickname for some reason...

        email = session['profile']['nickname']
        if len(parseaddr(email)[1]) == 0:
            return 'unable to log you in, invalid email supplied'

    user = db.session.query(User).filter_by(first_name=first_name,
                                            surname=surname,
                                            email=email).first()

    # if user doesnt exist in db, add them
    if (user is None):
        user = User(first_name=first_name, surname=surname, email=email)
        db.session.add(user)
        db.session.commit()

    # add user id from DB to the session
    session['user_id'] = user.id
    return redirect('/index')
コード例 #2
0
def check_permissions():
    sub_key = f'{get_token_auth_header()}:sub'
    moderator_key = f'{get_token_auth_header()}:moderator'

    redis = Redis(host=current_app.config['REDIS_HOST'],
                  port=int(current_app.config['REDIS_PORT']),
                  db=0)

    sub = redis.get(sub_key)
    is_moderator = redis.get(moderator_key)

    if not sub or not is_moderator:
        a0_users = Users(current_app.config['AUTH0_DOMAIN'])
        a0_user = a0_users.userinfo(get_token_auth_header())

        sub = a0_user.get('sub')
        is_moderator = 0

        if a0_user.get(APP_METADATA_KEY):
            role = a0_user.get(APP_METADATA_KEY).get('role')
            if role == MODERATOR and \
                current_app.config.get('INDEX_NAME') in a0_user.get(APP_METADATA_KEY).get('services'):
                is_moderator = 1

        redis.set(sub_key, sub)
        redis.expire(sub_key, 60)
        redis.set(moderator_key, is_moderator)
        redis.expire(moderator_key, 60)

    return {
        'sub': sub.decode() if isinstance(sub, bytes) else sub,
        'is_moderator': True if int(is_moderator) == 1 else False
    }
コード例 #3
0
    def auth0_callback_view(self):  # pragma: no cover
        """This callback is called after a successful Auth0 login.

        Args:
            code(str): Auth0's authentication code.
        """

        # Check for errors
        error = request.args.get('error')
        if error:
            error_code = request.args.get('error_description')
            return redirect(
                url_for('regular.unauthorized', error_code=error_code))

        from auth0.v3.authentication import GetToken
        from auth0.v3.authentication import Users
        import json

        # Retrieve AUTH0 settings from the local settings file
        AUTH0_DOMAIN = current_app.config.get('AUTH0_DOMAIN', '')
        AUTH0_CLIENT_ID = current_app.config.get('AUTH0_CLIENT_ID', '')
        AUTH0_CLIENT_SECRET = current_app.config.get('AUTH0_CLIENT_SECRET', '')
        AUTH0_CALLBACK_URL = url_for('user.auth0_callback', _external=True)

        auth0_users = Users(AUTH0_DOMAIN)

        # Retrieve Auth0 code from the URL query parameters
        code = request.args.get('code')

        # Decode Auth0 code and extract the Auth0 Token
        get_token = GetToken(AUTH0_DOMAIN)
        token = get_token.authorization_code(AUTH0_CLIENT_ID,
                                             AUTH0_CLIENT_SECRET, code,
                                             AUTH0_CALLBACK_URL)

        # Retrieve user_info from AUTH0 token
        user_info_str = auth0_users.userinfo(token['access_token'])
        user_info = json.loads(user_info_str)
        email = user_info['email']
        email_verified = user_info['email_verified']

        # Retrieve User record by email
        user, user_email = self.db_manager.get_user_and_user_email_by_email(
            email)
        if not user:
            # Create new user if needed
            user = self.db_manager.add_user(
                email=email,
                active=True,
                first_name=user_info.get('given_name', ''),
                last_name=user_info.get('family_name', ''),
            )
            self.db_manager.commit()

        # Retrieve next URL from 'state' query param
        state = request.args.get('state', '/')
        safe_next_url = self.make_safe_url(state)

        # Log user in
        return self._do_login_user(user, safe_next_url)
コード例 #4
0
def callback_handling():
    code = request.args.get('code')
    get_token = GetToken(const['AUTH0_DOMAIN'])
    auth0_users = Users(const['AUTH0_DOMAIN'])
    token = get_token.authorization_code(const['AUTH0_CLIENT_ID'],
                                         const['AUTH0_CLIENT_SECRET'], code,
                                         const['AUTH0_CALLBACK_URL'])
    user_info = auth0_users.userinfo(token['access_token'])
    session['profile'] = json.loads(user_info)
    print('USER INFO')
    # check if user in db
    user = User.query.filter_by(email=session['profile']['email']).first()
    print('CHECK')
    if user is None:
        print('new user being added to db')
        userid = session['profile']["sub"]
        userid = userid[userid.index('|') + 1:len(userid)]
        new_user = User(userid, session['profile']['email'],
                        session['profile']['nickname'],
                        session['profile']['picture'])
        db.session.add(new_user)
        db.session.commit()
    else:
        print('old user')
    return redirect('/dashboard')
コード例 #5
0
def callback_handling():
    code = request.args.get('code')
    get_token = GetToken('manishsethis.auth0.com')
    auth0_users = Users('manishsethis.auth0.com')
    token = get_token.authorization_code(os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], code, 'http://localhost:5000/callback')
    user_info = auth0_users.userinfo(token['access_token'])
    session['profile'] = json.loads(user_info)
    return redirect('/dashboard')
コード例 #6
0
def callback_handling():
    code = request.args.get(constants.CODE_KEY)
    get_token = GetToken(AUTH0_DOMAIN)
    auth0_users = Users(AUTH0_DOMAIN)
    token = get_token.authorization_code(AUTH0_CLIENT_ID,
                                         AUTH0_CLIENT_SECRET, code, AUTH0_CALLBACK_URL)
    user_info = auth0_users.userinfo(token['access_token'])
    session[constants.PROFILE_KEY] = json.loads(user_info)
    return redirect('/dashboard')
コード例 #7
0
    def decorated(*args, **kwargs):
        token = get_token_auth_header()
        jsonurl = urlopen("https://" + AUTH0_DOMAIN + "/.well-known/jwks.json")
        jwks = json.loads(jsonurl.read())
        unverified_header = jwt.get_unverified_header(token)
        rsa_key = {}
        for key in jwks["keys"]:
            if key["kid"] == unverified_header["kid"]:
                rsa_key = {
                    "kty": key["kty"],
                    "kid": key["kid"],
                    "use": key["use"],
                    "n": key["n"],
                    "e": key["e"]
                }
        if rsa_key:
            try:
                payload = jwt.decode(token,
                                     rsa_key,
                                     algorithms=ALGORITHMS,
                                     audience=API_AUDIENCE,
                                     issuer="https://" + AUTH0_DOMAIN + "/")
            except jwt.ExpiredSignatureError:
                raise AuthError(
                    {
                        "code": "token_expired",
                        "description": "token is expired"
                    }, 401)
            except jwt.JWTClaimsError as e:
                print(e)
                raise AuthError(
                    {
                        "code":
                        "invalid_claims",
                        "description":
                        "incorrect claims,"
                        "please check the audience and issuer"
                    }, 401)
            except Exception:
                raise AuthError(
                    {
                        "code": "invalid_header",
                        "description": "Unable to parse authentication"
                        " token."
                    }, 401)

            _request_ctx_stack.top.current_user = payload
            users = Users(AUTH0_DOMAIN)
            user = users.userinfo(token)
            print(user)
            return f(*args, **kwargs)
        raise AuthError(
            {
                "code": "invalid_header",
                "description": "Unable to find appropriate key"
            }, 401)
コード例 #8
0
ファイル: auth.py プロジェクト: dokadzwirusem/backend
 def decorated(*args, **kwargs):
     try:
         app_metadata_key = 'https://koronapoints.netlify.com/app_metadata'
         a0_users = Users(current_app.config['AUTH0_DOMAIN'])
         a0_user = a0_users.userinfo(get_token_auth_header())
         user = {'sub': a0_user.get('sub')}
         if a0_user.get(app_metadata_key):
             user['role'] = a0_user.get(app_metadata_key).get('role')
     except Auth0Error:
         return redirect('login')
     return f(*args, **kwargs, user=user)
コード例 #9
0
ファイル: weblogin.py プロジェクト: rahulyhg/Kotlin-
def callback_handling():
    code = request.args.get('code')
    get_token = GetToken('abdul4343.eu.auth0.com')
    auth0_users = Users('abdul4343.eu.auth0.com')
    token = get_token.authorization_code(
        'xYbqBYbjcd2rS6o9Xb0HrLwQWHXu8jH1',
        'rZHMb64rreOI6j0umN8_ZHpcer4VuJbdVCUO3hEdB795kEadyp7GhNdw2Fy5lEFO',
        code, 'http://192.168.0.6:5000/callback')
    user_info = auth0_users.userinfo(token['access_token'])
    #session['profile'] = json.loads(user_info)
    print(json.loads(user_info))
    return json.loads(user_info)
コード例 #10
0
def callback_handling():

    code = request.args.get(CODE_KEY)
    get_token = GetToken(AUTH0_DOMAIN)
    auth0_users = Users(AUTH0_DOMAIN)
    token = get_token.authorization_code(AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET,
                                         code, AUTH0_CALLBACK_URL)
    user_info = auth0_users.userinfo(token['access_token'])
    session[PROFILE_KEY] = json.loads(user_info)
    # return user_info
    # extract data to register user on DB in order top track question set progress
    register_user()

    return redirect('/index')
コード例 #11
0
def do_get_token():
    get_token = GetToken(AUTH0_DOMAIN)
    result = get_token.login(client_id=CLIENT_ID,
                             client_secret=CLIENT_SECRET,
                             username=HC_USER_USERNAME,
                             password=HC_USER_PASSWORD,
                             scope='openid email profile',
                             realm='healthcheck-users',
                             audience='')

    del result['id_token']  # we don't need this - just mucks up console output
    print("Token result: ", result)

    users = Users(AUTH0_DOMAIN)
    user_info = users.userinfo(result['access_token'])
    print("User info: ", user_info)
コード例 #12
0
ファイル: views.py プロジェクト: skeeph/histmap
def callback(request):
    """
    Auth0 callback view
    """
    code = request.GET['code']
    get_token = GetToken(settings.AUTH0_DOMAIN)
    auth0_users = Users(settings.AUTH0_DOMAIN)
    token = get_token.authorization_code(settings.AUTH0_CLIENT_ID,
                                         settings.AUTH0_SECRET, code,
                                         settings.AUTH0_CALLBACK_URL)
    user_info = auth0_users.userinfo(token['access_token'])
    uinfo = json.loads(user_info)
    request.session['profile'] = uinfo
    user = authenticate(**uinfo)
    if user:
        do_login(request, user)
    return redirect(reverse_lazy("users:profile"))
コード例 #13
0
def callback_handling():
    error = request.args.get('error')
    if error is None:
        code = request.args.get('code')
        redirect_url = request.args.get('redirectto')
        if redirect_url is None:
            redirect_url = '/'
        get_token = GetToken(AUTH0_DOMAIN)
        auth0_users = Users(AUTH0_DOMAIN)
        token = get_token.authorization_code(AUTH0_CLIENT_ID,
                                             AUTH0_CLIENT_SECRET,
                                             code, AUTH0_CALLBACK_URL)
        user_info = auth0_users.userinfo(token['access_token'])
        session['profile'] = json.loads(user_info)
        return redirect(redirect_url)
    else:
        error_msg = request.args.get('error_description')
        return f'<h1>{error}</h1><p>{error_msg}<p>', 401
コード例 #14
0
def auth0_callback(request):
    code = request.GET.get('code')
    get_token = GetToken('techjargon.auth0.com')
    auth0_users = Users('techjargon.auth0.com')
    # token = get_token.authorization_code('QADeAHqjls_NxG6lnY_MQiqJ2wErFUpx', '00I5NqJtwLDZBBUBXQLTYLL195BvPMDZ3uFqc6OcnunuOsyuYvI7cCQ0tORWre4a', code, 'http://techjargon-dev.fidenz.info/authors/callback/')
    token = get_token.authorization_code(settings.AUTH_0['CLIENT_ID'],
                                         settings.AUTH_0['CLIENT_SECRET'],
                                         code, settings.AUTH_0['CALLBACK_URL'])
    user_info = auth0_users.userinfo(token['access_token'])
    user = json.loads(user_info)
    # request.session['profile'] = user
    flag, message = __check_n_register(user)
    if flag:
        _user = User.objects.get(email=user['email'])
        _user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, _user)
        return redirect('/')
    else:
        return redirect('/authors/signin/')
コード例 #15
0
    def get(self):
        code = self.get_argument("code")
        get_token = GetToken(AUTH0_DOMAIN)
        auth0_users = Users(AUTH0_DOMAIN)

        url = "https://finnalyst.auth0.com/oauth/token"
        headers = {'Content-type': 'application/x-www-form-urlencoded'}
        data = {
            "client_id": AUTH0_CLIENT_ID,
            "redirect_uri": "http://54.153.126.234:8888/static/index.html",
            "client_secret": AUTH0_CLIENT_SECRET,
            "code": code,
            "grant_type": 'authorization_code',
        }
        r = requests.post(url, data=json.dumps(data), headers=headers)
        print(r.json())
        # token = get_token.authorization_code(AUTH0_CLIENT_ID,
        #                                      AUTH0_CLIENT_SECRET, code, AUTH0_CALLBACK_URL)
        # print(token)
        # user_info = auth0_users.userinfo(token['access_token'])
        # session[constants.PROFILE_KEY] = json.loads(user_info)
        return self.redirect('/static/index.html')
コード例 #16
0
ファイル: server.py プロジェクト: rmeyers/roi_prototype
def callback_handling():
    code = request.args.get(constants.CODE_KEY)

    if code is None:
        return redirect('/')

    get_token = GetToken(AUTH0_DOMAIN)
    auth0_users = Users(AUTH0_DOMAIN)
    token = get_token.authorization_code(AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET,
                                         code, AUTH0_CALLBACK_URL)
    access_token = token['access_token']
    user_info = json.loads(auth0_users.userinfo(access_token))

    # Check that the access token is valid.
    url = ('https://capextool.auth0.com/userinfo/?access_token=%s' %
           access_token)
    # Submit request, parse response
    h = httplib2.Http()
    response = h.request(url, 'GET')[1]
    str_response = response.decode('utf-8')
    result = json.loads(str_response)

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    auth0Id = user_info['sub']
    if result['sub'] != auth0Id:
        response = make_response(
            json.dumps("Token's sub doesn't match sub from cURL."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # # Verify that the access token is valid for this app.
    # if result['issued_to'] != CLIENT_ID:
    #     response = make_response(
    #         json.dumps("Token's client ID does not match app's."), 401)
    #     response.headers['Content-Type'] = 'application/json'
    #     return response

    stored_access_token = login_session.get('access_token')
    stored_sub = login_session.get('profile', {}).get('sub')
    if stored_access_token is not None and auth0Id == stored_sub:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Add user info
    login_session[constants.PROFILE_KEY] = user_info

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(login_session['profile']['name'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    flash("you are now logged in under %s" % login_session['profile']['name'])

    return redirect('/user/%s/dashboard' % user_id)
コード例 #17
0
def get_user_info(access_token):
    '''Given an auth token, requests the user info'''
    auth0_users = Users(DOMAIN)
    user_info_str = auth0_users.userinfo(access_token)
    # e.g. '{"sub":"github|12345","email":"*****@*****.**","email_verified":true}''
    return json.loads(user_info_str)
コード例 #18
0
from auth0.v3.exceptions import Auth0Error
from flask import Flask
from flask import redirect
from flask import render_template
from flask import session

import config
from config import AUTH0_CLIENT_ID, AUTH0_CONNECTION, AUTH0_DOMAIN, SESSION_PROFILE_KEY
from forms import LoginForm, SignupForm
from utils import safe_auth0_call

APP = Flask(__name__)
APP.config.from_object(config)

auth0_db = Database(AUTH0_DOMAIN)
auth0_users = Users(AUTH0_DOMAIN)


def requires_auth(f):
    """Decorator to check whether the user is logged in. Redirect to login page if not."""

    @wraps(f)
    def wrapper(*args, **kwargs):
        if SESSION_PROFILE_KEY not in session:
            return redirect('/login')
        return f(*args, **kwargs)

    return wrapper


@APP.route('/')