tatsuyamoriguchi / Sleep-Tracer

1 stars 0 forks source link

User account verification to alert if no user account exists #70

Closed tatsuyamoriguchi closed 1 month ago

tatsuyamoriguchi commented 1 month ago

Error message is displayed, "Wrong eMail address or password" Console shows:

retrievePassword SecItemCopyMatching status: -25300
No password found for the given email
isLoggedIn = false
Password unmatched

The code is searching for a password, not email address. It's not checking if any user account is already created or not.

tatsuyamoriguchi commented 1 month ago

To determine whether any account exists in the Keychain (regardless of the email), you can modify the function to query all items stored under the specific service without specifying an account. This way, if any item is found, it means at least one account exists in the Keychain for that service.

Here's an updated version of your function to check for any account existence:

func checkAnyAccountExists() throws -> Bool {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: Keychain.service,
        kSecMatchLimit as String: kSecMatchLimitOne,
        kSecReturnAttributes as String: kCFBooleanTrue!
    ]

    var result: AnyObject?
    let status = SecItemCopyMatching(query as CFDictionary, &result)
    print("checkAnyAccountExists SecItemCopyMatching status: \(status)")

    if status == errSecSuccess {
        // At least one account exists
        return true
    } else if status == errSecItemNotFound {
        // No account exists
        return false
    } else {
        // An unexpected error occurred
        throw KeychainError.unhandledError(status: status)
    }
}

This function constructs a query that looks for any item associated with the Keychain.service. It does not specify an account, so it will match any item stored under that service. The kSecMatchLimitOne and kSecReturnAttributes options ensure that the query is efficient and only returns attributes (not data) if an item is found. The function then checks the status returned by SecItemCopyMatching: