Exemplo n.º 1
0
        public async Task <IActionResult> Login([Bind] Models.Credentials creds)
        {
            var apiResponse = await _uniAPI.Post <Jwt, Models.Credentials>("Login", creds);

            if (!(apiResponse.Result is EmptyResult))
            {
                var jwt = apiResponse.Value;
                if (!String.IsNullOrWhiteSpace(jwt.Token))
                {
                    _uniAPI.SetJWT(jwt);

                    var cookieOptions = new CookieOptions()
                    {
                        Expires = DateTime.Now.AddHours(24)
                    };
                    Response.Cookies.Append("Jwt", jwt.Token, cookieOptions);

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                                  _jwtService.ValidateToken(jwt),
                                                  new AuthenticationProperties()
                    {
                        ExpiresUtc = DateTime.UtcNow.AddHours(24)
                    });

                    return(RedirectToRoutePermanent("Default", new { controller = "Register", action = "Index" }));
                }
                else
                {
                    return(LocalRedirectPermanent("~/Login/"));
                }
            }

            return(LocalRedirectPermanent("~/Login/"));
        }
Exemplo n.º 2
0
        private string GenerateToken(Models.Credentials credentials)
        {
            var simmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Utilities.Base64Decode(TokenConfig.Value.EncryptedKey)));

            var signingCredentials = new SigningCredentials(simmetricSecurityKey, SecurityAlgorithms.HmacSha256);

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, credentials.Username),
                new Claim(ClaimTypes.Country, "CL")
            };

            var token = new JwtSecurityToken(
                issuer: TokenConfig.Value.Issuer,
                audience: TokenConfig.Value.Audience,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddHours(TokenConfig.Value.HoursToExpire),
                signingCredentials: signingCredentials,
                claims: claims
                );

            var generatedToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(generatedToken);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> PostAsync([FromBody] Models.Credentials credentials)
        {
            Models.Customer customer;
            if (AuthenticatedToken != null) //social auth
            {
                NewRelic.Api.Agent.NewRelic.AddCustomParameter("credentials.email", AuthenticatedToken.Payload["email"].ToString());
                customer = await _customerRepository.Get(AuthenticatedToken.Payload["email"].ToString());

                if (customer == null)
                {
                    customer = new Models.Customer
                    {
                        Nombre = AuthenticatedToken.Payload["name"].ToString(),
                        Mail   = AuthenticatedToken.Payload["email"].ToString(),
                        Tipo   = (int)Models.Credentials.Types.Social, //social user
                        Estado = 2,                                    //initial state
                        Condos = new List <Models.Condo>()
                    };
                    if (!await _customerRepository.CreateOrUpdate(customer))
                    {
                        return(new BadRequestObjectResult(customer)); //problems creating customer on db
                    }
                }
            }
            else
            {
                NewRelic.Api.Agent.NewRelic.AddCustomParameter("credentials.email", credentials.email);
                var getUserInfo = await _customerRepository.CheckPassword(credentials);

                if ((getUserInfo == null || getUserInfo.Tables.Count == 0 || getUserInfo.Tables[0].Rows.Count == 0))
                {
                    return(new UnauthorizedResult());
                }
                customer = getUserInfo.Tables[0].Select().ToCustomer();
            }

            if (customer.Estado > 2)
            {
                return(new ForbidResult()); //user disabled
            }
            var defaultDuration = !Request.Query.TryGetValue("tokenDuration", out StringValues customTokenDuration);
            var tokenDuration   = defaultDuration ? 5 : double.Parse(customTokenDuration);
            var jwt             = Jwt.Create(customer, tokenDuration);

            return(new OkObjectResult(new
            {
                email = customer.Mail,
                firstName = customer.Nombre,
                idToken = jwt,
                name = customer.Nombre,
                photoUrl = customer.Icono,
                provider = customer.Tipo == (int)Models.Credentials.Types.Social ? "social" : "internal",
                state = customer.Estado,
                data = customer.Condos,
                validTo = tokenDuration == 0 ? DateTime.MaxValue.ToUniversalTime().ToString() : DateTime.Now.AddMinutes(tokenDuration).ToUniversalTime().ToString()
            }));
        }
Exemplo n.º 4
0
        public async Task <DataSet> CheckPassword(Models.Credentials credentials)
        {
            var args = new Dictionary <string, string>
            {
                { "MAIL", credentials.email },
                { "PASS", credentials.password }
            };

            return(await Helpers.Sql.Execute("[desoincl_inmueble].[SP_USUARIO_VALIDA_CREDENCIALES]", args));
        }
Exemplo n.º 5
0
        public async Task <bool> UpdatePassword(Models.Credentials credentials)
        {
            var args = new Dictionary <string, string>
            {
                { "MAIL", credentials.email },
                { "CLAVE", credentials.password }
            };
            var res = await Helpers.Sql.ExecuteScalar("[desoincl_inmueble].[SP_USUARIO_CAMBIO_CLAVE]", args);

            return(res > 0);
        }
Exemplo n.º 6
0
        public IActionResult Post([FromBody] Models.Credentials credentials)
        {
            var login = this.userservice.Authenticate(credentials.username, credentials.password);

            if (!string.IsNullOrEmpty(login.Token))
            {
                CookieOptions options = new CookieOptions();
                options.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Append(Helpers.Helpers.AuthToken, login.Token, options);
            }
            return(Json(login));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Login([FromBody] Models.Credentials credentials)
        {
            var result = await _signInManager.PasswordSignInAsync(credentials.Email, credentials.Password, false, false);

            if (!result.Succeeded)
            {
                return(BadRequest());
            }

            var user = await _userManager.FindByEmailAsync(credentials.Email);

            return(Ok(CreateToken(user)));
        }
Exemplo n.º 8
0
        public ActionResult RequestToken(Models.Credentials credentials)
        {
            if (credentials != null && credentials.Username == credentials.Password)
            {
                var generatedToken = GenerateToken(credentials);

                return(Ok(generatedToken));
            }
            else
            {
                return(Unauthorized(TokenConfig.Value.UnauthorizedMessage));
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> NewCustomer([FromBody] Models.Credentials credentials)
        {
            NewRelic.Api.Agent.NewRelic.AddCustomParameter("credentials.email", credentials.email);
            // TODO add some abuse prevention mechanism

            // check if customer exists
            if (await _customerRepository.Get(credentials.email) != null)
            {
                return(new BadRequestObjectResult("If you continue having problemas please contact us !!"));
            }

            var newCustomer = new Models.Customer
            {
                Nombre   = credentials.email.StringWithoutDomain(),
                Mail     = credentials.email,
                Tipo     = (int)Models.Credentials.Types.System,
                Estado   = 2, //initial state
                Condos   = new List <Models.Condo>(),
                Password = Password.CreateWithRandomLength()
            };

            if (!await _customerRepository.CreateOrUpdate(newCustomer))
            {
                return(new BadRequestObjectResult(newCustomer)); //problems creating customer on db
            }
            var destination = new List <SendGrid.Helpers.Mail.EmailAddress> {
                new SendGrid.Helpers.Mail.EmailAddress(newCustomer.Mail, newCustomer.Nombre)
            };
            var payload = new
            {
                name     = newCustomer.Nombre,
                password = newCustomer.Password
            };
            var mail = await Email.SendTransactional(destination, Email.Templates.Transactional.NewCustomer, payload);

            if (mail.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                return(new OkResult());
            }
            else
            {
                var error = await mail.Body.ReadAsStringAsync();

                return(new ObjectResult(error)
                {
                    StatusCode = (int)mail.StatusCode
                });
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> ResetPassword([FromBody] Models.Credentials credentials)
        {
            //TODO add some abuse prevention mechanism
            //report user to newrelic
            NewRelic.Api.Agent.NewRelic.AddCustomParameter("credentials.email", credentials.email);
            var customer = await _customerRepository.Get(credentials.email);

            if (customer == null)
            {
                return(new BadRequestObjectResult("If you continue having problemas please contact us!!"));
            }

            if (customer.Tipo == (int)Models.Credentials.Types.Social)
            {
                return(new BadRequestObjectResult("Invalid option, you cannot reset your password from here!!"));
            }

            var destination = new List <SendGrid.Helpers.Mail.EmailAddress> {
                new SendGrid.Helpers.Mail.EmailAddress(credentials.email, credentials.email)
            };
            var payload = new
            {
                name     = credentials.email,
                password = Password.CreateWithRandomLength()
            };
            var result = await _customerRepository.UpdatePassword(new Models.Credentials {
                email = payload.name, password = payload.password
            });

            if (result)
            {
                var mail = await Email.SendTransactional(destination, Email.Templates.Transactional.PasswordReset, payload);

                if (mail.StatusCode == System.Net.HttpStatusCode.Accepted)
                {
                    return(new OkResult());
                }
                else
                {
                    var error = await mail.Body.ReadAsStringAsync();

                    return(new ObjectResult(error)
                    {
                        StatusCode = (int)mail.StatusCode
                    });
                }
            }
            return(new StatusCodeResult(304)); //not modified
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Register([FromBody] Models.Credentials credentials)
        {
            var user = new IdentityUser {
                UserName = credentials.Email, Email = credentials.Email
            };

            var result = await _userManager.CreateAsync(user, credentials.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            await _signInManager.SignInAsync(user, false);

            return(Ok(CreateToken(user)));
        }
Exemplo n.º 12
0
        public Models.Response Login(String Name, Models.Credentials Credentials)
        {
            try
            {
                // Get Database
                ViewModel.Manager.Database database = this.Server.Database(Name);

                // Login
                ViewModel.Manager.Session session = database.Login(Credentials.Username, Credentials.Password);
                HttpCookie cookie = new HttpCookie(tokencookie, session.Token);
                HttpContext.Current.Response.Cookies.Add(cookie);

                return(new Models.Responses.Empty(session));
            }
            catch (Exception e)
            {
                throw this.ProcessException(e);
            }
        }
Exemplo n.º 13
0
        public async Task Run()
        {
            var credentials = credentialManager.GetSavedCredentials();

            if (credentials == null)
            {
                //TODO: credentials = AskUserForCredentials();
                credentials = new Models.Credentials {
                    Login = "******", Password = "******"
                };
            }
            var devices = await communication.GetUserDevices(credentials);

            if (devices == null || !devices.Any())
            {
                Debug.WriteLine("Error. No devices was found.");
                return;
            }

            allSensorTypes = await communication.GetAllSensors();

            foreach (var device in devices)
            {
                _devices.Add(device.Token, device);
                await SetUserSensors(device.Token);
            }
            var tokens = devices.Select(x => x.Token).ToArray();

            RequstDataAndUpdateUI(tokens);

            Device.StartTimer(TimeSpan.FromSeconds(sampleIntervalSeconds), () =>
            {
                if (isCanceled)
                {
                    return(false);
                }

                RequstDataAndUpdateUI(tokens);
                return(true);
            });
        }