示例#1
0
        internal static TResponse AuthExecute <TModel, TResponse>(Merchant merchant, Request <TModel, TResponse> request, string gatewayUrl = null) where TResponse : IResponse
        {
            AddMerchant(merchant, request, gatewayUrl);

            string result = null;

            Task.Run(async() =>
            {
                result = await HttpUtil
                         .GetAsync($"{request.RequestUrl}?{request.GatewayData.ToUrl()}");
            })
            .GetAwaiter()
            .GetResult();

            var gatewayData = new GatewayData();

            gatewayData.FromJson(result);

            OAuthResponse baseResponse = (OAuthResponse)(object)gatewayData.ToObject <TResponse>(StringCase.Snake);

            baseResponse.Raw         = result;
            baseResponse.GatewayData = gatewayData;

            return((TResponse)(object)baseResponse);
        }
示例#2
0
        private void Authenticate()
        {
            ShellService.OAuthManager["consumer_key"]    = ApiKey;
            ShellService.OAuthManager["consumer_secret"] = SecretKey;
            OAuthResponse requestToken =
                ShellService.OAuthManager.AcquireRequestToken(settings.RequestTokenUrl, "POST");
            var url = settings.AuthorizeUrl + @"?oauth_token=" + ShellService.OAuthManager["token"];

            var authenticateViewModel = authenticateViewModelFactory.CreateExport().Value;

            authenticateViewModel.AddUrl(url);
            authenticateViewModel.ShowDialog(ShellService.ShellView);
            string oauthTokenUrl = authenticateViewModel.GetUrl();

            Regex  regex        = new Regex("oauth_verifier=(.*)");
            string oauthVerifer = regex.Match(oauthTokenUrl).Groups[1].ToString();

            OAuthResponse accessToken =
                ShellService.OAuthManager.AcquireAccessToken(settings.AccessTokenUrl, "POST", oauthVerifer);

            regex      = new Regex("oauth_token=(.*)&oauth_token_secret");
            OAuthToken = regex.Match(accessToken.AllText).Groups[1].ToString();

            regex            = new Regex("oauth_token_secret=(.*)");
            OAuthTokenSecret = regex.Match(accessToken.AllText).Groups[1].ToString();

            ShellService.OAuthManager["token"]        = OAuthToken;
            ShellService.OAuthManager["token_secret"] = OAuthTokenSecret;
        }
示例#3
0
        public ActionResult GenerateAuthTokenFromCode(string code, long state)
        {
            OAuthResponse response = null;
            ViewResult    result   = new ViewResult();

            try
            {
                OAuth2Api oAuth = new OAuth2Api();
                response = oAuth.ExchangeCodeForAccessToken(OAuthEnvironment.PRODUCTION, code);
                authorizationManager.SetEbayAuth(response.AccessToken, response.RefreshToken, state);
                result.StatusCode = StatusCodes.Status200OK;
                result.ViewName   = "AuthSuccess";
                return(result);
            }
            catch (NotAuthorizedException ex)
            {
                telemetryClient.TrackException(ex, new Dictionary <string, string> {
                    { "ErrorMessage", ex.Message }
                });
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex, new Dictionary <string, string> {
                    { "ErrorMessage", response?.ErrorMessage }
                });
            }
            result.StatusCode = StatusCodes.Status500InternalServerError;
            result.ViewName   = "AuthError";
            return(result);
        }
示例#4
0
        public OAuthResponse Token()
        {
            var context = new HttpOAuthContext<int>(HttpContext.Current);
              var accessToken = this.oAuthProvider.GrantAccessToken(context);
              WebOperationContext.Current.OutgoingResponse.StatusCode = accessToken.StatusCode();
              WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
              WebOperationContext.Current.OutgoingResponse.Headers["Cache-Control"] = "no-store";
              var response = new OAuthResponse();
              if (accessToken.ErrorCode == ErrorCode.None)
              {
            response.AccessToken = accessToken.AccessToken.Token;
            response.RefreshToken = accessToken.AccessToken.RefreshToken;
            if (accessToken.AccessToken.Expires.HasValue)
            {
              response.ExpiresIn =
            (int)(accessToken.AccessToken.Expires.Value - accessToken.AccessToken.TimeStamp).TotalSeconds;
            }

              }
              else
              {
            response.Error = accessToken.Error();
              }

              return response;
        }
        private bool TokenWithinSafeTimeLimits(OAuthResponse token)
        {
            int      secondsToHalfwayExpire = Math.Min(token.expires_in / 2, 1800);
            TimeSpan TimeToExpiration       = token.expiration_time - DateTime.UtcNow;

            return(TimeToExpiration.TotalSeconds > secondsToHalfwayExpire);
        }
示例#6
0
        // GET: Request
        public async Task <ActionResult> Index(string id)
        {
            ViewBag.MenuItmes = new Dictionary <string, string>
            {
                ["Home"] = "#header",
                ["Appointment Request"] = "#apptRequest",
                ["photos"]   = "#photos",
                ["Location"] = "#location",
            };

            var instagramConfig = new InstagramConfig("2551176810b7497ebe94e79fa551ea06", "2551176810b7497ebe94e79fa551ea06");

            OAuthResponse oAuthResponse = new OAuthResponse();

            oAuthResponse.User        = null;
            oAuthResponse.AccessToken = "8915529.2551176.b8c936bdabf74276a2844e4a29394b34";

            var           users         = new Users(instagramConfig, oAuthResponse);
            UsersResponse usersResponse = await users.Search("tattoor.co", 1);

            var user = usersResponse.Data.First();

            ViewBag.Image    = user.ProfilePicture;
            ViewBag.FullName = user.FullName;
            ViewBag.Header   = user.Bio; // "Get an appointment request page (just like this one) for yourself! For free!";

            var recent = await users.Recent(user.Id, string.Empty, string.Empty, 8, null, null);

            ViewBag.Media = recent.Data.Select(media => media.Images.StandardResolution.Url).ToList();

            ViewBag.FAQs = new List <FAQ>
            {
                new FAQ
                {
                    Question = "How much do you charge?",
                    Answer   = "Appointment request pages (just like this one) are free! Get one for yourself!"
                },
                new FAQ
                {
                    Question = "If this is free, how do you make money?",
                    Answer   = "In order to generate revenue, we'll be offering other services in the future"
                },
            };


            ViewBag.Locations = new List <Location>
            {
                new Location
                {
                    Name       = "Tattoor Office",
                    Address1   = "1631 Camino De Salmon St",
                    City       = "Corona",
                    State      = "CA",
                    PostalCode = "92881"
                },
            };

            return(View());
        }
示例#7
0
        public string AuthorizeApp(string pin)
        {
            OAuthResponse accessToken = OAuth.AcquireAccessToken("http://api.discogs.com/oauth/access_token", "POST", pin, _UserAgent);
            var           search      = "http://api.discogs.com/oauth/identity";
            var           authHeader  = OAuth.GenerateAuthzHeader(search, "GET");

            return(authHeader);
        }
        private string AddAuthResponseToStore(OAuthResponse oauthResponse)
        {
            var store = (HttpContext.Cache["InstaSharp.AuthInfo"] as Dictionary <string, OAuthResponse>) ?? new Dictionary <string, OAuthResponse>();
            var guid  = System.Guid.NewGuid().ToString();

            store.Add(guid, oauthResponse);
            HttpContext.Cache["InstaSharp.AuthInfo"] = store;
            return(guid);
        }
示例#9
0
        /// <summary>
        /// Handles OAuth handshake
        /// </summary>

        public ActionResult OAuth()
        {
            if (Request.QueryString["code"] != null)
            {
                creds = o.Get(Request.QueryString["code"], "http://localhost:53902/Home/OAuth");
                return(RedirectToAction("Send"));
            }
            return(Redirect(o.GenAuthUrl("http://localhost:53902/Home/OAuth").ToString()));
        }
        public void RegisterOrReauthorize_NewUser_ShouldRequestNewAccessTokenAndWriteToDatabase()
        {
            IConfiguration        config               = Mock.Of <IConfiguration>();
            IBungieApiService     bungieApiService     = Mock.Of <IBungieApiService>();
            IManifestDao          manifestDao          = Mock.Of <IManifestDao>();
            EmissaryDbContext     dbContext            = Mock.Of <EmissaryDbContext>();
            IEmissaryDao          emissaryDao          = Mock.Of <IEmissaryDao>();
            IAuthorizationService authorizationService = Mock.Of <IAuthorizationService>();


            ulong        discordId             = 221313820847636491;
            long         destinyProfileId      = 4611686018467260757;
            int          destinyMembershipType = BungieMembershipType.Steam;
            EmissaryUser expectedUser          = new EmissaryUser(discordId, destinyProfileId, destinyMembershipType);

            string authCode = "auth-code";

            OAuthResponse authResponse = new OAuthResponse();

            authResponse.AccessToken = "access-token";

            // Mock.Get(bungieApiService)
            //     .Setup(m =>
            //         m.GetOAuthAccessToken(It.Is<OAuthRequest>(r =>
            //             r.AuthCode == authCode)))
            //     .Returns(authResponse);

            Mock.Get(authorizationService).Setup(m => m.AuthorizeUser(discordId, authCode)).Returns(authResponse);

            UserMembershipsResponse membershipsResponse = new UserMembershipsResponse();

            membershipsResponse.DestinyMemberships = new List <DestinyMembership>();
            membershipsResponse.DestinyMemberships.Add(new DestinyMembership("pimpdaddy", destinyProfileId, destinyMembershipType, BungieMembershipType.Steam));

            Mock.Get(bungieApiService)
            .Setup(m =>
                   m.GetMembershipsForUser(It.Is <UserMembershipsRequest>(r =>
                                                                          r.AccessToken == "access-token")))
            .Returns(membershipsResponse);

            IEmissary      emissary = new Emissary(config, bungieApiService, manifestDao, dbContext, emissaryDao, authorizationService);
            EmissaryResult result   = emissary.RegisterOrReauthorize(discordId, authCode);

            Assert.IsTrue(result.Success);

            // Mock.Get(bungieApiService).Verify(m => m.GetOAuthAccessToken(It.IsAny<OAuthRequest>()), Times.Once());
            Mock.Get(authorizationService).Verify(m => m.AuthorizeUser(discordId, authCode), Times.Once());
            Mock.Get(authorizationService).VerifyNoOtherCalls();
            Mock.Get(bungieApiService).Verify(m => m.GetMembershipsForUser(It.IsAny <UserMembershipsRequest>()), Times.Once());

            Mock.Get(emissaryDao)
            .Verify(m =>
                    m.AddOrUpdateUser(It.Is <EmissaryUser>(u =>
                                                           u.DiscordId == discordId &&
                                                           u.DestinyProfileId == destinyProfileId &&
                                                           u.DestinyMembershipType == destinyMembershipType)), Times.Once());
        }
示例#11
0
        public void ExchangeCodeForAccessToken_Success()
        {
            OAuthEnvironment environment   = OAuthEnvironment.PRODUCTION;
            String           code          = "v^1.1**********************jYw";
            OAuthResponse    oAuthResponse = oAuth2Api.ExchangeCodeForAccessToken(environment, code);

            Assert.NotNull(oAuthResponse);
            PrintOAuthResponse(environment, "ExchangeCodeForAccessToken", oAuthResponse);
        }
示例#12
0
        public void GetAccessToken_Success()
        {
            OAuthEnvironment environment   = OAuthEnvironment.PRODUCTION;
            String           refreshToken  = "v^1.1*****************I2MA==";
            OAuthResponse    oAuthResponse = oAuth2Api.GetAccessToken(environment, refreshToken, userScopes);

            Assert.NotNull(oAuthResponse);
            PrintOAuthResponse(environment, "GetAccessToken", oAuthResponse);
        }
        public void WhenParametersAreNull_ThenWriteEmptyBody()
        {
            var writer  = new JsonOAuthMessageWriter();
            var message = new OAuthResponse();

            writer.Write(message, null);

            Assert.AreEqual(string.Empty, message.Body);
        }
示例#14
0
        public async Task <string> GetTokenAsync(bool forceRefresh = false)
        {
            Task <OAuthResponse> oAuthTokenTask;
            OAuthResponse        oAuthToken = null;
            string token            = null;
            bool   newAuthTokenTask = false;

            // get tokenTask from cache (it's either null, pending or completed)
            lock (tokenCache)
            {
                tokenCache.TryGetValue(TokenCacheKey, out oAuthTokenTask);
            }

            // if we have a tokenTask
            if (oAuthTokenTask != null)
            {
                // resolve the task to get the token
                oAuthToken = await oAuthTokenTask.ConfigureAwait(false);

                token = oAuthToken.access_token;
            }

            // lock around evaluating getting a new token so only one updated task will be created at a time
            lock (tokenCache)
            {
                // token is missing, expired or force refresh
                if (token == null ||
                    TokenNotExpired(oAuthToken) == false ||
                    forceRefresh ||
                    TokenWithinSafeTimeLimits(oAuthToken) == false)
                {
                    // someone else could have already updated the task under their own lock before we got our lock, get the value again
                    tokenCache.TryGetValue(TokenCacheKey, out Task <OAuthResponse> oAuthTokenTask2);

                    // if the cache value hasn't changed, then we are the one to do it.
                    if (oAuthTokenTask == oAuthTokenTask2)
                    {
                        oAuthTokenTask            = RefreshTokenAsync();
                        tokenCache[TokenCacheKey] = oAuthTokenTask;

                        // we can't await in a lock, so we will signal to await the new oAuthTokenTask
                        newAuthTokenTask = true;
                    }
                }
            }

            // if we have new token we need to pull it out again
            if (newAuthTokenTask)
            {
                oAuthToken = await oAuthTokenTask.ConfigureAwait(false);

                token = oAuthToken.access_token;
            }

            return(token);
        }
        public void WhenParametersIsNull_ThenNothingIsWritten()
        {
            var writer = new UrlEncodedBodyOAuthMessageWriter();

            var message = new OAuthResponse();

            writer.Write(message, null);

            Assert.AreEqual("", message.Body);
        }
示例#16
0
        public string AuthenticateUser()
        {
            OAuth = new OAuth.Manager();
            OAuth["consumer_key"]    = _ConsumerKey;
            OAuth["consumer_secret"] = _ConsumerSecret;
            OAuthResponse requestToken = OAuth.AcquireRequestToken("http://api.discogs.com/oauth/request_token", "POST", _UserAgent);
            string        url          = "http://www.discogs.com/oauth/authorize?oauth_token=" + OAuth["token"];

            return(url);
        }
示例#17
0
        public static bool UpdateLocation(HttpContext context, Location location, Uri callback)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (location == null)
            {
                throw new ArgumentNullException("location");
            }

            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            // Update the user's location
            var request = OAuthRequest.Create(
                new EndPoint("https://fireeagle.yahooapis.com/api/0.1/update", "POST"),
                FireEagle.OAuthService,
                callback,
                HttpContext.Current.Session.SessionID);

            request.VerificationHandler = AspNetOAuthRequest.HandleVerification;

            // Send the location latitude and longitude with the request
            OAuthResponse response = request.GetResource(
                new NameValueCollection()
            {
                { "lat", location.Point.Latitude.ToString(CultureInfo.InvariantCulture) },
                { "lon", location.Point.Longitude.ToString(CultureInfo.InvariantCulture) }
            });

            if (!response.HasProtectedResource)
            {
                throw new AuthorizationRequiredException()
                      {
                          AuthorizationUri = FireEagle.OAuthService.BuildAuthorizationUrl(response.Token)
                      }
            }
            ;

            // Store the access token
            context.Session["access_token"] = response.Token;

            // Load the response XML
            XmlDocument responseXml = new XmlDocument();

            responseXml.Load(response.ProtectedResource.GetResponseStream());

            // Check the response status
            return(responseXml.SelectSingleNode("rsp/@stat").Value == "ok");
        }
    }
示例#18
0
        protected TestBase()
        {
            bool testingNewApiNov17 = false;

            if (testingNewApiNov17)
            {
                // test account client id
                Config = new InstagramConfig()
                {
                    ClientId = "fa50f43776ba4cfdaaaa375acc5ccab7"
                };

                ConfigWithSecret = new InstagramConfig()
                {
                    ClientId     = "fa50f43776ba4cfdaaaa375acc5ccab7",
                    CallbackUri  = "https://instasharpapi.azurewebsites.net/Realtime/Callback",
                    ClientSecret = "cd0d5d2f66f146c28cef06d4f4d2dc82"
                };


                // dummy account data. InstaSharpTest
                Auth = new OAuthResponse()
                {
                    AccessToken = "1415228826.fa50f43.1069f6ca1f734e2f930f70fdc7822885",
                    User        = new Models.UserInfo {
                        Id = 1415228826
                    }
                };
            }
            else
            {
                // test account client id
                Config = new InstagramConfig()
                {
                    ClientId = "554dfe9286994bbe98417d8dc7b69a24"
                };

                ConfigWithSecret = new InstagramConfig()
                {
                    ClientId     = "554dfe9286994bbe98417d8dc7b69a24",
                    CallbackUri  = "https://instasharpapi.azurewebsites.net/Realtime/Callback",
                    ClientSecret = "39de8776637b47d2829cd1a4708ae180"
                };


                // dummy account data. InstaSharpTest
                Auth = new OAuthResponse()
                {
                    AccessToken = "1415228826.554dfe9.502432355f084ea581b679a2f94bb350",
                    User        = new Models.UserInfo {
                        Id = 1415228826
                    }
                };
            }
        }
示例#19
0
        /// <summary>
        /// Checks whether token expired or not
        /// </summary>
        /// <param name="tokenObject"></param>
        /// <returns></returns>
        public static bool IsTokenExpired(this OAuthResponse tokenObject)
        {
            var tokenExpiration = TimeSpan.FromMinutes(5);

            if ((DateTime.Now - tokenObject.TokenDate).TotalSeconds - tokenObject.ExpiresIn >
                tokenExpiration.TotalSeconds || string.IsNullOrEmpty(tokenObject.AccessToken))
            {
                return(true);
            }
            return(false);
        }
        public void WhenParameterIsNull_ThenParameterIsNotWrittenToBody()
        {
            var writer  = new JsonOAuthMessageWriter();
            var message = new OAuthResponse();

            writer.Write(message, new Dictionary <string, object> {
                { "test", null }
            });

            Assert.IsFalse(message.Body.Contains("test"));
        }
        public async Task <string> GetTokenAsync(bool forceRefresh = false)
        {
            Task <OAuthResponse> oAuthTokenTask = null;
            OAuthResponse        oAuthToken     = null;

            // get tokenTask from cache
            lock (tokenTaskCache)
            {
                // if we are being forced or don't have a token in our cache at all
                if (forceRefresh || !tokenCache.TryGetValue(CacheKey, out oAuthToken))
                {
                    // we will await this task, because we don't have a token and we need it
                    oAuthTokenTask = _getCurrentTokenTask(forceRefresh: forceRefresh);
                }
                else
                {
                    // we have an oAuthToken
                    // check to see if our token is expired
                    if (TokenExpired(oAuthToken))
                    {
                        // it is, we should await the current task (someone could have already asked for a new token)
                        oAuthTokenTask = _getCurrentTokenTask(forceRefresh: false);

                        // if the task is completed and is the expired token, then we need to force a new one
                        // (This happens if bot has been 100% idle past the expiration point)
                        if (oAuthTokenTask.Status == TaskStatus.RanToCompletion && oAuthTokenTask.Result.access_token == oAuthToken.access_token)
                        {
                            oAuthTokenTask = _getCurrentTokenTask(forceRefresh: true);
                        }
                    }

                    // if enough time has gone by, then create new background refresh token task
                    if (autoRefreshTimes.TryGetValue(CacheKey, out DateTime refreshTime))
                    {
                        // if we are past the refresh time
                        if (DateTime.UtcNow > refreshTime)
                        {
                            // we don't await this task, as it's simply going to be put into the tokenTaskCache
                            _getCurrentTokenTask(forceRefresh: true);
                        }
                    }
                }
            }

            // if we have an oAuthTokenTask then we need to await it
            if (oAuthTokenTask != null)
            {
                oAuthToken           = await oAuthTokenTask;
                tokenCache[CacheKey] = oAuthToken;
            }

            return(oAuthToken?.access_token);
        }
示例#22
0
        public void WhenParametersIsNull_ThenNothingIsWritten()
        {
            var writer = new QueryStringOAuthMessageWriter();

            var message = new OAuthResponse {
                LocationUri = "http://mydomain.com"
            };

            writer.Write(message, null);

            Assert.AreEqual("http://mydomain.com", message.LocationUri);
        }
示例#23
0
        public IActionResult Authenticate(OAuthRequest request)
        {
            Console.WriteLine("Received GitHub intall: '{0}', '{1}'", request.code, request.state);
            OAuthResponse response = RequestAccessToken(request.code, request.state);

            Console.WriteLine("Received GitHub OAuth: '{0}', '{1}'", request.code, response.access_token);
            UserManager.Instance.AddGitHubAuth(request.state, response.access_token);

            Response.Headers["REFRESH"] = String.Format("3;URL={0}", _options.WEBSITE_BASE_URL); // Redirect to the base URL after three seconds

            return(Ok("Successfully authenticated. Now redirecting..."));
        }
示例#24
0
        private OAuthResponse GetResponseFromSession()
        {
            OAuthResponse oauthResponse = null;
            var           sessionValue  = this.Context.Session.GetString(SessionKey);

            if (!string.IsNullOrEmpty(sessionValue))
            {
                oauthResponse = JsonConvert.DeserializeObject <OAuthResponse>(sessionValue);
            }

            return(oauthResponse);
        }
        public void DoesNotWriteEmptyParameters()
        {
            var writer  = new UrlEncodedBodyOAuthMessageWriter();
            var message = new OAuthResponse();

            var parameters = new Dictionary <string, object> {
                { "param1", null }, { "param2", "" }
            };

            writer.Write(message, parameters);

            Assert.AreEqual(string.Empty, message.Body);
        }
            public void UpdateValue(OAuthEnvironment environment, OAuthResponse oAuthResponse, DateTime expiresAt)
            {
                AppTokenCacheModel appTokenCacheModel = new AppTokenCacheModel
                {
                    OAuthResponse = oAuthResponse,

                    //Setting a buffer of 5 minutes for refresh
                    ExpiresAt = expiresAt.Subtract(new TimeSpan(0, 5, 0))
                };


                envAppTokenCache.Add(environment.ConfigIdentifier(), appTokenCacheModel);
            }
示例#27
0
        public static Location GetLocation(HttpContext context, Uri callback)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            // Find the user's location
            var request = OAuthRequest.Create(
                new EndPoint("https://fireeagle.yahooapis.com/api/0.1/user", "GET"),
                FireEagle.OAuthService,
                callback,
                HttpContext.Current.Session.SessionID);

            request.VerificationHandler = AspNetOAuthRequest.HandleVerification;

            OAuthResponse response = request.GetResource();

            if (!response.HasProtectedResource)
            {
                throw new AuthorizationRequiredException()
                      {
                          AuthorizationUri = FireEagle.OAuthService.BuildAuthorizationUrl(response.Token)
                      }
            }
            ;

            // Store the access token
            context.Session["access_token"] = response.Token;

            // Load the response XML
            XmlDocument responseXml = new XmlDocument();

            responseXml.Load(response.ProtectedResource.GetResponseStream());

            // Check the response status
            if (responseXml.SelectSingleNode("rsp/@stat").Value == "ok")
            {
                return(Location.Parse(responseXml.SelectSingleNode("rsp/user/location-hierarchy/location[@best-guess='true']")));
            }
            else
            {
                return(null);
            }
        }
        private async Task <string> RefreshAndStoreToken()
        {
            try
            {
                OAuthResponse oAuthToken = await RefreshTokenAsync().ConfigureAwait(false);

                cache.AddOrUpdate(TokenCacheKey, oAuthToken, (key, oldToken) => oAuthToken);
                return(oAuthToken.access_token);
            }
            catch (OAuthException)
            {
                throw;
            }
        }
        public void RegisterOrReauthorize_UserAlreadyExists_ShouldRefreshAccessTokenAndWriteToDatabase()
        {
            IConfiguration        config               = Mock.Of <IConfiguration>();
            IBungieApiService     bungieApiService     = Mock.Of <IBungieApiService>();
            IManifestDao          manifestDao          = Mock.Of <IManifestDao>();
            EmissaryDbContext     dbContext            = Mock.Of <EmissaryDbContext>();
            IEmissaryDao          emissaryDao          = Mock.Of <IEmissaryDao>();
            IAuthorizationService authorizationService = Mock.Of <IAuthorizationService>();


            ulong        discordId             = 221313820847636491;
            long         destinyProfileId      = 4611686018467260757;
            int          destinyMembershipType = BungieMembershipType.Steam;
            string       expiredAccessToken    = "expired-access-token";
            EmissaryUser user = new EmissaryUser(discordId, destinyProfileId, destinyMembershipType);

            Mock.Get(emissaryDao).Setup(m => m.GetUserByDiscordId(discordId)).Returns(user);

            string authCode = "auth-code";

            OAuthResponse oauthResponse  = new OAuthResponse();
            string        newAccessToken = "new-access-token";

            oauthResponse.AccessToken = newAccessToken;

            Mock.Get(bungieApiService)
            .Setup(m =>
                   m.GetOAuthAccessToken(It.Is <OAuthRequest>(r =>
                                                              r.AuthCode == authCode)))
            .Returns(oauthResponse);

            Mock.Get(authorizationService).Setup(m => m.AuthorizeUser(discordId, authCode)).Returns(oauthResponse);

            IEmissary      emissary = new Emissary(config, bungieApiService, manifestDao, dbContext, emissaryDao, authorizationService);
            EmissaryResult result   = emissary.RegisterOrReauthorize(discordId, authCode);

            Assert.IsTrue(result.Success);
            Assert.IsTrue(result.Message.ToLower().Contains("authorized"));

            Mock.Get(authorizationService).Verify(m => m.AuthorizeUser(discordId, authCode), Times.Once());

            Mock.Get(emissaryDao).Verify(m => m.GetUserByDiscordId(discordId), Times.Once());

            Mock.Get(emissaryDao).Verify(m =>
                                         m.AddOrUpdateUser(It.Is <EmissaryUser>(r =>
                                                                                r.DiscordId == discordId)), Times.Never());

            // Mock.Get(emissaryDao).Verify(m => m.AddOrUpdateAccessToken(It.Is<BungieAccessToken>(r => r.AccessToken == "new-access-token")), Times.Once());
        }
示例#30
0
        private void config(object sender, RoutedEventArgs e)
        {
            OAuthz["consumer_key"]    = "uIVVbzq2RbTYuGU2NIV9Wclc4";
            OAuthz["consumer_secret"] = "5lFp89RKHEzJ8IFyjfnQk0kmGWEqpb0otFI9gF9i2jLsR7D0Pz";
            OAuthResponse requestToken = OAuthz.AcquireRequestToken("https://api.twitter.com/oauth/request_token", "POST");

            // start up the browser to get the access token
            var url = "https://api.twitter.com/oauth/authorize?oauth_token=" + OAuthz["token"];

            System.Diagnostics.Process.Start(url);
            verifyTwitter2 verifyTWindow = new verifyTwitter2();

            verifyTWindow.Show();
            verifyTWindow.RaiseCustomEvent += new EventHandler <CustomEventArgs>(verifyTWindow_RaiseCustomEvent);
        }
        public void WritesBody()
        {
            var parameters = new Dictionary <string, object>();

            parameters.Add("test", "myval");
            parameters.Add("test2", 5);

            var writer  = new JsonOAuthMessageWriter();
            var message = new OAuthResponse();

            writer.Write(message, parameters);

            Assert.IsTrue(message.Body.Contains("\"test\":\"myval\""));
            Assert.IsTrue(message.Body.Contains("\"test2\":5"));
        }
示例#32
0
        /// <summary>
        /// Receives login event and inits authorization vars.
        /// </summary>
        public void MainForm_LoginReady(OAuthResponse response)
        {
            try
            {
                // Set app authorization
                _authorization = response;

                // Get user info and set salute label text
                UsersHelper uh = new UsersHelper();
                uh.AccessToken = _authorization.AccessToken;
                User user = uh.GetUser(response.UserId);
                saluteLabel.Text = "Hi, " + user.FirstName + " " + user.LastName + " (" + user.Email + ")";

                // Hide login form and enable main form buttons
                _loginForm.Hide();
                EnableControlButtons();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Login failure: " + ex.Message);
            }
        }
 private bool TokenNotExpired(OAuthResponse token)
 {
     return token.expiration_time > DateTime.UtcNow;
 }
示例#34
0
        /// <summary>
        /// Receives logout event and resets authorization vars.
        /// </summary>
        public void MainForm_LogoutReady()
        {
            // Reset authorization, form controls and values
            saluteLabel.Text = "";
            DisableButtons();
            ResetAccountValues();
            _authorization = null;

            this.Cursor = Cursors.Default;
        }