Example #1
0
 def mutate(self, info, refresh_token):
     return RefreshMutation(
         RefreshField(
             acces_token=create_access_token(get_jwt_identity()),
             message="Refresh success",
         )
     )
Example #2
0
    def mutate(self, info, input):
        data = input_to_dictionary(input)

        validations_schema = {
            'email': {
                'type': 'string',
                'required': True,
                'regex': r"^(\w+[.|\w])*@(\w{2,}[.])*\w{2,}$"
            },
            'password': {
                'type': 'string',
                'required': True,
                'regex': r"^(?=.*?[a-zA-Z])(?=.*?[0-9]).*$",
                'minlength': 8,
                'maxlength': 50
            }
        }

        validate = Validate(data, validations_schema)
        if validate.is_invalid:
            return validate.error_node

        account = AccountModel.query.filter_by(email=data.get('email')).first()

        if account is None:
            return LoginError(code="EMAIL_NOT_FOUND",
                              message="the email is not registered in the app")

        if not check_passwod(account.password, data.get('password')):
            return LoginError(code="INCORRECT_DATA",
                              message="user or email is incorrect")

        account_info = {'email': account.email, 'id': account.id}
        return LoginSuccess(access_token=create_access_token(account_info),
                            account=account)
Example #3
0
 def mutate(cls, _, info, username, password):
     return AuthMutation(
         access_token=create_access_token(username,
                                          user_claims=user_claims),
         refresh_token=create_refresh_token(username,
                                            user_claims=user_claims),
     )
Example #4
0
 def mutate(self, info, username, password):
     user = User.query.filter_by(username=username).first()
     print(user)
     if not user:
         raise Exception('Authenication Failure : User is not registered')
     return AuthMutation(access_token=create_access_token(username),
                         refresh_token=create_refresh_token(username))
Example #5
0
    def mutate(self):

        # Retrieves User claim(user id) from refresh_token and creates new
        # acces_token
        username = get_jwt_identity()
        acces_token = create_access_token(identity=username)

        return RefreshMutation(acces_token)
Example #6
0
 def mutate(cls, _, info, username, password):
     user = User(username=username).fetch()
     if user is None:
         return AuthMutation(ok=False)
     if not (app.becrypt.check_password_hash(user.passwordHash, password)):
         return AuthMutation(ok=False)
     return AuthMutation(access_token=create_access_token(user.username),
                         ok=True)
 def mutate(cls, info):
     current_user = get_jwt_identity()
     claim = get_jwt_claims()
     if claim == admin_claim:
         return Refresh(new_token=create_access_token(
             identity=current_user, user_claims=admin_claim))
     else:
         return Refresh(new_token=None)
Example #8
0
 def mutate(cls, _, info, username, password):
     if username in allowed.USERS.keys(
     ) and password == allowed.USERS[username]:
         return AuthMutation(
             access_token=create_access_token(username),
             refresh_token=create_refresh_token(username),
         )
     else:
         return {}
Example #9
0
 def mutate(cls, _, info, username, password):
     if User(username=username).fetch() is not None:
         return RegisterMutation(ok=False)
     pwhash = app.becrypt.generate_password_hash(password)
     user = User(username=username, passwordHash=pwhash)
     user.save()
     return RegisterMutation(ok=True,
                             access_token=create_access_token(
                                 user.username))
Example #10
0
 def mutate(cls, _, info, username, password):
     query = f'EXEC sp_validate_user \'{username}\', \'{password}\''
     query_result = sql_server_execute_query(query)
     userId = query_result[0]
     result = AuthMutation(
         access_token=create_access_token(userId),
         refresh_token=create_refresh_token(userId),
     ) if userId['userId'] else AuthMutation(access_token=None, refresh_token=None)
     return result
Example #11
0
    def mutate(self, info, email_or_username, password, with_google):
        #if email_or_username is None or password is None or email_or_username == '' or password == '':
        #    return Authentication(response= ResponseMessage(text= 'Kolom tidak boleh ada yang kosong!', status= False))

        #LOGIN WITH GOOGLE
        if with_google:
            google_auth = Authentication.login_with_google(with_google)

            if google_auth is False:
                return Authentication(response=ResponseMessage(
                    text=
                    'Terjadi kesalahan terhadap akun Google anda, silahkan coba kembali',
                    status=False))
            else:
                email_or_username = with_google.email
                password = with_google.password

        authenticated_user = mongo.db.users.find_one({
            '$or': [{
                'email': email_or_username
            }, {
                'username': email_or_username
            }],
            'is_admin':
            False
        })

        if authenticated_user is None:
            return Authentication(response=ResponseMessage(
                text='Alamat surel/nama pengguna atau kata sandi anda salah!',
                status=False))
        else:
            try:
                if not with_google and check_password_hash(
                        authenticated_user['password'], password) is False:
                    return Authentication(response=ResponseMessage(
                        text=
                        'Alamat surel/nama pengguna atau kata sandi anda salah!',
                        status=False))
            except:
                return Authentication(response=ResponseMessage(
                    text=
                    'Alamat surel/nama pengguna atau kata sandi anda salah!',
                    status=False))

        if 'img_url' not in authenticated_user:
            authenticated_user['img_url'] = 'https://via.placeholder.com/100'

        if 'date_of_birth' in authenticated_user:
            authenticated_user['date_of_birth'] = authenticated_user[
                'date_of_birth'].date()

        return Authentication(
            authenticated_user=authenticated_user,
            access_token=create_access_token(str(authenticated_user['_id'])),
            refresh_token=create_refresh_token(str(authenticated_user['_id'])),
            response=ResponseMessage(text='Berhasil masuk', status=True))
Example #12
0
    def mutate(cls, _):
        """
        Mutation class method, authentication is required to access method.

        :param _ :type...
        :return :type RefreshMutation (self)
        """
        current_user = get_jwt_identity()
        return RefreshMutation(new_token=create_access_token(
            identity=current_user))
 def mutate(cls, _, info, username, password):
     if not (AdminModel.objects(username=username) and check_password_hash(
             AdminModel.objects.get(username=username).password, password)):
         return Auth(ok=False)
     else:
         return Auth(
             access_token=create_access_token(username,
                                              user_claims=admin_claim),
             refresh_token=create_refresh_token(username,
                                                user_claims=admin_claim),
             ok=True)
Example #14
0
    def mutate(self, info, **kwargs):
        user = User.objects(**kwargs).first()

        if user is not None:
            access_token = create_access_token(identity=kwargs["email"])
            refresh_token = create_refresh_token(identity=str(uuid4()))

            return AuthMutation(result=AuthField(access_token=access_token,
                                                 refresh_token=refresh_token,
                                                 message="Login Success"))
        else:
            return AuthMutation(result=AuthField(message="Login failed"))
 def mutate(cls, info, username, password):
     """
     This class is to create the mutation in the side of the graphql
     :param info:
     :param username: Graphene.String type
     :param password: Graphene.String type
     :return: JWT token type
     """
     return AuthMutation(
         access_token=create_access_token(username, password),
         refresh_token=create_refresh_token(username),
     )
Example #16
0
    def mutate(cls, _, info, email, password):

        user = User.query.filter(User.email == email).first()
        if not user:
            raise GraphQLError("Incorrect email or password.")
        if not user.check_password(password):
            raise GraphQLError("Incorrect email or password.")

        return AuthMutation(
            access_token=create_access_token({"id": user.id}),
            refresh_token=create_refresh_token({"id": user.id}),
        )
Example #17
0
    def mutate(cls, _, info: ResolveInfo, email: str,
               password: str) -> "AuthMutation":
        """
        Mutate is a class method that creates an access and refresh tokens for the given user.

        :param _ :type...
        :param info :type ResolveType
        :param email :type str: User object's email
        :param password :type str: User object's password
        :return :type AuthMutation (self)
        """
        return AuthMutation(
            access_token=create_access_token(email),
            refresh_token=create_refresh_token(email),
        )
Example #18
0
def test_query_jwt_required(flask_app: Flask):
    test_cli = flask_app.test_client()

    with flask_app.test_request_context():
        access_token = create_access_token('username')

    response = request(
        test_cli, "query", 'protected(token:"{0}")'.format(access_token),
        """... on AuthInfoField{
                                message
                            }
                            ... on MessageField{
                                message
                            }""")

    assert response['protected']["message"] == "Hello World!"
Example #19
0
    def mutate(self, info, **kwargs):
        user = AccountModel.objects(**kwargs).first()

        if user is not None:
            access_token = create_access_token(identity=kwargs["id"])
            refresh_token = create_refresh_token(identity=str(uuid4()))

            return AuthMutation(
                AuthField(
                    access_token=access_token,
                    refresh_token=refresh_token,
                    message="Login Success",
                )
            )
        else:
            return AuthMutation(
                ResponseMessageField(is_success=False, message="Login failed")
            )
Example #20
0
def test_mutation_jwt_required(flask_app: Flask):
    test_cli = flask_app.test_client()

    with flask_app.test_request_context():
        access_token = create_access_token('username')

    response = request(
        test_cli, "mutation", 'protected(token:"{0}")'.format(access_token),
        """message {
                        ... on MessageField {
                                message
                            }
                        ... on AuthInfoField {
                                message
                            }
                        }""")

    assert response['protected']["message"][
        "message"] == "Protected mutation works"
Example #21
0
    def mutate(self, info, Input):
        username, password = Input['username'], Input['password']

        # Username and password authentication
        _user = UserTable(username)
        valid_password = _user.valid_password(password)

        # Verifying that authentication was successful and that the user is
        # enabled
        if not (_user.exists and valid_password):
            err = ('''Authentication Failure: incorrect credentials or user not
                   enabled!''')
            raise GraphQLError(err)

        # Creating tokens
        access_token = create_access_token(username)
        refresh_token = create_refresh_token(username)

        return AuthMutation(access_token, refresh_token)
Example #22
0
    def mutate(self, info, email, password):
        cleaned_email = email.strip().lower()
        user: User = User.query.filter_by(email=cleaned_email).one_or_none()
        if not user or not user.password or not user.is_correct_password(
                password):
            return LoginMutation(
                ResponseMessageField(is_success=False, message="Login failed"))

        access_token = create_access_token(identity={
            "email": user.email,
            "full_name": user.full_name
        })
        refresh_token = create_refresh_token(identity=str(uuid4()))

        return LoginMutation(
            AuthField(
                access_token=access_token,
                refresh_token=refresh_token,
                message="Login Success",
            ))
Example #23
0
    def mutate(cls, _, info, username, password):
        print("\n[MUTATION]: [AuthMutation]: mutate: user: {}, password: {}".
              format(username, password),
              file=sys.stderr)

        try:
            dbUser = db.dbMan.getUser(username)
            if dbUser == None or password != dbUser["password"]:
                raise GraphQLError(
                    "[MUTATION]: [AuthMutation]: wrong password")
        except Exception as e:
            print(e, file=sys.stderr)
            raise GraphQLError(e)
        tok = create_access_token(username)
        refrshTok = create_refresh_token(username)
        SessionManager.session.addNewSession(username, tok)
        return AuthMutation(
            access_token=tok,
            refresh_token=refrshTok,
        )
Example #24
0
    def mutate(self, info, email_or_username, password):
        result = mongo.db.users.find_one({
            '$or': [{
                'email': email_or_username
            }, {
                'username': email_or_username
            }],
            'is_admin':
            True
        })

        if result is None or check_password_hash(result['password'],
                                                 password) is False:
            return AdminAuthentication(response=ResponseMessage(
                text='Alamat surel/nama pengguna atau kata sandi anda salah!',
                status=False))

        return AdminAuthentication(
            access_token=create_access_token(str(result['_id'])),
            refresh_token=create_refresh_token(str(result['_id'])),
            response=ResponseMessage(text='Berhasil masuk', status=True))
Example #25
0
    def mutate(self, info, email, password):
        # setup variables
        error = ''
        ok = False
        access_token = ''
        refresh_token = ''

        # retrieve user from db
        user = UserModel.find_user(email=email)

        if user is not None:
            if user.check_password(password):
                ok = True
                access_token = create_access_token(email)
                refresh_token = create_refresh_token(email)
            else:
                error = 'User credentials do not match.'
        else:
            error = 'User not found.'

        return UserLogin(ok=ok,
                         error=error,
                         access_token=access_token,
                         refresh_token=refresh_token)
Example #26
0
def sign_in_user(email, password):
    """
	This function will perform the sign in functionality and return an access token to be used in later requests.
	:param email: The email address of the user you hope to sign in.
	:param password: The password of the user you hope to sign in.
	:return temp_dict: A dictionary containing both the user object and the auth token
	"""
    email = cleanse_input(email)
    password = cleanse_input(password)
    user = User.query.filter(User.user_email == email).first()

    if user is None:
        raise GraphQLError(error_user_does_not_exist())

    bcrypt = Bcrypt(
        app
    )  # Create the bcrypt object that will handle password hashing and verification

    email_match = email == user.user_email
    password_match = bcrypt.check_password_hash(user.user_password, password)

    # If the given user credentials are valid
    if email_match and password_match:
        # Fetch user's role from the database and include it as claims on the JWT being generated
        user_claims = {"roles": user.user_role}

        # A temporary dictionary that will be returned to the graphql resolver
        temp_dict = {
            'auth_token': create_access_token(user.id,
                                              user_claims=user_claims),
            'user': user
        }

        return temp_dict
    else:
        raise GraphQLError(error_invalid_credentials())
Example #27
0
 def mutate(self, info, **kwargs):
     user = User(email=kwargs.get('email')).fetch_by_email()
     if user is None:
         return LoginUser(success=False,
                          user_not_exists=True,
                          wrong_password=None,
                          access_token=None,
                          refresh_token=None,
                          user=None)
     if user.password == kwargs.get('password'):
         return LoginUser(
             success=True,
             wrong_password=None,
             user_not_exists=None,
             access_token=create_access_token(kwargs.get('email')),
             refresh_token=create_refresh_token(kwargs.get('email')),
             user=UserSchema(**user.as_dict()))
     else:
         return LoginUser(success=False,
                          wrong_password=True,
                          user_not_exists=False,
                          access_token=None,
                          refresh_token=None,
                          user=UserSchema(**user.as_dict()))
Example #28
0
 def mutate(self, _, info):
     current_user = get_jwt_identity()
     return RefreshMutation(new_token=create_access_token(
         identity=current_user, user_claims=user_claims))
Example #29
0
 def mutate(self, _):
     current_user = get_jwt_identity()
     return RefreshMutation(new_token=create_access_token(
         identity=current_user))
Example #30
0
 def mutate(cls, _, **kwargs):
     return RefreshMutation(result=RefreshField(
         access_token=create_access_token(get_jwt_identity()),
         message="Refresh success"))