Exemplo n.º 1
0
def facebook_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in.", category="error")
        return False

    resp = blueprint.session.get("/me")
    if not resp.ok:
        msg = "Failed to fetch user info."
        flash(msg, category="error")
        return False

    info = resp.json()
    user_id = info["id"]

    # Find this OAuth token in the database, or create it
    query = OAuth.query.filter_by(provider=blueprint.name,
                                  provider_user_id=user_id)
    try:
        oauth = query.one()
    except NoResultFound:
        oauth = OAuth(provider=blueprint.name,
                      provider_user_id=user_id,
                      token=token)

    if oauth.user:
        login_user(oauth.user)
        flash("Successfully signed in.")

    else:
        # Create a new local user account for this user
        user = User(name=info["name"])
        # Associate the new local user account with the OAuth token
        oauth.user = user
        # Save and commit our database models
        db.session.add_all([user, oauth])
        db.session.commit()

        new_profile = Profile(user_id=user.id)
        db.session.add(new_profile)
        db.session.commit()
        # Log in the new local user account
        login_user(user)
        flash("Successfully signed in.")

    # Disable Flask-Dance's default behavior for saving the OAuth token
    token_query = Token.query.filter_by(user_id=current_user.id)
    try:
        token = token_query.one()
    except NoResultFound:
        token = Token(user_id=current_user.id, uuid=str(uuid.uuid4().hex))
        db.session.add(token)
        db.session.commit()
    return redirect("http://localhost:3000/?api_key={}".format(token.uuid))
Exemplo n.º 2
0
def google_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in.", category="error")
        return False

    resp = blueprint.session.get("/oauth2/v2/userinfo")
    if not resp.ok:
        msg = "Failed to fetch user info."
        flash(msg, category="error")
        return False

    google_info = resp.json()
    google_user_id = google_info["id"]

    # Find this OAuth token in the database, or create it
    query = OAuth.query.filter_by(
        provider=blueprint.name,
        provider_user_id=google_user_id,
    )
    try:
        oauth = query.one()
    except NoResultFound:
        google_user_login = str(google_info["email"])
        oauth = OAuth(
            provider=blueprint.name,
            provider_user_id=google_user_id,
            provider_user_login=google_user_login,
            token=token,
        )

    if oauth.user:
        login_user(oauth.user)
        flash("Successfully signed in.")

    else:
        # Create a new local user account for this user
        user = User(username=google_info["email"])
        # Associate the new local user account with the OAuth token
        oauth.user = user
        # Save and commit our database models
        db.session.add_all([user, oauth])
        db.session.commit()
        # Log in the new local user account
        login_user(user)
        flash("Successfully signed in.")

    # Disable Flask-Dance's default behavior for saving the OAuth token
    return False
Exemplo n.º 3
0
def google_authorized(blueprint, token):
    if not token:
        msg = "Failed to log in with Google."
        flash(msg, category="danger")
        return redirect(url_for('login'))

    resp = blueprint.session.get("/oauth2/v1/userinfo")
    if not resp.ok:
        msg = "Failed to fetch user info from Google."
        flash(msg, category="danger")
        return redirect(url_for('login'))

    google_info = resp.json()
    google_user_id = str(google_info["id"])

    query = OAuth.query.filter_by(
        provider=blueprint.name,
        provider_user_id=google_user_id,
    )

    try:
        oauth = query.one()
    except NoResultFound:
        oauth = OAuth(
            provider=blueprint.name,
            provider_user_id=google_user_id,
            token=token,
        )

    if oauth.user:
        login_user(oauth.user)
    else:
        user = User(
            username=google_info["email"],
            name=google_info["name"],
        )
        oauth.user = user
        db.session.add_all([user, oauth])
        db.session.commit()
        login_user(user)

    flash("Successfully signed in with Google.", category="success")
    return redirect(url_for('dashboard'))
Exemplo n.º 4
0
def user(db_session):
    u = User(email="*****@*****.**", active=True)
    oauth = OAuth(
        user=u,
        provider="google",
        provider_user_id="12345",
        token={"access_token": GOOGLE_ACCESS_TOKEN},
    )
    db_session.add_all([u, oauth])
    db_session.commit()
    return u
def user(db_session):
    u = User(email="*****@*****.**")
    oauth = OAuth(
        user=u,
        provider="heroku",
        provider_user_id="12345",
        token={"access_token": HEROKU_ACCESS_TOKEN},
    )
    db_session.add_all([u, oauth])
    db_session.commit()
    return u
Exemplo n.º 6
0
def google_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with Google.", category="error")
        return False

    resp = blueprint.session.get("/oauth2/v2/userinfo")
    if not resp.ok:
        msg = "Failed to fetch user info from Google."
        flash(msg, category="error")
        return False

    google_info = resp.json()
    google_user_id = str(google_info['id'])

    # Find this OAuth token in the database, or create it
    query = OAuth.query.filter_by(
        provider=blueprint.name,
        provider_user_id=google_user_id,
    )
    try:
        oauth = query.one()
    except NoResultFound:
        oauth = OAuth(
            provider=blueprint.name,
            provider_user_id=google_user_id,
            token=token,
        )

    if oauth.user:
        login_user(oauth.user)
        flash("Successfully signed in with Google.")
    else:
        # Create a new user
        user = User(username=google_info['email'])
        oauth.user = user
        db.session.add_all([user, oauth])
        db.session.commit()
        login_user(user)
        flash("Successfully created a new account using Google.")

    return False
Exemplo n.º 7
0
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with GitHub.", category="error")
        return False

    account_info = blueprint.session.get('/user')
    if not account_info.ok:
        msg = "Failed to fetch user info from GitHub."
        flash(msg, category="error")
        return False
    github_info = account_info.json()

    # Find this OAuth token in the database, or create it
    query = OAuth.query.filter_by(provider=blueprint.name)
    try:
        oauth = query.one()
    except NoResultFound:
        oauth = OAuth(
            provider=blueprint.name,
            token=token,
        )
    if oauth.user:
        login_user(oauth.user)
        flash("Successfully signed in with GitHub.")

    else:
        user = User(
            # Remember that `email` can be None, if the user declines
            # to publish their email address on GitHub!
            email=github_info["email"],
            username=github_info["name"],
            image_file=github_info["avatar_url"],
        )
        oauth.user = user
        db.session.add_all([user, oauth])
        db.session.commit()
        login_user(user)
        flash("Successfully signed in with GitHub.")
    return False
def test_oauth_login_user(db_session, app, blueprint, google_access_token):
    token = {"access_token": google_access_token}

    user = User(email="*****@*****.**", active=True)
    oauth = OAuth(
        user=user,
        provider="google",
        provider_user_id="106473082171117460211",
        token=token,
    )
    db_session.add_all([user, oauth])
    db_session.commit()
    assert User.query.count() == 1
    assert OAuth.query.count() == 1

    with app.test_request_context("/login/google/authorized"):
        returned = google_logged_in(blueprint, token)
        logged_in_uid = flask.session.get("user_id")

    assert returned is False
    # counts are unchanged
    assert User.query.count() == 1
    assert OAuth.query.count() == 1
    assert logged_in_uid == str(user.id)
Exemplo n.º 9
0
def test_oauth_login_user(db_session, app, blueprint, heroku_access_token):
    token = {"access_token": heroku_access_token}

    user = User(email="*****@*****.**")
    oauth = OAuth(
        user=user,
        provider="heroku",
        provider_user_id="e0292023-c34c-4008-acc8-28186d597d63",
        token=token,
    )
    db_session.add_all([user, oauth])
    db_session.commit()
    assert User.query.count() == 1
    assert OAuth.query.count() == 1

    with app.test_request_context("/login/heroku/authorized"):
        returned = heroku_logged_in(blueprint, token)
        logged_in_uid = flask.session.get("user_id")

    assert returned is False
    # counts are unchanged
    assert User.query.count() == 1
    assert OAuth.query.count() == 1
    assert logged_in_uid == str(user.id)
Exemplo n.º 10
0
def oauth(provider):
    """
    This route authenticates the user by receiving a provider
    and oauth token and verifying a user exists. When a user logs
    in new jwt tokens cookies will be set in the response.

    Args {string} provider - facebook or google

    Returns {Object<json>} 200
            success: {string}
            user: {Object<json>}

    Throws {Exception{Object<json}}:
            error: Authorization 401
                   NoResultFound 401
                   SQLAlchemyError 400
                   MissingUser 400
                   InactiveUser 400
    """
    # If no authorization header, return error
    if not request.headers.get('Authorization'):
        return jsonify({'error': 'Not a valid request'}), 401

    # Get the token from authorization header and convert to dictionary
    token = request.headers.get('Authorization').split('Bearer ')[1]
    token = json.loads(token)

    # Try to find oauth user in database
    query = OAuth.query.filter_by(
        provider=provider,
        provider_uid=token['userID'],
    )

    try:
        oauth = query.first()

    # If no result found, return error
    except NoResultFound:
        return jsonify(
            {'error':
             "The user doesn't exist. Sign up to create an account"}), 404

    # If some other sqlalchemy error is thrown, return error
    except SQLAlchemyError:
        return jsonify({'error': 'Some problem occurred!'}), 400

    # If not oauth create a new user
    if not oauth:

        # Get user data from request
        data = request.get_json()

        # If name or email is missing, return error
        if not (data['name'] or not data['email'] or not data['picture']
                or not data['provider_user_id']):
            return make_response(jsonify({'error': 'Missing data!'}), 400)

        # Create user object
        user = User(name=data['name'],
                    email=data['email'],
                    picture=data['picture'],
                    created_at=datetime.utcnow())

        user.generate_public_id()

        # Try to add user to database
        try:
            db.session.add(user)
            db.session.commit()

        # If username already in database, return error
        except IntegrityError:
            return jsonify({'error':
                            'User with name or email already exists'}), 400

        # If some other sqlalchemy error is thrown, return error
        except SQLAlchemyError:
            return jsonify({'error': 'Some problem occurred!'}), 400

        # Create new oauth token account for user
        oauth = OAuth(
            provider=provider,
            provider_uid=data['provider_user_id'],
            token=token,
        )

        # Associate the new local user account with the OAuth token
        oauth.user = user

        # Save and commit database models
        db.session.add(oauth)
        db.session.commit()

    # If there is no user relation, return error
    if not oauth.user:
        return jsonify({'error': 'Some problem occurred!'}), 400

    user = oauth.user

    # Serialze the user object
    user_schema = UserSchema()
    output = user_schema.dump(user).data

    # Create the tokens to be sent to the user
    expires = timedelta(seconds=1800)
    access_token = create_access_token(identity=user.public_id,
                                       expires_delta=expires)
    refresh_token = create_refresh_token(identity=user.public_id)

    # Get the csrf tokens so they can be set as headers in response
    csrf_access_token = get_csrf_token(access_token)
    csrf_refresh_token = get_csrf_token(refresh_token)

    # Create json response
    response = make_response(
        jsonify({
            'user': output,
            'success': 'Login successful!'
        }), 200)

    # Set JWT cookies and headers and return response
    set_access_cookies(response, access_token)
    set_refresh_cookies(response, refresh_token)
    response.set_cookie('public_id', user.public_id)
    response.headers['access'] = csrf_access_token
    response.headers['refresh'] = csrf_refresh_token

    return response
Exemplo n.º 11
0
def orcid_logged_in(orcid_blueprint, token):
    """
    Handles the oauth dance for ORCID logins
    Args:
      orchid_blueprint: The instantiated orcid blueprint
      token: the ouath token
    Result:
      Will do one of four things:

      1. If user is not logged in, but there is an oauth, will login
      2. If user is not logged in, will create a new user using information from orchid, and login
      3. If a user is logged in, and oauth is associated already, will pass through
      4. If a user is logged in, but no oauth associated, will associate the oauth


    """
    # Check if I have an API token

    if not token:
        flash("Failed to log in.", category="error")
        return False

    # get the orcid id information
    # ORCID API calls require that the orcid id be in the request, so that needs
    # to be extracted from the token prior to making any requests
    orcid_user_id = token['orcid']

    response = orcid_blueprint.session.get("{}/record".format(orcid_user_id))

    if not response.ok:
        flash("Failed to get ORCID User Data", category="error")
        return False

    orcid_record = response.json()
    pprint(orcid_record)

    # Find this OAuth in the
    query = OAuth.query.filter_by(provider=orcid_blueprint.name,
                                  provider_user_id=orcid_user_id)
    try:
        oauth = query.one()
    except NoResultFound:
        oauth = OAuth(provider=orcid_blueprint.name,
                      provider_user_id=orcid_user_id,
                      provider_user_login=orcid_user_id,
                      token=token)

    if current_user.is_anonymous:
        print("Current user is anonymous")
        if oauth.user:
            # Case 1 (above)
            return current_app.user_manager._do_login_user(
                oauth.user, url_for("main.public"))
        else:
            # Case 2 (above)
            print("!!! No Oauth")
            orcid_person = orcid_record['person']

            # check if there is a user with this email address
            # Check to see if the ORCID user has an email exposed, otherwise, we cannot use it

            if len(orcid_person['emails']['email']) == 0:
                flash(
                    Markup(
                        "Failed to create new user, must have at least one ORCID "
                        "email address accessible to restricted. Please login to your "
                        "ORCID account at http://orcid.org and update your permissions."
                        " Please see <a href='https://support.orcid.org/hc/en-us/articles/360006897614'>"
                        " Visibitility in ORCID</a> "
                        "for more information."))
                return redirect(url_for("user.login"))
                return False

            orcid_email = orcid_person['emails']['email'][0]['email']

            query = User.query.filter_by(email=orcid_email)
            try:
                nrc_u = query.one()
                oauth.user = nrc_u
                db.session.add(oauth)
                db.session.commit()
                login_user(oauth.user)

            except NoResultFound:
                print("!!!! we need to make an account")
                # Case 3
                try:
                    user = User(
                        email=orcid_person['emails']['email'][0]['email'],
                        full_name="{} {}".format(
                            orcid_person['name']['given-names']['value'],
                            orcid_person['name']['family-name']['value']),
                        active=True,
                        email_confirmed_at=datetime.utcnow(),
                    )

                    user.add_role("member")
                    user.add_role("registered-orcid", add_to_roles=True)

                    oauth.user = user

                    db.session.add_all([user, oauth])
                    db.session.commit()
                    ## Need to use private method to bypass in this case
                    flash(
                        "Please update your Profile affiliation and affiliation type"
                    )
                    return current_app.user_manager._do_login_user(
                        user, url_for('profile.current_user_profile_page'))
                except Exception as e:
                    flash(
                        "There was an error creating a user from the ORCID credentials: {}"
                        .format(e))
                    return redirect(url_for("user.login"))
    else:
        print("!!! Authenticated User")
        if oauth.user:
            flash(
                "Account already associated with another user, cannot be associated"
            )
            return redirect(url_for('profile.current_user_profile_page'))
        else:
            # Case 4 (above)
            print("!!! SHOULD BE HERE")
            oauth.user = current_user
            db.session.add(oauth)
            db.session.commit()
            flash("Successfully linked ORCID account")

    return False
def google_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with Google.", category="error")
        return

    resp = blueprint.session.get("/oauth2/v2/userinfo")
    if not resp.ok:
        msg = "Failed to fetch user info from Google."
        flash(msg, category="error")
        return

    google_info = resp.json()
    google_user_id = str(google_info["id"])

    # Find this OAuth token in the database, or create it
    query = OAuth.query.filter_by(
        provider=blueprint.name, provider_user_id=google_user_id
    )
    try:
        oauth = query.one()
    except NoResultFound:
        google_user_login = str(google_info["email"])
        oauth = OAuth(
            provider=blueprint.name,
            provider_user_id=google_user_id,
            provider_user_login=google_user_login,
            token=token,
        )

    # Now, figure out what to do with this token. There are 2x2 options:
    # user login state and token link state.

    if current_user.is_anonymous:
        if oauth.user:
            # If the user is not logged in and the token is linked,
            # log the user into the linked user account
            login_user(oauth.user)
            flash("Successfully signed in with Google.")
        else:
            # If the user is not logged in and the token is unlinked,
            # create a new local user account and log that account in.
            # This means that one person can make multiple accounts, but it's
            # OK because they can merge those accounts later.
            user = User(username=google_info["email"])
            oauth.user = user
            db.session.add_all([user, oauth])
            db.session.commit()
            login_user(user)
            flash("Successfully signed in with Google.")
    else:
        if oauth.user:
            # If the user is logged in and the token is linked, check if these
            # accounts are the same!
            if current_user != oauth.user:
                # Account collision! Ask user if they want to merge accounts.
                url = url_for("auth.merge", username=oauth.user.username)
                return redirect(url)
        else:
            # If the user is logged in and the token is unlinked,
            # link the token to the current user
            oauth.user = current_user
            db.session.add(oauth)
            db.session.commit()
            flash("Successfully linked Google account.")

    # Indicate that the backend shouldn't manage creating the OAuth object
    # in the database, since we've already done so!
    return False
Exemplo n.º 13
0
def app_login():
    """
    .. :quickref: OAuth; Login

    Login

    :return: JSON

    **Example request**:

        .. sourcecode:: http

            GET /API/App/login HTTP/1.1
            Host: inthenou.uprm.edu
            Accept: application/json

    **Body of Request**:

        .. code-block:: json

            {
                "access_token":"test_Token",
                "id":"113768707919850641968",
                "email":"*****@*****.**",
                "display_name":"Jonathan X Santiago Gonzalez"
            }

    **Example response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK
            Vary: Accept
            Content-Type: text/javascript

            {
                "uid": "11"
            }

    :resheader Content-Type: application/json
    :resheader Set-Cookie: Sets the "Session" header in the user's cookies.
    :statuscode 201: User Created
    :statuscode 403: User with that email exists
    """
    if request.method == 'POST':
        info = request.json
        user_usub = info["id"]
        query = User.query.filter_by(provider=user_usub)
        try:
            user = query.one()

        except NoResultFound:
            token = str(datetime.now())  # today's datetime
            cookie = base64.b64encode(bytes(token, 'utf-8'))
            cookie = str(cookie)[2:-1]
            return ({"Token": (cookie)}), 200

        query = OAuth.query.filter_by(token=info['access_token'],
                                      id=user.id,
                                      user=user)
        try:
            oauth = query.one()
        except NoResultFound:
            oauth = OAuth(token=info['access_token'],
                          id=user.id,
                          user=user,
                          provider="google")
            db.session.add_all([oauth])
            db.session.commit()
        login_user(oauth.user)
        session['token'] = info['access_token']
        flash("Successfully signed in.")
        # sessionDict = str(session)[20:-1]
        # # print(sessionDict)
        # # {'_fresh': True, '_id': '934028cbba09af9ef6c35734f503a02c84a5f9d54e92c85bd1b3c7b0eb9167791a93fe9cf0a6a57c1af31d4d319031a244a2514124fa970b7ebb39d06249737f', '_user_id': '2', 'token': 'ya29.a0Ae4lvC25jHQPYb40hlyWPdxeVpgE8lPKEhYURwbfNkWdfO-4z4joM3zZByq1UlFdXbjt5y40-qYGy3lClOL6ffCyWRIYIBfgbia-vKBpA5Aspd5LNNIueAJI-zlO04k-vPHYUxmP2r3imNF33avaI3Xe0-3jSS-yOrNV"}
        # cookie = encodeFlaskCookie(secret_key=os.getenv(
        #     "FLASK_SECRET_KEY"), cookieDict=sessionDict)
        # # print(cookie)
        # session['cookys'] = cookie
        # # print(decodeFlaskCookie(secret_key=os.getenv("FLASK_SECRET_KEY"), cookieValue=cookie))

        response = make_response({"uid": str(user.id)})

        response.headers['Session'] = str(session)

        return (response)
    else:
        return jsonify(Error="Method not allowed."), 405
def google_logged_in(google_blueprint, token):

  ## Check if I have an API token
  if not token:
    flash("Failed to log in.", category="error")
    return False

  ## Get this blueprints session
  response = google_blueprint.session.get("/oauth2/v2/userinfo")

  if not response.ok:
    flash("Failed to fetch the user info from session", category="error")
    return False

  google_info = response.json()
  google_user_id = google_info["id"]

  # Find this OAuth token in the database, or create it
  query = OAuth.query.filter_by(
    provider=google_blueprint.name, provider_user_id=google_user_id
  )
  try:
    oauth = query.one()
  except NoResultFound:
    google_user_login = str(google_info["email"])
    oauth = OAuth(
      provider=google_blueprint.name,
      provider_user_id=google_user_id,
      provider_user_login=google_user_login,
      token=token,
    )

  if current_user.is_anonymous:
    if oauth.user:
      login_user(oauth.user)
      flash("Successfully logged in through Google")
    else:
      ### No user, so create a user
      user = User(email=google_info['email'],
                  first_name=google_info['given_name'],
                  last_name=google_info['family_name'],
                  active=True,
                  email_confirmed_at=datetime.utcnow())
      ### make the user a member
      user.roles.append(Role.query.filter(Role.name=="member").first())
      oauth.user = user

      db.session.add_all([user,oauth])
      db.session.commit()

      login_user(user)
      flash("Successfully signed in with Google.")
  else:
    if oauth.user:
      flash("Account already associated with another user")

    else:
      oauth.user = current_user
      db.session.add(oauth)
      db.session.commit()
      flash("Successfully linked to Google Account")

  return False
Exemplo n.º 15
0
def signup():
    """
    .. :quickref: OAuth; Signup

    Signup
    Uses :func:`~app.TagHandler.TagHandler.batchSetUserTags` as well as
    :func:`~app.UserHandler.UserHandler.getUserByID`

    :return: JSON

    **Example request**:

        .. sourcecode:: http

            GET /API/App/signup HTTP/1.1
            Host: inthenou.uprm.edu
            Accept: application/json

    **Body of Request**:

        .. code-block:: json

            {
                "access_token":"test_Token",
                "id":"113768707919850641968",
                "email":"*****@*****.**",
                "display_name":"Jonathan X Santiago Gonzalez",
                "tags":[
                    {"tid":1,"tname":"ADMI","tagweight":0},
                    {"tid":2,"tname":"ADOF","tagweight":0},
                    {"tid":3,"tname":"AGRO","tagweight":0},
                    {"tid":4,"tname":"ALEM","tagweight":0},
                    {"tid":5,"tname":"ANTR","tagweight":0}
                ]
            }

    **Example response**:

        .. sourcecode:: http

            HTTP/1.1 403 FORBIDDEN
            Vary: Accept
            Content-Type: text/javascript

            {
                "Error": "User with that email exists <User 11>"
            }

    :resheader Content-Type: application/json
    :statuscode 201: User Created
    :statuscode 403: User with that email exists
    """
    if request.method == 'POST':

        if not request.json:
            return jsonify(Error="No JSON provided."), 400
        info = request.json
        local = {}
        for key in info:
            if key in SIGNUPKEYS:
                local[key] = info[key]

        for key in SIGNUPKEYS:
            if key not in local:
                return jsonify(Error="Missing input parameter: " + str(key))

        user_usub = local["id"]
        query = User.query.filter_by(provider=user_usub)

        try:
            user = query.one()
            return jsonify(Error="User with that email exists " +
                           str(user)), 403
        except NoResultFound:
            # Create account for new user
            print("User being created")
            user = User(
                email=local["email"],
                provider=user_usub,
                display_name=local["display_name"],
                user_type="Student",
                user_role=int(1),
                role_issuer=int(1),
            )
            if (user):
                db.session.add_all([user])
                db.session.commit()

            query = OAuth.query.filter_by(token=local['access_token'],
                                          id=user.id,
                                          user=user)

            try:
                oauth = query.one()
            except NoResultFound:
                oauth = OAuth(token=local['access_token'],
                              id=user.id,
                              user=user,
                              provider="google")
                db.session.add_all([oauth])
                db.session.commit()
                login_user(oauth.user)
                info['uid'] = int(current_user.id)
                print("Registering tags : " + str(local["tags"]))

                tags = TagHandler().batchSetUserTags(uid=user.id,
                                                     json=info,
                                                     weight=100,
                                                     no_json=True)
                tags['User'] = UserHandler().getUserByID(current_user.id,
                                                         no_json=True)
            return (tags), 201
    else:
        return jsonify(Error="Method not allowed."), 405
Exemplo n.º 16
0
def dashboard_login():
    """
    .. :quickref: OAuth;  Dashboard Login

    Dashboard Login

    :return: JSON

    **Example request**:

        .. sourcecode:: http

            GET /API/Dashboard/login HTTP/1.1
            Host: inthenou.uprm.edu
            Accept: application/json

    **Body of Request**:

        .. code-block:: json

            {
                "access_token":"test_Token",
                "id":"113768707919850641968",
                "email":"*****@*****.**",
                "display_name":"Jonathan X Santiago Gonzalez"
            }

    **Example response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK
            Vary: Accept
            Content-Type: text/javascript

            {
                "uid": "11"
            }

    :resheader Content-Type: application/json
    :resheader Set-Cookie: Sets the "Session" header in the user's cookies.
    :statuscode 200: User logged in 
    :statuscode 404: User not found
    :statuscode 401: User does not have permission to login 
    """
    if request.method == 'POST':
        info = request.json
        user_usub = info["id"]
        query = User.query.filter_by(provider=user_usub)
        try:
            user = query.one()

        except NoResultFound:
            return jsonify(Error="User not found, try signing up "), 404

        if user.user_role > 2:
            query = OAuth.query.filter_by(token=info['access_token'],
                                          id=user.id,
                                          user=user)
        else:
            return jsonify(
                Error="User does not have permission to login "), 401
        try:
            oauth = query.one()
        except NoResultFound:
            oauth = OAuth(token=info['access_token'],
                          id=user.id,
                          user=user,
                          provider="google")
            db.session.add_all([oauth])
            db.session.commit()
        login_user(oauth.user)
        session['token'] = info['access_token']
        flash("Successfully signed in.")
        response = make_response({"uid": str(user.id)})

        response.headers['Session'] = str(session)

        return (response)

    else:
        return jsonify(Error="Method not allowed."), 405
Exemplo n.º 17
0
def google_logged_in(blueprint, token):
    """Log in user on successful Google authorization."""
    # If user doesn't have valid oauth token, flash error
    if not token:
        flash("Failed to log in {name}".format(name=blueprint.name))
        return

    # Get user data from oauth session
    resp = blueprint.session.get("/oauth2/v2/userinfo")

    # If failed to get data, flash error
    if not resp.ok:
        msg = "Failed to fetch user info from {name}.".format(
            name=blueprint.name)
        flash(msg, category="error")
        return False

    # Setup query
    user_info = resp.json()
    user_id = str(user_info["id"])
    query = OAuth.query.filter_by(
        provider=blueprint.name,
        provider_user_id=user_id,
    )

    # Try to find oauth user in database
    try:
        oauth = query.one()

    # If no result found, create new oauth token account for user
    except NoResultFound:
        oauth = OAuth(
            provider=blueprint.name,
            provider_user_id=user_id,
            token=token,
        )

    # If query successful, log in user
    if oauth.user:
        login_user(oauth.user)
        flash(
            "Successfully signed in with {name}.".format(name=blueprint.name))

    # If query not successful, create new user then log in user
    else:
        # Create a new local user account for this user
        user = User(name=user_info['name'],
                    email=user_info['email'],
                    picture=user_info['picture'])
        user.generate_public_id()

        # Associate the new local user account with the OAuth token account
        oauth.user = user

        # Save and commit database models
        db.session.add_all([user, oauth])
        db.session.commit()

        # Log in the new local user account
        login_user(user)
        flash(
            "Successfully signed in with {name}.".format(name=blueprint.name))

    # Create the tokens to be sent to the user
    expires = timedelta(seconds=20)
    access_token = create_access_token(identity=current_user.public_id,
                                       expires_delta=expires)
    refresh_token = create_refresh_token(identity=current_user.public_id)

    # Set JWT cookies in the response and
    # redirect user to the home page
    response = make_response(redirect(url_for('site.index')))
    set_access_cookies(response, access_token)
    set_refresh_cookies(response, refresh_token)
    response.set_cookie('public_id', current_user.public_id)

    return response
def orcid_logged_in(orcid_blueprint, token):

  ## Check if I have an API token

  if not token:
    flash("Failed to log in.", category="error")
    return False

  print(token.items())

  ## get the orcid id information
  ## ORCID API calls require that the orcid id be in the request, so that needs
  ## to be extracted from the token prior to making any requests
  orcid_user_id = token['orcid']

  response = orcid_blueprint.session.get("{}/record".format(orcid_user_id))

  if not response.ok:
    flash("Failed to get ORCID User Data", category="error")
    return False

  orcid_record = response.json()
  pprint(orcid_record)

  # Find this OAuth in the
  query = OAuth.query.filter_by(
    provider=orcid_blueprint.name,provider_user_id=orcid_user_id)
  try:
    oauth = query.one()
  except NoResultFound:
    oauth = OAuth(
      provider=orcid_blueprint.name,
      provider_user_id=orcid_user_id,
      provider_user_login=orcid_user_id,
      token=token)


  if current_user.is_anonymous:
    if oauth.user:
      login_user(oauth.user)
      flash("Successfully logged in through ORCID")
    else:
      orcid_person = orcid_record['person']

      ### check if there is a user with this email address
      # Check to see if the ORCID user has an email exposed, otherwise, we cannot use it
      # if not orcid_record['person']['emails']
      if len(orcid_person['emails']['email']) == 0:
        flash("Failed to create new user, must have at least one ORCID email address accessible to restricted")
        return False

      orcid_email = orcid_person['emails']['email'][0]['email']

      query = User.query.filter_by(email=orcid_email)
      try:
        nrc_u = query.one()
        oauth.user = nrc_u
        db.session.add(oauth)
        db.session.commit()
        login_user(oauth.user)

      except NoResultFound:
        # create a new user

        user = User(email=orcid_person['emails']['email'][0]['email'],
                    first_name = orcid_person['name']['given-names']['value'],
                    last_name = orcid_person['name']['family-name']['value'],
                    active=True,
                    email_confirmed_at=datetime.utcnow())

        user.roles.append(Role.query.filter(Role.name=="member").first())
        oauth.user = user

        db.session.add_all([user,oauth])
        db.session.commit()

        login_user(user)
  else:
    if oauth.user:
      flash ("Account already associated with another user")
    else:
      oauth.user = current_user
      db.session.add(oauth)
      db.session.commit()
      flash("Successfully linked ORCID account")

  return False