Пример #1
0
        async Task SignIn()
        {
            try
            {
#if DEBUG
                if ((bool)Application.Current.Resources["LoginOk"])
                {
                    Application.Current.MainPage = new MasterPage()
                    {
                        IsPresented = true
                    };
                    return;
                }
#endif

                if (!ValidateInformation())
                {
                    await Application.Current.MainPage.DisplayAlert("Aviso", "Verifica que todos los campos se encuentren completos.", "Aceptar");
                }
                else if (!IsBusy)
                {
                    IsBusy = true;

                    //clean any previous session
                    SignOutPage.CleanCurrentSession();
                    //launch task

                    SignInAccountRequest model = new SignInAccountRequest()
                    {
                        username = Username, password = Password
                    };
                    SignInAccountResponse response = await RestHelper.SignInAccountAsync(model);

                    if (response.Status != ResponseStatus.Ok)
                    {
                        await Application.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar");
                    }
                    else
                    {
                        Settings.Profile_Username = response.Username;
                        Settings.Profile_Picture  = $"{Settings.ImageStorageUrl}/{Settings.AccountImageStorageUrl}/{response.Image}";
                        IsBusy = false;
                        await Task.Delay(10);

                        Application.Current.MainPage = new MasterPage()
                        {
                            IsPresented = true
                        };
                    }
                    IsBusy = false;
                }
            }
            catch (Exception ex)
            {
                Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
                await Application.Current.MainPage.DisplayAlert("Error", "Ocurrió un error inesperado", "Aceptar");
            }
        }
Пример #2
0
        public static async Task <SignInAccountResponse> SignInAccountAsync(SignInAccountRequest model)
        {
            int IterationsToRetry        = 5;
            int TimeToSleepForRetry      = 3000;
            SignInAccountResponse result = new SignInAccountResponse();

            if (Helpers.ConnectivyHelper.CheckConnectivity() != Enums.ConnectivtyResultEnum.HasConnectivity)
            {
                result.Status  = Enums.ResponseStatus.CommunicationError;
                result.Message = "El dispositivo no pudo comunicarse con el servidor, comprueba que tengas conexión a internet";
                return(result);
            }

            model.token = GetToken();

            for (int i = 0; i <= IterationsToRetry; i++)
            {
                try
                {
                    using (var client = new HttpClient())
                    {
                        var    service  = $"{Settings.FunctionURL}/api/SignInAccount/";
                        byte[] byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
                        using (var content = new ByteArrayContent(byteData))
                        {
                            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            var httpResponse = await client.PostAsync(service, content);

                            result = JsonConvert.DeserializeObject <SignInAccountResponse>(await httpResponse.Content.ReadAsStringAsync());

                            if (httpResponse.StatusCode == HttpStatusCode.OK)
                            {
                                result.Status = Enums.ResponseStatus.Ok;
                            }
                            else
                            {
                                result.Status = Enums.ResponseStatus.Error;
                            }
                            return(result);
                        }
                    }
                }
                catch (Exception)
                {
                    result.Status  = Enums.ResponseStatus.CommunicationError;
                    result.Message = "Ocurrió un error durante el proceso, por favor intenta de nuevo o espera unos minutos antes de vovler a intentar";
                    Thread.Sleep(TimeToSleepForRetry);
                    continue;
                }
            }
            return(result);
        }
Пример #3
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context)
        {
            TelemetryClient telemetryClient = new TelemetryClient
            {
                InstrumentationKey = Settings.APPINSIGHTS_INSTRUMENTATIONKEY
            };

            telemetryClient.TrackTrace("Starting function: SignInAccount");

            SignInAccountResponse result = new SignInAccountResponse
            {
                IsSucceded = true,
                ResultId   = (int)SignInAccountResultEnum.Success
            };

            try
            {
                string  requestBody = new StreamReader(req.Body).ReadToEnd();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);
                string  token       = data?.token;
                string  username    = data?.username;
                string  password    = data?.password;

                Dictionary <ParameterTypeEnum, object> parameters = new Dictionary <ParameterTypeEnum, object>
                {
                    { ParameterTypeEnum.Username, username },
                    { ParameterTypeEnum.Password, password }
                };

                telemetryClient.TrackTrace("Validating token");

                //validate token
                if (!string.IsNullOrEmpty(token))
                {
                    var      decrypted_token = SecurityHelper.Decrypt(token, Settings.SECURITY_SEED);
                    byte[]   token_bytes     = Convert.FromBase64String(decrypted_token);
                    DateTime when            = DateTime.FromBinary(BitConverter.ToInt64(token_bytes, 0));

                    if (when < DateTime.UtcNow.AddMinutes(-5))
                    {
                        result.IsSucceded = false;
                        result.ResultId   = (int)SignInAccountResultEnum.InvalidToken;
                    }
                    else
                    {
                        telemetryClient.TrackTrace("Calling helper");
                        SignInAccountHelper helper = new SignInAccountHelper(telemetryClient, Settings.STORAGE_ACCOUNT, Settings.RPC_CLIENT, Configurations.GetMongoDbConnectionInfo());
                        result = helper.SignInAccount(parameters);
                    }
                }
                else
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignInAccountResultEnum.MissingToken;
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)SignInAccountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)SignInAccountResultEnum.Failed;
            }

            //get message for result id
            string message = EnumDescription.GetEnumDescription((SignInAccountResultEnum)result.ResultId);

            //build json result object
            dynamic jsonresult = new JObject();

            jsonresult.message  = message;
            jsonresult.username = result.Username;
            jsonresult.image    = result.Image;

            telemetryClient.TrackTrace("Finishing function: SignInAccount");

            //send ok result or bad request
            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(jsonresult) : (ActionResult) new BadRequestObjectResult(jsonresult));
        }
Пример #4
0
        public SignInAccountResponse SignInAccount(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            SignInAccountResponse result = new SignInAccountResponse
            {
                IsSucceded = true,
                ResultId   = (int)SignUpAccountResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Username, out global::System.Object ousername);
                string username = ousername.ToString().ToLower();

                parameters.TryGetValue(ParameterTypeEnum.Password, out global::System.Object opassword);
                string password = opassword.ToString();

                //database helpers
                DBUserAccountHelper dbUserAccountHelper = new DBUserAccountHelper(DBCONNECTION_INFO);

                telemetryClient.TrackTrace("Validating username length");

                //validate username length
                if (!RegexValidation.IsValidUsername(username))
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignInAccountResultEnum.InvalidUsernameLength;
                    return(result);
                }

                telemetryClient.TrackTrace("Validating username existance");

                //validate if account exists
                UserAccount userAccount = dbUserAccountHelper.GetUser(username);

                if (userAccount == null)
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)SignInAccountResultEnum.NotExists;
                    return(result);
                }
                else
                {
                    if (userAccount.password == MD5Hash.CalculateMD5Hash(password))
                    {
                        result.IsSucceded = true;
                        result.ResultId   = (int)SignInAccountResultEnum.Success;
                        result.Username   = userAccount.username;
                        result.Image      = $"{userAccount.username}.png";
                    }
                    else
                    {
                        result.IsSucceded = false;
                        result.ResultId   = (int)SignInAccountResultEnum.IncorrectPassword;
                        return(result);
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)SignUpAccountResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }