public ExternalToken GetRefreshToken(string authCode, string redirectUri)
        {
            var tokenFromGoogle = jsonConverter.Deserilize <GoogleApiTokenResponse>(this.GetRestRefreshToken(authCode, redirectUri));

            if (!string.IsNullOrEmpty(tokenFromGoogle.refresh_token))
            {
                var refreshToken = new ExternalToken
                {
                    AccessToken    = tokenFromGoogle.refresh_token,
                    ExpirationDate = serverTime.RequestStarted.AddYears(100),
                    Type           = "Google_Refresh_Token"
                };
                externalTokenRepository.Add(refreshToken);
            }

            var accessToken = new ExternalToken
            {
                AccessToken    = tokenFromGoogle.access_token,
                Type           = "Google_Access_Token",
                ExpirationDate = serverTime.RequestStarted.AddSeconds(tokenFromGoogle.expires_in)
            };

            externalTokenRepository.Add(accessToken);
            externalTokenRepository.SaveChanges();

            return(externalTokenRepository.First(et => et.Type == "Google_Refresh_Token"));
        }
        public void CanGetAccessTokenValidInDb()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new LocalRepository <ExternalToken>();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var now = new DateTime(2014, 12, 17, 10, 0, 0);

            serverTime.Setup(st => st.RequestStarted).Returns(now);
            var validAccessToken = new ExternalToken
            {
                AccessToken    = "AccessToken",
                ExpirationDate = now.AddHours(1),
                Type           = "Google_Access_Token"
            };

            externalTokenRepository.Add(validAccessToken);
            var token = api.GetAccessToken();

            Assert.AreEqual("AccessToken", token.AccessToken);
            Assert.AreEqual("Google_Access_Token", token.Type);
            Assert.AreEqual(11, token.ExpirationDate.Hour);
        }
Beispiel #3
0
        //Lykke is the owner of that token

        /*
         *  string tokenName,
         *  uint8 divisibility,
         *  string tokenSymbol,
         *  string version
         */
        public async Task <IExternalToken> CreateExternalTokenAsync(string tokenName, byte divisibility, string tokenSymbol, string version, bool allowEmission, BigInteger initialSupply)
        {
            string        id      = Guid.NewGuid().ToString();
            List <object> @params = new List <object>()
            {
                _settings.EthereumMainAccount, tokenName, divisibility, tokenSymbol, version
            };
            string abi      = allowEmission ? _settings.EmissiveTokenContract.Abi : _settings.NonEmissiveTokenContract.Abi;
            string byteCode = allowEmission ? _settings.EmissiveTokenContract.ByteCode : _settings.NonEmissiveTokenContract.ByteCode;

            if (!allowEmission)
            {
                @params.Add(initialSupply);
            }

            string contractAddress = await _contractService.CreateContract(abi,
                                                                           byteCode, @params.ToArray());

            IExternalToken externalToken = new ExternalToken()
            {
                Id              = id,
                Name            = tokenName,
                ContractAddress = contractAddress,
                Divisibility    = divisibility,
                InitialSupply   = initialSupply.ToString(),
                TokenSymbol     = tokenSymbol,
                Version         = version
            };

            await _tokenRepository.SaveAsync(externalToken);

            return(externalToken);
        }
Beispiel #4
0
        private Task <ExternalToken> GetExternalToken(Guid state, CancellationToken cancellationToken)
        {
            var task = Task.Run(async delegate
            {
                ExternalToken externalToken = null;

                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    if (object.Equals(externalToken, null))
                    {
                        _externaLoginStorage.TryGetValue(state, out externalToken);
                    }

                    if (!object.Equals(externalToken, null) && !object.Equals(externalToken.Token, null))
                    {
                        return(externalToken);
                    }

                    await Task.Delay(TimeSpan.FromSeconds(0.5));
                }

                return(externalToken);
            }, cancellationToken);

            task.Wait(TimeSpan.FromSeconds(10));

            return(task);
        }
Beispiel #5
0
        public async Task <bool> ValidateToken([FromBody] ExternalToken token)
        {
            bool available = await this.externalAuthService.ValidateToken(token.ProviderId, token.AccessToken);

            if (!available)
            {
                throw new ServiceException(Constants.InvalidAccessToken);
            }

            return(true);
        }
Beispiel #6
0
        public IHttpActionResult ExternaLogin(Guid state, ExternalClient externalClient, string lang = "en",
                                              string source  = null,
                                              string formId  = null,
                                              string build   = null,
                                              string partner = null,
                                              Guid?visitorId = null,
                                              int?uid        = null, string cmp = null,
                                              bool?optin     = null,
                                              bool?trial     = null)
        {
            var service = OauthServiceFactory.CreateService(OauthManager.GetExternalClientName(externalClient));

            if (object.Equals(service, null))
            {
                return(NotFound());
            }

            var url   = new Uri(service.GetAuthenticationUrl(lang));
            var query = HttpUtility.ParseQueryString(url.Query);

            query.Add("state", state.ToString("N"));

            var uriBuilder = new UriBuilder(url);

            uriBuilder.Query = query.ToString();

            var externalToken = new ExternalToken(state, OauthManager.GetExternalClientName(externalClient))
            {
                VisitorId = visitorId,
                Uid       = uid,
                Cmp       = cmp,
                Optin     = optin,
                Build     = build,
                Partner   = partner,
                Trial     = trial
            };

            if (!string.IsNullOrEmpty(source))
            {
                externalToken.Source = string.Format("{0}-{1}", source, externalClient);
            }

            if (!string.IsNullOrEmpty(formId))
            {
                externalToken.FormId = FormIdBuilder.Build(formId, string.Format("-{0}", externalClient));
            }

            _externaLoginStorage.AddOrUpdate(state, externalToken, (key, oldValue) => externalToken);

            return(Redirect(uriBuilder.ToString()));
        }
Beispiel #7
0
        // Link updates the user with an additional login method
        public override void Link(ExternalToken externalToken, Callback callback)
        {
            var request = m_Client.LinkExternalId(m_State.accessToken, new ExternalTokenAuthRequest
            {
                accessToken = externalToken.accessToken,
                idToken     = externalToken.idToken,
                idProvider  = externalToken.idProvider,
                redirectUri = externalToken.redirectUri,
                authCode    = externalToken.authCode,
                clientId    = externalToken.clientId,
            });

            DoAuthenticateUpdate(request, true, callback);
        }
        public async Task <ActionResult> SendExamNotification(int Id)
        {
            string trav_access_token = TempData["access_token"].ToString();

            TempData.Keep("access_token");
            TempData.Keep("EmpData");


            App  = new HttpClient();
            Urle = Replacable_URL + "/api/Employee/IsExternalInstructor/" + Id;
            App.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            App.DefaultRequestHeaders.Add("Authorization", trav_access_token);
            HttpResponseMessage Response = await App.GetAsync(Urle);

            var responseData  = Response.Content.ReadAsStringAsync().Result;
            var ExcpectedObj  = new { Email = "" };
            var EmpEmailState = JsonConvert.DeserializeAnonymousType(responseData, ExcpectedObj);

            var Host = System.Web.HttpContext.Current.Request.UrlReferrer?.Authority;

            if (EmpEmailState.Email != "0")
            {
                int Secret_Token   = SecretToken();
                var RedierctedLink = "http://" + Host + "/Exam/CreateExamExternal/?AccessSecret=" + Secret_Token;

                var ExternalToken = new ExternalToken()
                {
                    Code        = Secret_Token,
                    Ins_Id      = Id,
                    Expire_Date = DateTime.Now.AddDays(2)
                };
                var App_2 = new HttpClient();
                var Url   = Replacable_URL + "/api/Employee/InsertExternalToken";
                App_2.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                App_2.DefaultRequestHeaders.Add("Authorization", trav_access_token);
                var response = App.PostAsync(Url, new StringContent(
                                                 new JavaScriptSerializer().Serialize(ExternalToken), Encoding.UTF8, "application/json")).Result;

                var _Email = EmpEmailState.Email;
                SendMailSMTP(_Email, "20/20/1994", RedierctedLink);
                return(Json(new { Message = 0 }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                //Real Time
                ViewBag.HostUrl = Host;
                return(Json(new { Message = 1 }, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #9
0
        // ExternalAuth signs in a user with an external token from a social login
        public override void ExternalAuth(ExternalToken externalToken, Callback callback)
        {
            var request = m_Client.ExternalTokenAuth(new ExternalTokenAuthRequest
            {
                accessToken = externalToken.accessToken,
                idToken     = externalToken.idToken,
                idProvider  = externalToken.idProvider,
                redirectUri = externalToken.redirectUri,
                authCode    = externalToken.authCode,
                clientId    = externalToken.clientId,
                openid      = externalToken.openid,
            });

            DoAuthenticate(request, callback);
        }
        public ExternalToken GetAccessToken(bool forceToGetNew = false)
        {
            ExternalToken authToken = null;
            var           requestTimePlusThreeMins = serverTime.RequestStarted.AddMinutes(3);

            var hasValidTokenInDb = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > requestTimePlusThreeMins);

            if (hasValidTokenInDb && !forceToGetNew)
            {
                authToken =
                    externalTokenRepository.First(
                        t => t.Type == "Google_Access_Token" && t.ExpirationDate > requestTimePlusThreeMins);
            }
            else
            {
                var refreshToken = externalTokenRepository.First(et => et.Type == "Google_Refresh_Token").AccessToken;
                if (string.IsNullOrEmpty(refreshToken))
                {
                    throw new Exception("Refresh Token Not Available");
                }
                var tokenFromGoogle = jsonConverter.Deserilize <GoogleApiTokenResponse>(this.GetRestAccessToken(refreshToken));


                var hasTokenInDb = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.AccessToken == tokenFromGoogle.access_token);

                if (!hasTokenInDb)
                {
                    authToken = new ExternalToken
                    {
                        AccessToken    = tokenFromGoogle.access_token,
                        ExpirationDate = serverTime.RequestStarted.AddSeconds(tokenFromGoogle.expires_in),
                        Type           = "Google_Access_Token"
                    };
                    externalTokenRepository.Add(authToken);
                    externalTokenRepository.SaveChanges();
                }
                else
                {
                    authToken = externalTokenRepository.First(t => t.Type == "Google_Access_Token" && t.AccessToken == tokenFromGoogle.access_token);
                }
            }

            return(authToken);
        }
Beispiel #11
0
        public IActionResult RegisterExternalToken([FromBody] ExternalToken model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var SocialConfig = new SocialConfig();

            SocialConfig.Facebook = new SocialApp()
            {
                AppId = "242553336313565", AppSecret = "87f4a02e389a94375d7b66a6d3d7c971"
            };
            SocialConfig.Google = new SocialApp()
            {
                AppId = "67665367723-2clkplsi4d95kfv4tior0997lsblvf4a.apps.googleusercontent.com", AppSecret = "87f4a02e389a94375d7b66a6d3d7c971"
            };
            var            socialAuthServices = new SocialAuthServices(SocialConfig);
            var            me             = socialAuthServices.VerifyTokenAsync(model);
            CustomerEntity CustomerEntity = null;

            if (!me.IsVerified)
            {
                return(Unauthorized());
            }
            else
            {
                var EShopContext = new EShopContext();
                if (model.Provider == "Facebook")
                {
                    Customer Customer = EShopContext.Customers.FirstOrDefault(c => c.FacebookId == me.Id);
                    if (Customer == null)
                    {
                        Customer = new Customer();
                        Customer.FacebookEmail = me.Email;
                        Customer.FacebookId    = me.Id;
                        Customer.Display       = me.Name;
                        Customer.Picture       = me.UrlAvatar;
                        EShopContext.Customers.Add(Customer);
                        EShopContext.SaveChanges();
                    }
                    CustomerEntity = new CustomerEntity(Customer);
                }
                else if (model.Provider == "Google")
                {
                    Customer Customer = EShopContext.Customers.FirstOrDefault(c => c.GoogleId == me.Id);
                    if (Customer == null)
                    {
                        Customer             = new Customer();
                        Customer.GoogleEmail = me.Email;
                        Customer.GoogleId    = me.Id;
                        Customer.Display     = me.Name;
                        Customer.Picture     = me.UrlAvatar;
                        EShopContext.Customers.Add(Customer);
                        EShopContext.SaveChanges();
                    }
                    CustomerEntity = new CustomerEntity(Customer);
                }
            }
            if (CustomerEntity != null)
            {
                var tokenString = _JwtHandler.CreateToken(CustomerEntity);
                return(Ok(new { token = tokenString }));
            }
            return(Ok());
        }
Beispiel #12
0
 public bool InsertExternalToken(ExternalToken obj)
 {
     return(Emp.CreateExternalSafeToken(obj));
 }
        public void CanGetNewAccessTokenIfNotValidInDbOrForcedForNew()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new LocalRepository <ExternalToken>();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var now = new DateTime(2014, 12, 17, 10, 0, 0);

            serverTime.Setup(st => st.RequestStarted).Returns(now);
            var validRefreshToken = new ExternalToken
            {
                AccessToken    = "RefreshToken",
                ExpirationDate = now.AddYears(100),
                Type           = "Google_Refresh_Token"
            };

            var inValidAccessToken = new ExternalToken
            {
                AccessToken    = "AccessToken",
                ExpirationDate = now.AddHours(-2),
                Type           = "Google_Access_Token"
            };

            externalTokenRepository.Add(validRefreshToken);
            externalTokenRepository.Add(inValidAccessToken);

            var restResponse = new RestResponse();

            restResponse.Content = "{ \"access_token\" : \"NewAccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600}";
            restClient.Setup(rc => rc.Execute(It.IsAny <RestRequest>()))
            .Returns(restResponse);

            var googleApiTokenResponse = new GoogleApiTokenResponse
            {
                access_token = "NewAccessToken",
                expires_in   = 3600,
                token_type   = "Bearer"
            };

            jsonConverter.Setup(
                jc =>
                jc.Deserilize <GoogleApiTokenResponse>(
                    "{ \"access_token\" : \"NewAccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600}"))
            .Returns(googleApiTokenResponse);

            var hasValidTokenInDb = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now);

            Assert.AreEqual(false, hasValidTokenInDb);

            var token = api.GetAccessToken();

            var gotNewValidToken = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now);

            Assert.AreEqual(true, gotNewValidToken);

            Assert.AreEqual("NewAccessToken", token.AccessToken);
            Assert.AreEqual("Google_Access_Token", token.Type);
            Assert.AreEqual(11, token.ExpirationDate.Hour);
        }