Example #1
0
 public override void Reset() {
     IsReady = false;
     _authToken = null;
     _authExpiration = default(DateTime);
     ValuesStorage.Remove(KeyAuthToken);
     ValuesStorage.Remove(KeyAuthExpiration);
 }
Example #2
0
    public void OnAuthFinished(AuthResponse authResponse)
    {
        this.authCoroutine = null;

        if (authResponse == null || authResponse.code != 0)
        {
            Debug.Log("Ошибка логина");
        }
        else
        {
            Toolbox.Instance.sessionId = authResponse.sessionId;
            Debug.Log("Логин успешен");
        }
    }
        /// <summary>
        /// Authentication Step 2.
        /// 10.3.2.2. Получение аутентификационного токена
        /// </summary>
        private AuthToken GetToken(OmsApiClient omsClient, AuthResponse authResponse, string signedData)
        {
            var url = omsClient.AuthUrl + "auth/cert/{OmsConnectionID}";

            return(omsClient.Post <AuthToken>(url, new
            {
                uuid = authResponse.UUID,
                data = signedData,
            },
                                              new[]
            {
                new Parameter("OmsConnectionID", OmsConnectionID, ParameterType.UrlSegment),
            }));
        }
        public void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
        {
            var webResult = args.WebAuthenticationResult;

            if (webResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                Uri responseUri = new Uri(webResult.ResponseData.ToString());
                if (!responseUri.Query.Contains("error="))
                {
                    AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1));
                    PlatformAdapter.Resolve <IAuthHelper>().EndLoginFlow(SalesforceConfig.LoginOptions, authResponse);
                }
            }
        }
Example #5
0
        private void onEventHandlerLoginSuccess(EventWatcher watcher, BaseEventArgs evtArgs)
        {
            // InputVCodeControl.DismissInputVcodeBox();
            // PageManager.getInstance().PopAllPages(true);
            AuthResponse mObject = null;

            if ((evtArgs.mObject != null) && (evtArgs.mObject is AuthResponse))
            {
                mObject = (AuthResponse)evtArgs.mObject;
            }
            //GConfigMgr.settings.strLastLoginName = this.textBoxAccount.get_Text();
            //GConfigMgr.saveSetting();
            Log.i("onEventHandlerLoginSuccess", "login success");
        }
        public Promise <AuthResponse> Auth(Auth model)
        {
            string url = string.Format("http://my.api.com/api/auth");

            return(FakeHttpClient.Post <Auth, AuthResponse>(url, model, fakeResponse: () => new AuthResponse {
                UserId = 150, DisplayName = "Chiko", Token = "Chiko::150"
            })
                   .Then(delegate(AuthResponse x)
            {
                AuthResponse auth = x;
                return auth;       // By doing this you will be returning - Promise<User>
            }));                   //NOTE: USE THE ONE BELOW INSTEAD! This is just for showing purposes only.
            //.Then(x => x.Content);
        }
Example #7
0
        public IActionResult Login([FromBody] LoginRequest model)
        {
            AuthResponse response = new AuthResponse();
            string       tokenId  = string.Empty;

            if (userService.Login(model, out tokenId) != 0)
            {
                response.Token           = tokenId;
                response.IsAuthenticated = true;
                return(Ok(response));
            }

            return(Unauthorized());
        }
Example #8
0
        private ActionResult CreateSessionFor(AuthResponse response)
        {
            if (response.Status != AuthStatus.Success)
            {
                throw new Exception("Unexpected error when validating MFA");
            }
            var username = response.Embedded.User.Profile.Login;
            var createPersistentCookie = true;

            FormsAuthentication.SetAuthCookie(username, createPersistentCookie);
            // Store the most recent response in the session
            Session[oktaResponseKey] = response;
            return(RedirectToAction("CompleteMfa", "Account"));
        }
Example #9
0
        /// <summary>
        /// Callback that is invoked once the authentication request is processed or expires.
        /// </summary>
        /// <param name="request"></param>
        private static void OnVerificationResponse(AuthResponse request, NtkService boundApi)
        {
            /**
             * 3. ApprovalGranted is a convenience property, but it does not perform
             * signature validation.
             *
             * In a real-world scenario, you could now verify the response payload
             * to be sure of the received data.
             */

            Console.WriteLine("SUCCESS: verification response: {0}", request.ApprovalGranted);
            Console.WriteLine("Storing keytoken {0} for user ID {1}", request.KeyToken, request.UserId);
            userKeyTokens.Add(request.KeyToken, request.UserId);
        }
Example #10
0
        private async static Task <AuthResponse> GetAuthResponse(string username, string password)
        {
            var requestModel = new AuthRequest
            {
                ApplicationId = Constants.BrightApplicationIdString,
                Username      = username,
                Password      = password
            };

            var response = await _httpClient.PostAsJsonAsync($"https://api.glowmarkt.com/api/v0-1/auth", requestModel);

            response.EnsureSuccessStatusCode();
            return(AuthResponse.FromJson(await response.Content.ReadAsStringAsync()));
        }
Example #11
0
        public static async Task <Task> SaveUserData(AuthResponse authResponse, string userInfo, string password, string email)
        {
            await SecureStorage.SetAsync(StorageConstants.AccessToken, authResponse.AccessToken.JwtToken);

            await SecureStorage.SetAsync(StorageConstants.AccessTokenExpireTime, authResponse.AccessToken.Expire.ToString());

            await SecureStorage.SetAsync(StorageConstants.UserId, userInfo);

            await SecureStorage.SetAsync(StorageConstants.UserPassword, password);

            await SaveUserEmail(email);

            return(Task.CompletedTask);
        }
Example #12
0
    /// <summary>
    /// Performs Username/Password authentication.
    /// </summary>
    /// <exception cref="Socks5Exception">The server returned invalid or
    /// unexpected data, or authentication failed.</exception>
    private void Authenticate()
    {
        byte[] bytes = new AuthRequest(Username, Password).Serialize();
        stream.Write(bytes, 0, bytes.Length);
        // Read the server's response.
        bytes = new byte[2];
        stream.Read(bytes, 0, 2);
        AuthResponse response = AuthResponse.Deserialize(bytes);

        if (!response.Success)
        {
            throw new Socks5Exception("Authentication failed.");
        }
    }
Example #13
0
        private async void Landing_Loaded(object sender, RoutedEventArgs e)
        {
            _authResponse = await DoLogin();

            if (!_authResponse.IsAuthenticated)
            {
                MessageBox.Show("Unable to authenticate");
            }
            // _authResponse.UserInfo.Picture;
            this.Hide();
            var main = new Main();

            main.Show();
        }
Example #14
0
        public IActionResult Login([FromBody] LoginRequest model)
        {
            AuthResponse authResponse = _authService.Login(model, IpAddress());

            if (authResponse == null)
            {
                return(BadRequest("Invalid Email or Password"));
            }

            SetTokenCookie(authResponse.RefreshToken);
            authResponse.RefreshToken = null;

            return(Ok(authResponse));
        }
Example #15
0
        public AuthResponse Auth(UserDTO user)
        {
            List <User> users = new List <User>();

            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل", Role = "admin"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل", Brand = "اپل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });
            users.Add(new User {
                Username = "******", Password = "******", Category = "گوشی موبایل"
            });

            if (!string.IsNullOrEmpty(user.Username) && !string.IsNullOrEmpty(user.Password))
            {
                User _user = users.Where(x =>
                                         x.Username.ToLower() == user.Username.ToLower().Trim() &&
                                         x.Password.ToLower() == user.Password.ToLower().Trim()
                                         ).FirstOrDefault();
                if (user != null)
                {
                    AuthResponse res = new AuthResponse {
                        Success = true, User = _user
                    };
                    return(res);
                }
            }
            return(new AuthResponse {
                Success = false, User = null
            });
        }
        public async Task <ActionResult <AuthResponse> > Login(AuthRequest loginRequest)
        {
            var user = await _userManager.FindByEmailAsync(loginRequest.UserName);

            if (user == null)
            {
                return(NotFound("El usuario no existe"));
            }

            var checkPwd = await _userManager.CheckPasswordAsync(user, loginRequest.Password);

            if (!checkPwd)
            {
                return(Unauthorized("Contraseña inválida"));
            }

            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
            };

            var roles = await _userManager.GetRolesAsync(user);

            foreach (string role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            DateTime expiration = DateTime.Now.AddMinutes(60);

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                _configuration.GetSection("Tokens:Issuer").Get <string>(),
                loginRequest.AudienceKey,
                claims,
                null,
                expiration,
                creds);
            AuthResponse response = new AuthResponse()
            {
                Token      = new JwtSecurityTokenHandler().WriteToken(token),
                Expiration = expiration
            };

            return(response);
        }
Example #17
0
        public async Task <ActionResult <AuthResponse> > Login(LoginRequest request)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var signInResult = await signInManager.PasswordSignInAsync(request.Email, request.Password, isPersistent : false, lockoutOnFailure : false);

            if (!signInResult.Succeeded)
            {
                logger.LogWarning("Login failed for user {UserName}", request.Email);
                return(BadRequest());
            }

            var user = await userManager.FindByNameAsync(request.Email);

            var userClaims = await userManager.GetClaimsAsync(user);

            var userRoles = await userManager.GetRolesAsync(user);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sid, user.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
                new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName ?? string.Empty)
            }.Union(userRoles.Select(role => new Claim(ClaimTypes.Role, role)))
            .Union(userClaims);

            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecurityKey));
            var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

            var jwtSecurityToken = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(jwtSettings.ExpirationMinutes),
                signingCredentials: signingCredentials
                );

            var result = new AuthResponse(new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken), jwtSecurityToken.ValidTo);

            return(Ok(result));
        }
Example #18
0
        public override async Task SignIn(CancellationToken cancellation)
        {
            await Prepare(cancellation);

            if (IsReady && DateTime.Now < _authExpiration)
            {
                return;
            }

            var data         = InternalUtils.GetGoogleDriveCredentials();
            var clientId     = data.Item1.Substring(2);
            var clientSecret = data.Item2.Substring(2);

            var code = await GetAutenficationCode(clientId, cancellation);

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            if (code == null)
            {
                throw new UserCancelledException();
            }

            var response = await Request.Post <AuthResponse>(@"https://www.googleapis.com/oauth2/v4/token", new NameValueCollection {
                { @"code", code },
                { @"client_id", clientId },
                { @"client_secret", clientSecret },
                { @"redirect_uri", RedirectUrl },
                { @"grant_type", @"authorization_code" }
            }.GetQuery(), null, cancellation);

            if (cancellation.IsCancellationRequested)
            {
                return;
            }

            if (response == null)
            {
                throw new Exception(ToolsStrings.Uploader_CannotFinishAuthorization);
            }

            _authToken      = response;
            _authExpiration = DateTime.Now + TimeSpan.FromSeconds(response.ExpiresIn) - TimeSpan.FromSeconds(20);
            ValuesStorage.SetEncrypted(KeyAuthToken, JsonConvert.SerializeObject(_authToken));
            ValuesStorage.Set(KeyAuthExpiration, _authExpiration);
            IsReady = true;
        }
Example #19
0
        private async Task <bool> GetBearerTokenAsync()
        {
            var client = new HttpClient();

            client.BaseAddress = new Uri(_uri);

            var byteArray = new UTF8Encoding().GetBytes(_key + ":" + _secret);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            var formData = new List <KeyValuePair <string, string> >();

            formData.Add(new KeyValuePair <string, string>("grant_type", "client_credentials"));
            var request = new HttpRequestMessage(HttpMethod.Post, "/iii/sierra-api/v2/token");

            request.Content = new FormUrlEncodedContent(formData);

            try
            {
                //throw new WebException("token error bruh' Uri.", WebExceptionStatus.NameResolutionFailure);
                var response = await client.SendAsync(request);

                var payload = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    ApiError.Log(response);
                    return(false);
                }

                var          serializer     = new JavaScriptSerializer();
                AuthResponse SierraResponse = serializer.Deserialize <AuthResponse>(payload);

                _token_expires = DateTime.UtcNow.AddSeconds(SierraResponse.expires_in);
                _token         = SierraResponse.access_token;
            }
            catch (Exception ex)
            {
                _token = null;
                ApiError.Log(ex);
            }
            finally
            {
                client.Dispose();
            }

            // no token no init
            return(_token != null);
        }
        public async Task Connect(string host, string auth, bool isSecure, string group = null, string code = null)
        {
            Hostname         = host;
            Authentification = auth;
            State            = "Verbinde...";
            IsActive         = true;

            try
            {
                socket = new ClientWebSocket();
                socket.Options.AddSubProtocol("chat");
                await socket.ConnectAsync(new Uri((isSecure ? "wss://":"ws://") + host), source.Token);

                int         seq = SequenceNumber++;
                AuthRequest msg = new AuthRequest(auth, seq, group, code);
                ReceiveTokenSource = new CancellationTokenSource();
                ProcessReceivingMessages();
                await socket.SendAsync(msg.GetBytes(), WebSocketMessageType.Binary, true, source.Token);

                IRemoteMessage resp = await WaitForResponse(seq);

                if (resp is StateResponse)
                {
                    StateResponse response = (StateResponse)resp;
                    switch (response.Code)
                    {
                    case StateCodes.WrongKey:
                        throw new Exception("Authentifizierung am Server fehlgeschlagen");

                    case StateCodes.GroupNotFound:
                        throw new Exception("Angegebene Gruppe ist nicht auf dem Server vorhanden");

                    case StateCodes.WrongGroupKey:
                        throw new Exception("Authentifizierung in der Gruppe fehlgeschlagen");
                    }
                }
                else if (resp is AuthResponse)
                {
                    AuthResponse response = (AuthResponse)resp;
                    Group = response.Group;
                }
                State = "Verbunden (" + Group + ")";
            } catch (Exception ex)
            {
                State       = ex.Message;
                IsActive    = false;
                IsConnected = false;
            }
        }
        public string Put(string id, [FromBody] string value)
        {
            AuthResponse auth     = new AuthResponse();
            CarPark      location = MongoDBHelper.SearchByObjectID <CarPark>(id);

            if (location != null)
            {
                location.aspaces = location.aspaces + 1;
                MongoDBHelper.InsertEntity <CarPark>(location);
                auth.Status = 0;
                return(JsonConvert.SerializeObject(auth));
            }
            auth.Status = 1;
            return(JsonConvert.SerializeObject(auth));
        }
Example #22
0
    private void FailAuthentication(NetworkConnection conn, AuthResponse response)
    {
        Debug.Log("[Server] Authentication failed. Sending result to client.");


        conn.Send(response, 0);

        // must set NetworkConnection isAuthenticated = false
        conn.isAuthenticated = false;

        // disconnect the client after 1 second so that response message gets delivered
        StartCoroutine(DelayedDisconnect(conn, 1));

        Debug.Log("[Server] Rejected connection and responded to client: " + ((PlayerData)conn.authenticationData).steamName + " - " + ((PlayerData)conn.authenticationData).id);
    }
        public async Task Test_auth_clientsignature_success()
        {
            if (this.deribitcredentials.client_id == null || this.deribitcredentials.client_secret == null)
            {
                throw new Exception("This test requires client credentials");
            }
            AuthResponse authresponse = await deribit.Authentication.Auth(new AuthRequest()
            {
                grant_type    = GrantType.client_credentials,
                client_id     = this.deribitcredentials.client_id,
                client_secret = this.deribitcredentials.client_secret,
            }.Sign());

            Assert.That(authresponse.refresh_token, Is.Not.Null);
        }
        private AuthResponse BuildResponse(IdentityUser user, string accessToken)
        {
            var response = new AuthResponse
            {
                AccessToken = accessToken,
                LoggedUser  = new UserViewModel
                {
                    UserId   = user.Id,
                    Username = user.UserName,
                    Email    = user.Email
                }
            };

            return(response);
        }
Example #25
0
        public void AuthenticateConsumerNullOAuthConsumerKey()
        {
            //Arrange
            AuthenticateSettings obAuthSettings = new AuthenticateSettings();

            obAuthSettings.OAuthConsumerKey = null;

            //Act
            IAuthenticate obAuthenticate = new Authenticate();
            AuthResponse  obAuthRespose  = obAuthenticate.AuthenticateConsumer(obAuthSettings);

            //Assert
            // When Consumer key is null, the expected output is null Authentication Response.
            Assert.AreEqual(obAuthRespose, null);
        }
Example #26
0
        public async Task <bool> TestAuthentication()
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"auth.test?token={_apiKey}");

            if (!response.IsSuccessStatusCode)
            {
                return(false);
            }

            string responseContent = await response.Content.ReadAsStringAsync();

            AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(responseContent);

            return(authResponse.ok);
        }
        private static async Task Login(string username, string password)
        {
            string json = LoginRequestData.CreateLoginRequestDataAsJson(username, password);
            string url  = Constants.REST_MULTIDIALOGO_STAGE_HOST + "/users/login";

            HttpResponseMessage response = await http.SendAsync(Utils.CreateRequest(url, null, Utils.CreateStringContent(json), "Post"));

            string responseContent = await response.Content.ReadAsStringAsync();

            AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(responseContent);

            Console.WriteLine("Nuovo token ricevuto: " + authResponse.GetTokenResponse().Token);

            StoreTokens(authResponse);
        }
Example #28
0
        private void SetupExchangeCodeRequest(bool succeeded = true, string accessToken = null, string refreshToken = null)
        {
            var authResponse = new AuthResponse
            {
                AccessToken  = accessToken ?? Guid.NewGuid().ToString(),
                ExpiresIn    = 10,
                RefreshToken = refreshToken ?? Guid.NewGuid().ToString()
            };

            _mockRequestExecutor
            .Setup(x => x.ExchangeCode(It.IsAny <AccountAccessContext>()))
            .ReturnsAsync(succeeded ? ServiceObjectResult <AuthResponse> .Succeeded(authResponse) : ServiceObjectResult <AuthResponse> .Failed(null, new List <string> {
                "Value"
            }));
        }
        public static IActionResult GetResponseResult(this Controller controller, AuthResponse authResponse)
        {
            switch (authResponse.AuthResponseStatus)
            {
            case AuthResponseStatus.Ok:
                return(controller.Ok(GetAuthData(authResponse)));

            case AuthResponseStatus.NotFound:
                return(controller.NotFound(GetAuthData(authResponse)));

            case AuthResponseStatus.BadRequest:
            default:
                return(controller.BadRequest(GetAuthData(authResponse)));
            }
        }
Example #30
0
        public void AuthenticateConsumerEmptyOAuthConsumerSecret()
        {
            //Arrange
            AuthenticateSettings obAuthSettings = new AuthenticateSettings();

            obAuthSettings.OAuthConsumerSecret = string.Empty;

            //Act
            IAuthenticate obAuthenticate = new Authenticate();
            AuthResponse  obAuthRespose  = obAuthenticate.AuthenticateConsumer(obAuthSettings);

            //Assert
            // When Consumer Secret is empty, the expected output is null Authentication Response.
            Assert.AreEqual(obAuthRespose, null);
        }
        public async Task Test_auth_password_success()
        {
            if (this.deribitcredentials.username == null || this.deribitcredentials.password == null)
            {
                throw new Exception("This test requires username/password");
            }
            AuthResponse authresponse = await deribit.Authentication.Auth(new AuthRequest()
            {
                grant_type = GrantType.password,
                username   = this.deribitcredentials.username,
                password   = this.deribitcredentials.password,
            });

            Assert.That(authresponse.refresh_token, Is.Not.Null);
        }
Example #32
0
        public override async Task Prepare(CancellationToken cancellation) {
            if (IsReady && DateTime.Now < _authExpiration) return;

            var data = InternalUtils.GetGoogleDriveCredentials();
            var clientId = data.Item1.Substring(2);
            var clientSecret = data.Item2.Substring(2);

            var enc = ValuesStorage.GetEncryptedString(KeyAuthToken);
            if (enc == null) return;
            
            try {
                _authToken = JsonConvert.DeserializeObject<AuthResponse>(enc);
            } catch (Exception) {
                Logging.Warning("Can’t load auth token");
                return;
            }

            if (DateTime.Now < _authExpiration) {
                IsReady = true;
                return;
            }

            var refresh = await Request.Post<RefreshResponse>(@"https://www.googleapis.com/oauth2/v4/token", new NameValueCollection {
                { @"client_id", clientId },
                { @"client_secret", clientSecret },
                { @"refresh_token", _authToken.RefreshToken },
                { @"grant_type", @"refresh_token" }
            }.GetQuery(), null, cancellation);
            if (cancellation.IsCancellationRequested) return;

            if (refresh == null) {
                ValuesStorage.Remove(KeyAuthToken);
            } else {
                _authToken.AccessToken = refresh.AccessToken;
                _authExpiration = DateTime.Now + TimeSpan.FromSeconds(refresh.ExpiresIn) - TimeSpan.FromSeconds(20);
                ValuesStorage.SetEncrypted(KeyAuthToken, JsonConvert.SerializeObject(_authToken));
                ValuesStorage.Set(KeyAuthExpiration, _authExpiration);
                IsReady = true;
            }
        }
 public void OnAuthResponse(AuthResponse response)
 {
 }
Example #34
0
 public ResponseLogin(AuthResponse resp)
 {
     Response = resp;
 }
Example #35
0
 public void OnAuthResponse(AuthResponse response)
 {
     throw new NotImplementedException();
 }
Example #36
0
        private async Task OnExternalLoginFailure(
            IApplicationBuilder app,
            HttpContext context,
            string error,
            string authSchema)
        {
            await context.Response.WriteAsync(string.Format("External Login for {0} Failed.<br/>Error: ", authSchema));
            await context.Response.WriteAsync(error);

            var authResponse = new AuthResponse
            {
                Success = false,
                Message = "Login failed"
            };

            context.Response.Clear();
            context.Response.ContentType = "application/json; charset=utf-8";
            string json = JsonConvert.SerializeObject(authResponse);
            await context.Response.WriteAsync(json);
        }
 public void OnAuthResponse(AuthResponse response)
 {
     Send("/AuthResponse", Serialize(response));
 }
 public void OnAuthResponse(AuthResponse response)
 {
     OnAuthResponseMessage authResponse = new OnAuthResponseMessage();
     authResponse.payload = response;
     WebSocket.Send(Serialize(authResponse));
 }
        public void OnAuthResponse(AuthResponse response)
        {
            if (response.Success)
            {
                if (Result.SUCCESS.Equals(response.Payment.result))
                {
                    POSPayment payment = new POSPayment(response.Payment.id, response.Payment.order.id, response.Payment.employee.id, response.Payment.amount, response.Payment.tipAmount, response.Payment.cashbackAmount);
                    if (response.IsAuth)
                    {
                        Store.CurrentOrder.Status = POSOrder.OrderStatus.AUTHORIZED;
                        payment.PaymentStatus = POSPayment.Status.AUTHORIZED;
                    }
                    else
                    {
                        Store.CurrentOrder.Status = POSOrder.OrderStatus.CLOSED;
                        payment.PaymentStatus = POSPayment.Status.PAID;
                    }

                    Store.CurrentOrder.AddPayment(payment);
                    uiThread.Send(delegate (object state)
                    {
                        if (payment.CashBackAmount > 0)
                        {
                            ShowCashBackForm(payment.CashBackAmount);
                        }
                        RegisterTabs.SelectedIndex = 0;
                        NewOrder();
                    }, null);
                }
            }
            else if (response.Result.Equals(ResponseCode.FAIL))
            {
                uiThread.Send(delegate (object state)
                {
                    AlertForm.Show(this, response.Reason, response.Message);
                    PaymentReset();
                }, null);
            }
            else if (response.Result.Equals(ResponseCode.CANCEL))
            {
                uiThread.Send(delegate (object state)
                {
                    AlertForm.Show(this, response.Reason, response.Message);
                    PaymentReset();
                }, null);
            }
        }
Example #40
0
 public W8049Password2(AuthResponse resp)
 {
     Response = resp;
 }
Example #41
0
 public void UpdateAuthContext(AuthResponse authContext)
 {
     System.Web.HttpContext.Current.Session.Add("UserContext", authContext);
 }
Example #42
0
        public override async Task SignIn(CancellationToken cancellation) {
            await Prepare(cancellation);
            if (IsReady && DateTime.Now < _authExpiration) return;

            var data = InternalUtils.GetGoogleDriveCredentials();
            var clientId = data.Item1.Substring(2);
            var clientSecret = data.Item2.Substring(2);

            var code = await GetAutenficationCode(clientId, cancellation);
            if (cancellation.IsCancellationRequested) return;

            if (code == null) {
                throw new UserCancelledException();
            }

            var response = await Request.Post<AuthResponse>(@"https://www.googleapis.com/oauth2/v4/token", new NameValueCollection {
                { @"code", code },
                { @"client_id", clientId },
                { @"client_secret", clientSecret },
                { @"redirect_uri", RedirectUrl },
                { @"grant_type", @"authorization_code" }
            }.GetQuery(), null, cancellation);
            if (cancellation.IsCancellationRequested) return;

            if (response == null) {
                throw new Exception(ToolsStrings.Uploader_CannotFinishAuthorization);
            }

            _authToken = response;
            _authExpiration = DateTime.Now + TimeSpan.FromSeconds(response.ExpiresIn) - TimeSpan.FromSeconds(20);
            ValuesStorage.SetEncrypted(KeyAuthToken, JsonConvert.SerializeObject(_authToken));
            ValuesStorage.Set(KeyAuthExpiration, _authExpiration);
            IsReady = true;
        }