Пример #1
0
        public async Task <object> Login([FromBody] LoginDto loginData)
        {
            var result = await _signInManager.PasswordSignInAsync(loginData.Email, loginData.Password, false, false);

            if (result.Succeeded)
            {
                var appUser  = _userManager.Users.SingleOrDefault(r => r.Email == loginData.Email);
                var AppLogin = new AppUserLogin
                {
                    active      = appUser.Active,
                    Email       = appUser.Email,
                    id          = appUser.Id,
                    SAPID       = appUser.SAPID,
                    Name        = appUser.Name,
                    User        = appUser.UserName,
                    Active_Burn = appUser.Active_Burn,
                    Serie       = appUser.Serie
                };
                var token = await GenerateJwtToken(loginData.Email, appUser);

                appUser.Warehouse = _context.Warehouses.Find(appUser.WarehouseID);
                //UserDetailOutput Roles = Redirect($"/api/User/{appUser.Id}");
                UserController   userController = new UserController(_context, _userManager, _roleManager);
                var              Roles          = (ObjectResult)userController.Get(appUser.Id).Result;
                UserDetailOutput userDetail     = (UserDetailOutput)Roles.Value;
                //Task<IActionResult> RolList = new RoleController(_context,_roleManager).Get(Roles.RoleId);
                return(Ok(new { token, AppLogin, warehouseCode = appUser.Warehouse.WhsCode, userDetail.RolePermissions }));
            }
            return(BadRequest("Error al Intentar Iniciar Sesion"));
        }
Пример #2
0
        public async Task <AuthResponse> Login(AppUserLogin model)
        {
            // get user based on username
            var user = await _db.AppUsers.Where(a => a.UserName == model.Username).SingleOrDefaultAsync();

            // check if username is not found
            if (user == null)
            {
                _logger.LogInformation("Username not found for " + model.Username);
                return(new AuthResponse()
                {
                    Error = "Username was not found."
                });
            }

            // validate password
            if (!Encryption.ValidateHashedPassword(model.Password, user.PasswordHash))
            {
                _logger.LogInformation("Invalid login for " + model.Username);
                throw new UnauthorizedAccessException();
            }

            // get JWT token string
            var token = _jwtService.GenerateEncodedToken(user);

            // return auth response
            return(new AuthResponse(token));
        }
Пример #3
0
        private async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            AppUserLogin login = new AppUserLogin
            {
            };

            return(null);
        }
Пример #4
0
        public async Task <IActionResult> Login([FromBody] AppUserLogin model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var token = await _service.Login(model);

            return(new OkObjectResult(token));
        }
Пример #5
0
 public async Task <IActionResult> SignIn(AppUserLogin appUserLogin)
 {
     if (ModelState.IsValid)
     {
         if (await _authService.Login(appUserLogin))
         {
             return(RedirectToAction("Index", "Home"));
         }
         ModelState.AddModelError("", "Kullanıcı adı veya şifre hatalı");
     }
     return(View(appUserLogin));
 }
 public async Task <IActionResult> SignIn(AppUserLogin appUserLogin)
 {
     if (ModelState.IsValid)
     {
         if (await _authService.LogIn(appUserLogin))
         {
             return(RedirectToAction("Index", "Home"));
         }
         ModelState.AddModelError("", "Username or password is incorrect.");
     }
     return(View(appUserLogin));
 }
Пример #7
0
        public static AppUserLogin Create(UserLogin userLogin)
        {
            if (userLogin == null)
            {
                return(null);
            }

            var appUserLogin = new AppUserLogin
            {
                LoginProvider = userLogin.LoginProvider,
                ProviderKey   = userLogin.ProviderKey,
                UserId        = userLogin.UserId
            };

            return(appUserLogin);
        }
Пример #8
0
        public static UserLogin Create(AppUserLogin appUserLogin)
        {
            if (appUserLogin == null)
            {
                return(null);
            }

            var userLogin = new UserLogin
            {
                LoginProvider = appUserLogin.LoginProvider,
                ProviderKey   = appUserLogin.ProviderKey,
                UserId        = appUserLogin.UserId
            };

            return(userLogin);
        }
Пример #9
0
        public async Task <bool> Login(AppUserLogin appUserLogin)
        {
            var jsonData      = JsonConvert.SerializeObject(appUserLogin);
            var stringContent = new StringContent(jsonData, Encoding.UTF8, "application/json");

            using var httpClient = new HttpClient();

            var responseMessage = await httpClient.PostAsync("http://localhost:63846/Api/Auth/SignIn", stringContent);

            if (responseMessage.IsSuccessStatusCode)
            {
                var token = JsonConvert.DeserializeObject <AccessToken>(await responseMessage.Content.ReadAsStringAsync());
                _accessor.HttpContext.Session.SetString("token", token.Token);
                return(true);
            }
            return(false);
        }
Пример #10
0
        public ActionResult Login(AppUserLogin login, string ReturnUrl = "")
        {
            string message = "";

            using (EMSDbContext dc = new EMSDbContext())
            {
                var validUser = dc.AppUsers.Where(a => a.UserName == login.UserName).FirstOrDefault();
                if (validUser != null)
                {
                    if (string.Compare(Crypto.Hash(login.Password), validUser.Password) == 0)
                    {
                        int    timeout   = login.RememberMe ? 525600 : 20; // 525600 min = 1 year
                        var    ticket    = new FormsAuthenticationTicket(login.UserName, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);
                        var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
                        cookie.Expires  = DateTime.Now.AddMinutes(timeout);
                        cookie.HttpOnly = true;
                        Response.Cookies.Add(cookie);


                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                    else
                    {
                        message = "Invalid credential provided";
                    }
                }
                else
                {
                    message = "Invalid credential provided";
                }
            }
            ViewBag.Message = message;
            return(View());
        }
Пример #11
0
        public AppUserLogin Login(string UserName, string Password)
        {
            AppUserLogin User = new AppUserLogin();

            try
            {
                string ConnectionPath = connectionStrings.DefaultConnection;
                using (var sqlCon = new SqlConnection(ConnectionPath))
                {
                    using (SqlCommand cmd = new SqlCommand("stp_ValidateUser", sqlCon))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Login", UserName);
                        cmd.Parameters.AddWithValue("@active", "yes");
                        cmd.Parameters.AddWithValue("@pw", Password);

                        sqlCon.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                User.Name    = DataHelper.ConvertTo <string>(reader["user_name"]);
                                User.Email   = DataHelper.ConvertTo <string>(reader["UEmailId"]);
                                User.LoginId = DataHelper.ConvertTo <string>(reader["Login"]);
                            }
                        }

                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(User);
        }
Пример #12
0
        public async Task <IActionResult> Post([FromBody] CredentialsViewModel credentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                AppUserLogin LoggedInUser = _AuthRepository.Login(credentials.UserName, credentials.Password);

                if (LoggedInUser.LoginId != String.Empty)
                {
                    var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
                    var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                    var tokeOptions = new JwtSecurityToken(
                        issuer: "http://localhost:50188",
                        audience: "http://localhost:50188",
                        claims: new List <Claim>(),
                        expires: DateTime.Now.AddMinutes(5),
                        signingCredentials: signinCredentials
                        );

                    var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                    return(Ok(new { Token = tokenString }));
                }
                else
                {
                    return(Unauthorized());
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState)));
            }
        }