Exemplo n.º 1
0
    def load_user_from_request_header(request):
        try:
            access_token_enc = request.headers["Authorization"]
            access_token_dec = auth.decodeJWT(access_token_enc)

            if(access_token_dec['exp'] < time.time()):
                return None

            # id_token_enc = request.headers["ID"]
            # kid = jwt.get_unverified_header(id_token_enc)['kid']
            # key = public_keys[kid]
            # access_token_dec = jwt.decode(id_token_enc, public_keys[kid], algorithms='RS256')

            access_token = request.headers["Authorization"]
            cognito = Cognito(
                environ.get('COGNITO_REGION'), environ.get('COGNITO_ACCESS'), access_token=access_token, user_pool_region='us-east-2')
            username = cognito.get_user()._metadata.get("username")
            if username is None:
                return None

            return User(username)

        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
            print(e)
            return None
Exemplo n.º 2
0
 def setUp(self):
     self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID')
     self.app_id = env('COGNITO_APP_ID')
     self.username = env('COGNITO_TEST_USERNAME')
     self.password = env('COGNITO_TEST_PASSWORD')
     self.user = Cognito(self.cognito_user_pool_id,self.app_id,
                      username=self.username)
Exemplo n.º 3
0
 def login(self, username=None, password=None, id_token=None, access_token=None, refresh_token=None, token_storage_file=None):
     """ Authenticates the current user using access tokens if provided or username/password if no tokens available.
         Provide a path for storing the token data that can be used to reauthenticate without providing the password.
         Tokens stored in the file are updated when they expire.
     """
     # Use warrant to go through the SRP authentication to get an auth token and refresh token
     client = boto3.client('cognito-idp', region_name='us-east-2', 
         config=botocore.client.Config(signature_version=botocore.UNSIGNED))
     if id_token is not None and access_token is not None and refresh_token is not None:
         # use existing tokens
         self.cognito = Cognito(USER_POOL, CLIENT_ID,
             user_pool_region='us-east-2', 
             id_token=id_token, 
             access_token=access_token, 
             refresh_token=refresh_token)
         self.cognito.client = client
     elif username is not None and password is not None:
         #log in with username and password
         self.cognito = Cognito(USER_POOL, CLIENT_ID, 
             user_pool_region='us-east-2', username=username)
         self.cognito.client = client
         self.cognito.authenticate(password=password)
     else:
         raise Exception('No authentication method found. Must supply username/password or id/auth/refresh tokens.')
     if self.cognito.access_token is not None:
         if token_storage_file is not None: self.token_storage_file = token_storage_file
         self._check_token()
         user = self.cognito.get_user()
         self.username = user._data['email']
         self.customer = self.get_customer_details()
         self._store_tokens()
     return self.customer is not None
Exemplo n.º 4
0
    def post(self):

        headers = {'Content-Type': 'text/html'}
        token = request.args.get('id_token')

        if token:
            return respondToToken(token)
        else:
            if request.form:
                user = request.form['username']
                pwd = request.form['pwd']
                u = Cognito(COGNITO_USER_POOL,COGNITO_APP_ID, username=user)
                print "No Token, Trying to login for user %s" %(user)
                try:
                    u.authenticate(password=pwd)
                except:
                    return make_response(
                          render_template('TokenError.html',
                                      msg="Login Failed. Access Denied"
                                    ),404,headers)
                try:
                    resp =  respondToToken(u.id_token)

                    return resp
                except:

                    return make_response(
                          render_template('TokenError.html',
                                      msg="Something very bad happend!! Can Not Open Homepage!!"
                                    ),404,headers)
Exemplo n.º 5
0
 def updateProfile(self, id_token, refresh_token, access_token, attr_map):
     u = Cognito(self.USER_POOL_ID,
                 self.CLIENT_ID,
                 id_token=id_token,
                 refresh_token=refresh_token,
                 access_token=access_token)
     u.update_profile(attr_map)
Exemplo n.º 6
0
def login():

	loadMe = json.dumps(request.get_json(silent=True)["user"])
	payInfo = json.loads(loadMe)
	try:

		u = Cognito(pool_id, client_id, user_pool_region='us-east-2',
                    access_key=os.environ["AWS_ACCESS_KEY"], secret_key=os.environ['AWS_SECRET_KEY'],
                    username=payInfo["email"]);
		u.authenticate(password=payInfo["password"]);
		uuid = generate_uuid(payInfo)
		response = table.get_item(
			Key={
				'userID' : uuid
			}
		)
		item = response['Item'];
		# return jsonify(item);
		convertedItem = json.loads(json.dumps(item, default=decimal_default));
		adminStatus = convertedItem['admin'];
		wholeTable = getTable();
		if (adminStatus == 1):
			return response_with(responses.SUCCESS_200, value={"value" : wholeTable}, message={"userID" : uuid, "admin" : adminStatus});
		elif (adminStatus == 0): #just a reg employee
			return response_with(responses.SUCCESS_200, value={"value": convertedItem}, message={"userID" : uuid, "admin" : adminStatus}); #returns just user

	except Exception as e:
		return response_with(responses.UNAUTHORIZED_401, value={"value" : str(e)})
Exemplo n.º 7
0
 def get_token(self, username: str, password: str) -> str:
     u = Cognito(self.user_pool,
                 self.client_id,
                 self.region,
                 username=username)
     u.authenticate(password=password)
     return u.access_token
Exemplo n.º 8
0
def authenticate_new_user(userPoolId,appClientId, username, password, region ):
    
    u = Cognito(userPoolId, appClientId, username = username,user_pool_region=region)

    authenticateUser = u.admin_authenticate(password)
    
    return authenticateUser
Exemplo n.º 9
0
def login(username, password):
    """
    Use username and password to get Canotic api key.
    """
    user = Cognito(access_key='AKIAIOSFODNN7EXAMPLE', secret_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                   user_pool_id=COGNITO_USERPOOL_ID, client_id=COGNITO_CLIENT_ID,
                   user_pool_region=COGNITO_REGION, username=username)
    try:
        user.authenticate(password)
    except ClientError as e:
        if e.response['Error']['Code'] == 'UserNotFoundException' or e.response['Error'][
            'Code'] == 'NotAuthorizedException':
            print("Incorrect username or password")
            return
        else:
            print(f"Unexpected error: {e}")
            return

    client = Client(auth_token=user.access_token)
    api_keys = client.get_apikeys()
    if len(api_keys) > 0:
        save_api_key(api_keys[0])
        print(f'Api key {api_keys[0]} was set')
    else:
        print(f'User {username} doesn\'t have any api keys')
Exemplo n.º 10
0
def create_user(username, password, name, group):
    """
    Create user and add him to the specifed group
    """
    if not username:
        raise ValidationError("error.create_user.invalid_user")
    if not password:
        raise ValidationError("error.create_user.invalid_password")
    if not name:
        raise ValidationError("error.create_user.invalid_name")
    if not group:
        raise ValidationError("error.create_user.invalid_group")

    client = boto3.client("cognito-idp")

    # check if group exists or through exception
    try:
        client.get_group(UserPoolId=cognito_userpool_id, GroupName=group)
    except Exception as e:
        log.exception(
            "Failed to get_group, error.create_user.invalid_group, AWS Exception:  {}"
            .format(e))
        raise ValidationError("error.create_user.invalid_group")

    # here I am using warrant library because I found it easier than boto3
    cognito = Cognito(cognito_userpool_id, cognito_app_client_id)
    cognito.add_base_attributes(name=name)
    # Register the user using warrant
    try:
        register_res = cognito.register(username, password)
    except ClientError as e:
        if "Username should be an email." in e.response["Error"]['Message']:
            raise ValidationError("error.create_user.invalid_user")
        elif "An account with the given email already exists." in e.response[
                "Error"]['Message']:
            raise ValidationError("error.create_user.already_exists")
        elif "Password did not conform with policy" in e.response["Error"][
                'Message']:
            raise ValidationError("error.create_user.invalid_password")
        else:
            log.exception(
                "Failed to register a user, error.create_user.failed, AWS Exception:  {}"
                .format(e))
            raise ValidationError("error.create_user.failed")

    # add user to the group using boto3 library
    try:
        client.admin_add_user_to_group(UserPoolId=cognito_userpool_id,
                                       Username=username,
                                       GroupName=group)
    except Exception as e:
        log.exception(
            "Failed to add to a group, error.create_user.addtogroup.failed, AWS Exception:  {}"
            .format(e))
        raise ValidationError("error.create_user.addtogroup.failed")

    return register_res
Exemplo n.º 11
0
    def authenticate(self, username, password):
        clientId = self.identity['provider']['client_id']
        userPoolId = self.identity['provider']['userpool_id']

        u = Cognito(userPoolId, clientId, username=username)
        u.authenticate(password=password)
        # TODO: if this fails, we should error gracefully with a 401
        token = u.id_token
        self.allowed_perms = self.set_perms(token)
Exemplo n.º 12
0
    def logout(self, auth):
        u = Cognito(
            self.pool_id,
            self.client_id,
            id_token=auth["id_token"],
            refresh_token=auth["refresh_token"],
            access_token=auth["access_token"],
        )

        u.logout()
Exemplo n.º 13
0
 def post(self):
     data = self.parser.parse_args()
     u = Cognito(os.environ['COGNITO_USERPOOL_ID'],
                 os.environ['COGNITO_APP_CLIENT_ID'],
                 username=data['username'])
     try:
         u.authenticate(password=data['password'])
     except ClientError as e:
         return {'message': str(e)}
     return {'access_token': u.id_token}
Exemplo n.º 14
0
def valid_login(username, password):
    cognito = Cognito(cognito_userpool_id,
                      cognito_app_client_id,
                      username=username)
    try:
        cognito.authenticate(password)
    except Exception as e:
        print(e)
        return False
    return True
Exemplo n.º 15
0
    def post(self):
        """Sends a verification code to the user to use to change their password."""
        json_data = request.get_json(force=True)
        print(json_data)
        email = json_data['email']

        try:
            u = Cognito(cognitoUserPoolId, cognitoUserPoolClientId, awsRegion, username=email)
            u.initiate_forgot_password()
            return ReturnDocument(email, "success").asdict()
        except ClientError as err:
            return ReturnDocument(err.__str__(), "error").asdict()
Exemplo n.º 16
0
 def test_set_attributes(self):
     u = Cognito(self.cognito_user_pool_id,self.app_id)
     u._set_attributes({
             'ResponseMetadata':{
                 'HTTPStatusCode':200
             }
     },
         {
             'somerandom':'attribute'
         }
     )
     self.assertEqual(u.somerandom,'attribute')
Exemplo n.º 17
0
 def check_auth(self, auth):
     u = Cognito(
         self.pool_id,
         self.client_id,
         id_token=auth.get("id_token"),
         refresh_token=auth.get("refresh_token"),
         access_token=auth.get("access_token"),
     )
     try:
         u.check_token()
     except AttributeError:
         raise NotAuthenticated
Exemplo n.º 18
0
def cognitoConfig(argUsername=""):
    # poolID = os.environ['poolID']
    # cognitoAppClientID = os.environ['cognitoAppClientID']
    if argUsername:
        # config = Cognito(poolID,cognitoAppClientID, username : aqrUsername )
        config = Cognito("us-east-1_PqI7vgPYC",
                         "70uonffglttpu0juiu5p8spom0",
                         username=argUsername)
    else:
        # config = Cognito(poolID,cognitoAppClientID)
        config = Cognito("us-east-1_PqI7vgPYC", "70uonffglttpu0juiu5p8spom0")
    return config
Exemplo n.º 19
0
def confirm_signup(username):
    if request.method == 'POST':
        code = request.form['confirm_code']
        u = Cognito(USER_POOL_ID, CLIENT_ID, REGION, username=username,
                    access_key='dummy_not_used', secret_key='dummy_not_used')
        try:
            u.confirm_sign_up(code, username=username)
        except ClientError as e:
            flash(e.response.get('Error').get('Message'))
            return redirect(url_for('confirm_signup', username=username))
        return redirect(url_for('login', username=username))

    return render_template('confirm_signup.html')
Exemplo n.º 20
0
def get_cognito(request):
    c = Cognito(settings.COGNITO_USER_POOL_ID,
                settings.COGNITO_APP_ID,
                access_token=request.session.get('ACCESS_TOKEN'),
                id_token=request.session.get('ID_TOKEN'),
                refresh_token=request.session.get('REFRESH_TOKEN'))
    changed = c.check_token()
    if changed:
        request.session['ACCESS_TOKEN'] = c.access_token
        request.session['REFRESH_TOKEN'] = c.refresh_token
        request.session['ID_TOKEN'] = c.id_token
        request.session.save()
    return c
Exemplo n.º 21
0
def do_work():

    user_pool_id = os.environ['AWS_COGNITO_POOL_ID']
    client_id = os.environ['AWS_COGNITO_CLIENT_ID']
    client_secret = os.environ.get('AWS_COGNITO_SECRET_KEY')
    username = os.environ.get('COGNITO_USER')
    password = os.environ['COGNITO_PASSWORD']
    u = Cognito(user_pool_id=user_pool_id,
                client_id=client_id,
                client_secret=client_secret,
                username=username)
    u.authenticate(password=password)
    print(u.access_token)
Exemplo n.º 22
0
def signout():
    if 'id_token' in session and 'access_token' in session and 'refresh_token':
        u = Cognito(cognito_userpool_id,
                    cognito_client_id,
                    cognito_userpool_region,
                    id_token=session['id_token'],
                    refresh_token=session['refresh_token'],
                    access_token=session['access_token'])
        u.logout()

    logout_user()
    # to do
    return redirect(url_for('index'))
Exemplo n.º 23
0
def confirm_user(username, con_code):

    if not username:
        raise ValidationError("error.confirm_user.invalid_username")
    if not con_code:
        raise ValidationError("error.confirm_user.invalid_confirmation_code")

    # here I am using warrant library because I found it easier than boto3
    cognito = Cognito(cognito_userpool_id, cognito_app_client_id)
    try:
        cognito.confirm_sign_up(confirmation_code=con_code, username=username)
    except Exception as e:
        raise ValidationError("error.confirm_user.failed")
Exemplo n.º 24
0
def authenticate_user(config, username, password):

    u = Cognito(config['aws']['cognitio']['userPoolId'],
                config['aws']['cognitio']['userPoolClientId'],
                username=username)
    u.authenticate(password=password)
    user = u.get_user(attr_map={
        "given_name": "first_name",
        "family_name": "last_name"
    })

    print user.username, user.email_verified, u.access_token

    return u.access_token
Exemplo n.º 25
0
 def setUp(self):
     if env('USE_CLIENT_SECRET') == 'True':
         self.app_id = env('COGNITO_APP_WITH_SECRET_ID')
         self.client_secret = env('COGNITO_CLIENT_SECRET')
     else:
         self.app_id = env('COGNITO_APP_ID')
         self.client_secret = None
     self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID')
     self.username = env('COGNITO_TEST_USERNAME')
     self.password = env('COGNITO_TEST_PASSWORD')
     self.user = Cognito(self.cognito_user_pool_id,
                         self.app_id,
                         username=self.username,
                         client_secret=self.client_secret)
Exemplo n.º 26
0
def register_new_user(userPoolId, appClientId, userPoolRegion, username, password):
    """
    Test userpool in AWS database for existing accounts.
    
    Inputs: 
        - awsService = 'cognito-idp'
        - regionName = "us-east-2"
    outputs:
        - Response from AWS
    """
    u = Cognito(userPoolId, appClientId, userPoolRegion)
    u.add_base_attributes()
    data = u.register(username, password)
    return data
Exemplo n.º 27
0
def logout_user():
    access = request.headers.get('accessToken')
    refresh = request.headers.get('refreshToken')
    _id = request.headers.get('idToken')

    u = Cognito(CONSTANTS['cognito_id'],
                CONSTANTS['cognito_app'],
                id_token=_id,
                refresh_token=refresh,
                access_token=access)
    u.logout()
    return Response(json.dumps({"status": True}),
                    status=200,
                    mimetype='application/json')
Exemplo n.º 28
0
    def post(self):
        """Allows a user to enter a code provided when they reset their password to update their password."""
        json_data = request.get_json(force=True)
        print(f"Reset pwd code: {json_data}")
        email = json_data['email']
        code = json_data['code']
        password = json_data['password']
        try:
            u = Cognito(cognitoUserPoolId, cognitoUserPoolClientId, awsRegion, username=email)
            u.confirm_forgot_password(code, password=password)

            return ReturnDocument(email, "success").asdict()
        except ClientError as err:
            return ReturnDocument(err.__str__(), "error").asdict()
Exemplo n.º 29
0
    def post(self):
        """Confirm user registration"""
        json_data = request.get_json(force=True)

        email = json_data['email']
        code = json_data['code']

        try:
            u = Cognito(cognitoUserPoolId, cognitoUserPoolClientId, awsRegion)
            u.confirm_sign_up(code, username=email)

            return ReturnDocument(email, "success").asdict()
        except ClientError as err:
            return ReturnDocument(err.__str__(), "error").asdict()
Exemplo n.º 30
0
def employeeSignIn():
	loadMe = json.dumps(request.form)
	payInfo = json.loads(loadMe)
	try:
		uuid = generate_uuid(payInfo)
		response = table.get_item(
			Key={
					'userID' : uuid
				}
		)
		item = response['Item'];
		dumpedItem = json.loads(json.dumps(item, default=decimal_default));
	except Exception as e:
		return response_with(responses.UNAUTHORIZED_401, value={"value" : str(e)})
	else:
		return response_with(responses.SUCCESS_200, value={"value" : dumpedItem});

		loadMe = json.dumps(request.get_json(silent=True)["info"])
		payInfo = json.loads(loadMe)
		admin = payInfo["admin"]

		u = Cognito(pool_id, client_id, user_pool_region="us-east-2", access_key=os.environ["AWS_ACCESS_KEY"],
				secret_key=os.environ["AWS_SECRET_KEY"]);
		u.add_base_attributes(email=payInfo["email"], name="name");
		#email has to be proper email format
		#password needs to have uppercase, lowercase, and a number
		res = u.register(payInfo["email"], payInfo["password"]);

		try:
			uuid = generate_uuid(payInfo)
			response = table.put_item(
				Item={
					'userID' : uuid,
					'name': payInfo["name"],
					'email': payInfo["email"],
					'password': sha256encrypt(payInfo["password"]),
					'hireDate' : payInfo["hireDate"], #format: MM/DD/YYYY
					'department' : payInfo["department"],
					'salary' : int(payInfo["salary"]),
					'admin' :int(admin)
				}
			)
		except Exception as e:
			return response_with(responses.INVALID_FIELD_NAME_SENT_422, value={"value" : str(e)});
		else:
			return response_with(responses.SUCCESS_200, value={
				"userID" : uuid,
				"admin" : int(admin)
			})
Exemplo n.º 31
0
def handler(event, context):
    print(event)
    cognito_pool_id = os.environ['COGNITO_POOL_ID']
    cognito_client_id = os.environ['COGNITO_CLIENT_ID']
    username = event['username']
    password = event['password']

    cognito = Cognito(
        cognito_pool_id,
        cognito_client_id,
        user_pool_region=os.environ['AWS_REGION'],
        username=username)

    try:
        cognito.authenticate(password=password)
    except Exception as e:
        print(e)
        raise Exception
    else:
        return cognito.id_token
Exemplo n.º 32
0
def _cognito(cloud, **kwargs):
    """Get the client credentials."""
    import botocore
    import boto3
    from warrant import Cognito

    cognito = Cognito(
        user_pool_id=cloud.user_pool_id,
        client_id=cloud.cognito_client_id,
        user_pool_region=cloud.region,
        **kwargs
    )
    cognito.client = boto3.client(
        'cognito-idp',
        region_name=cloud.region,
        config=botocore.config.Config(
            signature_version=botocore.UNSIGNED
        )
    )
    return cognito