How to add state tracking AWS iOS? - swift

I am having trouble using this code from AWS documentation to check the user state. No matter where I place it prints nothing. I also have properly set up my project with the AWS iOS SDK. I have placed in the AppDelegate and in different view controller's viewDidLoad and viewDidAppear however it still prints nothing.
AWSMobileClient.default().addUserStateListener(self) { (userState, info) in
switch (userState) {
case .guest:
print("user is in guest mode.")
case .signedOut:
print("user signed out")
case .signedIn:
print("user is signed in.")
case .signedOutUserPoolsTokenInvalid:
print("need to login again.")
case .signedOutFederatedTokensInvalid:
print("user logged in via federation, but currently needs new tokens")
default:
print("unsupported")
}
}

Related

How to handle user after registration?

I need to register my user's with both phone authentication and email authentication. I have successfully done both. However, with the way I've structured my code, it's a bit flimsy.
After a user registers with their phone number, they are automatically signed in. But before they gain access to the application I need them to register with their email as well but I can't do so until they are signed in with their phone.
Group {
if (self.session.session != nil) {
if user?.metadata.creationDate != user?.metadata.lastSignInDate {
AppView()
} else {
EmailRegisterView()
}
} else {
OnBoardingView()
}
}.onAppear(perform: {
session.listen()
})
With the code I have, if the user for some reason logs out of their account on the same day that they've created it, they will be taken to the EmailRegisterView() again which will cause problems.
Is there another way to redirect users to the EmailRegisterView() only if they are new users, and once they have finished there, send them to the AppView()?
Here is my code for the phone authentication...
func phoneRegister () {
let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.verificationCode, verificationCode: self.code)
Auth.auth().signIn(with: credential) { (result, error) in
if error != nil{
self.alertMessage = (error?.localizedDescription)!
self.alert.toggle()
return
}
UserDefaults.standard.set(true, forKey: "status")
NotificationCenter.default.post(name: NSNotification.Name("statusChange"), object: nil)
}
}
Looks like you can add a key to user default and check the value every time the user open the app.
If the userdefault bool key, let's say IsUserRegistered, doesn't exist or is set to false, then you navigate to login page/register page and set the key to true. Otherwise, if the the key is set to true, you just display the home view.

How to relinquish MacOS Camera,Microphone

In trying to code up a prototype, it struct me there's no way revert the request?
So, you add the entitlements of interest to your app's capabilities, and here is I check:
internal func avStatus(for media: AVMediaType) -> AVAuthorizationStatus {
let status = AVCaptureDevice.authorizationStatus(for: media)
switch status {
case .authorized: // The user has previously granted access to the microphone.
return .authorized
case .notDetermined: // The user has not yet been asked for microphone access.
return .notDetermined
case .denied: // The user has previously denied access.
return .denied
case .restricted: // The user can't grant access due to restrictions.
return .restricted
default:
Swift.print("Unknown AV status \(status) for .audio")
return status
}
}
I was thinking that a user action to request the use of the entitlement, and relinquish would be needed:
#objc #IBAction func audioVideoServicesPress(_ sender: AnyObject) {
let service = sender.title.components(separatedBy: " ").last
let media : AVMediaType = service == "Audio" ? .audio : .video
let status = self.avStatus(for: media)
guard ![.denied,.restricted].contains(status) else { return }
if status == .authorized {
print("how do we relinquish need in the a/v device")
}
else
{
AVCaptureDevice.requestAccess(for: media, completionHandler: { granted in
return
})
}
}
In other user actions, if they had disabled or denied, then I would route them to the proper settings app, but before I get there, how to undo the request?
This is no way to un-request access the a/v device?
I think that suggests I'm going about this all wrong?
There is nothing to "relinquish."
The user's button press is an intent. The user wants to perform some action that can be performed only if you have authorization. So if you have it or can get, your job now is to do it.
Okay, so either you have authorization or you don't. If authorization status is .undetermined, you might get it. If it's .authorized, you already did get it. In either of those cases, do what the user intends!
At the time of your print line, you have authorization so now go ahead and do whatever the user pressed the button intending to do.
Similarly, do not return in the completion handler for requesting access; instead, check granted and if true, do whatever the user pressed the button intending to do.
In any other case, you are hosed, so do nothing. The user's intent requires an authorization you don't have and cannot get. You might put up a dialog explaining why you can't do it, or send them off to where they can access their settings, but that's all you can do from here.

swift: How to keep ios user logged in using mongoDB Realm database and authentication

I want to keep user logged and not need to show login form everytime they open the app. I am using MongoDB Realm for database and authentication.
Right now the login works fine but it's required everytime the app is opened.
this my login code
#objc func signUp() {
setLoading(true);
app.usernamePasswordProviderClient().registerEmail(username!, password: password!, completion: {[weak self](error) in
// Completion handlers are not necessarily called on the UI thread.
// This call to DispatchQueue.main.sync ensures that any changes to the UI,
// namely disabling the loading indicator and navigating to the next page,
// are handled on the UI thread:
DispatchQueue.main.sync {
self!.setLoading(false);
guard error == nil else {
print("Signup failed: \(error!)")
self!.errorLabel.text = "Signup failed: \(error!.localizedDescription)"
return
}
print("Signup successful!")
// Registering just registers. Now we need to sign in, but we can reuse the existing username and password.
self!.errorLabel.text = "Signup successful! Signing in..."
self!.signIn()
}
})
}
#objc func signIn() {
print("Log in as user: \(username!)");
setLoading(true);
app.login(withCredential: AppCredentials(username: username!, password: password!)) { [weak self](maybeUser, error) in
DispatchQueue.main.sync {
self!.setLoading(false);
guard error == nil else {
// Auth error: user already exists? Try logging in as that user.
print("Login failed: \(error!)");
self!.errorLabel.text = "Login failed: \(error!.localizedDescription)"
return
}
guard let user = maybeUser else {
fatalError("Invalid user object?")
}
print("Login succeeded!");
self?.navigationController?.pushViewController(hostingController, animated: true)
}
this is my app rootView where I want to check and keep the user logged in
struct AppRootView: View {
var body: some View {
AnyView {
// check if user has already logged in here and then route them accordingly
if auth.token != nil {
homeMainView()
} else {
LoginController()
}
}
}
}
how can I keep user login with MongoDB realm?
From what I understand*, once a user authenticates, they will stay authenticated 'logged in' on that device until they are manually logged out, keeping in mind that once they are logged out their access token remains active for 30 minutes.
Two things from the guide
The access token for a session expires after thirty minutes. However,
a new session can be started by retrieving a new access token from
MongoDB Realm using the refresh token. (Important ->) The SDKs automatically take
care of refreshing access tokens, so you do not need to worry about
this when implementing client applications.
and
MongoDB Realm handles the access tokens and refresh tokens that
comprise a user session automatically.
What we are doing, which appears to be working ok, is this: When the app opens, we call a func handleSignIn which checks to see if the app has a .currentUser. If so, then we configure Realm. If not, a login/signup view is presented. Here's a snippit
func handleSignIn() {
if let _ = gTaskApp.currentUser() {
print("user is logged in")
self.configRealmSync()
} else {
print("not logged in; present sign in/signup view")
with gTaskApp being a global reference to our app
let gTaskApp = RealmApp(id: Constants.REALM_APP_ID)
*This is a work in progress so please feel free to correct me

Auth0 swift4 failing to handle gist scope

I am trying to use Auth0 to authorise a my app to allow Gist comments.
I am not able to get "gist" scope back.
I have configured Auth0 account correctly. Also Github account correct and everything is setup.
My login code is as follows.
Auth0
.webAuth()
.scope("gist")
.audience("https://pjdavis1970.eu.auth0.com/userinfo")
.start {
switch $0 {
case .failure(let error):
print("Error: \(error)")
case .success(let credentials):
credentialsManager.store(credentials: credentials)
DispatchQueue.main.async {
AppData.sharedInstance.setLoggedIn(loggedIn: true)
self.setButtonStatus()
}
}
}
This is returning nil in scopes. This means I am unable to use gist api to post comments. Any ideas?

Firebase authentication: linking multiple accounts in Swift

I've set up Firebase authentication for my iOS app using Facebook, Google & email/password sign in and it's all working fine. This authentication only happens when the user wants to access high-priority parts of my app (i.e. I don't require users to sign in to start using the app).
On app start up, I sign users in anonymously in the background and that's working fine too.
I've read the documentation but I'm struggling to understand the code required to enable me to link an anonymous account to a Facebook/email signed in account in the following flow:
new user opens app
user signed in anonymously in the background (new user.uid "A" created)
low priority data stored against anonymous user in Firebase realtime DB
user hits a high-priority area so needs to authenticate
user signs in using Facebook (new user.uid "B" created)
previous user.uid "A" needs to be linked to user.uid "B"
My method currently looks like this:
func signupWithFacebook(){
// track the anonymous user to link later
let prevUser = FIRAuth.auth()?.currentUser
FBSDKLoginManager().logInWithReadPermissions(["public_profile", "email"], fromViewController: self) { (result, error) in
if let token = result?.token?.tokenString {
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(token)
FIRAuth.auth()?.signInWithCredential(credential, completion: { (user, error) in
if user != nil && error == nil {
// Success
self.success?(user: user!)
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
})
}
})
}
}
}
Any pointers to remove the confusion would be great.
UPDATE:
I've realised I was confused about the app logic because of users being created during testing. Instead of 2 separate users being created for the above scenario (one authenticated via Facebook and another anonymously), all that happens is that the original anonymous user.uid "A" is "linked" to some Facebook authentication credentials. In the Firebase console this is shown by the anonymous uid changing from anonymous to one with the Facebook logo next to it.
This is what my working method looks like:
func signupWithFacebook(){
FBSDKLoginManager().logInWithReadPermissions(["public_profile", "email"], fromViewController: self) { (result, error) in
if let token = result?.token?.tokenString {
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(token)
FIRAuth.auth()?.currentUser!.linkWithCredential(credential) { (user, error) in
if user != nil && error == nil {
// Success
self.success?(user: user!)
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
})
} else {
print("linkWithCredential error:", error)
}
}
}
}
}
So your code follows the first 2 steps in this link. But the documentation explicity says not to call signInWithCredential but instead call
FIRAuth.auth()?.currentUser.linkWithCredential(credential) { (user, error) in
// ...
}
After getting your credential from Facebook's SDK.
Quote from link: "If the call to linkWithCredential:completion: succeeds, the user's new account can access the anonymous account's Firebase data."