private VirtuClient.VirtuClient createVirtuClient(AuthenticationInput authenticationInput = null)
        {
            ConfigurationManagerHelper configurationManagerHelper = ConfigurationManagerHelper.Default;

            VirtuClient.VirtuClient result = new VirtuClient.VirtuClient(new Uri(configurationManagerHelper.VirtuBaseUrl));
            result.Logger = (log) =>
            {
                using (var db = new Model())
                {
                    db.Logs.Add(new Log()
                    {
                        Start     = log.Start,
                        End       = log.End,
                        Input     = log.Input,
                        Output    = log.Output,
                        Exception = log.Exception,
                        Name      = log.Name ?? "",
                    });
                    db.SaveChanges();
                }
            };
            result.Authenticate(authenticationInput ?? new AuthenticationInput()
            {
                createPersistentCookie = true,
                userName = configurationManagerHelper.VirtuUserName,
                password = configurationManagerHelper.VirtuPassword,
            });
            return(result);
        }
        public async Task <Guid> Authenticate(AuthenticationInput authInputs)
        {
            EmailAuthenticate authenticationByEmail = new EmailAuthenticate();

            var transactID = await authenticationByEmail.SendAuthenticationEmail(authInputs);

            return(transactID);
        }
        public async Task <IActionResult> CreateToken([FromBody] CreateTokenRequest request)
        {
            var input = new AuthenticationInput(request.UserName, request.Password);

            await _useCase.Execute(input);

            return(_presenter.ViewModel);
        }
        public async Task <ApiOutput <AuthenticationOutput> > Login(AuthenticationInput input)
        {
            var output = await _apiClient.Authenticate(input);

            if (output.Success)
            {
                await _localStorage.SetItemAsync("authToken", output.Result.AccessToken);

                _authenticationStateProvider.MarkUserAsAuthenticated(input.UserNameOrEmailAddress);
            }

            return(output);
        }
Exemple #5
0
        public async Task <ActionResult <dynamic> > Authenticate(AuthenticationInput authenticationInput)
        {
            var usuario = await _userService.Authenticate(authenticationInput.Username, authenticationInput.Password);

            if (usuario == default)
            {
                return(Unauthorized(new { message = "Usuário inválido" }));
            }

            var token = _tokenService.GenerateToken(usuario);

            return(new { usuario, token });
        }
        public PaellaUser Execute(AuthenticationInput input)
        {
            var user = _userService.FindByName(input.UserName);

            if (user != null && _userService.CheckPassword(user, input.Password))
            {
                return(user);
            }
            else
            {
                throw new Exception();
            }
        }
        public async Task Execute(AuthenticationInput input)
        {
            var user = await _userService.FindByName(input.UserName);

            if (user != null && await _userService.CheckPassword(user, input.Password))
            {
                _outputHandler.Handle(user);
            }
            else
            {
                _outputHandler.Error("Not Authenticated");
            }
        }
Exemple #8
0
        public async Task <AuthenticationOutput> Execute(AuthenticationInput input)
        {
            switch (input.Action)
            {
            case AuthenticationActions.LOGIN:
                return(await this.ExecuteLogIn(input));

            case AuthenticationActions.LOGOUT:
                return(await this.ExecuteLogOut(input));

            default:
                return(new AuthenticationOutput(null, false, "Error: Invalid User Action"));
            }
        }
Exemple #9
0
        private async Task <AuthenticationOutput> ExecuteLogIn(AuthenticationInput input)
        {
            AuthenticationResult result;

            try {
                result = this._domainManager.Authenticate(input.UserName, input.Password);
            } catch (LDAPCommunicationException e) {
                this._logger.Error(e, "Could not connect to domain");
                return(new AuthenticationOutput(null, false, "Authentication Error: Could not connect to domain"));
            }
            switch (result.Status)
            {
            case AuthenticationStatus.Authenticated: {
                var    user       = ((AuthenticatedResult)result).User;
                string permission = ((AuthenticatedResult)result).Permission;
                var    entity     = await this._userRepository.GetEntityAsync(e => e.UserName == user.UserName);

                IUserService userService;
                if (entity != null)
                {
                    userService = await this.CreateUserServiceExisitingUser(entity, input.SaveCredentials, permission, input.Password);
                }
                else
                {
                    userService = await this.CreateUserServiceNewUser(user, input.SaveCredentials, permission, input.Password);
                }
                if (userService != null)
                {
                    return(new AuthenticationOutput(userService, true, "Success:  User logged in"));
                }
                else
                {
                    return(new AuthenticationOutput(null, false, "Error: Login Failed, Please contact admin"));
                }
            }

            case AuthenticationStatus.NoPermissions:
                return(new AuthenticationOutput(null, false, "Error: Invalid Credentials, please check input and try again"));

            case AuthenticationStatus.InvalidCredentials:
                return(new AuthenticationOutput(null, false, "Error: Invalid Credentials, please check input and try again"));

            case AuthenticationStatus.UserNotFound:
                return(new AuthenticationOutput(null, false, "Error: User Not Found, Please contact admin"));

            default:
                return(new AuthenticationOutput(null, false, "Internal Error: Invalid Auth Status, Please contact admin"));
            }
        }
Exemple #10
0
        private AccountDescriptor AuthenticateStateAccount(AuthenticationInput authenticationInput)
        {
            AccountDescriptor accountDescriptor = null;

            byte[] key = DecryptStateKeys(authenticationInput.Account, authenticationInput.Password);
            if (key != null)
            {
                accountDescriptor = new AccountDescriptor {
                    AccountType = authenticationInput.Account.AccountType, SecretSpendKey = key, PublicSpendKey = authenticationInput.Account.PublicSpendKey, AccountInfo = authenticationInput.Account.AccountInfo, AccountId = authenticationInput.Account.AccountId
                };

                _executionContextManager.InitializeStateExecutionServices(authenticationInput.Account.AccountId, accountDescriptor.SecretSpendKey);
            }

            return(accountDescriptor);
        }
 //
 public AuthenticationResult GetAuthentication(AuthenticationInput parameters)
 {
     return(this.tryAction(
                createRequest: () => this.getNewRequest("Authentication_JSON_AppService.axd/Login", Method.POST).AddJsonBody(parameters),
                createResponse: request => this.execute(request),
                createResult: response =>
     {
         bool?success = this.deserializeContent <SimpleResult <bool> >(this.getContent(response))?.d;
         if (success != true)
         {
             throw new VirtuResponceException($"success: {success?.ToString() ?? "null"}");
         }
         return new AuthenticationResult()
         {
             Cookie = response.Cookies.Single(),
         };
     }));
 }
Exemple #12
0
        private async Task <AuthenticationOutput> ExecuteLogOut(AuthenticationInput input)
        {
            if (input.UserService.CurrentSessionId.HasValue)
            {
                var session = await this._sessionRepository.GetEntityAsync(e => e.Id == input.UserService.CurrentSessionId);

                if (session != null)
                {
                    session.Out = DateTime.Now;
                    var updated = await this._sessionRepository.UpdateAsync(session);

                    if (updated != null)
                    {
                        var count = await this._unitOfWork.Save();

                        if (count > 0)
                        {
                            return(new AuthenticationOutput(null, true, "Succesfully Logged Out"));
                        }
                        else
                        {
                            await this._unitOfWork.Undo();

                            this._logger.Error("Error:  Could not log out,Session Save Failed");
                            return(new AuthenticationOutput(null, false, "Error:  Could not log out, Session Save Failed.  Please Contact Admin"));
                        }
                    }
                    else
                    {
                        await this._unitOfWork.Undo();

                        this._logger.Error("Error:  Could not log out, Session Update Failed");
                        return(new AuthenticationOutput(null, false, "Error:  Could not log out, Session Update Failed.  Please Contact Admin"));
                    }
                }
                else
                {
                    this._logger.Error("Error:  Could not log out, Current Session Not Found.");
                    return(new AuthenticationOutput(null, false, "Error:  Could not log out, Current Session Not Found.  Please Contact Admin"));
                }
            }
            return(new AuthenticationOutput(null, false, "Not Implemented Yet"));
        }
Exemple #13
0
        private AccountDescriptor AuthenticateUtxoAccount(AuthenticationInput authenticationInput)
        {
            AccountDescriptor      accountDescriptor = null;
            Tuple <byte[], byte[]> keys = DecryptUtxoKeys(authenticationInput.Account, authenticationInput.Password);

            if (keys != null)
            {
                accountDescriptor = new AccountDescriptor {
                    AccountType = authenticationInput.Account.AccountType, SecretSpendKey = keys.Item1, SecretViewKey = keys.Item2, PublicSpendKey = authenticationInput.Account.PublicSpendKey, PublicViewKey = authenticationInput.Account.PublicViewKey, AccountInfo = authenticationInput.Account.AccountInfo, AccountId = authenticationInput.Account.AccountId
                };

                byte[] pwdBytes = Encoding.ASCII.GetBytes(authenticationInput.Password);

                byte[] pwdHash = ConfidentialAssetsHelper.FastHash256(pwdBytes);

                _executionContextManager.InitializeUtxoExecutionServices(authenticationInput.Account.AccountId, accountDescriptor.SecretSpendKey, accountDescriptor.SecretViewKey, pwdHash);
            }

            return(accountDescriptor);
        }
Exemple #14
0
        public async Task Execute(AuthenticationInput input)
        {
            var client = await _clientRepository.GetUserByCredentials(
                input.Login,
                CryptUtils.EncryptPassword(input.Password)
                );

            if (client == null)
            {
                return;
            }

            _outputHandler.Standard(new AuthenticationOutput(
                                        client.Id,
                                        client.Name,
                                        client.Surname,
                                        client.Email,
                                        client.PhoneNumber,
                                        ""));
        }
Exemple #15
0
        public async Task <LoginResponse> Login(AuthenticationInput authenticationInput)
        {
            // Login with email and password
            var user = await _repository.Get(authenticationInput.EmailAddress);

            if (user == null)
            {
                return(new LoginResponse {
                    Success = false,
                    Message = ErrorMessages.InvalidUserName,
                    User = null,
                });
            }

            //// Verify user active or not
            //if (!user.EmailVerified && !user.SmsVerified)
            //{
            //    throw new AppException(ErrorMessages.UserHasntVerifyAccount);
            //}

            //
            // Check password
            var hashedPassword = authenticationInput.Password;

            if (hashedPassword != user.Password)
            {
                return(new LoginResponse
                {
                    Success = false,
                    Message = ErrorMessages.IncorrectPassword,
                    User = null
                });
            }

            return(new LoginResponse
            {
                Success = true,
                Message = null,
                User = user
            });
        }
Exemple #16
0
        public IActionResult CreateToken([FromBody] CreateTokenRequest request)
        {
            try
            {
                var input = new AuthenticationInput(request.UserName, request.Password);
                var user  = _useCase.Execute(input);
                var token = _tokenService.CreateToken(user);

                var response = new CreateTokenResponse
                {
                    Token   = new JwtSecurityTokenHandler().WriteToken(token),
                    Expires = token.ValidTo
                };

                return(Created("https://paella.com", response));
            }
            catch (System.Exception)
            {
                return(BadRequest());
            }
        }
Exemple #17
0
        public async Task <Guid> AuthenticateUser(string userEmail)
        {
            _logger.LogInformation("AuthenticateUser started", new object[] { userEmail });
            try
            {
                AuthenticationInput authInputs = new AuthenticationInput();
                authInputs.AuthenticationType      = Constants.AuthenticationType.Email;
                authInputs.AuthenticationMode      = Constants.AuthneticationMode.TokenBasedAuthention;
                authInputs.Receiver                = userEmail;
                authInputs.Subject                 = "Adventure Tour Management Token Verification";
                authInputs.EncryptedNetworkKeyPath = await _connectService.GetConnectionAsync();

                var result = await authentication.Authenticate(authInputs);

                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw;
            }
        }
Exemple #18
0
        public async Task <Guid> SendAuthenticationEmail(AuthenticationInput input)
        {
            EmailDTO messageDTO = new EmailDTO();
            var      transactId = Guid.NewGuid();

            if (input.AuthenticationMode == Constants.AuthneticationMode.WebBasedAuthentication)
            {
                messageDTO.MailMessage = await MailTextAsync(input.AuthenticationMode, transactId, input.VerificationLink);
            }
            else
            {
                messageDTO.MailMessage = await MailTextAsync(input.AuthenticationMode, transactId);
            }

            messageDTO.MailSubject             = input.Subject;
            messageDTO.MailTo                  = input.Receiver;
            messageDTO.EncryptedNetworkKeyPath = input.EncryptedNetworkKeyPath;
            SendCommunications comms = new SendCommunications();
            await comms.SendEmail(messageDTO);

            return(transactId);
        }
        public async Task AuthenticateUseCase_ValidInput_ShouldReturnTheUser()
        {
            // Arrange
            var userService = new FakeUserService();
            var presenter   = new FakeAuthenticateOutputHandler();

            var sut = new AuthenticateUseCase(presenter, userService);

            var input = new AuthenticationInput("username", "password");

            // Act
            await sut.Execute(input);

            // Assert
            presenter.ErrorMessage
            .Should()
            .BeNull();

            presenter.ViewModel
            .Should()
            .BeEquivalentTo(userService.User);
        }
Exemple #20
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                ApiLoginRequest parm = new ApiLoginRequest();
                using (StreamReader sr = new StreamReader(context.Request.InputStream))
                {
                    String data = sr.ReadToEnd();
                    parm = new JavaScriptSerializer().Deserialize <ApiLoginRequest>(data);
                }

                ApiLoginResponse ap = new ApiLoginResponse();
                using (DLSMEntities db = new DLSMEntities())
                {
                    using (var dbContextTransaction = db.Database.BeginTransaction())
                    {
                        try
                        {
                            var passold  = parm.passWord;
                            var bytes    = new UTF8Encoding().GetBytes(parm.passWord);
                            var hasBytes = System.Security.Cryptography.MD5.Create().ComputeHash(bytes);
                            var hashpass = Convert.ToBase64String(hasBytes);
                            parm.passWord = hashpass;

                            if (CodeConfig == "1")
                            {
                                _mdmServiceWrapper.AuthenticationUserAsync(new MdmAuthenticationInput())

                                DLSM.MdmServiceTest.MdmUserServiceClient soap = new DLSM.MdmServiceTest.MdmUserServiceClient();

                                try
                                {
                                    MdmServiceTest.authenUser client = new MdmServiceTest.authenUser();

                                    authenUserBean bean = new authenUserBean();
                                    bean.userId    = parm.userName;
                                    bean.password  = passold;
                                    bean.ipAddress = ip;

                                    //bean.userId = "3859900089704";
                                    //bean.password = "******";

                                    AuthenticationInput input = new AuthenticationInput();
                                    input.userId   = uid;
                                    input.password = upw;

                                    AuthenUserInput aut = new AuthenUserInput();
                                    aut.authenticationInput = input;
                                    aut.authenUserBeanInput = bean;

                                    authenUser au = new authenUser();
                                    au.AuthenUserInput = aut;

                                    authenUserResponse resp = soap.authenUser(au);
                                    if (resp.AuthenUserOutput.authenUserResponse.@return.authenUserResult.ToString() == "True")
                                    {
                                        try
                                        {
                                            MdmServiceTest.getUserInfo clientget = new MdmServiceTest.getUserInfo();

                                            getUserInfoBean beanget = new getUserInfoBean();
                                            beanget.authenUserToken = [email protected];

                                            GetUserInfoInput inputget = new GetUserInfoInput();
                                            inputget.getUserInfoBeanInput = beanget;
                                            inputget.authenticationInput  = input;

                                            clientget.GetUserInfoInput = inputget;

                                            getUserInfoResponse respget = soap.getUserInfo(clientget);
                                            if (respget.GetUserInfoOutput.getUserInfoResponse.@return.name.ToString() != "")
                                            {
                                                try
                                                {
                                                    GetUserInfo gui = new GetUserInfo();
                                                    gui.Title          = [email protected];
                                                    gui.Name           = [email protected];
                                                    gui.Surname        = [email protected];
                                                    gui.OffLocCode     = [email protected];
                                                    gui.OffLocDesc     = [email protected];
                                                    gui.OrgFullNameDes = respget.GetUserInfoOutput.getUserInfoResponse.@return.orgFullNameDes;
                                                    gui.PositionDesc   = respget.GetUserInfoOutput.getUserInfoResponse.@return.positionDesc;
                                                    db.GetUserInfoes.Add(gui);
                                                    db.SaveChanges();
                                                }
                                                catch (Exception ex)
                                                {
                                                    dbContextTransaction.Rollback();
                                                    ap.valid_authen = "0";
                                                    ap.message      = "GetUserInfo Error";
                                                }
                                            }
                                            else
                                            {
                                                ap.valid_authen = "0";
                                                ap.message      = "getUserInfo Error";
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            ap.valid_authen = "0";
                                            ap.message      = "authenUser Error";
                                        }
                                    }
                                    else
                                    {
                                        ap.valid_authen = "0";
                                        ap.message      = resp.AuthenUserOutput.authenUserResponse.@return.authenUserResult.ToString();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    dbContextTransaction.Rollback();
                                    ap.valid_authen = "0";
                                    ap.message      = "authenUser Error";
                                }
                            }
                            //else
                            //{
                            //    //ไม่วิ่งผ่าน mdmservice
                            //    parm.passWord = null;
                            //}
                        }
                        finally
                        {
                            try
                            {
                                var result = db.sp_ApiLogin(parm.userName, parm.passWord, parm.workStationName).ToList();
                                if (result.Count() > 0)
                                {
                                    ap.WH_ID             = "" + result[0].WH_ID;
                                    ap.userName          = result[0].userName;
                                    ap.staffId           = "" + result[0].staffId;
                                    ap.Offname           = result[0].OffName;
                                    ap.regisIdNumb       = result[0].regisIdNumb;
                                    ap.regisFirstName    = result[0].regisFirstName;
                                    ap.regisLastName     = result[0].regisLastName;
                                    ap.regisFirstNameENG = result[0].regisFirstNameENG;
                                    ap.regisLastNameENG  = result[0].regisLastNameENG;
                                    ap.titleName         = result[0].titleName;
                                    ap.titleNameENG      = result[0].titleNameENG;
                                    ap.workstationId     = "" + result[0].workstationId;
                                    ap.workstationName   = result[0].workstationName;
                                    ap.officeCode        = result[0].officeCode;
                                    ap.printerName       = result[0].printerName;
                                    ap.printerIP         = result[0].printerIP;
                                    ap.valid_authen      = "1";
                                    ap.authorized        = "" + result[0].authorized;
                                    ap.camaraName        = result[0].camaraName;
                                    ap.cameraSerialNo    = result[0].cameraSerialNo;
                                    ap.androidName       = result[0].androidName;
                                    ap.anroidSerialNo    = result[0].anroidSerialNo;
                                    ap.signImage         = result[0].signImage;
                                    ap.message           = "OK";

                                    dbContextTransaction.Commit();
                                }
                                else
                                {
                                    dbContextTransaction.Rollback();
                                    ap.valid_authen = "0";
                                    ap.message      = "not found";
                                }
                            }
                            catch (Exception ex)
                            {
                                dbContextTransaction.Rollback();
                                ap.valid_authen = "0";
                                ap.message      = ex.InnerException == null ? (ex.Message == null ? "Error: Login catch 2" : ex.Message) : ex.InnerException.Message;
                            }
                        }
                    }
                }
                string json = new JavaScriptSerializer().Serialize(ap);

                context.Response.ContentType = "text/javascript";
                context.Response.Write(json);
            }
            catch (Exception ex)
            {
                ApiLoginResponse ap = new ApiLoginResponse();
                ap.valid_authen = "0";
                ap.message      = ex.InnerException == null ? (ex.Message == null ? "Error: Login catch 1" : ex.Message) : ex.InnerException.Message;

                string json = new JavaScriptSerializer().Serialize(ap);
                context.Response.ContentType = "text/javascript";
                context.Response.Write(json);
            }
        }
        public async Task <IActionResult> Authenticate(AuthenticationInput input)
        {
            await _authenticationUserUseCase.Execute(input);

            return(_authenticationPresenter.ViewModel);
        }
Exemple #22
0
 public async Task <ActionResult <LoginResponse> > Post([FromBody] AuthenticationInput input)
 {
     return(await _userService.Login(input));
 }
 public void Authenticate(AuthenticationInput parameters)
 {
     this.AuthenticationResult = this.GetAuthentication(parameters);
 }