mistry
mistry

Reputation: 509

Can I use Realm for all data storage, or should I use NSUserDefaults for storing username/password?

I have an application which has a username/password login. Once logged in, the user should remain logged in until they log out, i.e. the user remains logged in even if they have no connection.

Currently I am authenticating the user, but I am unable to keep them logged in. Should I store the user details in NSUserDefaults for logging in on launch, or is there a way of keeping the user logged in using just Realm?

Thanks in advance!

SyncUser.logIn(with: userCredentials, server: (url! as URL)) { user, error in
    guard user != nil else {
        // Handles error
    }
    DispatchQueue.main.async {
        let configuration = Realm.Configuration(
            syncConfiguration: SyncConfiguration(user: user!, realmURL: URL(string: "realm://127.0.0.1:9080/~/realmtasks")!)
        )
        Realm.Configuration.defaultConfiguration = configuration

        self.performSegue(withIdentifier: "logInSegue", sender: self)
    }
}

Update: Maybe the answer to my problem is Apple Keychain?

Upvotes: 1

Views: 868

Answers (2)

Andrea
Andrea

Reputation: 26383

You should not store passwords or any sensitive information inside NSUserDefault, by using a simple file manager you can read all the data stored in it, it is really unsafe.
you don't even need a database or sort of. The right place to store sensitive info is the keychain of your device.
There are a lot of libs on github that can help you in using it.
Pay attention that what you save inside the keychain will persist even after you remove the application.

Upvotes: 2

Anurag Sharma
Anurag Sharma

Reputation: 4855

You can consider this for saving credentials in the keychain. Just need to create an Objective-c file and import it in the Bridging-header-file of your project.

.h

#import <Foundation/Foundation.h>

@interface KeychainUserPass : NSObject

+ (void)save:(NSString *)service data:(id)data;
+ (id)load:(NSString *)service;
+ (void)delete:(NSString *)service;

@end

.m

#import "KeychainUserPass.h"

@implementation KeychainUserPass

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {

    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge id)kSecClassGenericPassword, (__bridge id)kSecClass,
            service, (__bridge id)kSecAttrService,
            service, (__bridge id)kSecAttrAccount,
            (__bridge id)kSecAttrAccessibleAfterFirstUnlock, (__bridge id)kSecAttrAccessible,
            nil];
}

+ (void)save:(NSString *)service data:(id)data {

    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}

+ (id)load:(NSString *)service {

    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef keyData = NULL;

    if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        }
        @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        }
        @finally {}
    }
    if (keyData) CFRelease(keyData);
    return ret;
}

+ (void)delete:(NSString *)service {

    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
}


@end

Usage:

Save: KeychainUserPass.save("email", data: self.YOUR_TEXT_FIELD.text!)

Load: YOUR_STRING = KeychainUserPass.load("email") as? String

Delete: KeychainUserPass.delete("email")

Upvotes: 1

Related Questions