public void createSession() { // Đọc thông tin cấu hình từ Client new ClientInitProcess().docThongTinCauHinhClient(1); // Kiểm tra kết nối, server, service trước khi request Common.Utilities.IsRequestAllow(ApplicationConstant.SystemService.ZAMainAppService.layGiaTri()); LLogging.WriteLog("Process createSession after validation: ", LLogging.LogType.SYS, DateTime.Now.ToLongTimeString()); // Khởi tạo và gán các giá trị cho request SessionRequest request = Common.Utilities.PrepareRequest(new SessionRequest()); request.License = ClientInformation.License; request.Version = ClientInformation.Version; request.Module = DatabaseConstant.Module.QTHT; request.Function = DatabaseConstant.Function.HT_LOGIN; request.Action = DatabaseConstant.Action.DANG_NHAP; // Lấy kết quả trả về SessionResponse response = Client.getSession(request); // Kiểm tra kết quả trả về Common.Utilities.ValidResponse(request, response); // Xử lý dữ liệu trả về string sessionId = response.SessionId; ClientInformation.SessionId = sessionId; }
private void SessionRequestHandler(SessionRequest request) { SessionResponse response = new SessionResponse(request); EventArguments.SessionRequestEventArguments args = new EventArguments.SessionRequestEventArguments(() => { //Confirm Session response.IsConfirmed = true; response.ClientName = request.ClientName; response.PublicKey = PublicKey; if (clientPublicKey.ContainsKey(request.ClientName)) { clientPublicKey[request.ClientName] = request.PublicKey; } else { clientPublicKey.Add(request.ClientName, request.PublicKey); } SendMessage(response); }, () => { //Refuse Session response.IsConfirmed = false; response.ClientName = request.ClientName; SendMessage(response); }); args.Request = request; OnSessionRequest(args); }
private void SessionResponseHandler(SessionResponse response) { foreach (var receiver in Server.Receivers.Where(x => x != this && x.Status == StatusEnum.Validated)) { if (receiver.ClientName == response.ClientName) { response.ClientName = this.ClientName; if (response.IsConfirmed) { //receiver.OtherSideReceiver = this; //this.OtherSideReceiver = receiver; //this.Status = StatusEnum.InSession; //receiver.Status = StatusEnum.InSession; } else { response.HasError = true; response.Exception = new Exception("The session request was refused by " + response.ClientName); } receiver.SendMessage(response); return; } } }
private void SessionRequestHandler(SessionRequest request) { SessionResponse response; if (this.Status != StatusEnum.Validated) //Added after a code project user comment. { response = new SessionResponse(request); response.IsConfirmed = false; response.HasError = true; response.Exception = new Exception("Could not request a new session. The current client is already in session, or is not loged in."); SendMessage(response); return; } foreach (var receiver in Server.Receivers.Where(x => x != this)) { if (receiver.Email == request.Email) { if (receiver.Status == StatusEnum.Validated) { request.Email = this.Email; receiver.SendMessage(request); return; } } } response = new SessionResponse(request); response.IsConfirmed = false; response.HasError = true; response.Exception = new Exception(request.Email + " does not exists or not loged in or in session with another user."); SendMessage(response); }
public async Task <SessionResponse> Obter(SessionRequest sessionRequest) { string url = UrlEndpoint.URL_WS_DEV_PAGSEGURO + UrlEndpoint.PATH_SESSIONS; var values = new Dictionary <string, string> { { "email", sessionRequest.Email }, { "token", sessionRequest.Token } }; var content = new FormUrlEncodedContent(values); try { var response = await client.PostAsync(url, content); var responseString = await response.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument(); doc.LoadXml(responseString); string json = JsonConvert.SerializeXmlNode(doc); JObject j = JObject.Parse(json); SessionResponse session = JsonConvert.DeserializeObject <SessionResponse>(j.GetValue("session").ToString()); return(session); } catch (Exception e) { throw; } }
public async Task <SessionResponse> Login(string email, string password) { SessionResponse resp = new SessionResponse(); UserModel user = new UserModel(); user.Email = email; user.UserPassword = password; var uri = new Uri(AppSettings.WepApiURL + UserSessionApiController + "/UserLogin"); // _userSessionApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); var task = _userSessionApiClient.PostAsync(uri, content); task.Wait(); var response = task.Result; response.EnsureSuccessStatusCode(); string responseAsString = await response.Content.ReadAsAsync <string>(); if (!string.IsNullOrEmpty(responseAsString)) { resp = JsonConvert.DeserializeObject <SessionResponse>(responseAsString); return(resp); } return(null); }
/// <summary> /// logout /// </summary> /// <param name="netSuiteService">netsuite webservice instance</param> /// <param name="sessionResponse">session service response</param> public void logout(NetSuiteService netSuiteService, SessionResponse sessionResponse) { if (sessionResponse != null && sessionResponse.status.isSuccess) { netSuiteService.logout(); } }
private void SessionResponseHandler(SessionResponse response) { foreach (var receiver in Server.Receivers.Where(x => x != this)) { if (receiver.Email == response.Email) { response.Email = this.Email; if (response.IsConfirmed) { receiver.OtherSideReceiver = this; this.OtherSideReceiver = receiver; this.Status = StatusEnum.InSession; receiver.Status = StatusEnum.InSession; } else { response.HasError = true; response.Exception = new Exception("The session request was refused by " + response.Email); } receiver.SendMessage(response); return; } } }
private void OnCreateSession(SessionResponse response, Dictionary <string, object> customData) { Log.Debug("TestAssistantV2.OnCreateSession()", "Session: {0}", response.SessionId); _sessionId = response.SessionId; Test(response != null); _createSessionTested = true; }
public ActionResult RequestSession(QlikSessionViewModel model) { Authentication auth = new Authentication(model.Server, model.VirtualProxy, model.Port, model.Certificate, model.UserDirectory, model.User, model.SessionId); try { SessionResponse response = auth.GetSession(); DateTime now = DateTime.Now; HttpCookie cookie = new HttpCookie(string.Format("X-Qlik-Session{0}", string.IsNullOrEmpty(model.VirtualProxy) ? string.Empty : "-" + model.VirtualProxy)); cookie.Value = response.SessionId; cookie.Expires = DateTime.MinValue; cookie.HttpOnly = true; cookie.Domain = model.Server; // only works if qliksense url domain is same with this web app Request.Cookies.Add(cookie); Response.Cookies.Add(cookie); return(Json(string.Format("{0}{1}/qmc", model.Server, string.IsNullOrEmpty(model.VirtualProxy) ? string.Empty : "/" + model.VirtualProxy))); } catch (Exception ex) { return(Json(ex.Message)); } }
public SessionResponse Session(SessionRequest request) { var sessionResponse = new SessionResponse { Errors = new List <string>(), Success = true }; var user = _userRepository.GetByUsername(request.Username); if (user == null) { sessionResponse.Success = false; sessionResponse.Errors.Add("User not in DB"); return(sessionResponse); } if (request.Password != user.Password) { sessionResponse.Success = false; sessionResponse.Errors.Add("Incorrect Password"); } if (!sessionResponse.Success) { return(sessionResponse); } var session = _sessionRepository.GenerateSession(request.Username, request.Password); sessionResponse.Success = true; sessionResponse.Key = session.Key; sessionResponse.UserId = session.UserId; return(sessionResponse); }
private void ProcessLoginError(SessionResponse ssnResponse, ServiceInvocationEventArgs invokerEventArgs) { Exception thrownException = invokerEventArgs.Exception; StatusDetail errorStatus = ssnResponse != null ? StatusResponse.GetStatusError(ssnResponse.status) : null; if (errorStatus != null) { thrownException = new NsException(errorStatus.message, thrownException); } else if (invokerEventArgs.InvokationAttempt == Configuration.RetryCount) { thrownException = new RetryCountExhaustedException("Login Failed.", thrownException); } else // If the _nsSvc.login(..) call repeatedly threw exceptions... { thrownException = new NsException("Login Failed.\nExceptions have been logged.", thrownException); } invokerEventArgs.Exception = thrownException; if (thrownException != null) { OnServiceInvocationError(invokerEventArgs); throw thrownException; } }
public string CreateInvalidSession([FromBody] string userId) { SessionResponse response = new SessionResponse(); string json = ""; Session session = new Session(userId); session.Host = Request.Headers["User-Agent"].ToString(); //session.Principal = HttpContext.Request.Scheme; //session.UserId = userId; //session.Type = Request.Headers["User-Agent"].ToString(); try { bool sessionCreated = _sessionRepositorio.Create(session); if (sessionCreated) { response.Session = session; } } catch (Exception ex) { _logger.Error(ex.GetBaseException(), "SessionController - CreateInvalidSession -> {userId}", userId); response.Message = ex.GetBaseException().Message;//*"Erro ao criar sessão";*/ } json = JsonConvert.SerializeObject(response); return(json); }
public string KeepAliveSession([FromBody] SessionViewModel sessionVM) { SessionResponse response = new SessionResponse(); string json = ""; try { Session sessionUpdated = _sessionRepositorio.KeepAliveSession(sessionVM.Session); //if (sessionUpdated != null) // sessionVM.Session = sessionUpdated; response.Session = sessionUpdated; response.Message = "Sessão renovada"; } catch (Exception ex) { response.Session = null; response.Message = "Erro ao renovar sessão"; var jsonSession = new JsonResult(""); if (sessionVM != null) { jsonSession = Json(sessionVM); } _logger.Error(ex.GetBaseException(), "SessionController - KeepAliveSession -> {jsonSession}", jsonSession); throw; } json = JsonConvert.SerializeObject(response); return(json); }
public string ActivateSession([FromBody] SessionViewModel session) { SessionResponse response = new SessionResponse(); string json = ""; try { Session sessionUpdated = _sessionRepositorio.ActivateSession(session.Session, session.accessToken); if (sessionUpdated != null) { session.Session = sessionUpdated; } response.Session = sessionUpdated; response.Message = "Sessão ativada"; } catch (Exception ex) { response.Session = null; response.Message = "Erro ao ativar sessão"; var jsonSession = new JsonResult(""); if (session != null) { jsonSession = Json(session); } _logger.Error(ex.GetBaseException(), "SessionController - ActivateSession -> {jsonSession}", jsonSession); throw; } json = JsonConvert.SerializeObject(response); return(json); }
public async Task <IActionResult> Obter([FromBody] SessionRequest sessionRequest) { try { SessionResponse retorno = await sessionService.Obter(sessionRequest); Response response = new Response { Status = "success", Message = "ID da sessão obtido com sucesso", Error = false, Data = retorno }; return(new ObjectResult(response)); } catch (Exception e) { Response response = new Response { Status = "error", Message = e.Message, Error = true, Data = null }; //return StatusCode(500, response); return(BadRequest(response)); } }
public async Task <SessionResponse> RenewSession() { User currentUser = await _users.Where(u => u.Id.ToString() == User.Identity.Name).FirstOrDefaultAsync(); SessionResponse renewalResponse = GenerateLoginResponse(currentUser); return(renewalResponse); }
private SessionResponse constructResponse(Sessions sessions) { SessionResponse response = new SessionResponse(); response.SessionId = sessions.SessionId; response.IsLogin = sessions.IsLogin; return(response); }
private async Task <Dictionary <string, string> > CreateAuthenticationAndSessionResponse(TParty party, List <Claim> claims, OidcDownSequenceData sequenceData) { try { var authenticationResponse = new AuthenticationResponse { State = sequenceData.State, ExpiresIn = party.Client.AccessTokenLifetime, }; var sessionResponse = new SessionResponse { SessionState = claims.FindFirstValue(c => c.Type == JwtClaimTypes.SessionId).GetSessionStateValue(party.Client.ClientId, sequenceData.RedirectUri) }; logger.ScopeTrace(() => $"Response type '{sequenceData.ResponseType}'."); var responseTypes = sequenceData.ResponseType.ToSpaceList(); if (responseTypes.Where(rt => rt.Contains(IdentityConstants.ResponseTypes.Code)).Any()) { authenticationResponse.Code = await oauthAuthCodeGrantDownLogic.CreateAuthCodeGrantAsync(party.Client as TClient, claims, sequenceData.RedirectUri, sequenceData.Scope, sequenceData.Nonce, sequenceData.CodeChallenge, sequenceData.CodeChallengeMethod); } string algorithm = IdentityConstants.Algorithms.Asymmetric.RS256; if (responseTypes.Where(rt => rt.Contains(IdentityConstants.ResponseTypes.Token)).Any()) { authenticationResponse.TokenType = IdentityConstants.TokenTypes.Bearer; authenticationResponse.AccessToken = await jwtDownLogic.CreateAccessTokenAsync(party.Client as TClient, claims, sequenceData.Scope?.ToSpaceList(), algorithm); } if (responseTypes.Where(rt => rt.Contains(IdentityConstants.ResponseTypes.IdToken)).Any()) { authenticationResponse.IdToken = await jwtDownLogic.CreateIdTokenAsync(party.Client as TClient, claims, sequenceData.Scope?.ToSpaceList(), sequenceData.Nonce, responseTypes, authenticationResponse.Code, authenticationResponse.AccessToken, algorithm); } logger.ScopeTrace(() => $"Authentication response '{authenticationResponse.ToJsonIndented()}'.", traceType: TraceTypes.Message); var nameValueCollection = authenticationResponse.ToDictionary(); if (!sessionResponse.SessionState.IsNullOrWhiteSpace()) { logger.ScopeTrace(() => $"Session response '{sessionResponse.ToJsonIndented()}'.", traceType: TraceTypes.Message); nameValueCollection = nameValueCollection.AddToDictionary(sessionResponse); } logger.ScopeTrace(() => $"Redirect Uri '{sequenceData.RedirectUri}'."); logger.ScopeTrace(() => "Down, OIDC Authentication response.", triggerEvent: true); return(nameValueCollection); } catch (KeyException kex) { var errorAuthenticationResponse = new AuthenticationResponse { State = sequenceData.State, Error = IdentityConstants.ResponseErrors.ServerError, ErrorDescription = kex.Message }; return(errorAuthenticationResponse.ToDictionary()); } }
/// <summary> /// Is Valid OIDC Session Response. /// </summary> public static void Validate(this SessionResponse response) { if (response == null) { new ArgumentNullException(nameof(response)); } response.SessionState.ValidateMaxLength(IdentityConstants.MessageLength.SessionStatedMax, nameof(response.SessionState), response.GetTypeName()); }
private void JoinTableHandler(JoinTableRequest request) { SessionResponse response = new SessionResponse(request); response.Email = request.Email; response.IsConfirmed = true; SendMessage(response); OnAutoAcceptInvite(this); }
private SessionResponse constructResponse(Sessions sessions, Users user) { SessionResponse response = constructResponse(sessions); response.FirstName = user.FirstName; response.LastName = user.LastName; response.Email = user.Email; return(response); }
private static SessionResponse SetSessionValue(SessionApiParams apiParams, string sessionKey) { var sessionResponse = new SessionResponse(); Console.WriteLine($@"Creating new session key: {sessionKey}"); SessionData.AddOrUpdate(sessionKey, apiParams.Value, (oldItem, newItem) => apiParams.Value); sessionResponse.Result = "200"; return(sessionResponse); }
/// <summary> /// call the login service /// </summary> /// <param name="account">netsuite account</param> private void executeLogin(string account) { string _account = string.IsNullOrEmpty(account) ? ConfigurationManager.AppSettings["account"].Split(',')[0] : account; if (_account.Contains('|')) { _account = _account.Split('|')[0]; } Login login = new Login(_account); bool isSandbox = false; if (!string.IsNullOrEmpty(account)) { DialogResult dlrSandbox = MessageBox.Show("Connect to sandbox account?", "Question", MessageBoxButtons.YesNo); isSandbox = (dlrSandbox == DialogResult.Yes); } netSuiteService = new DataCenterAwareNetSuiteService(login.Account, isSandbox); ///password not mandatory in configuration if (string.IsNullOrEmpty(login.Password)) { FrmDialog passwordDialog = new FrmDialog(); passwordDialog.Text = login.Email; if (passwordDialog.ShowDialog(this) == DialogResult.OK) { login.Password = passwordDialog.txtPassword.Text; } else { login.Password = string.Empty; } passwordDialog.Dispose(); } sessionResponse = login.login(netSuiteService); if (sessionResponse != null && sessionResponse.status.isSuccess) { lblToolStripStatus.Text = ((isSandbox) ? "SANDBOX " : "") + "Account: " + login.Account + " - Email: " + login.Email; appendLog("Login done [" + lblToolStripStatus.Text + "]"); netSuiteService.addListCompleted += netSuiteService_addListCompleted; loadTasks(); } else { tmrTimeout.Stop(); lblToolStripStatus.Text = "Login failed!"; appendLog(lblToolStripStatus.Text, NOTIFICATION_ERROR); } }
private void SessionResponseHandler(SessionResponse response) { foreach (var receiver in Server.Receivers.Where(x => x != this)) { if (receiver.Email == response.Email) { response.Email = this.Email; if (response.IsConfirmed) { receiver.OtherSideReceiver = this; this.OtherSideReceiver = receiver; this.Status = StatusEnum.InSession; receiver.Status = StatusEnum.InSession; if (this.InGameProperties.Room == -1 && receiver.InGameProperties.Room == -1) { this.InGameProperties.Room = receiver.InGameProperties.Room = GetRandomTable(Server.Receivers); } else if (this.InGameProperties.Room == -1) { this.InGameProperties.Room = receiver.InGameProperties.Room; } else { receiver.InGameProperties.Room = this.InGameProperties.Room; } UpdateTablesInProcessRequest processRequest = new UpdateTablesInProcessRequest(GetListTableInProcess(Server.Receivers)); foreach (Receiver re in Server.Receivers) { if (re.Status == StatusEnum.Validated) { re.SendMessage(processRequest); } } } else { response.HasError = true; response.Exception = new Exception("The session request was refused by " + response.Email); } receiver.SendMessage(response); if (!response.HasError) { this.SendMessage(new AcceptPlayRequest()); receiver.SendMessage(new AcceptPlayRequest()); } return; } } }
private void LoadSelectionScreen(SessionResponse sessionInfo) { clients.TryGetValue(sessionInfo.SessionId, out var worldClient); worldClient.CryptoManager.GenerateAES(sessionInfo.KeyPair.Key, sessionInfo.KeyPair.IV); using var sendPacket = new Packet(PacketType.GAME_HANDSHAKE); sendPacket.WriteByte(0); // 0 means there was no error. sendPacket.WriteByte(2); // no idea what is it, it just works. sendPacket.Write(CryptoManager.XorKey); worldClient.SendPacket(sendPacket); SelectionScreenManagers[worldClient.Id].SendSelectionScrenInformation(worldClient.UserID); }
public async Task <string> GetAuthToken() { using (System.Net.Http.HttpClient httpClient = ClientBuilder .Create(_baseUri) .WithHandler(innerHandler => new LoggingHandler(_loggerFactory, innerHandler)) .Build()) { SessionResponse response = await httpClient .MakeSession(_username, _password, _serialNumber) .ConfigureAwait(false); return(response.SecurityToken); } }
public void GivenIAmInTheTutorialSessionSectionOne() { //Arrange mockMapper = GetDefaultMapperInstance(); mockSessionService = GetDefaultSessionServiceInstance(); SessionResponse var1 = new SessionResponse(sessionTemp); mockMapper.Setup(r => r.Map <SaveSessionResource, Session>(saveSessionTemp)).Returns(sessionTemp); mockSessionService.Setup(r => r.SaveAsync(tutorTemp.Id, sessionTemp)).ReturnsAsync(var1);//SAVE mockMapper.Setup(r => r.Map <Session, SessionResource>(var1.Resource)).Returns(new SessionResource { Id = sessionTemp.Id, Title = sessionTemp.Title, Price = sessionTemp.Price }); }
private void CreateAgentSession(SessionResponse sessionResponse, DriverOptions options) { // A generic driver session request returns a partial response, so we'll need to fill in the server address and session ID ourselves. Uri serverAddress = sessionResponse.ServerAddress.Equals(string.Empty) ? null : new Uri(sessionResponse.ServerAddress); if (sessionResponse.SessionId == null) { sessionResponse.SessionId = Guid.NewGuid().ToString(); } this.AgentSession = new AgentSession(serverAddress, sessionResponse.SessionId, sessionResponse.Dialect, options); Logger.Info($"Session [{sessionResponse.SessionId}] initialized"); }
private void OnCreateSessionResponse(RESTConnector.Request req, RESTConnector.Response resp) { SessionResponse result = new SessionResponse(); fsData data = null; Dictionary <string, object> customData = ((CreateSessionRequestObj)req).CustomData; customData.Add(Constants.String.RESPONSE_HEADERS, resp.Headers); if (resp.Success) { try { fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } object obj = result; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } customData.Add("json", data); } catch (Exception e) { Log.Error("Assistant.OnCreateSessionResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } } if (resp.Success) { if (((CreateSessionRequestObj)req).SuccessCallback != null) { ((CreateSessionRequestObj)req).SuccessCallback(result, customData); } } else { if (((CreateSessionRequestObj)req).FailCallback != null) { ((CreateSessionRequestObj)req).FailCallback(resp.Error, customData); } } }
public object Any(Session request) { var untyped = SessionBag["untyped"] as CustomSession ?? new CustomSession(); var typed = SessionBag.Get<CustomSession>("typed") ?? new CustomSession(); untyped.Counter++; typed.Counter++; SessionBag["untyped"] = untyped; SessionBag.Set("typed", typed); var response = new SessionResponse { Typed = typed, UnTyped = untyped, }; return response; }
public void SetCompleted(SessionResponse response) { _response = response; _stopWatch.Stop(); }
public async Task<int> LoginWithLoginValueAsync(string login, string password, Platform platform, string uid) { var sessionResponse = await this.client.AuthenticationClient.CreateSessionWithLoginAsync (login, password); if (await HandleResponse(sessionResponse, HttpStatusCode.Created)){ UserId = sessionResponse.Result.Session.UserId; SessionResponse = sessionResponse.Result; return sessionResponse.Result.Session.UserId; } else if (sessionResponse.StatusCode == HttpStatusCode.NotFound) { return -1; } else if ((int)sessionResponse.StatusCode == 422) { // Add logout return -1; } return 0; }
/// <summary> /// call the login service /// </summary> /// <param name="account">netsuite account</param> private void executeLogin(string account) { string _account = string.IsNullOrEmpty(account) ? ConfigurationManager.AppSettings["account"].Split(',')[0] : account; if (_account.Contains('|')) _account = _account.Split('|')[0]; Login login = new Login(_account); bool isSandbox = false; if(!string.IsNullOrEmpty(account)) { DialogResult dlrSandbox = MessageBox.Show("Connect to sandbox account?", "Question", MessageBoxButtons.YesNo); isSandbox = (dlrSandbox == DialogResult.Yes); } netSuiteService = new DataCenterAwareNetSuiteService(login.Account, isSandbox); ///password not mandatory in configuration if (string.IsNullOrEmpty(login.Password)) { FrmDialog passwordDialog = new FrmDialog(); passwordDialog.Text = login.Email; if (passwordDialog.ShowDialog(this) == DialogResult.OK) { login.Password = passwordDialog.txtPassword.Text; } else { login.Password = string.Empty; } passwordDialog.Dispose(); } sessionResponse = login.login(netSuiteService); if (sessionResponse != null && sessionResponse.status.isSuccess) { lblToolStripStatus.Text = ((isSandbox) ? "SANDBOX " : "") + "Account: " + login.Account + " - Email: " + login.Email; appendLog("Login done [" + lblToolStripStatus.Text + "]"); netSuiteService.addListCompleted += netSuiteService_addListCompleted; loadTasks(); } else { tmrTimeout.Stop(); lblToolStripStatus.Text = "Login failed!"; appendLog(lblToolStripStatus.Text, NOTIFICATION_ERROR); } }
public SessionResponsePacket(string username, SessionResponse response) { Username = username; Response = response; }
/// <summary> /// logout /// </summary> /// <param name="netSuiteService">netsuite webservice instance</param> /// <param name="sessionResponse">session service response</param> public void logout(NetSuiteService netSuiteService, SessionResponse sessionResponse) { if (sessionResponse != null && sessionResponse.status.isSuccess) netSuiteService.logout(); }