﻿# The example shows how to delete a record from a safe box in SecureAnyBox
#   in this example, helper method find_record_by_name is used to get record id 
#   for a given record name ('account1') and safe box name ('test box')
# variable record_name contains name of the record
# variable safe_box_name contains name of the safe box
#
# used SABClient methods:
#
# login(self, username, password, domain='system', access_code=None)
# logout(self)
# find_record_by_name(self, record_name, box_name, parent_box_id=None)
# delete_record(self, record_id)

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:
    # to delete any record, we need to know an id of record we can get a record id from URL in SecureAnyBox
    # web interface (e.g in https://172.22.14.2/sab/static/safe-search.page#$acc/record/101 the 101 is a
    # record id)

    # or we can find the record by name (internally SABClient will list records in given safe box and find one 
    # with name matching record name or return None if no such record was found)

    safe_box_name = 'test box'
    record_name = 'account1'
    record = sab.find_record_by_name(record_name, safe_box_name);

    if record is None:
        print('record "' + record_name + '" was not found.')
        exit(1)  # quit with non-zero exit code so that calling script can test if this script failed or not


    result = sab.delete_record(record['id'])

    # if the record was deleted, delete_record returns True
    if result:
        print('record "' + record_name + '" was deleted')

# 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

