Пример #1
0
 public HttpResponseMessage LogIn([FromBody] LogInDto logInDto)
 {
     return(Request.ExecuteProtectedAndWrapResult <LogInDto, SessionModel>(
                dto => AccountService.LogIn(dto),
                ModelState, logInDto
                ));
 }
Пример #2
0
        public async Task <SessionModel> LogIn(LogInDto logInForm)
        {
            return(await base.Execute <SessionModel>(async() =>
            {
                using (UnitOfWork db = new UnitOfWork())
                {
                    AccountEntity account = await db.GetRepo <AccountEntity>().FirstOrDefault(
                        acc => acc.login == logInForm.Login
                        );

                    if (account == null)
                    {
                        throw new NotFoundException("Account");
                    }

                    string saltedPassword = account.password + logInForm.Salt;
                    string saltedPasswordHash = HashingService.GetHashHex(saltedPassword);

                    if (logInForm.PasswordSalted.ToUpper() != saltedPasswordHash.ToUpper())
                    {
                        throw new WrongPasswordException();
                    }

                    return SessionService.CreateSessionFor(account.id);
                }
            }));
        }
        public async Task <Session> LogIn(LogInDto logInDto)
        {
            AccountEntity account = await AccountRepo.GetByLogin(logInDto.Login);

            if (account == null)
            {
                throw new NotFoundException("User with such login");
            }

            string originalPasswordSalted = Hasher.GetHash(account.Password + logInDto.Salt);

            if (originalPasswordSalted.ToUpper() != logInDto.PasswordSalted.ToUpper())
            {
                throw new UnauthorizedAccessException("Wrong password");
            }

            if (SessionService.IsActive(account.Id))
            {
                return(SessionService.GetByAccountId(account.Id));
            }

            //await PayService.CheckPaymentRequired(account.Login);

            return(SessionService.CreateSessionFor(account.Id));
        }
Пример #4
0
        public ActionResult Login(LogInDto model, string returnUrl)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                Usuario usuario = _usuarioBl.ValidateUser(model.UserName, model.Password);

                if (usuario == null)
                {
                    ViewBag.MessageError = Resources.Usuario.CredencialesIncorrectas;
                    return(View(model));
                }

                var usuarioDto = MapperHelper.Map <Usuario, UsuarioDto>(usuario);
                GenerarTickectAutenticacion(usuarioDto);

                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception ex)
            {
                LogError(ex);
                ViewBag.MessageError = Resources.Master.OcurrioError;
                return(View(model));
            }
        }
Пример #5
0
        public async Task <ActionResult <UserDto> > LogIn(LogInDto logInDto)
        {
            var user = await _context.Users.SingleOrDefaultAsync(u => u.UserName == logInDto.Username);

            if (user == null)
            {
                return(Unauthorized("Invalid User"));
            }

            using var hmac = new HMACSHA512(user.PasswordSalt);
            var computehash = hmac.ComputeHash(Encoding.UTF8.GetBytes(logInDto.Password));

            for (int i = 0; i < computehash.Length; i++)
            {
                if (computehash[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Invalid Password"));
                }
            }
            return(new UserDto
            {
                Username = user.UserName,
                Token = await _tokenService.CreateToken(user)
            });
        }
Пример #6
0
        public IActionResult AuthUser([FromBody] LogInDto user)
        {
            var methodName = MethodBase.GetCurrentMethod().ReflectedType.FullName;

            _logger.LogInformation(Constants.EnterMethod, methodName);

            if (user == null)
            {
                return(BadRequest(Constants.InvalidInput));
            }

            try
            {
                var dbUser = _context.User.Where(u => u.Email.ToLower() == user.Email.ToLower() &&
                                                 _passwordHasher.Check(u.Password, user.Password).Verified).FirstOrDefault();

                if (dbUser != null)
                {
                    var authUser = CreateAuthentifiedUser(dbUser);

                    _logger.LogInformation(Constants.ExitMethod, methodName);
                    return(Ok(authUser));
                }
                else
                {
                    return(NotFound(Constants.InvalidLogInUser));
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex.StackTrace, ex);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Пример #7
0
        public async Task <ActionResult <UserDto> > LogIn(LogInDto logindto)
        {
            var user = await _context.Users
                       .Include(p => p.Photos)
                       .SingleOrDefaultAsync(x => x.UserName == logindto.UserName);

            if (user == null)
            {
                return(Unauthorized("Invalid UserName"));
            }

            using var hmac = new HMACSHA512(user.PasswordSalt);

            var computedhash = hmac.ComputeHash(Encoding.UTF8.GetBytes(logindto.Password));

            for (int i = 0; i < computedhash.Length; i++)
            {
                if (computedhash[i] != user.PasswordHash[i])
                {
                    return(Unauthorized("Invalid password"));
                }
            }

            return(new UserDto
            {
                UserName = user.UserName,
                Token = _tokenService.CreateToken(user),
                PhotoUrl = user.Photos.FirstOrDefault(x => x.IsMain)?.Url,
                KnownAs = user.KnownAs,
                Gender = user.Gender
            });
        }
Пример #8
0
        public async Task <LogInResponseDto> GenerateTokenAsync(LogInDto logIn)
        {
            LogInResponseDto response = null;

            var user = await _userRepository.GetUserByUserNameAsync(logIn.UserName);

            if (user == null)
            {
                return(response);
            }

            var authenticate = AuthenticateUser(logIn, user);

            if (authenticate)
            {
                var token = GenerateJSONWebToken(user);

                response = new LogInResponseDto
                {
                    FullName = user.FullName,
                    Token    = token
                };
            }

            return(response);
        }
Пример #9
0
        public async Task <ActionResult <UserDto> > Login(LogInDto loginDto)
        {
            var user = await _userManager.Users
                       .Where(x => x.UserName.ToLower() == loginDto.Username.ToLower())
                       .Include(p => p.Photos)
                       .SingleOrDefaultAsync(); //x => x.UserName.ToLower() == loginDto.Username.ToLower());

            if (user == null)
            {
                return(Unauthorized("Invalid username"));
            }

            var result = await _signInManager
                         .CheckPasswordSignInAsync(user, loginDto.Password, false);

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

            return(new UserDto
            {
                Username = user.UserName,
                Token = await _tokenService.CreateToken(user),
                PhotoUrl = user.Photos.FirstOrDefault(x => x.IsMain)?.Url,
                KnownAs = user.KnownAs,
                Gender = user.Gender
            });
        }
Пример #10
0
        public ActionResult LogIn(LogInDto model)
        {
            bool IsSuccess = false;
            var  url       = string.Empty;
            var  errorList = string.Empty;

            if (ModelState.IsValid)
            {
                ValidationStateDictionary states = new ValidationStateDictionary();
                bool isFirstLogIn = false;
                bool status       = Access.SignIn(model.Username, model.Password, model.TokenCode, _securityService, _finacleRepository, out isFirstLogIn, ref states);

                if ((!states.IsValid))
                {
                    IsSuccess = false;
                    errorList = ValidationHelper.BuildModelErrorList(states);
                    Danger(string.Format("{0}<br />{1}", Constants.Messages.ErrorNotice, errorList), true);
                    ModelState.AddModelErrors(states);
                }
                else
                {
                    if (!String.IsNullOrEmpty(model.ReturnUrl))
                    {
                        url       = model.ReturnUrl;
                        IsSuccess = true;
                    }
                    else
                    {
                        if (!isFirstLogIn)
                        {
                            var roleName = ((Identity)ControllerContext.HttpContext.User.Identity).Roles;
                            url       = Helper.GetRootURL() + "/admin";
                            IsSuccess = true;
                        }
                        else
                        {
                            url       = Helper.GetRootURL() + "/MyProfile/changepassword";
                            IsSuccess = true;
                        }
                    }
                }
            }

            model.Password = "******";
            SetAuditInfo(IsSuccess ? "Successful" : Helper.StripHtml(errorList, true),
                         JsonConvert.SerializeObject(model),
                         string.IsNullOrEmpty(model.Username) ? "not-supplied" : model.Username);

            if (IsSuccess)
            {
                return(new RedirectResult(url));
            }
            else
            {
                // If we got this far, something failed, redisplay form
                return(View(model));
            }
        }
Пример #11
0
        public ActionResult Login()
        {
            var login = new LogInDto
            {
                UserName = "",
                Password = ""
            };

            return(View(login));
        }
        public async Task <IActionResult> LogIn(LogInDto logInDto)
        {
            var authenticationResponse = await accountService.Authorize(logInDto, Request.Headers[HeaderNames.UserAgent].ToString());

            if (authenticationResponse == null)
            {
                return(BadRequest <LogInDto>(r => r.Password, LocalizedResources.UserAuthenticationError));
            }
            return(Ok(authenticationResponse));
        }
Пример #13
0
        public async Task <IActionResult> LogInAsync([FromBody] LogInDto logInDto)
        {
            var response = await _authService.LogInAsync(logInDto);

            if (response.Error != null)
            {
                return(BadRequest(response));
            }

            return(Ok(response));
        }
Пример #14
0
 public UserLoggedInDto LogIn([FromBody] LogInDto dto)
 {
     return(new UserLoggedInDto()
     {
         DisplayName = dto.UserName,
         Email = "*****@*****.**",
         Id = "1",
         Token = "token",
         TokenExpirationDate = DateConverter.Convert(DateTime.Now.AddSeconds(3600)),
         AccountType = "admin",
     });
 }
Пример #15
0
        public async Task <SessionDto> LogIn(LogInForm logInForm)
        {
            string   salt           = Guid.NewGuid().ToString();
            string   passwordSalted = Hasher.GetHash(Hasher.GetHash(logInForm.Password) + salt);
            LogInDto dto            = new LogInDto(logInForm.Login, passwordSalted, salt);

            Session = await Server.SendPost <LogInDto, SessionDto>(
                ServerHolder.SERVER_URL + LOG_IN_ENDPOINT, dto
                );

            return(Session);
        }
Пример #16
0
        public ActionResult Login()
        {
            var m         = new LogInDto();
            var returnUrl = Request.QueryString["ReturnUrl"] as string;

            if (!string.IsNullOrEmpty(returnUrl))
            {
                m.Message   = GetUrlTargetMessage(returnUrl);
                m.ReturnUrl = returnUrl;
            }
            return(View(m));
        }
Пример #17
0
        //aca van los mapeos de la base de datos

        internal static LogInDto BuildUserData(IDataReader reader)
        {
            LogInDto User = new LogInDto();

            User.user_id    = int.Parse(reader["user_id"].ToString());
            User.nombre     = (reader["nombre"].ToString());
            User.apellido   = (reader["apellido"].ToString());
            User.mail       = (reader["mail"].ToString());
            User.rol        = int.Parse(reader["rol"].ToString());
            User.telefono   = (reader["telefono"].ToString());
            User.contraseña = (reader["contraseña"].ToString());

            return(User);
        }
Пример #18
0
        private bool AuthenticateUser(LogInDto login, User user)
        {
            if (login == null || user == null)
            {
                return(false);
            }

            if (VerifyPasswordHash(login.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(true);
            }

            return(false);
        }
Пример #19
0
        public IActionResult Post([FromBody] LogInDto request)
        {
            try
            {
                var user      = login.Execute(request);
                var stringObj = JsonConvert.SerializeObject(user);
                var enced     = enc.EncryptString(stringObj);

                return(Ok(new { token = enced }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
Пример #20
0
        public async Task <IActionResult> LogIn([FromBody] LogInDto dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            User currentUser = _context.Users.Where(u => u.Email.Equals(dto.Email.ToLower()) && u.Password.Equals(dto.Password)).FirstOrDefault();

            if (currentUser == null)
            {
                return(BadRequest());
            }

            return(Ok(JsonConvert.SerializeObject(currentUser.Email)));
        }
Пример #21
0
        public async Task <IActionResult> LogInAsync(LogInDto user)
        {
            try
            {
                LogInResponseDto res = await _userService.GenerateTokenAsync(user);

                if (res != null)
                {
                    return(Ok(res));
                }

                return(BadRequest("رمز یا گذرواژه غلط"));
            }
            catch (Exception e)
            {
                return(Unauthorized(e));
            }
        }
Пример #22
0
        public SessionModel LogIn(LogInDto dto)
        {
            AccountModel account = AccountRepo.GetByLogin(dto.Login);

            if (account == null)
            {
                throw new NotFoundException("Login");
            }

            string originalPasswordSalted = Hasher.GetHash(account.Password + dto.Salt);

            if (originalPasswordSalted.ToUpper() != dto.PasswordSalted.ToUpper())
            {
                throw new UnauthorizedException("Wrong password");
            }

            return(SessionService.CreateSessionFor(account.Id));
        }
Пример #23
0
        public async Task <IActionResult> LoginPostAsync([FromBody] LogInDto logInfo)
        {
            //1.验证用户名和密码

            var isVaildFlag = await signInManager.PasswordSignInAsync(logInfo.Email, logInfo.Password, false, false);

            if (!isVaildFlag.Succeeded)
            {
                return(BadRequest());
            }
            var user = await userManager.FindByEmailAsync(logInfo.Email);

            //2.生成JWT
            //2.1 确定头部加密算法
            var head = SecurityAlgorithms.HmacSha256;
            //2.2 要加密数据
            var dataClaims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id)
            };
            var roleNames = await userManager.GetRolesAsync(user);

            foreach (string roleName in roleNames)
            {
                dataClaims.Add(new Claim(ClaimTypes.Role, roleName));
            }
            //2.3 数字签名部分
            var configkeyBytes        = Encoding.UTF8.GetBytes(configration["SignatureKey:loginKey"]);
            var signingKey            = new SymmetricSecurityKey(configkeyBytes);
            var mysigningCreadentials = new SigningCredentials(signingKey, head);

            //public JwtSecurityToken(string issuer = null, string audience = null, IEnumerable<Claim> claims = null, DateTime? notBefore = null, DateTime? expires = null, SigningCredentials signingCredentials = null)
            var token = new JwtSecurityToken(
                issuer: configration["SignatureKey:Issuer"],
                audience: configration["SignatureKey:Audience"],
                dataClaims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddDays(int.Parse(configration["SignatureKey:ExpiresDays"])),
                mysigningCreadentials
                );
            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);

            //3. 返回数据
            return(Ok(tokenStr));
        }
Пример #24
0
        public async Task <ActionResult> LogInUser(string user, string password)
        {
            try
            {
                LogInDto objUser = await _clientesService.LogInUser(user, password);

                return(Response.Ok(objUser));
            }
            catch (BaseException e)
            {
                _logger.LogInformation(ExceptionHandlerHelper.ExceptionMessageStringToLogger(e));
                return(Response.HandleExceptions(e));
            }
            catch (Exception e)
            {
                _logger.LogError(e, GetType().Name + "." + MethodBase.GetCurrentMethod().Name);
                return(Response.InternalServerError());
            }
        }
Пример #25
0
        public Logged Execute(LogInDto request)
        {
            var user = context.Users
                       .Where(u => u.Email == request.Email)
                       .Where(u => u.Password == request.Password)
                       .FirstOrDefault();

            if (user == null)
            {
                throw new NotFoundEx();
            }
            return(new Logged
            {
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                RoleName = user.Role.RoleName
            });
        }
Пример #26
0
        public async Task <ActionResult <UserDto> > Login(LogInDto logInDto)
        {
            var user = _userManager.Users
                       .Include(p => p.Photos)
                       .FirstOrDefault(x => x.Email == logInDto.Email);

            if (user == null)
            {
                return(Unauthorized());
            }
            var result = await _signInManager.CheckPasswordSignInAsync(user, logInDto.Password, false);

            if (result.Succeeded)
            {
                return(CreateUserObject(user));
            }

            return(Unauthorized());
        }
Пример #27
0
        public IActionResult LogIn([FromBody] LogInDto model)
        {
            var user = this.UnitOfWork.UserManager.FindByEmailAsync(model.Email).Result;

            if (user == null)
            {
                return(BadRequest("Your email or password is invalid"));
            }

            if (!this.UnitOfWork.UserManager.CheckPasswordAsync(user, model.Password).Result)
            {
                return(BadRequest("Your email or password is invalid"));
            }

            var userRoles = this.UnitOfWork.UserManager.GetRolesAsync(user).Result;
            var token     = JwtManager.GenerateToken(user, userRoles);

            return(Ok(token));
        }
        public async Task <bool> LogIn(LogInForm logInForm)
        {
            LogInDto dto = new LogInDto();

            dto.Login = logInForm.Login;
            dto.Salt  = SaltService.GetRandomSalt();

            string hashedPwd = HashingService.GetHash(logInForm.Password);

            dto.PasswordSalted = SaltService.GetSaltedHash(hashedPwd, dto.Salt);

            RestRequest request = new RestRequest(LOG_IN_ENDPOINT, Method.POST);

            request.AddJsonBody(JsonConvert.SerializeObject(dto));

            IRestResponse response = await Client.ExecuteAsync(request);

            return(response.StatusCode == HttpStatusCode.OK);
        }
Пример #29
0
        public async Task <LogInDto> LogInUser(string user, string password)
        {
            LogInDto      objUser = null;
            SqlDataReader reader  = null;

            using (SqlCommand oCommand = await base.GetCommandAsync())
            {
                try
                {
                    oCommand.CommandType = CommandType.Text;
                    oCommand.CommandText = @"SELECT * FROM usuarios WHERE mail = @user and contraseña = @password";

                    oCommand.AddParameter("user", DbType.String, user);
                    oCommand.AddParameter("password", DbType.String, password);

                    IAsyncResult asyncResult = ExecuteAsync(oCommand, "LogInUser");
                    reader = oCommand.EndExecuteReader(asyncResult);

                    while (await reader.ReadAsync())
                    {
                        objUser = ModelBuilderHelper.BuildUserData(reader);
                    }
                    return(objUser);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, GetType().Name + "." + MethodBase.GetCurrentMethod().Name);
                    throw new AggregateException(_classFullName + ".LogInUser(string user, string password)", ex);
                }
                finally
                {
                    if (reader != null && !reader.IsClosed)
                    {
                        reader.Close();
                    }
                    if (!TransactionOpened())
                    {
                        base.CloseCommand();
                    }
                }
            }
        }
Пример #30
0
        public async Task <string> LogIn(LogInDto logInDto)
        {
            var user = await _userRepo.GetAsync(logInDto.Email); // TODO

            if (user == null)
            {
                throw new ApplicationException();
            }

            var password        = new PasswordHelper(user.Password, logInDto.Password);
            var isPasswordValid = password.VerifyPassword();

            if (!isPasswordValid)
            {
                throw new ApplicationException();
            }

            var token = JwtHelper.GenerateJwtToken(user);

            return(token);
        }