﻿# The example shows how to find a record or safebox by text pattern in SecureAnyBox
#   in this example, helper method search_text is used to get found object properties 

# SABClient methods used:
#
# login(self, username, password, domain='system', access_code=None)
# logout(self)
# search_text(self, pattern)

import sys
import json
import sabclient

# If the logged-on user requests a second factor, SABClient calls the second factor callback 
#   to retrieve the six-digit code
def get_second_factor():
  print('** SECOND FACTOR AUTHENTICATION **')
  print()
  s = input("Enter 6-digit code from your authenticator application: ") 
  return s

################################## main ######################################################

# first we need to create SecureAnyBox (SAB) client for given SAB server address (including base path);
# the callback applies when the second factor is required to sign in
sab = sabclient.SABClient('http://127.0.0.1:8843/secureanybox/', callback=get_second_factor)

# Then we need to authenticate the user.
# Don't use admin account, create account with minimum access rights, only to the required safe box
result = sab.login('serviceuser', 'password', access_code='123456', domain='test')

if result:

    # method SABClient.search_text can search stored records (such as Safe Boxes, Safe Box Groups, 
    # Accounts, etc.), by their name, specified tag of a field value in text pattern. However, it 
    # is not possible to search record by a field value which is encrypted.    
    pattern = 'acc'
    result_list = sab.search_text(pattern)

    # result_list contains found records
    # You can get following fields:

    # id ... ID of Record
    # name ... Record name
    # description ... Record description
    # type ... Record type (ACCOUNT, SAFEBOX, SAFEBOX_GROUP)
    # ownerId ... ID of owner user
    # template ... type of record (account, account-sec, file, cert, ccard)
    # parent ... name of parent Safe Box

    print()
    print('id', 'name', 'safe-box')
    print()
    for obj in result_list:
        id = obj["id"]
        name = obj["name"]
        safe_box_name = obj["parent"]

        print (id, '"'+name+'"', safe_box_name)

# when not needed anymore, you can logout the client, which will destroy session cookies and the client can no
# longer be used to work with SAB server
sab.logout

