Exemplo n.º 1
0
 Task SendAuthError(AuthError error)
 {
     PacketOut p = new PacketOut();
     p.w.Write((byte)AuthOp.AUTH_LOGON_CHALLENGE);
     p.w.Write((byte)0);
     p.w.Write((byte)error);
     SendPacket(p);
     return TaskDone.Done;
 }
Exemplo n.º 2
0
    private IEnumerator Register(string _email, string _password, string _username)
    {
        if (_username == "")
        {
            //If the username field is blank show a warning
            warningRegisterText.text = "Missing Username";
        }
        else if (passwordRegisterField.text != passwordRegisterVerifyField.text)
        {
            //If the password does not match show a warning
            warningRegisterText.text = "Password Does Not Match!";
        }
        else
        {
            //Call the Firebase auth signin function passing the email and password
            var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
            //Wait until the task completes
            yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

            if (RegisterTask.Exception != null)
            {
                //If there are errors handle them
                Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
                FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Register Failed!";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;

                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;

                case AuthError.WeakPassword:
                    message = "Weak Password";
                    break;

                case AuthError.EmailAlreadyInUse:
                    message = "Email Already In Use";
                    break;
                }
                warningRegisterText.text = message;
            }
            else
            {
                //User has now been created
                //Now get the result
                AUser = RegisterTask.Result;

                if (AUser != null)
                {
                    //Create a user profile and set the username
                    UserProfile profile = new UserProfile {
                        DisplayName = _username
                    };

                    //Call the Firebase auth update user profile function passing the profile with the username
                    var ProfileTask = AUser.UpdateUserProfileAsync(profile);
                    //Wait until the task completes
                    yield return(new WaitUntil(predicate: () => ProfileTask.IsCompleted));

                    if (ProfileTask.Exception != null)
                    {
                        //If there are errors handle them
                        Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                        FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                        AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
                        warningRegisterText.text = "Username Set Failed!";
                    }
                    else
                    {
                        //Username is now set
                        //Now return to login screen
                        UIManager.instance.LoginScreen();
                        warningRegisterText.text = "";
                    }
                }
            }
        }
    }
Exemplo n.º 3
0
    private IEnumerator Register(string _email, string _password, string _username)
    {
        if (_username == "")
        {
            warningLoginText.text = "Missing Username";
        }
        else if (passwordRegisterField.text != passwordVerifyRegisterField.text)
        {
            warningLoginText.text = "Password Does Not Match!";
        }
        else
        {
            var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
            yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

            if (RegisterTask.Exception != null)
            {
                Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
                FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Register Failed!";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;

                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;

                case AuthError.WeakPassword:
                    message = "Weak Password";
                    break;

                case AuthError.InvalidEmail:
                    message = "Email Already In Use";
                    break;
                }
                warningLoginText.text = message;
            }
            else
            {
                User = RegisterTask.Result;
                if (User != null)
                {
                    UserProfile profile = new UserProfile {
                        DisplayName = _username
                    };
                    var ProfileTask = User.UpdateUserProfileAsync(profile);
                    yield return(new WaitUntil(predicate: () => ProfileTask.IsCompleted));

                    if (ProfileTask.Exception != null)
                    {
                        Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                        FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                        AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
                        warningLoginText.text = "Username Set Failed!";
                    }
                    else
                    {
                        //Username is now set
                        reference.Child("Users").Child(User.DisplayName).Child("username").SetValueAsync(User.DisplayName);
                        LoginObj.SetActive(false);
                        RegisterObj.SetActive(true);
                        SwitchText.text       = "Войти";
                        warningLoginText.text = "";
                    }
                }
            }
        }
    }
Exemplo n.º 4
0
        public async Task <HttpResponseMessage> GetFacebookLogin(string fbId)
        {
            LogWriter._login(TAG, string.Format("[>>] REQUEST: [{0}]", fbId));
            string secToken               = HttpContext.Current.Request.Headers["Authorization"].Replace("Basic ", "").Trim();
            HttpResponseMessage message   = new HttpResponseMessage();
            LoginResponse       loginResp = new LoginResponse();
            AuthError           authError = new AuthError();
            string cip = httpUtil.GetClientIPAddress(HttpContext.Current.Request);

            try
            {
                string   decodedStr   = decodeBase64(secToken);
                string[] clientSS     = decodedStr.Split(':');
                string   clientId     = clientSS[0];
                string   clientSecret = clientSS[1];
                if (clientId == "A54FQFR46BD3U2C51D9PZ0QY8AXXC482")
                {
                    if (dbconn.idbCheck(out dbres))
                    {
                        DataTable dt = new DataTable();
                        dt = dbconn.getTable(appServiceQry._getFBUser(fbId));
                        if (dt.Rows.Count != 0)
                        {
                            string cardno      = dt.Rows[0]["CARD_NO"].ToString();
                            string adminnumber = dt.Rows[0]["ADMIN_NO"].ToString();

                            int    expSeconds     = Convert.ToInt32(TimeSpan.FromMinutes(expiryMinut).TotalSeconds.ToString());
                            string authExpireDate = DateTime.Now.AddMinutes(expiryMinut).ToString(appConstantValues.DATE_TIME_FORMAT);
                            string authToken      = tokenGenerator.generateToken(cardno);
                            string refreshToken   = tokenGenerator.generateToken(cardno);
                            if (dbconn.registerToken(cardno, adminnumber, authToken, refreshToken, cip, authExpireDate))
                            {
                                loginResp.access_token  = authToken;
                                loginResp.refresh_token = refreshToken;
                                loginResp.expires_in    = expSeconds;
                                loginResp.token_type    = "bearer";
                                message = Request.CreateResponse(HttpStatusCode.OK, loginResp);
                            }
                            else
                            {
                                authError.error             = "invalid_request";
                                authError.error_description = "[DB] Хэрэглэгчийн нэвтрэх нэр эсвэл нууц үг буруу байна.";
                                message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                            }
                        }
                        else
                        {
                            authError.error             = "invalid_request";
                            authError.error_description = appConstantValues.MSG_LOGIN_FAILED;
                            message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                        }
                    }
                    else
                    {
                        authError.error             = "invalid_request";
                        authError.error_description = appConstantValues.MSG_INTERNAL_ERROR;
                        LogWriter._error(TAG, dbres);
                        message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                    }
                }
                else
                {
                    authError.error             = "invalid_request";
                    authError.error_description = appConstantValues.MSG_LOGIN_FAILED;
                    message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                }
            }
            catch (Exception ex)
            {
                authError.error             = "invalid_request";
                authError.error_description = ex.Message;
                exceptionManager.ManageException(ex, TAG);
                message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
            }
            LogWriter._login(TAG, string.Format(@"[<<] IP: [{0}], SUCCESS RESP: [{1}], FAILED RESP: [{2}], CLIENT TOKEN: [{3}]", cip, serializer.Serialize(loginResp), serializer.Serialize(authError), secToken));
            return(message);
        }
Exemplo n.º 5
0
        public HttpResponseMessage Post([FromBody] RefreshToken injson)
        {
            HttpResponseMessage message   = null;
            LoginResponse       loginResp = new LoginResponse();
            AuthError           authError = new AuthError();
            string cip   = httpUtil.GetClientIPAddress(HttpContext.Current.Request);
            string token = HttpContext.Current.Request.Headers["Authorization"].Replace("Bearer ", "").Trim();

            try
            {
                if (token == "YGHM9SHBC81LMR4G")
                {
                    if (dbconn.idbCheck(out dbres))
                    {
                        DataTable dt = dbconn.getTable(appServiceQry._checkRToken(injson.refresh_token));
                        if (dt.Rows.Count != 0)
                        {
                            string cardno         = dt.Rows[0]["CARD_NO"].ToString();
                            string adminnumber    = dt.Rows[0]["PHONE_NO"].ToString();
                            int    expSeconds     = Convert.ToInt32(TimeSpan.FromMinutes(2).TotalSeconds.ToString());
                            string authExpireDate = DateTime.Now.AddMinutes(2).ToString(appConstantValues.DATE_TIME_FORMAT);
                            string authToken      = tokenGenerator.generateToken(cardno);
                            string refreshToken   = tokenGenerator.generateToken(cardno);
                            //string commandResult = dbconn.iDBCommand(appServiceQry._registerToken(cardno, authToken, httpUtil.GetClientIPAddress(HttpContext.Current.Request), authExpireDate));
                            if (dbconn.registerToken(cardno, adminnumber, authToken, refreshToken, cip, authExpireDate))
                            {
                                loginResp.access_token  = authToken;
                                loginResp.refresh_token = refreshToken;
                                loginResp.expires_in    = expSeconds;
                                loginResp.token_type    = "bearer";
                                message = Request.CreateResponse(HttpStatusCode.OK, loginResp);
                            }
                            else
                            {
                                authError.error             = "invalid_request";
                                authError.error_description = "[DB] Хэрэглэгчийн нэвтрэх нэр эсвэл нууц үг буруу байна.";
                                message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                            }
                        }
                        else
                        {
                            authError.error             = "invalid_request";
                            authError.error_description = appConstantValues.MSG_LOGIN_FAILED;
                            message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                        }
                    }
                    else
                    {
                        authError.error             = "invalid_request";
                        authError.error_description = appConstantValues.MSG_INTERNAL_ERROR;
                        LogWriter._error(TAG, dbres);
                        message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                    }
                }
                else
                {
                    authError.error             = "invalid_request";
                    authError.error_description = appConstantValues.MSG_LOGIN_FAILED;
                    message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
                }
            }
            catch (Exception ex)
            {
                authError.error             = "invalid_request";
                authError.error_description = ex.Message;
                exceptionManager.ManageException(ex, TAG);
                message = Request.CreateResponse(HttpStatusCode.Unauthorized, authError);
            }
            LogWriter._login(TAG, string.Format(@"IP: [{0}], REQUEST: [{1}], SUCCESS RESP: [{2}], FAILED RESP: [{3}]", cip, serializer.Serialize(injson), serializer.Serialize(loginResp), serializer.Serialize(authError)));
            return(message);
        }
Exemplo n.º 6
0
        public async Task Then_It_Should_Throw_SpotifyWebApiClientException_When_Request_Is_Invalid(AuthError authError)
        {
            // Arrange
            var error = new StringContent(JsonConvert.SerializeObject(authError), Encoding.UTF8, "application/json");
            var fakeHttpMessageHandler = new FakeHttpMessageHandler(error, HttpStatusCode.BadRequest);

            MockHttpClientFactory.Setup(x => x.CreateClient(It.IsAny <string>())).Returns(new HttpClient(fakeHttpMessageHandler));

            _sut = new SpotifyWebApiClient(Mapper, MockHttpClientFactory.Object, MockApiSettings.Object, MockLogger.Object);

            // Act
            var ex = await Assert.ThrowsAsync <SpotifyWebApiClientException>(() => _sut.GetTokenAsync());

            // Aseert
            ex.ShouldNotBe(null);
        }
Exemplo n.º 7
0
 void GetErrorMessage(AuthError ErrorCode)
 {
     msg = ErrorCode.ToString();
     print(msg);
 }
Exemplo n.º 8
0
    public IEnumerator Register(string _email, string _password, string _displayName)
    {
        LoadingScreen.Instance.Show("Signing up...");
        yield return(new WaitUntil(() => auth != null));

        var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);

        yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

        LoadingScreen.Instance.Hide();
        if (RegisterTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
            FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
            AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
            string            message    = "Register Failed!";
            switch (errorCode)
            {
            case AuthError.MissingEmail:
                message = "Missing Email";
                break;

            case AuthError.MissingPassword:
                message = "Missing Password";
                break;

            case AuthError.WeakPassword:
                message = "Weak Password";
                break;

            case AuthError.EmailAlreadyInUse:
                message = "Email Already In Use";
                break;
            }
            ILogger.Instance.ShowMessage(message, LoggerType.error);
        }
        else
        {
            User = RegisterTask.Result;
            if (User != null)
            {
                UserProfile profile = new UserProfile {
                    DisplayName = _displayName
                };
                var ProfileTask = User.UpdateUserProfileAsync(profile);
                yield return(new WaitUntil(predicate: () => ProfileTask.IsCompleted));

                if (ProfileTask.Exception != null)
                {
                    Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                    FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                    AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
                    ILogger.Instance.ShowMessage("Diplay Name Set Failed!", LoggerType.error);
                }
                else
                {
                    PlayerPrefs.SetString(Constants.EMAIL_PREFS, _email);
                    PlayerPrefs.SetString(Constants.PASSWORD_PREFS, _password);
                    LoginScreenUI.Instance.AfterLogin();
                }
            }
        }
    }
Exemplo n.º 9
0
    private IEnumerator Login(string email, string password)
    {
        var loginTask = FirebaseAuth.DefaultInstance.SignInWithEmailAndPasswordAsync(emailInput.text, passwordInput.text);

        yield return(new WaitUntil(predicate: () => loginTask.IsCompleted));

        if (loginTask.Exception != null)
        {
            Debug.LogWarning(message: $"Login failed with {loginTask.Exception}");
            FirebaseException firebaseEx = loginTask.Exception.GetBaseException() as FirebaseException;
            AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

            string msg = "Login Failed";
            switch (errorCode)
            {
            case AuthError.MissingEmail:
                msg = "Missing Email";
                break;

            case AuthError.MissingPassword:
                msg = "Missing Password";
                break;

            case AuthError.WrongPassword:
                msg = "Wrong  Password";
                break;

            case AuthError.InvalidEmail:
                msg = "Invalid  Email";
                break;

            case AuthError.UserNotFound:
                msg = "Account does not exist";
                break;
            }
            //message.text = msg;
            ErrorMessage.text = msg;
            ErrorPanel.transform.SetAsLastSibling();
            ErrorPanel.SetActive(true);
        }
        // on successful login
        else
        {
            Firebase.Auth.FirebaseUser newUser = loginTask.Result;
            //update the text field
            Debug.LogFormat("User signed in successfully:");
            message.text = "Login Successful";



            //User Role Mapping
            var mapping = new Dictionary <string, string>()
            {
                { "*****@*****.**", "Student" },
                { "*****@*****.**", "Student" },
                { "*****@*****.**", "Manager" },
            };



            // Get the role of prospective user
            foreach (var map in mapping)
            {
                if (map.Key.Equals(newUser.Email))
                {
                    userRole = map.Value;
                }
            }

            // Update singleton instances
            singleton = Singleton.Instance();
            if (newUser.Email != null)
            {
                userMail = newUser.Email;
                userName = userMail.Split('@')[0];
            }
            Debug.Log("UserEmail: " + userMail);
            singleton.setUserEmail(userMail);
            Debug.Log("Role: " + userRole);
            singleton.setUserRole(userRole);
            Debug.Log("User Name: " + userName);
            singleton.setUserName(userName);

            // Scene Transition
            if (userRole.Equals("Student"))
            {
                SceneManager.LoadScene("SchedulesScene");
            }
            else if (userRole.Equals("Manager"))
            {
                SceneManager.LoadScene("ManagerTourView");
            }
        }
    }
Exemplo n.º 10
0
    /**
     * this method handles login authentication with firebase methods
     * @param _email - email for the game
     * @param _password - password for the game
     */
    private IEnumerator Login(string _email, string _password)
    {
        Debug.Log("In login");
        Debug.Log(_email);
        //Call the Firebase auth signin function passing the email and password
        Debug.Log("Starting calculation");
        var watch     = System.Diagnostics.Stopwatch.StartNew();
        var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);

        //Wait until the task completes

        yield return(new WaitUntil(predicate: () => LoginTask.IsCompleted));

        watch.Stop();
        Debug.Log("Calculation completed");
        Debug.Log("Time taken for login: "******"ms");

        if (LoginTask.Exception != null)
        {
            //If there are errors handle them
            Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
            FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
            AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

            string message = "Login Failed!";
            switch (errorCode)
            {
            case AuthError.MissingEmail:
                message = "Missing Email";
                break;

            case AuthError.MissingPassword:
                message = "Missing Password";
                break;

            case AuthError.WrongPassword:
                message = "Wrong Password";
                break;

            case AuthError.InvalidEmail:
                message = "Invalid Email";
                break;

            case AuthError.UserNotFound:
                message = "Account does not exist";
                break;
            }
            warningLoginText.text = message;
        }
        else
        {
            //User is now logged in
            //Now get the result
            User   = LoginTask.Result;
            userID = auth.CurrentUser.UserId;
            Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
            Debug.Log("userID = " + userID);
            warningLoginText.text = "";
            confirmLoginText.text = "Logged In";


            yield return(new WaitForSeconds(0.5f));

            if (_email == "*****@*****.**")
            {
                SceneManager.LoadScene("TeacherScene");
                usernameField.text    = User.DisplayName;
                confirmLoginText.text = "";
                ClearLoginFeilds();
            }
            else
            {
                usernameField.text = User.DisplayName;
                UIManager.instance.MenuScreen();
                confirmLoginText.text = "";
                ClearLoginFeilds();
                //ClearRegisterFeilds();
            }
        }
    }
Exemplo n.º 11
0
    IEnumerator Register(string email, string password, string username)
    {
        if (username == "")
        {
            warningRegText.text = "No username";
        }
        else if (passwordRegField.text != passwordRegVerifyField.text)
        {
            warningRegText.text = "Password donesn't match";
        }
        else
        {
            var registerTask = auth.CreateUserWithEmailAndPasswordAsync(email, password);
            yield return(new WaitUntil(predicate: () => registerTask.IsCompleted));

            if (registerTask.Exception != null)
            {
                // Register error
                Debug.LogWarning(message: $"Failed to register with {registerTask.Exception}");
                FirebaseException firebaseEx = (FirebaseException)registerTask.Exception.GetBaseException();
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Failed to register";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Enter email";
                    break;

                case AuthError.MissingPassword:
                    message = "Enter a password";
                    break;

                case AuthError.WeakPassword:
                    message = "Password too weak";
                    break;

                case AuthError.EmailAlreadyInUse:
                    message = "Email already in use";
                    break;

                default:
                    message = "Error idk why";
                    break;
                }
                warningRegText.text = message;
            }
            else
            {
                // User created!
                user = registerTask.Result;
                if (user != null)
                {
                    // Create user profile and set username
                    UserProfile profile = new UserProfile {
                        DisplayName = username
                    };
                    var profileTask = user.UpdateUserProfileAsync(profile);
                    yield return(new WaitUntil(predicate: () => profileTask.IsCompleted));

                    if (profileTask.Exception != null)
                    {
                        // Any errors?
                        Debug.LogWarning(message: $"Failed to register task with {profileTask.Exception}");
                        FirebaseException fireBaseEx = (FirebaseException)profileTask.Exception.GetBaseException();
                        AuthError         errorCode  = (AuthError)fireBaseEx.ErrorCode;
                        warningRegText.text = "Setting username error!";
                    }
                    else
                    {
                        var uiMan = uiManager.GetComponent <UIManager>();
                        uiMan.EnableProfilePage();
                        uiMan.InitiateProfilePage(username, email);
                        Debug.Log("IT WORKED!" + " Username: "******"";
                    }
                }
            }
        }
    }
Exemplo n.º 12
0
    private IEnumerator Register(string _email, string _password, string _username)
    {
        if (!validateEmail(_email))
        {
            Debug.Log("이메일 형식이 아닙니다.");
        }
        if (_username == "")
        {
            warningRegisterText.text = "Missing Username";
        }
        else if (passwordRegisterField.text != passwordRegisterVerifyField.text)
        {
            warningRegisterText.text = "Password Does Not Match!";
        }
        else
        {
            var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);

            yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

            if (RegisterTask.Exception != null)
            {
                Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
                FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Register Failed!";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;

                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;

                case AuthError.WeakPassword:
                    message = "Weak Password";
                    break;

                case AuthError.EmailAlreadyInUse:
                    message = "Email Already In Use";
                    break;
                }
                warningRegisterText.text = message;
            }
            else
            {
                User = RegisterTask.Result;
                if (User != null)
                {
                    UserProfile profile = new UserProfile {
                        DisplayName = _username
                    };

                    var ProfileTask = User.UpdateUserProfileAsync(profile);

                    yield return(new WaitUntil(predicate: () => ProfileTask.IsCompleted));

                    if (ProfileTask.Exception != null)
                    {
                        Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                        FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                        AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
                        warningRegisterText.text = "Username Set Failed!";
                    }
                    else
                    {
                        warningRegisterText.text = "";
                        GameObject.Find("UI_Manager").GetComponent <UIManager>().LoginScreen();
                    }
                }
            }
        }
    }
Exemplo n.º 13
0
    private async Task <FirebaseUser> LoginUserWithAuthentication(string email, string password, Action <string> OnErrorCallback)
    {
        FirebaseUser user    = null;
        string       message = "Login Failed";
        await DatosFirebaseRTHelper.Instance.auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                message = "Mail or Pass Invalid";
            }
            else if (task.IsCompleted)
            {
                if (task.Exception != null)
                {
                    Debug.LogWarning(message: $"failed to register task with {task.Exception}");
                    FirebaseException firebaseEx = task.Exception.GetBaseException() as FirebaseException;
                    AuthError errorCode          = (AuthError)firebaseEx.ErrorCode;

                    switch (errorCode)
                    {
                    case AuthError.EmailAlreadyInUse:
                        break;

                    case AuthError.InvalidEmail:
                        message = "Invalid Email";
                        break;

                    case AuthError.WrongPassword:
                        message = "Wrong Password";
                        break;

                    case AuthError.MissingEmail:
                        message = "Missing Email";
                        break;

                    case AuthError.MissingPassword:
                        message = "Missing Password";
                        break;

                    case AuthError.UserNotFound:
                        message = "Account does not exist";
                        break;

                    default:
                        message = errorCode.ToString();
                        break;
                    }
                }
                else
                {
                    user = task.Result;
                    Debug.LogFormat("User signed in succesfully: {0} ({1})", user.DisplayName, user.Email);
                    Debug.Log("Logged IN");
                }
            }
        });

        if (user == null)
        {
            OnErrorCallback?.Invoke(message);
        }

        return(user);
    }
Exemplo n.º 14
0
 public UserAuthException(AuthError status) : base()
 {
     Status = status;
 }