예제 #1
0
def create_session_token(sender, user, request, issuer="Django-Session", **kwargs):
    auth_token = create_token(user, issuer=issuer)
    auth_token.update_expiration() # 2hr default expiry
    auth_token.save()
    request.session['username'] = auth_token.user.username
    request.session['token'] = auth_token.key
    return auth_token
예제 #2
0
def globus_validate_code(request):
    """
    Validate 'code' returned from the IdP
    If valid: Return new AuthToken
        else: Return None
    """
    code = request.GET['code']
    if not code:
        return HttpResponse("NO Code found!")
    if type(code) == list:
        code = code[0]
    flow = globus_initFlow()
    try:
        credentials = flow.step2_exchange(code)
    except OAuthError as err:
        logger.exception("Error exchanging code w/ globus")
        return None
    token_profile = credentials.id_token
    username = token_profile['username']
    username = _extract_username_from_email(username)
    email = token_profile['username']
    full_name = token_profile['name']
    issuer = token_profile['iss']
    access_token = credentials.access_token
    expiry_date = credentials.token_expiry
    auth_token = create_token(username, access_token, expiry_date, issuer)
    return auth_token
예제 #3
0
def cas_callback_authorize(request):
    """
    Authorize a callback (From CAS IdP)
    """
    if "code" not in request.GET:
        # TODO - Maybe: Redirect into a login
        return HttpResponse("")
    oauth_client = get_cas_oauth_client()
    oauth_code = request.GET["code"]
    # Exchange code for ticket
    access_token, expiry_date = oauth_client.get_access_token(oauth_code)
    if not access_token:
        logger.warn("The Code %s is invalid/expired. Attempting another login." % oauth_code)
        return o_login_redirect(request)
    # Exchange token for profile
    user_profile = oauth_client.get_profile(access_token)
    if not user_profile or "id" not in user_profile:
        logger.error(
            "AccessToken is producing an INVALID profile!"
            " Check the CAS server and caslib.py for more"
            " information."
        )
        # NOTE: Make sure this redirects the user OUT of the loop!
        return login(request)
    # ASSERT: A valid OAuth token gave us the Users Profile.
    # Now create an AuthToken and return it
    username = user_profile["id"]
    auth_token = create_token(username, access_token, expiry_date, issuer="CAS+OAuth")
    # Set the username to the user to be emulated
    # to whom the token also belongs
    request.session["username"] = username
    request.session["token"] = auth_token.key
    return HttpResponseRedirect(settings.REDIRECT_URL + "/application/")
예제 #4
0
    def get(self, request, username):
        """
        Create a new token in the database on behalf of 'username'
        Returns success 201 Created - Body is JSON and contains
        """
        params = request.DATA
        user = request.user
        if not username:
            return Response("Username was not provided",
                            status=status.HTTP_400_BAD_REQUEST)
        if user.username is not 'admin' and not user.is_superuser:
            logger.error("URGENT! User: %s is attempting to emulate a user!"
                         % user.username)
            return Response("Only admin and superusers can emulate accounts. "
                            "This offense has been reported",
                            status=status.HTTP_401_UNAUTHORIZED)
        if not AtmosphereUser.objects.filter(username=username):
            return Response("Username %s does not exist as an AtmosphereUser"
                            % username, status=status.HTTP_404_NOT_FOUND)

        # User is authenticated, username exists. Make a token for them.
        token = create_token(username, issuer="DRF-EmulatedUser")
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            # Extra data passed only on emulation..
            "emulated_by": request.user.username,
            # Normal token data..
            "token": token.key,
            "username": token.user.username,
            "expires": expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return Response(auth_json, status=status.HTTP_201_CREATED)
예제 #5
0
 def create_token_from_jwt(self, jwt_assertion):
     """
     This method point represents the 'entry point'
     """
     decoded_assertion = self.decode_assertion(jwt_assertion)
     user, expiration = self.validate_assertion(decoded_assertion)
     auth_token = create_token(user.username, expiration)
     return auth_token
예제 #6
0
 def _token_for_username(self, username):
     token = create_token(username, issuer="DRF")
     expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
     auth_json = {
         'token': token.key,
         'username': token.user.username,
         'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
     }
     return Response(auth_json, status=status.HTTP_201_CREATED)
예제 #7
0
 def get(self, request):
     user = request.user
     if not user.is_authenticated():
         return Response("Logged-in User or POST required "
                         "to retrieve AuthToken",
                         status=status.HTTP_403_FORBIDDEN)
     token = lookupSessionToken(request)
     if not token:
         token = create_token(user.username)
     serialized_data = TokenSerializer(token).data
     return Response(serialized_data, status=status.HTTP_200_OK)
예제 #8
0
def validate_oauth_token(token, request=None):
    """
    Validates the token attached to the request (SessionStorage, GET/POST)
    On every request, ask OAuth to authorize the token
    """
    # Attempt to contact CAS
    try:
        user_profile = cas_profile_for_token(token)
    except ConnectionError:
        logger.exception("CAS could not be reached!")
        user_profile = None

    if not user_profile:
        return False
    username = user_profile.get("id")
    if not username:
        # logger.info("Invalid Profile:%s does not have username/attributes"
        #            % user_profile)
        return False

    # NOTE: REMOVE this when it is no longer true!
    # Force any username lookup to be in lowercase
    if not username:
        return None
    username = username.lower()

    # TEST 1 : Must be in the group 'atmo-user'
    # NOTE: Test 1 will be IGNORED until we can verify it returns 'entitlement'
    # EVERY TIME!
    #    raise Unauthorized("User %s is not a member of group 'atmo-user'"
    #                       % username)
    # TODO: TEST 2 : Must have an identity (?)
    if not User.objects.filter(username=username):
        raise Unauthorized("User %s does not exist as an User"
                           % username)
    auth_token = create_token(username, token)
    if not auth_token:
        return False
    return True
예제 #9
0
def token_auth(request):
    """
    VERSION 2 AUTH
    Authentication is based on the POST parameters:
    * Username (Required)
    * Password (Not Required if CAS authenticated previously)

    NOTE: This authentication is SEPARATE from
    django model authentication
    Use this to give out tokens to access the API
    """
    token = request.POST.get("token", None)

    username = request.POST.get("username", None)
    # CAS authenticated user already has session data
    # without passing any parameters
    if not username:
        username = request.session.get("username", None)

    password = request.POST.get("password", None)
    # LDAP Authenticate if password provided.
    if username and password:
        if ldap_validate(username, password):
            token = create_token(username, issuer="API")
            expireTime = token.issuedTime + auth_settings.TOKEN_EXPIRY_TIME
            auth_json = {
                "token": token.key,
                "username": token.user.username,
                "expires": expireTime.strftime("%b %d, %Y %H:%M:%S"),
            }
            return HttpResponse(content=json.dumps(auth_json), status=201, content_type="application/json")
        else:
            logger.debug("[LDAP] Failed to validate %s" % username)
            return HttpResponse("LDAP login failed", status=401)

    #    logger.info("User %s already authenticated, renewing token"
    #                % username)

    # ASSERT: Token exists here
    if token:
        expireTime = token.issuedTime + auth_settings.TOKEN_EXPIRY_TIME
        auth_json = {
            "token": token.key,
            "username": token.user.username,
            "expires": expireTime.strftime("%b %d, %Y %H:%M:%S"),
        }
        return HttpResponse(content=json.dumps(auth_json), content_type="application/json")

    if not username and not password:
        # The user and password were not found
        # force user to login via CAS
        return cas_loginRedirect(request, "/auth/")

    if cas_validateUser(username):
        logger.info("CAS User %s validated. Creating auth token" % username)
        token = createAuthToken(username)
        expireTime = token.issuedTime + auth_settings.TOKEN_EXPIRY_TIME
        auth_json = {
            "token": token.key,
            "username": token.user.username,
            "expires": expireTime.strftime("%b %d, %Y %H:%M:%S"),
        }
        return HttpResponse(content=json.dumps(auth_json), content_type="application/json")
    else:
        logger.debug("[CAS] Failed to validate - %s" % username)
        return HttpResponse("CAS Login Failure", status=401)