Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 22.05 KB | None | 0 0
  1.     using System.Collections;
  2.     using System.Collections.Generic;
  3.     using UnityEngine;
  4.     using PlayFab;
  5.     using PlayFab.ClientModels;
  6.     using LoginResult = PlayFab.ClientModels.LoginResult;
  7.     using System;
  8.  
  9.     #if FACEBOOK
  10.     using Facebook.Unity;
  11.     #endif
  12.  
  13.     /// <summary>
  14.     /// Supported Authentication types
  15.     /// Note: Add types to there to support more AuthTypes
  16.     /// See - https://api.playfab.com/documentation/client#Authentication
  17.     /// </summary>
  18.     public enum Authtypes
  19.     {
  20.         None,
  21.         Silent,
  22.         UsernameAndPassword,
  23.         EmailAndPassword,
  24.         RegisterPlayFabAccount,
  25.         Steam,
  26.         Facebook,
  27.         Google
  28.     }
  29.  
  30.     public class PlayFabAuthService
  31.     {
  32.  
  33.         //Events to subscribe to for this service
  34.         public delegate void DisplayAuthenticationEvent();
  35.         public static event DisplayAuthenticationEvent OnDisplayAuthentication;
  36.  
  37.         public delegate void LoginSuccessEvent(LoginResult success);
  38.         public static event LoginSuccessEvent OnLoginSuccess;
  39.  
  40.         public delegate void PlayFabErrorEvent(PlayFabError error);
  41.         public static event PlayFabErrorEvent OnPlayFabError;
  42.  
  43.         //These are fields that we set when we are using the service.
  44.         public string Email;
  45.         public string Username;
  46.         public string Password;
  47.         public string AuthTicket;
  48.         public GetPlayerCombinedInfoRequestParams InfoRequestParams;
  49.  
  50.         //this is a force link flag for custom ids for demoing
  51.         public bool ForceLink = false;
  52.  
  53.         //Accessbility for PlayFab ID & Session Tickets & Display Name
  54.         public static string PlayFabId { get { return _playFabId; } }
  55.         private static string _playFabId;
  56.         public static string SessionTicket { get { return _sessionTicket; } }
  57.         private static string _sessionTicket;
  58.         public static string DisplayName { get { return _displayName; } }
  59.         private static string _displayName;
  60.  
  61.         private const string _LoginRememberKey = "PlayFabLoginRemember";
  62.         private const string _PlayFabRememberMeIdKey = "PlayFabIdPassGuid";
  63.         private const string _PlayFabAuthTypeKey = "PlayFabAuthType";
  64.  
  65.         public static PlayFabAuthService Instance
  66.         {
  67.             get
  68.             {
  69.                 if (_instance == null)
  70.                 {
  71.                     _instance = new PlayFabAuthService();
  72.                 }
  73.                 return _instance;
  74.             }
  75.         }
  76.         private static PlayFabAuthService _instance;
  77.  
  78.         public PlayFabAuthService()
  79.         {
  80.             _instance = this;
  81.         }
  82.  
  83.  
  84.         /// <summary>
  85.         /// Remember the user next time they log in
  86.         /// This is used for Auto-Login purpose.
  87.         /// </summary>
  88.         public bool RememberMe
  89.         {
  90.             get
  91.             {
  92.                 return PlayerPrefs.GetInt(_LoginRememberKey, 0) == 0 ? false : true;
  93.             }
  94.             set
  95.             {
  96.                 PlayerPrefs.SetInt(_LoginRememberKey, value ? 1 : 0);
  97.             }
  98.         }
  99.  
  100.         /// <summary>
  101.         /// Remember the type of authenticate for the user
  102.         /// </summary>
  103.         public Authtypes AuthType
  104.         {
  105.             get
  106.             {
  107.                 return (Authtypes)PlayerPrefs.GetInt(_PlayFabAuthTypeKey, 0);
  108.             }
  109.             set
  110.             {
  111.  
  112.                 PlayerPrefs.SetInt(_PlayFabAuthTypeKey, (int)value);
  113.             }
  114.         }
  115.  
  116.         /// <summary>
  117.         /// Generated Remember Me ID
  118.         /// Pass Null for a value to have one auto-generated.
  119.         /// </summary>
  120.         private string RememberMeId
  121.         {
  122.             get
  123.             {
  124.                 return PlayerPrefs.GetString(_PlayFabRememberMeIdKey, "");
  125.             }
  126.             set
  127.             {
  128.                 var guid = string.IsNullOrEmpty(value) ? Guid.NewGuid().ToString() : value;
  129.                 PlayerPrefs.SetString(_PlayFabRememberMeIdKey, guid);
  130.             }
  131.         }
  132.  
  133.         public void ClearRememberMe()
  134.         {
  135.             PlayerPrefs.DeleteKey(_LoginRememberKey);
  136.             PlayerPrefs.DeleteKey(_PlayFabRememberMeIdKey);
  137.         }
  138.  
  139.         /// <summary>
  140.         /// Kick off the authentication process by specific authtype.
  141.         /// </summary>
  142.         /// <param name="authType"></param>
  143.         public void Authenticate(Authtypes authType)
  144.         {
  145.             AuthType = authType;
  146.             Authenticate();
  147.         }
  148.  
  149.         /// <summary>
  150.         /// Authenticate the user by the Auth Type that was defined.
  151.         /// </summary>
  152.         public void Authenticate()
  153.         {
  154.             var authType = AuthType;
  155.             Debug.Log(authType);
  156.             switch (authType)
  157.             {
  158.                 case Authtypes.None:
  159.                     if (OnDisplayAuthentication != null)
  160.                     {
  161.                         OnDisplayAuthentication.Invoke();
  162.                     }
  163.                     break;
  164.  
  165.                 case Authtypes.Silent:
  166.                     SilentlyAuthenticate();
  167.                     break;
  168.  
  169.                 case Authtypes.EmailAndPassword:
  170.                     AuthenticateEmailPassword();
  171.                     break;
  172.                 case Authtypes.RegisterPlayFabAccount:
  173.                     AddAccountAndPassword();
  174.                     break;
  175.                 case Authtypes.Steam:
  176.                     AuthenticateSteam();
  177.                     break;
  178.                 case Authtypes.Facebook:
  179.                     AuthenticateFacebook();
  180.                     break;
  181.  
  182.                 case Authtypes.Google:
  183.                     AuthenticateGooglePlayGames();
  184.                     break;
  185.  
  186.             }
  187.  
  188.  
  189.         }
  190.  
  191.  
  192.         /// <summary>
  193.         /// Authenticate a user in PlayFab using an Email & Password combo
  194.         /// </summary>
  195.         private void AuthenticateEmailPassword()
  196.         {
  197.             //Check if the users has opted to be remembered.
  198.             if (RememberMe && !string.IsNullOrEmpty(RememberMeId))
  199.             {
  200.                 //If the user is being remembered, then log them in with a customid that was
  201.                 //generated by the RememberMeId property
  202.                 PlayFabClientAPI.LoginWithCustomID(new LoginWithCustomIDRequest()
  203.                 {
  204.                     TitleId = PlayFabSettings.TitleId,
  205.                     CustomId = RememberMeId,
  206.                     CreateAccount = true,
  207.                     InfoRequestParameters = InfoRequestParams
  208.                 }, (result) =>
  209.                 {
  210.                     //Store identity and session
  211.                     _playFabId = result.PlayFabId;
  212.                     _sessionTicket = result.SessionTicket;
  213.  
  214.                     if (OnLoginSuccess != null)
  215.                     {
  216.                         //report login result back to subscriber
  217.                         OnLoginSuccess.Invoke(result);
  218.                     }
  219.                 }, (error) =>
  220.                 {
  221.                     if (OnPlayFabError != null)
  222.                     {
  223.                         //report error back to subscriber
  224.                         OnPlayFabError.Invoke(error);
  225.                     }
  226.                 });
  227.                 return;
  228.             }
  229.  
  230.             //a good catch: If username & password is empty, then do not continue, and Call back to Authentication UI Display
  231.             if (!RememberMe && string.IsNullOrEmpty(Email) && string.IsNullOrEmpty(Password))
  232.             {
  233.                 OnDisplayAuthentication.Invoke();
  234.                 return;
  235.             }
  236.  
  237.  
  238.             //We have not opted for remember me in a previous session, so now we have to login the user with email & password.
  239.             PlayFabClientAPI.LoginWithEmailAddress(new LoginWithEmailAddressRequest()
  240.             {
  241.                 TitleId = PlayFabSettings.TitleId,
  242.                 Email = Email,
  243.                 Password = Password,
  244.                 InfoRequestParameters = InfoRequestParams
  245.             }, (result) =>
  246.             {
  247.                 //store identity and session
  248.                 _playFabId = result.PlayFabId;
  249.                 _sessionTicket = result.SessionTicket;
  250.  
  251.                 //Note: At this point, they already have an account with PlayFab using a Username (email) & Password
  252.                 //If RememberMe is checked, then generate a new Guid for Login with CustomId.
  253.                 if (RememberMe)
  254.                 {
  255.                     RememberMeId = Guid.NewGuid().ToString();
  256.                     AuthType = Authtypes.EmailAndPassword;
  257.                     //Fire and forget, but link a custom ID to this PlayFab Account.
  258.                     PlayFabClientAPI.LinkCustomID(new LinkCustomIDRequest()
  259.                     {
  260.                         CustomId = RememberMeId,
  261.                         ForceLink = ForceLink
  262.                     }, null, null);
  263.                 }
  264.  
  265.                 if (OnLoginSuccess != null)
  266.                 {
  267.                     //report login result back to subscriber
  268.                     OnLoginSuccess.Invoke(result);
  269.                 }
  270.             }, (error) =>
  271.             {
  272.                 if (OnPlayFabError != null)
  273.                 {
  274.                     //Report error back to subscriber
  275.                     OnPlayFabError.Invoke(error);
  276.                 }
  277.             });
  278.         }
  279.  
  280.         /// <summary>
  281.         /// Register a user with an Email & Password
  282.         /// Note: We are not using the RegisterPlayFab API
  283.         /// </summary>
  284.         private void AddAccountAndPassword()
  285.         {
  286.             //Any time we attempt to register a player, first silently authenticate the player.
  287.             //This will retain the players True Origination (Android, iOS, Desktop)
  288.             SilentlyAuthenticate((result) => {
  289.  
  290.                 if (result == null)
  291.                 {
  292.                     //something went wrong with Silent Authentication, Check the debug console.
  293.                     OnPlayFabError.Invoke(new PlayFabError()
  294.                     {
  295.                         Error = PlayFabErrorCode.UnknownError,
  296.                         ErrorMessage = "Silent Authentication by Device failed"
  297.                     });
  298.                 }
  299.  
  300.                 //Note: If silent auth is success, which is should always be and the following
  301.                 //below code fails because of some error returned by the server ( like invalid email or bad password )
  302.                 //this is okay, because the next attempt will still use the same silent account that was already created.
  303.  
  304.                 //Now add our username & password.
  305.                 PlayFabClientAPI.AddUsernamePassword(new AddUsernamePasswordRequest()
  306.                 {
  307.                     Username = !string.IsNullOrEmpty(Username) ? Username : result.PlayFabId, //Because it is required & Unique and not supplied by User.
  308.                     Email = Email,
  309.                     Password = Password,
  310.                 }, (addResult) => {
  311.                     if (OnLoginSuccess != null)
  312.                     {
  313.                         //Store identity and session
  314.                         _playFabId = result.PlayFabId;
  315.                         _sessionTicket = result.SessionTicket;
  316.  
  317.                         //If they opted to be remembered on next login.
  318.                         if (RememberMe)
  319.                         {
  320.                             //Generate a new Guid
  321.                             RememberMeId = Guid.NewGuid().ToString();
  322.                             //Fire and forget, but link the custom ID to this PlayFab Account.
  323.                             PlayFabClientAPI.LinkCustomID(new LinkCustomIDRequest()
  324.                             {
  325.                                 CustomId = RememberMeId,
  326.                                 ForceLink = ForceLink
  327.                             }, null, null);
  328.                         }
  329.  
  330.                         //Override the auth type to ensure next login is using this auth type.
  331.                         AuthType = Authtypes.EmailAndPassword;
  332.  
  333.                         //Report login result back to subscriber.
  334.                         OnLoginSuccess.Invoke(result);
  335.                     }
  336.                 }, (error) => {
  337.                     if (OnPlayFabError != null)
  338.                     {
  339.                         //Report error result back to subscriber
  340.                         OnPlayFabError.Invoke(error);
  341.                     }
  342.                 });
  343.  
  344.             });
  345.         }
  346.  
  347.         private void AuthenticateFacebook()
  348.         {
  349.     #if FACEBOOK
  350.             if (FB.IsInitialized && FB.IsLoggedIn && !string.IsNullOrEmpty(AuthTicket))
  351.             {
  352.                 PlayFabClientAPI.LoginWithFacebook(new LoginWithFacebookRequest()
  353.                 {
  354.                     TitleId = PlayFabSettings.TitleId,
  355.                     AccessToken = AuthTicket,
  356.                     CreateAccount = true,
  357.                     InfoRequestParameters = InfoRequestParams
  358.                 }, (result) =>
  359.                 {
  360.                     //Store Identity and session
  361.                     _playFabId = result.PlayFabId;
  362.                     _sessionTicket = result.SessionTicket;
  363.  
  364.                     //check if we want to get this callback directly or send to event subscribers.
  365.                     if (OnLoginSuccess != null)
  366.                     {
  367.                         //report login result back to the subscriber
  368.                         OnLoginSuccess.Invoke(result);
  369.                     }
  370.                 }, (error) =>
  371.                 {
  372.  
  373.                     //report errro back to the subscriber
  374.                     if (OnPlayFabError != null)
  375.                     {
  376.                         OnPlayFabError.Invoke(error);
  377.                     }
  378.                 });
  379.             }
  380.             else
  381.             {
  382.                 if (OnDisplayAuthentication != null)
  383.                 {
  384.                     OnDisplayAuthentication.Invoke();
  385.                 }
  386.             }
  387.     #endif
  388.         }
  389.  
  390.         private void AuthenticateGooglePlayGames()
  391.         {
  392.     #if GOOGLEGAMES
  393.             PlayFabClientAPI.LoginWithGoogleAccount(new LoginWithGoogleAccountRequest()
  394.             {
  395.                 TitleId = PlayFabSettings.TitleId,
  396.                 ServerAuthCode = AuthTicket,
  397.                 InfoRequestParameters = InfoRequestParams,
  398.                 CreateAccount = true
  399.             }, (result) =>
  400.             {
  401.                 //Store Identity and session
  402.                 _playFabId = result.PlayFabId;
  403.                 _sessionTicket = result.SessionTicket;
  404.  
  405.                 //check if we want to get this callback directly or send to event subscribers.
  406.                 if (OnLoginSuccess != null)
  407.                 {
  408.                     //report login result back to the subscriber
  409.                     OnLoginSuccess.Invoke(result);
  410.                 }
  411.             }, (error) =>
  412.             {
  413.  
  414.                 //report errro back to the subscriber
  415.                 if (OnPlayFabError != null)
  416.                 {
  417.                     OnPlayFabError.Invoke(error);
  418.                 }
  419.             });
  420.     #endif
  421.         }
  422.  
  423.         private void AuthenticateSteam()
  424.         {
  425.  
  426.         }
  427.  
  428.  
  429.         private void SilentlyAuthenticate(System.Action<LoginResult> callback = null)
  430.         {
  431.     #if UNITY_ANDROID  //&& !UNITY_EDITOR
  432.  
  433.             //Get the device id from native android
  434.             AndroidJavaClass up = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  435.             AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject>("currentActivity");
  436.             AndroidJavaObject contentResolver = currentActivity.Call<AndroidJavaObject>("getContentResolver");
  437.             AndroidJavaClass secure = new AndroidJavaClass("android.provider.Settings$Secure");
  438.             string deviceId = secure.CallStatic<string>("getString", contentResolver, "android_id");
  439.  
  440.             //Login with the android device ID
  441.             PlayFabClientAPI.LoginWithAndroidDeviceID(new LoginWithAndroidDeviceIDRequest() {
  442.                 TitleId = PlayFabSettings.TitleId,
  443.                 AndroidDevice = SystemInfo.deviceModel,
  444.                 OS = SystemInfo.operatingSystem,
  445.                 AndroidDeviceId = deviceId,
  446.                 CreateAccount = true,
  447.                 InfoRequestParameters = InfoRequestParams
  448.             }, (result) => {
  449.            
  450.                 //Store Identity and session and display name
  451.              
  452.                 _playFabId = result.PlayFabId;
  453.                 _sessionTicket = result.SessionTicket;
  454.            
  455.                 //check if we want to get this callback directly or send to event subscribers.
  456.                 if (callback == null && OnLoginSuccess != null)
  457.                 {
  458.                     //report login result back to the subscriber
  459.                     OnLoginSuccess.Invoke(result);
  460.                 }else if (callback != null)
  461.                 {
  462.                     //report login result back to the caller
  463.                     callback.Invoke(result);
  464.                 }
  465.             }, (error) => {
  466.  
  467.                 //report errro back to the subscriber
  468.                 if(callback == null && OnPlayFabError != null){
  469.                     OnPlayFabError.Invoke(error);
  470.                 }else{
  471.                     //make sure the loop completes, callback with null
  472.                     callback.Invoke(null);
  473.                     //Output what went wrong to the console.
  474.                     Debug.LogError(error.GenerateErrorReport());
  475.                 }
  476.             });
  477.  
  478.     #elif  UNITY_IPHONE || UNITY_IOS && !UNITY_EDITOR
  479.             PlayFabClientAPI.LoginWithIOSDeviceID(new LoginWithIOSDeviceIDRequest() {
  480.                 TitleId = PlayFabSettings.TitleId,
  481.                 DeviceModel = SystemInfo.deviceModel,
  482.                 OS = SystemInfo.operatingSystem,
  483.                 DeviceId = SystemInfo.deviceUniqueIdentifier,
  484.                 CreateAccount = true,
  485.                 InfoRequestParameters = InfoRequestParams
  486.             }, (result) => {
  487.                 //Store Identity and session
  488.                 _playFabId = result.PlayFabId;
  489.                 _sessionTicket = result.SessionTicket;
  490.  
  491.                 //check if we want to get this callback directly or send to event subscribers.
  492.                 if (callback == null && OnLoginSuccess != null)
  493.                 {
  494.                     //report login result back to the subscriber
  495.                     OnLoginSuccess.Invoke(result);
  496.                 }else if (callback != null)
  497.                 {
  498.                     //report login result back to the caller
  499.                     callback.Invoke(result);
  500.                 }
  501.             }, (error) => {
  502.                 //report errro back to the subscriber
  503.                 if(callback == null && OnPlayFabError != null){
  504.                     OnPlayFabError.Invoke(error);
  505.                 }else{
  506.                     //make sure the loop completes, callback with null
  507.                     callback.Invoke(null);
  508.                     //Output what went wrong to the console.
  509.                     Debug.LogError(error.GenerateErrorReport());
  510.                 }
  511.             });
  512.     #else
  513.             PlayFabClientAPI.LoginWithCustomID(new LoginWithCustomIDRequest()
  514.             {
  515.                 TitleId = PlayFabSettings.TitleId,
  516.                 CustomId = SystemInfo.deviceUniqueIdentifier,
  517.                 CreateAccount = true,
  518.                 InfoRequestParameters = InfoRequestParams
  519.             }, (result) => {
  520.                 //Store Identity and session
  521.                 _playFabId = result.PlayFabId;
  522.                 _sessionTicket = result.SessionTicket;
  523.  
  524.                 //check if we want to get this callback directly or send to event subscribers.
  525.                 if (callback == null && OnLoginSuccess != null)
  526.                 {
  527.                     //report login result back to the subscriber
  528.                     OnLoginSuccess.Invoke(result);
  529.                 }
  530.                 else if (callback != null)
  531.                 {
  532.                     //report login result back to the caller
  533.                     callback.Invoke(result);
  534.                 }
  535.             }, (error) => {
  536.                 //report errro back to the subscriber
  537.                 if (callback == null && OnPlayFabError != null)
  538.                 {
  539.                     OnPlayFabError.Invoke(error);
  540.                 }
  541.                 else
  542.                 {
  543.                     //make sure the loop completes, callback with null
  544.                     callback.Invoke(null);
  545.                     //Output what went wrong to the console.
  546.                     Debug.LogError(error.GenerateErrorReport());
  547.                 }
  548.  
  549.             });
  550.     #endif
  551.         }
  552.  
  553.         public void UnlinkSilentAuth()
  554.         {
  555.             SilentlyAuthenticate((result) =>
  556.             {
  557.  
  558.     #if UNITY_ANDROID //&& !UNITY_EDITOR
  559.                 //Get the device id from native android
  560.                 AndroidJavaClass up = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  561.                 AndroidJavaObject currentActivity = up.GetStatic<AndroidJavaObject>("currentActivity");
  562.                 AndroidJavaObject contentResolver = currentActivity.Call<AndroidJavaObject>("getContentResolver");
  563.                 AndroidJavaClass secure = new AndroidJavaClass("android.provider.Settings$Secure");
  564.                 string deviceId = secure.CallStatic<string>("getString", contentResolver, "android_id");
  565.  
  566.                 //Fire and forget, unlink this android device.
  567.                 PlayFabClientAPI.UnlinkAndroidDeviceID(new UnlinkAndroidDeviceIDRequest() {
  568.                     AndroidDeviceId = deviceId
  569.                 }, null, null);
  570.  
  571.     #elif UNITY_IPHONE || UNITY_IOS && !UNITY_EDITOR
  572.                 PlayFabClientAPI.UnlinkIOSDeviceID(new UnlinkIOSDeviceIDRequest()
  573.                 {
  574.                     DeviceId = SystemInfo.deviceUniqueIdentifier
  575.                 }, null, null);
  576.     #else
  577.                 PlayFabClientAPI.UnlinkCustomID(new UnlinkCustomIDRequest()
  578.                 {
  579.                     CustomId = SystemInfo.deviceUniqueIdentifier
  580.                 }, null, null);
  581.     #endif
  582.  
  583.             });
  584.         }
  585.  
  586.  
  587.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement