Giter Club home page Giter Club logo

pfuser-digits's Introduction

PFUser-Digits

A way to authenticate Parse Users using the Twitter Digits API

Make sure you setup your project with Digits and with Parse

**Digits -> Firebase Migration

Steps:

1) Official Migration:

https://docs.fabric.io/apple/digits/apple-migration.html

2) Parse-Server changes:

Copy the firebaseServiceAccountKey.json from firebase into your server root folder, then add these before creating ParseServer:

process.env.FIREBASE_SERVICE_ACCOUNT_KEY = `${__dirname}/firebaseServiceAccountKey.json`;
process.env.FIREBASE_DATABASE_URL = "https://api-project-SOME_NUMBER.firebaseio.com";

Add this adapter when creating ParseServer:

oauth: {
    firebase: require("parse-server-firebase-auth-adapter")
}

Existing users with expired token

If there are any existing users, which are no longer logged into your digits session and you'd like to migrate them to a firebase session (you can't do it through the app if they're not logged in), you will need to manually add the following field in their mongoDB user instance:

"_auth_data_firebase" : {
   "id" : "COPY_THEIR_DIGITS_ID_HERE", 
   "access_token": "invalid"
}
You can run this script in mongoShell
users = db.getCollection("_User")

results = users.find({
  "_auth_data_twitter": {"$exists": true},
  "_auth_data_firebase": {"$exists": false}
 }).toArray()

results.forEach(function(e,i) { 
  d = {
    $set: {"_auth_data_firebase": {"id": e["_auth_data_twitter"]["id"], "access_token": "invalid"}} 
  } 
  users.update(e, d)
  print(e["_id"]) 
})

3) iOS Changes

This assumes you have already succesfully integrated Firebase into your project, as per the official migration guide. Make sure you have these pods installed:

pod "Fabric"
pod "Digits"
pod "Firebase/Core"
pod "Firebase/Auth"
pod "FirebaseUI/Phone"
pod "DigitsMigrationHelper"

Add the files "PFUser+Firebase.{h,m}" to your project.

Initialization (after you setup parse):

[PFUser enableFirebaseLogin];
[FIRApp configure];

Call this if your user is logged in (through digits):

[[User currentUser] tryMigrateDigitsSessionWithConsumerKey:@"KEY" consumerSecret:@"SECRET"];

Call these instead of the digits methods:

[User loginWithFirebaseInBackground];
[[User currentUser] linkWithFirebaseInBackground];

Installation

Add the files "PFUser+Digits.{h,m}" to your project.

Note: This cannot be a cocoapod at the moment since Digits is a static binary so it cannot be added as a dependency. If anyone knows a workaround please let me know.

Make sure to setup the twitter oauth when starting your parse server:

var api = new ParseServer({
    ...
    oauth: {
        twitter: {
            consumer_key: "CONSUMERKEY",
            consumer_secret: "CONSUMERSECRET"
        },
        facebook: {
            appIds: "FACEBOOK"
        }
    }
});

Parse.com version

If you are still using the Parse.com hosted server, you should use the old version of this repo, which required you to add extra cloud-code as well, it is still available under this branch: parse-hosted

Login with Digits

When you setup parse, you also need to call:

[PFUser enableDigitsLogin];

To use just call the function which will trigger the Digits sign-in flow and when succeded, will authenticate or create a new user on Parse.

You may call using blocks:

[PFUser loginWithDigitsInBackground:^(PFUser *user, NSError *error) {
    if(!error){
      // do something with user
    }
}];

Or Using Bolts:

[[PFUser loginWithDigitsInBackground] continueWithBlock: ^id (BFTask *task) {
    if(!task.error){
      PFUser *user = task.result;
      // do something with user
    }
}];

Link Existing Account

You can also link an existing account (anonymous or not) with Digits. This works in the same way as linking with Facebook and allows you to later on log back in using the Digits sign-in

[[PFUser currentUser] linkWithDigitsInBackground]; //returns BFTask*

or

[[PFUser currentUser] linkWithDigitsInBackground:^(PFUser* user, NSError* error) {}]; //block callback

Stored properties

After login or link theese digits properties are available for the current user:

-(nullable NSString *)digitsId;
-(nullable NSString *)digitsEmail;
-(nullable NSString *)digitsPhone;

You may wish to copy the digitsEmail to the stored email property on PFUser.

Note: to get the email you must specify DGTAccountFieldsEmail in the configuration as below for instance)

Logout

Even if you logout your Parse User the Digits session is maintained separately, so if you would like to logout of Digits together with Parse, make sure to do something like below when logging out:

[[PFUser logOutInBackground] continueWithSuccessBlock:^(BFTask* task) {
    [Digits sharedInstance] logout];
}];

Customising

For all the previous examples you can pass an DGTAuthenticationConfiguration object. Use it to configure the appearance of the login screen or pass in the phone number to verify. For more information view the Official documentation For example:

DGTAppearance *appearance = [DGTAppearance new];
appearance.backgroundColor = [UIColor whiteColor];
appearance.accentColor = [UIColor defaultLightBlueColor];
appearance.logoImage = [UIImage imageNamed:@"app_icon"];

DGTAuthenticationConfiguration *configuration = [[DGTAuthenticationConfiguration alloc] initWithAccountFields:DGTAccountFieldsEmail];
configuration.appearance = appearance;
configuration.phoneNumber = [User currentUser].phone;
configuration.title = NSLocalizedString(@"phone_login_title", nil);
[PFUser loginWithDigitsInBackgroundWithConfiguration:configuration];

License

The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pfuser-digits's People

Contributors

brianjd avatar bryant1410 avatar felix-dumit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

pfuser-digits's Issues

[Digits sharedInstance].session is sometimes nil causing crash

In restoreAuthenticationWithAuthData, sometimes the session will be nil. At least in testing on the simulator. It appears to be random, not sure why it's sometimes nil. When that happens the next line down will crash trying to pull out userID from nil. To fix, I just added the following:
if (!session) {
return NO;
}

Cheers

Swift 3 version? :)

Would love to have a Swift 3 version to integrate into my pure Swift app. 🏎

Revoke session on password change + Parse Server

In the ReadMe, you mention we need to disable revoking sessions when user changes password if using revokable sessions. With Parse Server, revocable sessions is required, and so is revoking sessions when the password changes.

What impact does this have? How can we work around this issue, to ensure Digits + Parse login will continue to work when the session is revoked when the password changes?

Application crash

Hi,
I used your nice tool , but unfortunately the app crashes.
Here is the log

2015-05-22 11:24:06.131 Webbit[1357:36363] [Fabric] Unable to locate application icon
2015-05-22 11:24:06.299 Webbit[1357:36363] [TwitterKit] initWithAuthConfig:authSession: Invalid parameter not satisfying: authConfig
2015-05-22 11:24:06.304 Webbit[1357:36363] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[**NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
* First throw call stack:
(
0 CoreFoundation 0x000000010da96f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010d6cebb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010d9a261f -[__NSPlaceholderDictionary initWithObjects:forKeys:count:] + 383
3 CoreFoundation 0x000000010d9b564b +[NSDictionary dictionaryWithObjects:forKeys:count:] + 59
4 Webbit 0x000000010ba4e81d __75+[PFUser(Digits) _privateDigitsLoginWithTitle:backgroundColor:accentColor:]_block_invoke + 605
5 Webbit 0x000000010baff5de -[Digits authenticateWithDigitsAppearance:viewController:title:completion:] + 751
6 Webbit 0x000000010ba4e4ff +[PFUser(Digits) _privateDigitsLoginWithTitle:backgroundColor:accentColor:] + 447
7 Webbit 0x000000010ba4d3a3 +[PFUser(Digits) loginWithDigitsInBackgroundWithTitle:backgroundColor:accentColor:] + 227
8 Webbit 0x000000010ba4cfd1 +[PFUser(Digits) loginWithDigitsInBackgroundWithTitle:backgroundColor:accentColor:completion:] + 177
9 Webbit 0x000000010ba4cf0a +[PFUser(Digits) loginWithDigitsInBackground:] + 90
10 Webbit 0x000000010ba49bca -[InboxTableViewController viewDidLoad] + 202
11 UIKit 0x000000010e2c1a90 -[UIViewController loadViewIfRequired] + 738
12 UIKit 0x000000010e2f006b -[UINavigationController _layoutViewController:] + 44
13 UIKit 0x000000010e2f05b5 -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 216
14 UIKit 0x000000010e2f06b4 -[UINavigationController _startTransition:fromViewController:toViewController:] + 92
15 UIKit 0x000000010e2f1487 -[UINavigationController _startDeferredTransitionIfNeeded:] + 523
16 UIKit 0x000000010e2f1f47 -[UINavigationController __viewWillLayoutSubviews] + 43
17 UIKit 0x000000010e437509 -[UILayoutContainerView layoutSubviews] + 202
18 UIKit 0x000000010e215973 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
19 QuartzCore 0x000000010c34fde8 -[CALayer layoutSublayers] + 150
20 QuartzCore 0x000000010c344a0e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
21 QuartzCore 0x000000010c34487e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
22 QuartzCore 0x000000010c2b263e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
23 QuartzCore 0x000000010c2b374a _ZN2CA11Transaction6commitEv + 390
24 UIKit 0x000000010e19a54d -[UIApplication _reportMainSceneUpdateFinished:] + 44
25 UIKit 0x000000010e19b238 -[UIApplication _runWithMainScene:transitionContext:completion:] + 2642
26 UIKit 0x000000010e199bf2 -[UIApplication workspaceDidEndTransaction:] + 179
27 FrontBoardServices 0x0000000112b1a2a3 __31-[FBSSerialQueue performAsync:]_block_invoke + 16
28 CoreFoundation 0x000000010d9cc53c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK
+ 12
29 CoreFoundation 0x000000010d9c2285 __CFRunLoopDoBlocks + 341
30 CoreFoundation 0x000000010d9c2045 __CFRunLoopRun + 2389
31 CoreFoundation 0x000000010d9c1486 CFRunLoopRunSpecific + 470
32 UIKit 0x000000010e199669 -[UIApplication _run] + 413
33 UIKit 0x000000010e19c420 UIApplicationMain + 1282
34 Webbit 0x000000010ba4b063 main + 115
35 libdyld.dylib 0x000000010fc8e145 start + 1
36 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Link with already-existing parse user logged in using digits

Hi, this tool looks great—is there any way to login with digits (creating an anonymous parse user) and then log back in with that digits phone number (in the event of, say, app deletion) and re-link with the same anonymous parse user?

If this already exists, sorry for the bother, I just can't really tell based on the code.

Failure to Login because `Data couldn't be read`

I've moved my Parse app to Google App Engine using MongoLab as my database.

I didn't bother migrating any data so its a clean slate.

My digits login/signup fails when attempting to login. I'm not entirely sure if this is a digits problem or something else but I'm posting it anyway.
screen shot 2016-02-28 at 4 56 26 pm
screen shot 2016-02-28 at 4 56 32 pm

Parse shutting down - What now

Im sure you heard the depressing news that Parse is shutting down.

Was wondering how this will affect this library. It looks like they are open sourcing thier server. As someone new to programming and only knows swift, would like to know what we need to do to continue using this library in our project.

Thanks

Permanently Logged-in Users

I want to have permanently logged in users just like whatsapp.

The only logic I have to implement this is to not have a logout method.

Is that sufficient or is there more to it than that?

I'm not familiar with Digits sessions - How long they persist along with parse.

Function not found error

Hi,

When i am using this class for login with digits , i am getting this error "[Error]: function not found (Code: 141, Version: 1.9.1)".

this is my code : -

  • (void)signInWithDigits
    {
    [[Digits sharedInstance] logOut];

    DGTAppearance *appearance = [DGTAppearance new];
    appearance.backgroundColor = [UIColor whiteColor];
    appearance.accentColor = [UIColor purpleColor];

    DGTAuthenticationConfiguration *configuration = [[DGTAuthenticationConfiguration alloc] initWithAccountFields:DGTAccountFieldsNone];
    configuration.appearance = appearance;
    configuration.title = @"Login with Digits";

    PFUser *oldUser = [PFUser currentUser];

    [PFUser loginWithDigitsInBackgroundWithConfiguration:configuration completion:^(PFUser *user, NSError *error) {}

can you please tell me what did i wrong ?

Migration guide for hosted Parse Server

Hi, Thanks for the migration guide! Can you give me a clue on how to perform step (2) from your guide with a hosted Parse Server (Parse On Buddy)? I don't think I have a possibility to modify the server or add anything to the root (don't have access to their console or ftp at all) and any actions are restricted to Parse-like web interface.
Thanks in advice!

How can i use this for android ???

Hi, this is working very well in my iOS app, but i still not able to login this in android.

Can you please give me idea of how to use this in android, even the method to call example, becomeInBackroud to get user session or other thing ???

Help please.

how do I logout - parse error code 209

Hey,

So I'm pretty sure I'm doing it wrong, but after logging out with PFUser.logout(), so I'm getting " Failed to run command eventually with error: Error Domain=Parse Code=209 "invalid session token" UserInfo={code=209, temporary=0, error=invalid session token, NSLocalizedDescription=invalid session token}
"...

Presumably I need to flush the session somehow.

Btw thanks so much for this repo. Digits is by far the better option tot he Twilio solution provided in parse docs.

PFSession not created (?) upon successful login

Thanks for the PFUser+Digits framework. Works good so far.

I see one issue (maybe two). Upon a successful sign-in with Phone number, I get a valid response in PFUser.currentUser(), which is great (and expected).
However, there is no associated PFSession object. If I try to obtain PFSession.getCurrentSession() it always returns an error (Error Domain=Parse Code=209 "invalid session token").

Similarly, when I check the Parse data, I see the User created correctly (I have two users, each corresponding to different phone numbers), but no objects in Session.

Any idea what's contributing to this?

Thanks

Invalid session token after linking an existing PFUser with Digits

After linking an existing account with Digits using linkWithDigitsInBackground, I keep receiving these errors:

Error Domain=Parse Code=209 "invalid session token" UserInfo={code=209, temporary=0, error=invalid session token, NSLocalizedDescription=invalid session token}

Is there something specific to do to avoid these errors?

Thanks,
Cyril

Parse Error Code 1 upon loginWithDigitsInBackgroundWithConfiguration

Using Parse Server, I've been able to log into Digits successfully, but then when it tries to log in with Parse (loginWithDigitsInBackgroundWithConfiguration) it fails. It looks like it's failing in logInCurrentUserAsyncWithAuthType:authData:revocableSession: as it's not triggering continueWithSuccessBlock. It does have auth data. I can successfully create a regular Parse user account.

currentUser is nil and error is:
Error Domain=Parse Code=1 "{"code":1,"message":"Internal server error."}" UserInfo={error={"code":1,"message":"Internal server error."}, NSLocalizedDescription={"code":1,"message":"Internal server error."}, code=1}

Let me know if you need any further information! Thanks

Add extra field to signup flow

Hi,

I want to add a final step after signup asking a user for their "name"

How could I do it?

This is my entire loginSignupCode

@IBAction func loginSignupButton(sender: AnyObject) {

    PFUser.loginWithDigitsInBackground { (user:PFUser?, error:NSError?) -> Void in
        if error == nil {

            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("ShowMessagesViewController", sender: self)
            }


        } else {
            print("there was an error")
        }
    }
}

PFUser never logs out and Can't bring back Digits Signup Flow

Two issues:
After initially signing up my PFUser, I can never get them to logout with any logout method.
Even after deleting the sessions and user in the Parse dashboard, the user still persists somewhere - magic. I occasionally get "Invalid session Token" errors.

That brings another issue:
I can't seem to bring back the Digits signup flow after initially creating a user on any given device.
The first time I try to signup -> I get the digitsSignup Flow.

Once I logout and try again, that Flow no longer shows up. Instead I'm automatically logged in. No matter what I do, that Digits Flow is lost for good for some reason.

class LoginSignupViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

    //If there is a user currently logged in, send them to the InitialViewController
    if PFUser.currentUser() != nil {
        dispatch_async(dispatch_get_main_queue()) {
        self.performSegueWithIdentifier("ShowInitialVC", sender: self)
        }
    }
}

}

//Digits login method
@IBAction func loginSignupButton(sender: AnyObject) {

    PFUser.loginWithDigitsInBackground { (user:PFUser?, error:NSError?) -> Void in
        if error == nil {

            dispatch_async(dispatch_get_main_queue()) {
                self.performSegueWithIdentifier("ShowInitialVC", sender: self)
            }

        } else {
            print("there was an error")
        }
    }
}

//MY LOGOUT METHOD
class InitialViewController: UIViewController {

@IBAction func logoutButton(sender: AnyObject) {

    PFUser.logOutInBackground()

     //Go back to root view controller
    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let loginSignupViewController = mainStoryboard.instantiateViewControllerWithIdentifier("LoginSignupViewController")
    presentViewController(loginSignupViewController, animated: true, completion: nil)
}

//PFUser+Digits.swift extension goes here!

Invalid configuration

Hi, thanks for the amazing tool.

I am getting this issue when calling loginWithDigitsInBackground:
[TwitterKit] initWithAPIClient:configuration: Invalid parameter not satisfying: configuration

I'm sure it is a mistake on my part though. Any help to point out where the issue could be? It's weird because I am supposed to see the DigitsKit and not Twitter since the change Twitter made a while ago (also mentioned in another issue).

Thanks in advance!

Error response from Twitter: Could not authenticate you.

Hi there! First of all, thank you very much for this category, I found it very helpful!
I have successfully integrated Digits with your category for one of my apps. However, when I performed exactly the same steps for another app, this doesn't seems worked. I'm getting an error from verifyDigitsLogin cloud code function. Here are the logs:

I2015-09-17T05:02:07.425Z]OAuth oauth_signature="tz0J6GcxKKMDSma9%2cF9cKSiiGKg%3D",oauth_nonce="A603B1D1-2458-4999-80AA-E4CDF82B89C0",oauth_timestamp="1442463126",oauth_consumer_key="xIn9jwGoZDl7e2AzIUgMXN2ZI",oauth_token="3675347803-znGyo526xSQXt8W50d9am47tfNcFHG83OyQ10wT",oauth_version="1.0",oauth_signature_method="HMAC-SHA1"

I2015-09-17T05:02:07.576Z]{"uuid":"e8d06d7a-d53a-f820-e2ad-463ac93349d5","status":401,"headers":{"content-encoding":"gzip","content-length":"89","content-type":"application/json;charset=utf-8","date":"Thu, 17 Sep 2015 05:02:07 GMT","server":"tsa_b","strict-transport-security":"max-age=631138519","x-connection-hash":"358148c835d378f8571e04bb587dd80a","x-response-time":"17"},"text":"{\"errors\":[{\"code\":32,\"message\":\"Could not authenticate you.\"}]}","data":{"errors":[]},"buffer":[123,34,101,114,114,111,114,115,34,58,91,123,34,99,111,100,101,34,58,51,50,44,34,109,101,115,115,97,103,101,34,58,34,67,111,117,108,100,32,110,111,116,32,97,117,116,104,101,110,116,105,99,97,116,101,32,121,111,117,46,34,125,93,125],"cookies":{}}

Any ideas what's going on?

Digits is shutting down...

Digits will stop working after Sept 30th.. It says we Need to move it to Firebase.. Or An Alternative would be Facebook AccountKit.. it would be great if you had an idea on how to update those codes to use either both. Sorry for the disturbance! i wish you a pleasant day!

Swift 3

Hello @felix-dumit,

Thank you for this perfect library. I'm trying to use it with swift 3.

But I'm getting this error when I'm trying to use it.

 public static func loginWithDigitsInBackgroundWithConfiguration(_ configuration: DGTAuthenticationConfiguration?) -> BFTask<AnyObject> {


        return PFUser._privateDigitsLoginWithConfiguration(configuration).continue{ task in
            guard let result = task.result as? [String:AnyObject] else {
                return nil
            }
            let requestURLString = result[Constants.requestURLStringKey] as! String
            let authorizationHeader = result[Constants.authorizationHeaderKey] as! String
            print(Constants)
            return PFCloud.callFunction(inBackground: "loginWithDigits", withParameters: ["requestURL": requestURLString, "authHeader": authorizationHeader])
            }.continue {
                PFUser.become(inBackground: $0.result as! String)
        }


    }

error
PFUser+Digits.swift:54:23: Ambiguous use of 'continue'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.