示例#1
0
        public ActionResult Login(UserLogin user)
        {
            var token = _serAuth.Authenticate(user.Email, user.Password);

            if (token == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect. !!!" }));
            }
            return(Ok(new { token }));
            //var pass = _aesHelper.DecryptStringAES(user.Password);
            //User find = _serUser.GetInfoUserByEmail(user.Email);
            //if(find == null)
            //{
            //    return BadRequest(new { message = "Email does not exist !!!" });
            //}
            //else
            //{
            //    var resp = BCrypt.Net.BCrypt.Verify(pass, find.Password);
            //    if (resp == false)
            //    {
            //        return Unauthorized(new { message = "Please check password !!!" });
            //    }
            //    var token = _serAuth.Authenticate(find);
            //    return Ok(new { token });
            //}
        }
示例#2
0
        public bool Authenticate(string username, string password)
        {
            //Run auth through the auth svc to get an identity
            AuthenticateService authsvc = new AuthenticateService();

            try {
                authsvc.Url = String.Format("http://{0}/FrontDeskServices/authsvc.asmx",
                                            TestConfig.AuthenticationAddress);
                Authentication.ServiceTicket     tik    = authsvc.Authenticate(username, password);
                FrontDesk.Services.ServiceTicket ticket = new FrontDesk.Services.ServiceTicket();
                ticket.HostAddress = tik.HostAddress;
                ticket.Username    = tik.Username;
                ticket.Ident       = tik.Ident;
                m_ident            = AuthorizedIdent.Create(ticket);
                if (m_ident != null)
                {
                    m_logger.Log("Authentication for: " + username +
                                 " succeeded.");
                    return(true);
                }
                else
                {
                    m_logger.Log("Authentication for: " + username +
                                 " failed.", TestLogger.LogType.ERROR);
                    return(false);
                }
            } catch (Exception er) {
                m_logger.Log("Error during authentication: MESSAGE: " + er.Message,
                             TestLogger.LogType.ERROR);
                return(false);
            }
        }
示例#3
0
        public string Authenticate(string Email, string Password)
        {
            AuthenticateService service = new AuthenticateService(_container);

            if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
            {
                var user = service.Authenticate(Email, Password);
                if (user != null)
                {
                    var authentication = Request.GetOwinContext().Authentication;
                    var identity       = new ClaimsIdentity("Bearer");
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.Id.ToString()));
                    identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
                    identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
                    identity.AddClaim(new Claim("companyname", user.Company.Name));

                    AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
                    ticket.Properties.IssuedUtc  = currentUtc;
                    ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
                    var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                    authentication.SignIn(identity);

                    return(token);
                }
            }

            return("false");
        }
        public async Task Login_Valid_Returns_True()
        {
            // Arrange
            var userList = new List <User>();

            userList.Add(new User {
                Id = 1
            });
            var mockUser = userList.AsQueryable().BuildMock();

            _Repo.Setup(x => x.Get(It.IsAny <Expression <Func <User, bool> > >())).Returns(mockUser.Object);

            var request = new SignInRequest {
                Username = "******", Password = "******"
            };
            var token = new AuthToken {
                token = ""
            };

            var tokenBuilder = new Mock <ITokenBuilderService>();

            tokenBuilder.Setup(x => x.GetToken(It.IsAny <int>())).Returns(token);
            var passwordService = new Mock <IPasswordService>();

            passwordService.Setup(x => x.ValidatePassword(It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            var authService = new AuthenticateService(_Repo.Object, tokenBuilder.Object, passwordService.Object);
            // Act
            var results = await authService.Authenticate(request);

            // Assert
            Assert.IsTrue(results.Success);
        }
示例#5
0
        public Task <ActionResult> SignIn(SignInViewModel viewModel)
        {
            return(CreateActionResultAsync(async() =>
            {
                if (!ModelState.IsValid)
                {
                    return View();
                }

                var dtoAccount =
                    Mapper.Map <SignInViewModel, AccountDTO>(viewModel);

                ClaimsIdentity claims;

                try
                {
                    claims = await AuthenticateService.Authenticate(dtoAccount);
                }
                catch (IdentityException e)
                {
                    return Content(e.Message);
                }

                SignIn(claims);

                return RedirectToAction("Index", "Home");
            }));
        }
        public User Display()
        {
            Console.Clear();
            Console.WriteLine("Please Log in\n");

            Console.Write("Username: "******"Password: "******"Successfully logged in!");
                Thread.Sleep(2000);
                Console.Clear();
                Console.WriteLine($"Role: {user.Role}");
                return(user);
            }
            else
            {
                Console.WriteLine("Access Denied!");
                Thread.Sleep(2000);
                Console.Clear();
                Display();
            }

            Console.ReadKey();
            return(user);
        }
 public void NotAuthenticate()
 {
     using (var db = new MainAuthExampleContext(_options))
     {
         var authService = new AuthenticateService(db);
         var result      = authService.Authenticate(new AnonymousUser("userNotExists", "pass1"));
         Assert.Null(result);
     }
 }
示例#8
0
 public string Login([FromBody] LoginUser user)
 {
     if (userService.ValidateUserData(user))
     {
         var token = authenticateService.Authenticate(user);
         return(token);
     }
     else
     {
         return(null);
     }
 }
        public async Task <ActionResult> CreateToken([FromBody] User attempt)
        {
            var user = await _authService.Authenticate(attempt);

            if (user != null)
            {
                var tokenString = _authService.BuildToken(user);
                return(Ok(new { token = tokenString, userId = user.id }));
            }

            return(ValidationProblem());
        }
        public IActionResult AuthenticateUser([FromBody] User model)
        {
            AuthenticateService authenticateService = new AuthenticateService();
            var user = authenticateService.Authenticate(model.username, model.password);

            if (user == null)
            {
                return(BadRequest(new { Message = "invalid username or password" }));
            }
            else
            {
                return(Ok(user));
            }
        }
示例#11
0
        /// <summary>
        /// Method to authenticate user
        /// </summary>
        /// <param name="company"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public UserBO AuthenticateUser(string company, string username, string password)
        {
            string dataAccessToken                 = string.Empty;
            string encryptedDataAccessToken        = string.Empty;
            AuthenticateService integrationService = new AuthenticateService();
            UserBO user = new UserBO();

            try
            {
                // Check for company, username, password required validation and then call Authenticate of Integration layer
                if (!String.IsNullOrEmpty(company))
                {
                    if (!String.IsNullOrEmpty(username))
                    {
                        if (!String.IsNullOrEmpty(password))
                        {
                            dataAccessToken      = integrationService.Authenticate(Constants.CONSUMER_SECRET_TOKEN, Constants.VERSION_5, company, username, password);
                            user.DataAccessToken = UtilityService.EncryptedText(dataAccessToken);
                        }
                        else
                        {
                            throw new Exception("Password cannot be Empty");
                        }
                    }
                    else
                    {
                        throw new Exception("Username cannot be Empty");
                    }
                }
                else
                {
                    throw new Exception("Company cannot be Empty");
                }
            }
            catch (DovicoException e)
            {
                logger.Log(LogLevel.Error, e);
                user.ErrorMessage = e.Message;
            }
            catch (Exception e)
            {
                logger.Log(LogLevel.Error, e);
                user.ErrorMessage = e.Message;
            }

            return(user);
        }
        public void Authenticate()
        {
            User result = null;

            using (var db = new MainAuthExampleContext(_options))
            {
                if (!db.Users.Where(u => u.Username.Equals("user1")).Any())
                {
                    db.Users.Add(new UserAuthenticationsEntity {
                        Username = "******", Password = "******"
                    });
                    db.SaveChanges();
                }

                var authService = new AuthenticateService(db);
                result = authService.Authenticate(new AnonymousUser("user1", "pass1"));
            }
            Assert.Equal(new Employee("user1"), result);
        }
        public async Task Login_InValid_Returns_False()
        {
            // Arrange
            var userList = new List <User>();
            var mockUser = userList.AsQueryable().BuildMock();

            _Repo.Setup(x => x.Get(It.IsAny <Expression <Func <User, bool> > >())).Returns(mockUser.Object);

            var request = new SignInRequest {
                Username = "******", Password = "******"
            };

            var tokenBuilder    = new Mock <ITokenBuilderService>();
            var passwordService = new Mock <IPasswordService>();
            var authService     = new AuthenticateService(_Repo.Object, tokenBuilder.Object, passwordService.Object);
            // Act
            var results = await authService.Authenticate(request);

            // Assert
            Assert.IsFalse(results.Success);
        }
示例#14
0
        public Task <ActionResult> Register(RegisterViewModel viewModel)
        {
            return(CreateActionResultAsync(async() =>
            {
                if (!ModelState.IsValid)
                {
                    return View();
                }

                var dtoAccount =
                    Mapper.Map <RegisterViewModel, AccountDTO>(viewModel);

                AccountService.Create(dtoAccount);

                var claims = await AuthenticateService.Authenticate(dtoAccount);

                SignIn(claims);

                return RedirectToAction("Index", "Home");
            }));
        }
示例#15
0
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            User user = null;

            if (!string.IsNullOrEmpty(context.UserName) && !string.IsNullOrEmpty(context.Password))
            {
                AuthenticateService service         = new AuthenticateService(_container);
                LogLoginService     loginLogService = new LogLoginService(_container);
                LogLogin            logLoginObj     = new LogLogin();
                user = service.Authenticate(context.UserName, context.Password);
                if (user != null)
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim("name", user.Name));
                    identity.AddClaim(new Claim("email", user.Email));
                    identity.AddClaim(new Claim("userid", user.Id.ToString()));
                    identity.AddClaim(new Claim("usertype", user.UserType.ToString()));
                    identity.AddClaim(new Claim("companyid", user.Company.Id.ToString()));
                    identity.AddClaim(new Claim("companyname", user.Company.Name));
                    identity.AddClaim(new Claim("ipaddress", context.Request.RemoteIpAddress));

                    context.Validated(identity);

                    logLoginObj.LoginLogType = LoginLogType.SUCCESS.ToString();
                    logLoginObj.UserId       = user.Id;
                }
                else
                {
                    logLoginObj.LoginLogType    = LoginLogType.FAILED.ToString();
                    logLoginObj.Comment         = "Başarısız Giriş";
                    logLoginObj.ExceptionString = string.Format("UserName:{0} - Password:{1} ", context.UserName, context.Password);
                }
                logLoginObj.IsDeleted = false;
                logLoginObj.LogDate   = DateTime.Now;
                loginLogService.Add(logLoginObj);
            }

            //if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password))
            //{
            //    var user = service.Authenticate(Email, Password);
            //    if (user != null)
            //    {
            //        var authentication = Request.GetOwinContext().Authentication;
            //        var identity = new ClaimsIdentity("Bearer");
            //        identity.AddClaim(new Claim("name", user.Name));
            //        identity.AddClaim(new Claim("email", user.Email));
            //        identity.AddClaim(new Claim("userid", user.Id.ToString()));
            //        identity.AddClaim(new Claim("isadmin", user.UserType.Value == 1 ? "true" : "false"));

            //        AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            //        var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
            //        ticket.Properties.IssuedUtc = currentUtc;
            //        ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
            //        var token = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

            //        authentication.SignIn(identity);

            //        return token;
            //    }
            //}

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
            }


            return(Task.FromResult <object>(null));
        }