Ejemplo n.º 1
0
    public async Task <bool> Handle(LoginRequest message, IOutputPort <LoginResponse> outputPort)
    {
        LogInResponse result = null;

        if (!string.IsNullOrEmpty(message.UserName) && !string.IsNullOrEmpty(message.Password))
        {
            result = await _userRepository.CheckPassword(message.UserName, message.Password);

            if (result != null && result.Success && result.User != null)
            {
                // generate refresh token
                var refreshToken = _tokenFactory.GenerateToken();
                result.User.AddRefreshToken(refreshToken, message.RemoteIpAddress);
                _userRepository.Update(result.User);
                // generate access token
                outputPort.Handle(new LoginResponse(await _jwtFactory.GenerateEncodedToken(result.User.IdentityId, result.User.UserName), refreshToken, true));
                return(true);
            }
        }
        outputPort.Handle(new LoginResponse(result != null ? result.Errors : new System.Collections.Generic.List <Error>()
        {
            new Error(HttpStatusCode.BadRequest.ToString(), "Invalid username or password!")
        }));
        return(false);
    }
        public string Login(LogInRequest ObjLogInRequest)
        {
            string ConnectionString = "data source=.;" + "database=Binoy;" + "Integrated Security=true";
            // string ConnectionString= "Data Source=tcp:binoyserver.database.windows.net,1433;" + "Initial Catalog=binoy;" + "User Id=Binoy;" + "Password=Malu@007;";
            SqlConnection connection = new SqlConnection(ConnectionString);

            connection.Open();
            SqlCommand command = new SqlCommand();

            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "WebsiteLoginProcedure_s2por";
            command.Parameters.AddWithValue("@username", ObjLogInRequest.UserId);
            command.Parameters.AddWithValue("@Password", ObjLogInRequest.PassWord);
            command.Connection = connection;
            SqlDataReader Reader           = command.ExecuteReader();
            LogInResponse ObjLogInResponse = new LogInResponse();

            if (Reader.Read())
            {
                ObjLogInResponse.Role = Reader["Role"].ToString();
                return(ObjLogInResponse.Role);
            }
            else
            {
                ObjLogInResponse.Role = "Invalid Username/Password";
                return(ObjLogInResponse.Role);
            }
        }
Ejemplo n.º 3
0
        public IActionResult LogIn([FromBody] LogInRequestDTO dto)
        {
            LogInResponse response = new LogInResponse();

            var userExists = uow.User.FindByEmail(dto.Email);

            if (!userExists.Success)
            {
                return(NotFound(response, userExists.Message));
            }

            User user = userExists.Data;

            var isLogin = uow.User.LogIn(user, dto.Password);

            if (!isLogin.Success)
            {
                return(NotFound(response, isLogin.Message));
            }

            response            = mapper.Map <LogInResponse>(user);
            response.Token      = isLogin.Message;
            response.ExpireDate = DateTime.Now.AddDays(1);

            return(Ok(response));
        }
Ejemplo n.º 4
0
        public async Task <LogInResponse> LogInAsync(LogInRequest request, CancellationToken cancellationToken)
        {
            var messages = new List <string>();

            var result = await _authRepository.LogInAsync(request.Email, request.Password, cancellationToken);

            if (result)
            {
                messages.Add("Logged in successfully");

                var roles = await _authRepository.FindUserRolesAsync(request.Email, cancellationToken);

                var logInResponse = new LogInResponse
                {
                    Token      = GenerateJwtToken(request, roles),
                    StatusCode = HttpStatusCode.OK,
                    Messages   = messages
                };

                return(logInResponse);
            }
            else
            {
                messages.Add("You Email address or password is not valid. Please try again with valid credentials");

                var logInResponse = new LogInResponse
                {
                    StatusCode = HttpStatusCode.Unauthorized,
                    Messages   = messages
                };

                return(logInResponse);
            }
        }
Ejemplo n.º 5
0
    public void LogIn()
    {
        Debug.Log("GuestLogin called");

        LogInRequest request = new LogInRequest();

        request.PID          = (int)PROTOCOL.PID.LOGIN;
        request.PlatformType = (int)LogInRequest.PLATFORM_TYPE.GUEST;
        request.UserId       = string.Empty;
        request.DeviceId     = string.Empty;

        Http http = gameObject.AddComponent <Http>();

        http.Send(request);
        string responseString = http.GetResponseString();


        Debug.Log("GuestLogin responseString:" + responseString);

        LogInResponse response = JsonUtility.FromJson <LogInResponse>(responseString);

        if (response != null)
        {
            Debug.Log("resprotocol : " + response.ToString() + "," + response.CODE + "," + response.MSG);
        }
    }
 private void HandleLogInResponse(LogInResponse response)
 {
     IsLoggedIn = true;
     PlayerStatsManager.Instance.ShowPlayerLoggedIn(response.Type);
     PlayerStatsManager.Instance.SetPlayerStats(response.PlayerStats);
     PlayerStatsManager.Instance.DrawPlayerStats();
 }
Ejemplo n.º 7
0
        private string GenerateJSONWebToken(LogInResponse user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            if (user.Response.Success == true)
            {
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Email, user.User.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.Name, user.User.Email)
                };

                var token = new JwtSecurityToken(
                    issuer: _config["Jwt:Issuer"],
                    audience: _config["Jwt:Audience"],
                    claims,
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: credentials
                    );

                var encodeToken = new JwtSecurityTokenHandler().WriteToken(token);
                return(encodeToken);
            }

            return(user.Response.Message);
        }
Ejemplo n.º 8
0
        //=====================================================================================================================
        //=====================================================================================================================
        //VALIDACION PARA EL INGRESO DE USUARIO
        async public void OnIngresar(Object sender, EventArgs e)
        {
            //SE VERICA SI EL ESTADO DEL ACCESO A LA RED ES NULO
            if (Connectivity.NetworkAccess == NetworkAccess.None) //=> true => NO HAY CONEXION A LA RED
            {
                //SE LE NOTIFICA AL USUARIO MEDIANTE UN MENSAJE QUE NO HAY CONEXION A LA RED
                await DisplayAlert("Mensaje", ConexionDatos.NetWorkConnectivityChangeMessage, ConexionDatos.OkText);
            }
            else if (Connectivity.NetworkAccess != NetworkAccess.None) // true => SI HAY CONEXION A LA RED
            {
                //SE VERIFICA SI LAS PROPIEDADES DE LA CLASE VIEW MODEL SE ENCUENTREN VACIOS
                if (string.IsNullOrEmpty(ConexionDatos.Username) ||
                    string.IsNullOrEmpty(ConexionDatos.Password))   //=> true => LAS PROPIEDADES SE ENCUENTRAN VACIAS O NULAS
                {
                    //SE LE NOTIFICA AL USUARIO MEDIANE UN MENSAJE QUE NINGUNA DE LAS DOS PROPIEDADES PUEDE SER VACIAS
                    ConexionDatos.MensajePantalla(ConexionDatos.UsernamePasswordEmptyMessage);
                }
                else //=> false => NINGUNA DE LAS PROPIEDADES SE ENCUENTRA VACIA
                {
                    //------------------------------------------------------------------------------
                    //CONEXION CON LA BASE DE DATOS (CLIENTE - SERVIDOR)
                    //SE LLAMA AL METODO QUE REALIZA LA SOLICITUD HTTP
                    //SE HACE VISIBLE EL ACTIVITY INDICATOR
                    ActivityIndicator.IsVisible = true;
                    //SE ACTIVA EL ACTIVITY INDICATOR
                    ActivityIndicator.IsRunning = true;
                    //INICIAMOS UNA SECCION DE CODIGO QUE SE EJECUTARA EN SEGUNDO PLANO UTILIZANDO LA FUNCION Run DE LA CLASE TasK
                    await Task.Run(async() =>
                    {
                        //LLAMAMOS AL METODO "LogInReques" DE LA CLASE "PaginaPrincipalViewModel" Y GUARDAMOS LA RESPUESTA OBTENIDA
                        loginresponse = await ConexionDatos.LogInRequest();
                        //SE DESACTIVA EL ACTIVITY INDICATOR
                        ActivityIndicator.IsRunning = false;
                    });

                    //SE DESACTIVA LA VISIBILIDAD DEL OBJETO ACTIVITYINDICATOR
                    ActivityIndicator.IsVisible = false;

                    //SE EVALUA EL ESTADO DE LA RESPUESTA
                    if (loginresponse != null)
                    {
                        //SE REALIZA EL LLAMADO A LA PAGINA "UserMainPage"
                        await Navigation.PushModalAsync(new UserMainPage(loginresponse.UserInfo.Persona, loginresponse.UserInfo.Usuario, loginresponse.UltimaFechaIngreso));

                        //SI LA RESPUESTA ES DIFERENTE DE NULL => SE OBTUVO UN RESULTADO
                        //SE LIMPIAN LAS ENTRADAS DE TEXTO PARA EL USERNAME Y PARA EL PASSWORD
                        usernameEntry.Text = string.Empty;
                        passwordEntry.Text = string.Empty;
                    }
                    else
                    {
                        //SI LA RESPUESTA ES NULA => NO SE OBTUVO RESULTADOS
                        //SE NOTIFICA AL USUARIO SOBRE EL INGRESO A LA PLATAFORMA
                        ConexionDatos.MensajePantalla(ConexionDatos.Result);
                        passwordEntry.Text = String.Empty;
                    }
                }
            }
        }
        public async Task <IActionResult> RefreshTokenAsync([FromBody] RefreshTokenRequest request)
        {
            return(await _exceptionService.HandleApiExceptionAsync <ApiException>(nameof(AuthenticationController), nameof(RefreshTokenAsync), async() =>
            {
                AccessToken response = await _authenticationService.RefreshTokenAsync(request.Token, request.UserEmail);

                LogInResponse logInResponse = _mapper.Map <AccessToken, LogInResponse>(response);
                return Ok(logInResponse);
            }));
        }
        public async Task <IActionResult> LogInAsync([FromBody] LogInRequest request)
        {
            return(await _exceptionService.HandleApiExceptionAsync <ApiException>(nameof(AuthenticationController), nameof(LogInAsync), async() =>
            {
                AccessToken accessTokenResponse = await _authenticationService.LogInAsync(request.Email, request.Password);

                LogInResponse logInResponse = _mapper.Map <AccessToken, LogInResponse>(accessTokenResponse);

                return Ok(logInResponse);
            }));
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> Login([FromBody] LogInRequest logInRequest)
        {
            string token = await userService.LogInAsync(logInRequest.Username, logInRequest.Password);

            var logInResponse = new LogInResponse()
            {
                Token    = token,
                Username = logInRequest.Username
            };

            return(Ok(logInResponse));
        }
        public async Task <ActionResult> LogIn(LogInRequest request)
        {
            HttpClient    client  = new HttpClient();
            string        str     = JsonConvert.SerializeObject(request);
            StringContent content = new StringContent(str, Encoding.UTF8, "application/json");
            var           result  = await client.PostAsync(baseUrl + "/account/Authenticate", content);

            var           r        = result.Content.ReadAsStringAsync().Result;
            LogInResponse response = JsonConvert.DeserializeObject <LogInResponse>(r);

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
        public static LogInWebResponse AsWebResponse(this LogInResponse response)
        {
            var result = new LogInWebResponse
            {
                Errors       = response.Errors,
                IsSuccessful = response.IsSuccessful,
                Message      = response.Message,
                StatusCode   = response.StatusCode,
                Data         = response.Data
            };

            return(result);
        }
Ejemplo n.º 14
0
        public Result <LogInResponse> CreateLogInResponse(int userID, UserSession session = null)
        {
            var user         = FindUser(userID).Payload;
            var languageCode = (from x in _dBContext.Language where x.LanguageID == user.LanguageID select x.LanguageName).FirstOrDefault();
            var currencyCode = (from x in _dBContext.Currency where x.CurrencyID == user.CurrencyID select x).FirstOrDefault();
            var response     = new LogInResponse
            {
                User         = user,
                UserSession  = session,
                LanguageName = languageCode,
                CurrencyCode = currencyCode,
            };

            return(new Result <LogInResponse>(response));
        }
Ejemplo n.º 15
0
        private LogInResponse BuildLogInResponse(LogInRequest req, bool success, string message)
        {
            var response = new Response()
            {
                Success = success,
                Message = message
            };
            var loginResponse = new LogInResponse()
            {
                User     = req?.User,
                Response = response
            };


            return(loginResponse);
        }
Ejemplo n.º 16
0
        public async Task <ActionResult <LogInResponse> > LogIn([FromBody] LogInRequest request)
        {
            var command = new LogInUserCommand
            {
                UserName = request.UserName,
                Password = request.Password
            };

            var token = await Mediator.Send(command);

            var response = new LogInResponse
            {
                Token  = token.Value,
                UserId = token.UserId
            };

            return(this.Ok(response));
        }
Ejemplo n.º 17
0
        private LogInResponse AuthenticateUser(LogInRequest req)
        {
            var registeredUsers = _dbContext.Users;
            var response        = new LogInResponse();

            foreach (var r in registeredUsers)
            {
                if ((req.User.Email == r.Email) && (req.User.Password == r.Password))
                {
                    response = BuildLogInResponse(req, true, "Logged In!");
                    return(response);
                }
                else
                {
                    response = BuildLogInResponse(null, false, "Email or Password is incorrent.");
                }
            }
            return(response);
        }
Ejemplo n.º 18
0
    private void LogInGameServer(string userId)
    {
        Debug.Log("LogInGameServer called. USERID: " + userId);

        LogInRequest request = new LogInRequest();

        request.PID          = (int)PROTOCOL.PID.LOGIN;
        request.PlatformType = (int)LogInRequest.PLATFORM_TYPE.GOOGLE;
        request.UserId       = userId;
        request.DeviceId     = string.Empty;

        Http http = gameObject.AddComponent <Http>();

        http.Send(request);
        string responseString = http.GetResponseString();

        LogInResponse response = JsonUtility.FromJson <LogInResponse>(responseString);

        Debug.Log("resprotocol : " + response.ToString() + "," + response.CODE + "," + response.MSG);
    }
Ejemplo n.º 19
0
        public LogInResponse LogIn(LogInRequest request, string login)
        {
            int    IdUser     = getIdUserByLogin(login);
            User   user       = _context.Users.Where(x => x.IdUser == IdUser).FirstOrDefault();
            string dbPassword = user.Password;

            if (dbPassword != request.Password)
            {
                throw new PasswordsNotMatchException("");
            }

            var response = new LogInResponse
            {
                Login     = user.Login,
                IsAdmin   = user.IsAdmin,
                IsTeacher = user.IsTeacher
            };

            return(response);
        }
Ejemplo n.º 20
0
        public async Task CreateWithRefreshToken(string token)
        {
            JObject parameters = new JObject {
                { "token", token }
            };

            LogInResponse response = await httpManager.Request <LogInResponse>(
                HttpMethod.Post,
                EnvironmentManager.singleton.environmentObject.loginApiBaseUrl + "/refresh-token",
                parameters,
                true
                );

            TokenManager.singleton.accessToken  = response.accessToken;
            TokenManager.singleton.refreshToken = response.refreshToken;

            Jwt jwt = new Jwt(response.accessToken);

            GameState.singleton.userModel = jwt.payload.user;
        }
Ejemplo n.º 21
0
        public async Task CreateWithCredentials(string email, string password)
        {
            JObject parameters = new JObject {
                { "email", email },
                { "password", password }
            };

            LogInResponse response = await httpManager.Request <LogInResponse>(
                HttpMethod.Post,
                EnvironmentManager.singleton.environmentObject.loginApiBaseUrl,
                parameters
                );

            TokenManager.singleton.accessToken  = response.accessToken;
            TokenManager.singleton.refreshToken = response.refreshToken;

            Jwt jwt = new Jwt(response.accessToken);

            GameState.singleton.userModel = jwt.payload.user;
        }
Ejemplo n.º 22
0
        /**
         * GET attemps log in
         */
        public LogInResponse attempLogIn(string user_name, string password)
        {
            LogInResponse res = new LogInResponse();

            res.success = false;
            res.message = "ERROR: User Invalid";
            employee emp   = new employee();
            var      query = "SELECT * FROM getEmployeeByUsername('" + user_name + "');";

            emp = _context.Database.SqlQuery <employee>(query).FirstOrDefault();
            if (emp != null)
            {
                res.message = "ERROR: Wrong Password";
                if (emp.password.Equals(password))
                {
                    res.success     = true;
                    res.message     = "LOGIN SUCCESSFUL";
                    res.information = emp;
                }
            }
            return(res);
        }
Ejemplo n.º 23
0
        private async Task <LogInResponse> GenerateJSONWebTokenAsync(AppUser userInfo)
        {
            var response    = new LogInResponse();
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var userRole    = (await _userManager.GetRolesAsync(userInfo)).FirstOrDefault();

            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, userInfo.Id.ToString()),
                new Claim(CustomJwtClaimName.UserName, userInfo.UserName.ToString()),
                new Claim(CustomJwtClaimName.Email, userInfo.Email.ToString()),
                new Claim(CustomJwtClaimName.UserId, userInfo.Id.ToString()),
                new Claim(ClaimTypes.Role, userRole)
            };

            var accessTokenLifeTime = _config.GetValue <int>("Jwt:AccessTokenLifeTime");

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                                             _config["Jwt:Issuer"],
                                             claims: claims,
                                             expires: DateTime.Now.AddMinutes(accessTokenLifeTime),
                                             signingCredentials: credentials);

            var refreshTokenResponse = new RefreshTokenResponse()
            {
                UserId = userInfo.Id,
                ID     = Guid.NewGuid().ToString()
            };
            var encRefTokenResponse = _taposRSA.EncryptData(JsonConvert.SerializeObject(refreshTokenResponse), "v1");

            response.Token        = new JwtSecurityTokenHandler().WriteToken(token);
            response.Expire       = accessTokenLifeTime * 60;
            response.RefreshToken = encRefTokenResponse;

            await StoreTokenInformation(userInfo.Id, response.Token, response.RefreshToken);

            return(response);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// here we are saveing data of user
 /// </summary>
 /// <param name="logInResponse">Log in response.</param>
 async void SaveLogInData(LogInResponse logInResponse)
 {
     try
     {
         //BindMyProfile(logInResponse);
         var loginCount = App.Database.GetLogInAsync();
         //var checkdata = (LogInTable)loginPage.BindingContext;
         //logInResponse.MobileUser.ID = 1;
         CrossSettings.Current.AddOrUpdateValue("FacultyId", (int)logInResponse.MobileUser.Code);
         CrossSettings.Current.AddOrUpdateValue("UserType", (int)UserType.currentUserType);
         if (loginCount != null)
         {
             await App.Database.SaveItemAsync(logInResponse.MobileUser, update : true).ConfigureAwait(false);
         }
         else
         {
             await App.Database.SaveItemAsync(logInResponse.MobileUser, update : false).ConfigureAwait(false);
         }
     }
     catch (Exception ex)
     {
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Logs player in
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="request"></param>
        public void LogIn(int clientID, LogInRequest request)
        {
            Player    player;
            LogInType logInType;

            try
            {
                logInType = PlayersManager.LogIn(clientID, request.PlayerID, out player);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error logging in client {clientID}: {e}");
                ErrorResponse error = new ErrorResponse();
                error.Type = ErrorType.LogInFailed;
                Server.SendDataToClient(clientID, (int)DataTypes.ErrorResponse, error);
                return;
            }

            LogInResponse response = new LogInResponse();

            response.Type        = logInType;
            response.PlayerStats = player.GetStatsData();
            Server.SendDataToClient(clientID, (int)DataTypes.LogInResponse, response);
        }
Ejemplo n.º 26
0
        public async Task <ActionResult <LogInResponse> > LogIn([FromBody] LogInRequest req)
        {
            var result   = _service.LogIn(req);
            var response = new LogInResponse();

            if (result.Response.Success == true)
            {
                var tokenStr = GenerateJSONWebToken(result);
                response = new LogInResponse()
                {
                    Response = new Response()
                    {
                        Success = true,
                        Message = "You have the Token"
                    },
                    JwtToken = tokenStr
                };
            }
            else
            {
                response = result;
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 27
0
        private void LoginDialogOnResponse(object?sender, DialogResponseEventArgs e)
        {
            var logInRequest = new LogInRequest()
            {
                Login = _player.Name, Password = e.InputText
            };

            try
            {
                LogInResponse response = MruV.Accounts.LogIn(logInRequest);
                if (response.Success)
                {
                    CharacterSelectFlow charsf = new CharacterSelectFlow(_player);
                    charsf.Start();
                }
                else
                {
                    _playerBadPassword++;

                    _player.SendClientMessage(Color.OrangeRed, "Złe hasło!");
                    if (_playerBadPassword == 3)
                    {
                        _player.SendClientMessage(Color.Red, "Zostałeś wyrzucony z serwera za potrójne wpisanie złego hasła.");
                        _player.Kick();
                    }
                    else
                    {
                        _loginDialog.Show(_player);
                    }
                }
            }
            catch (RpcException err)
            {
                _player.SendClientMessage($"Nie udało się zalogować, błąd: {err.Status.Detail}");
            }
        }
Ejemplo n.º 28
0
 public LogInResponseArgs(LogInResponse response, Object userState)
 {
     this.LogInResponse = response;
     this.UserState = userState;
 }
Ejemplo n.º 29
0
        //--------------------------------------------------------------------------------------------------
        //FUNCION QUE ACTUALIZARA LA INFORMACION DE UN USUARIO CUANDO SE REALICE EL LLAMADO DESDE
        //LA PAGINA "PaginaConsultaTableros" DE LA APLICACION "Mtto App". EN ESTA FUNCION SE RECIBEN
        //LOS PARAMETROS:
        // -username: PARAMETRO ENVIADO EN EL URL DE LA SOLICITUD (username=<username> || USERNAME=<username>)
        // -password: PARAMETRO ENVIADO EN EL URL DE LA SOLICITUD (password=<password> || PASSWORD=<password>)
        //--------------------------------------------------------------------------------------------------
        public async Task <IActionResult> LogInRequest([FromBody] LogInRequest request)
        {
            //SE CREA E INICIALIZA LA VARIABLE QUE SE RETORNARA SI TODAS LAS CONDICIONES SE CUMPLEN
            LogInResponse response = null;

            //SE EVALUA QUE EXISTA UN NOMBRE DE USUARIO QUE OBEDESCA AL NOMBRE DE USUARIO
            if (this._context.Usuarios.Any
                    (x => x.Username.ToLower() == request.Username.ToLower())) //=> true => EXISTE UN REGISTRO EN LA TABLA USUARIOS QUE RESPONDE AL
            //           NOMBRE DE USUARIO ENVIADO COMO PARAMETRO.
            {
                //SI EXISTE, SE OBTIENE TODA LA INFORMACION DE DICHO REGISTRO Y SE ALMACENA EN UNA VARIABLE DEL TIPO USUARIO
                Usuarios usuario = this._context.Usuarios.First                                   //=> METODO QUE RETORNA EL PRIMER REGISTRO QUE COINCIDA
                                       (x => x.Username.ToLower() == request.Username.ToLower()); //CON LA COMPARACION DE NOMBRE DE USUARIOS

                //SE COMPARA QUE LA PROPIEDAD DEL OBJETO usuario (OBJETO QUE CONTIENE TODA LA INFORMACION DE USUARIO
                //QUE DESEA INGRESAR) CON EL PARAMETRO "password"
                if (usuario.Password == request.Password) //=> true => LA CONTRASEÑA ENVIADA ES CORRECTA
                {
                    //SE INICIA LA TRANSACCION CON LA BASE DE DATOS
                    using (var transaction = this._context.Database.BeginTransaction())
                    {
                        //SE INICIA LA TRANSACCIONES CON LA BASE DE DATOS
                        try
                        {
                            //--------------------------------------------------------------------------------------------
                            //SE BUSCA LA INFORMACION PERSONAL DEL USUARIO QUE DESEA INGRESAR
                            var persona = await this._context.Personas.FindAsync(usuario.Cedula);

                            //--------------------------------------------------------------------------------------------
                            //SE EVALUA SI SE OBTUVO UN REGISTRO DE LA BUSQUEDA ANTERIOR
                            if (persona != null)
                            {
                                //DE EXISTIR SE DESECHA LA ENTIDAD RETENIDA
                                this._context.Entry(persona).State = EntityState.Detached;
                            }

                            //--------------------------------------------------------------------------------------------
                            //SE CREA E INICIALIZA UN OBJETO DEL TIPO "InformacionGeneral" (OBJETO QUE RETORNARA TODA LA
                            //INFORMACION DEL USUARIO QUE DESEA INGRESAR)
                            var fullinfo = InformacionGeneral.NewInformacionGeneral(persona, usuario);

                            //--------------------------------------------------------------------------------------------
                            //SE CREA E INICALIZA UN OBJETO DEL TIPO "UltimaConexion"
                            var ultimaconexion = new Ultimaconexion().NewUltimaConexion(persona, usuario);

                            //--------------------------------------------------------------------------------------------
                            //SE AÑADE A LA TABLAS "UltimaConexion" EL NUEVO REGISTRO
                            this._context.Ultimaconexion.Add(ultimaconexion);               //SE REGISTRA/AÑADE EN LA BASE DE DATOS
                            this._context.Entry(ultimaconexion).State = EntityState.Added;  //SE CAMBIA EL ESTADO DE LA ENTIDAD RETENIDA

                            //--------------------------------------------------------------------------------------------
                            //SE CREA E INICIALIZA UNA LISTA DE OBJETOS "UltimaConexion"
                            List <Ultimaconexion> lista = new List <Ultimaconexion>();
                            //SE LLENA LA LISTA PREVIAMENTE CREADA CON TODOS LOS REGISTROS DE CONEXION DEL USUARIO QUE DESEA INGRESAR
                            foreach (Ultimaconexion y in this._context.Ultimaconexion.ToList())
                            {
                                //SE EVAUA CADA UNO DE LOS REGISTROS DE LA LISTA Y SE COMPARA SI EL PARAMETRO UserId
                                //DEL REGISTRO ES IGUAL AL ID (CEDULA) DEL USUARIO QUE ESTA INGRESANDO
                                if (y.UserId == persona.Cedula)
                                {
                                    //SE AÑADE A LA LISTA EL REGISTRO.
                                    lista.Add(y);
                                }
                            }

                            //--------------------------------------------------------------------------------------------
                            //SE CREA UN NUEVO REGISTRO DE SOLICITUDES WEB Y SE AÑADE A LA TABLA "HistorialSolicitudesWeb"
                            Historialsolicitudesweb solicitudweb =
                                Historialsolicitudesweb.NewHistorialSolocitudesWeb(fullinfo.Usuario.Cedula, 0);

                            //--------------------------------------------------------------------------------------------
                            //SE REGISTRA/AÑADE UN NUEVO REGISTRO DE SOLICITUDES WEB
                            this._context.Historialsolicitudesweb.Add(solicitudweb);
                            this._context.Entry(solicitudweb).State = EntityState.Added;

                            //--------------------------------------------------------------------------------------------
                            //SE RETORNA EL TOKEN GENERADO LUEGO DE LA AUTENTICACION
                            string token = jwtauthenticationManager.Authenticate(request);

                            //--------------------------------------------------------------------------------------------
                            //SE EVALUA CUANTOS REGISTROS SE ACUMULARON EN LA LISTA "lista"
                            //MAS DE UN REGISTRO
                            if (lista.Count > 0)
                            {
                                //SE ENVIA LA INFORMACION DEL USUARIO Y EL PENULTIMO REGISTRO (ULTIMA CONEXION PREVIA A LA ACTUAL)
                                response = LogInResponse.NewLogInResponse(fullinfo, lista[lista.Count - 1].UltimaConexion1, token);
                            }
                            if (lista.Count == 0)
                            {
                                //SE ENVIA LA INFORMACION DEL USUARIO Y EL ULTIMO REGISTRO (CONEXION ACTUAL)
                                response = LogInResponse.NewLogInResponse(fullinfo, ultimaconexion.UltimaConexion1, token);
                            }
                            //--------------------------------------------------------------------------------------------
                            //SE GUARDAN LOS CAMBIOS REALIZADOS SOBRE LA BASE DE DATOS
                            await this._context.SaveChangesAsync();

                            //SE CULMINA LA TRANSACCION CON LA BASE DE DATOS
                            await transaction.CommitAsync();
                        }
                        //SI OCURRE ALGUNA EXCEPCION EN EL PROCESO DE LECTURA Y ESCRITURA DE LA BASE DE DATOS EL CODIGO
                        //SE REDIRIGE A LA SECCION CATCH DEL CICLO TRY...CATCH
                        catch (Exception ex) when(ex is DbUpdateException ||
                                                  ex is DbUpdateConcurrencyException)
                        {
                            Console.WriteLine("\n=================================================");
                            Console.WriteLine("=================================================");
                            Console.WriteLine("\nHa ocurrico un error:\n" + ex.Message.ToString());
                            Console.WriteLine("=================================================");
                            Console.WriteLine("=================================================\n");
                            //SE RETONA LA RESPUESTA "BadRequest" JUNTO CON UN MENSAJE INFORMANDO SOBRE EL ERROR
                            return(BadRequest("\nHa ocurrico un error, intentelo nuevamente"));
                        }
                    }
                }
                else
                {
                    //SI EL NOMBRE DE USUARIO CONICIDE PERO LA CONTRASEÑA NO SE RETORNA UN BADREQUEST
                    return(BadRequest("Contraseña incorrecta"));
                }
            }
            else
            {
                //SI EL NOMBRE DE USUARIO NO CONIDIDE SE RETORNA UN NOT FOUND
                return(NotFound("Nombre de usuario no encontrado"));
            }

            //SE RETORNA EL CODIGO 200 OK JUNTO CON TODA LA INFORMACION DEL USUARIO
            return(Ok(response));
        }
    private IEnumerable createAccount(Action <TestGuest> callback, string email, string lastName, string username, string parentEmail, string dateOfBirth, int numRetries)
    {
        RegisterRequest args = new RegisterRequest
        {
            legalAssertions = new List <string>
            {
                "ppV2",
                "GTOU"
            },
            marketing = new List <MarketingItem>
            {
                new MarketingItem
                {
                    code       = "WDIGFamilySites",
                    subscribed = true
                }
            },
            password = "******",
            profile  = new RegisterProfile
            {
                dateOfBirth     = dateOfBirth,
                email           = email,
                username        = username,
                parentEmail     = parentEmail,
                firstName       = "CpIntTestFirstName",
                lastName        = lastName,
                testProfileFlag = "y",
                region          = null
            }
        };
        WWW www = makeRegisterWww(args);

        while (!www.isDone)
        {
            yield return(null);
        }
        uint statusCode = getStatusCode(www.responseHeaders);

        if (statusCode >= 200 && statusCode <= 299)
        {
            string        responseText = www.text;
            LogInResponse response     = JsonMapper.ToObject <LogInResponse>(responseText);
            if (response.data != null && response.data.profile != null)
            {
                TestGuest obj = new TestGuest(response.data, "CpIntTestPassword1");
                callback(obj);
            }
            else if (numRetries < 2)
            {
                foreach (object item in retryCreateAccount(callback, email, lastName, username, parentEmail, dateOfBirth, numRetries))
                {
                    yield return(item);
                }
            }
            else
            {
                IntegrationTest.Fail("Got invalid data when creating TestGuest: " + JsonMapper.ToJson(response));
                callback(null);
            }
        }
        else if (numRetries < 2)
        {
            foreach (object item2 in retryCreateAccount(callback, email, lastName, username, parentEmail, dateOfBirth, numRetries))
            {
                yield return(item2);
            }
        }
        else
        {
            IntegrationTest.Fail("Error creating TestGuest: " + www.error + "\n" + www.text);
            callback(null);
        }
    }
Ejemplo n.º 31
0
        //=========================================================================================================
        //=========================================================================================================
        //METODO PARA VALIDAR EL INGRESO DE UN USUARIO POR MEDIO DE CONSUMO DE SERVICIOS WEB
        public async Task <LogInResponse> LogInRequest()
        {
            //SE CREA E INICIALIZA LA VARIABLE URL
            string url = string.Empty;

            //SE CREA E INICIALIZA LA VARIABLE QUE RETENDRA EL URL PARA REALIZAR LA SOLICITUD HTTP
            url = App.BaseUrl + $"/login";

            LogInRequest model = null;

            //SE EVALUA SI EL USUARIO QUE INTENTA ACCEDER A LA PLATAFORMA ES EL USUARIO ADMINISTRATOR
            if (username.ToLower() == "administrator")
            {
                model = new LogInRequest()
                {
                    Username = username,
                    Password = password,
                };
            }
            else
            {
                model = new LogInRequest()
                {
                    Username = username,
                    Password = Metodos.EncryptString(password),
                };
            }

            //SE CREA E INICIALIZA LA VARIABLE QUE VERIFICARA EL ESTADO DE CONEXION A INTERNET
            var current = Connectivity.NetworkAccess;

            //SE VERIFICA SI EL DISPOSITIVO SE ENCUENTRA CONECTADO A INTERNET
            if (current == NetworkAccess.Internet)
            {
                //EL EQUIPO SE ENCUENTRA CONECTADO A INTERNET
                //SE INICIA EL CICLO TRY...CATCH
                try
                {
                    //INICIAMOS EL SEGMENTO DEL CODIGO EN EL CUAL REALIZAREMOS EL CONSUMO DE SERVICIOS WEB MEDIANTE
                    //LA INICIALIZACION Y CREACION DE UNA VARIABLE QUE FUNCIONARA COMO CLIENTE EN LAS SOLICITUDES
                    //Y RESPUESTAS ENVIADAS Y RECIBIDAS POR EL SERVIDOR (WEB API)
                    //----------------------------------------------------------------------------------------------
                    //NOTA: CUANDO SE REALIZA LA CREACION E INICIALIZACION DE LA VARIABLE DEL TIPO HttpClient SE
                    //HACE UN LLAMADO A UN METODO ALOJADO EN LA CLASE "App" Y QUE ES ENVIADO COMO PARAMETRO DEL
                    //TIPO HttpClientHandler =>
                    //----------------------------------------------------------------------------------------------
                    using (HttpClient client = new HttpClient(App.GetInsecureHandler()))
                    {
                        //SE DA SET AL TIEMPO MAXIMO DE ESPERA PARA RECIBIR UNA RESPUESTA DEL SERVIDOR
                        client.Timeout = TimeSpan.FromSeconds(App.TimeInSeconds);
                        //SE REALIZA LA CONVERSION A OBJETO JSON
                        var json = JsonConvert.SerializeObject(model);
                        //SE AÑADE EL OBJETO JSON RECIEN CREADO COMO CONTENIDO BODY DEL NUEVO REQUEST
                        HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
                        //SE HACE LA CONFIGURACION DE LOS HEADERS DEL REQUEST
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        //SE REALIZA EL LLAMADO Y SE RECIBE UNA RESPUESTA
                        HttpResponseMessage response = await client.PostAsync(url, httpContent);

                        //SE EVALUA SI EL CODIGO DE ESTATUS RETORNADO ES EL CODIGO 200 OK
                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            //EL CODIGO DE ESTATUS RETORNADO ES EL CODIGO 200 OK
                            //SE RECIBE LA RESPUESTA COMPLETA OBTENIDA POR EL SERVIDOR (STRING)
                            result = await response.Content.ReadAsStringAsync();

                            //SE REALIZA LA EL MAPEO DE UN OBJETO JSON A UN OBJETO "LogInResponse"
                            LogInResponse loginresponse = await Task.FromResult(JsonConvert.DeserializeObject <LogInResponse>(result));

                            //SE DESENCRIPTA LA CONTRASEÑA
                            loginresponse.UserInfo.Usuario.Password = Metodos.DecryptString(loginresponse.UserInfo.Usuario.Password);
                            //SE RETORNA EL OBJETO
                            return(loginresponse);
                        }
                        else
                        {
                            //EL CODIGO DE ESTATUS RETORNADO ES DIFERENTE AL CODIGO DE ESTATUS 200 OK
                            //NOTA: EN EL CASO DEL CONTROLADOR ASIGNADO A PROCESAR LAS SOLICITUDES CON DICHA DIRECCION URL
                            //DENTRO DEL PROYECTO API SOLO TIENE TRES TIPOS DE RESPUESTA:
                            // - Ok (Se consiguo el nombre de usuario y la contraseña coincide)
                            // - Bad Request (Se consiguio el nombre de usuario pero la contraseña no coincide)
                            // - NotFound (No se consiguio el nombre de usuario)
                            result = JsonConvert.DeserializeObject <string>(await response.Content.ReadAsStringAsync());
                            //PUESTO QUE NO SE OBTUVO EL CODIGO DE ESTATUS 200 OK SE DESERIALIZA LA RESPUESTA OBTENIDA
                            //Y SE ALMACENA EN LA VARIABLE LOCAL "result"
                            //PUESTO QUE NO SE OBTUVO EL CODIGO 200 OK RETORNAREMOS NULL COMO RESPUESTA AL LLAMADO DEL METODO
                            return(null);
                        }
                    }
                }
                //DE OCURRIR UNA EXCEPCION DENTRO DEL CICLO TRY...CATCH SE PROCEDE A EJECUTAR LAS LINEAS DE CODIGO
                //CONTENIDAS DENTRO DE LA SECCION CATCH. AQUI SE EVALUARAN LAS EXCEPCIONES MAS COMUNES OBTENIDAS DURANTE
                //LAS PRUEBAS DE CONEXION CON EL SERVICIO WEB API
                catch (Exception ex) when(ex is HttpRequestException ||
                                          ex is Javax.Net.Ssl.SSLException ||
                                          ex is Javax.Net.Ssl.SSLHandshakeException ||
                                          ex is System.Threading.Tasks.TaskCanceledException)
                {
                    //SE MANDA A IMPRIMIR POR CONSOLA EL ERROR OBTENIDO (EJECUTADO SOLO CUANDO SE DEPURA EL PROYECTO)
                    ConsoleWriteline("\nOcurrio un error => \n\n" + ex.Message.ToString());
                    //SE NOTIFICA AL USUARIO QUE NO SE PUDO REALIZAR LA SOLICITUD WEB.
                    result = "\nProblemas de conexión con el servidor";
                    //PUESTO QUE NO SE OBTUVO EL CODIGO 200 OK RETORNAREMOS NULL COMO RESPUESTA AL LLAMADO DEL METODO
                    return(null);
                }
            }
            else
            {
                //EL EQUIPO NO ENCUENTRA CONECTADO A INTERNET, SE LE NOTIFICA AL USUARIO.
                result = "No hay conexión a internet";
                //PUESTO QUE NO SE OBTUVO EL CODIGO 200 OK RETORNAREMOS NULL COMO RESPUESTA AL LLAMADO DEL METODO
                return(null);
            }
        }