private AuthDetails GenAuthDetails(string scopeId, long userId)
        {
            // Fill the simple fields
            var authDetails = new AuthDetails();

            //authDetails.expires = // 5 minutes
            //    (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds + 300;
            authDetails.expires = ViewModel.Config.Expires;
            authDetails.userId  = userId;
            authDetails.salt    = ViewModel.Config.Salt;

            // Calculate and fill the signature
            var signatureBody = "" + ViewModel.Config.AppId + scopeId + userId +
                                authDetails.salt + authDetails.expires + ViewModel.Config.ApiKey;
            var enc           = new ASCIIEncoding();
            var sigBodyBinary = enc.GetBytes(signatureBody);
            var hasher        = SHA256Managed.Create();
            var sigBinary     = hasher.ComputeHash(sigBodyBinary);

            authDetails.signature = BitConverter.ToString(sigBinary).Replace("-", "");

            System.Diagnostics.Debug.WriteLine(string.Format("Creating signature with [AppId = {0}] [Scope = {1}] [UserId = {2}] [Salt = {3}] [Expires = {4}] [ApiKey = {5}]",
                                                             ViewModel.Config.AppId,
                                                             scopeId,
                                                             userId,
                                                             authDetails.salt,
                                                             authDetails.expires,
                                                             ViewModel.Config.ApiKey));
            System.Diagnostics.Debug.WriteLine(authDetails.signature);
            return(authDetails);
        }
        public async Task AuthHandlerReloginsDueToTimeout()
        {
            // ARRANGE
            var httpMessageHandlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            var response = "{\"success\":true,\"result\":{\"token\":\"FRESH_SAMPLE_TOKEN\",\"tpCustomerId\":\"SAMPLE_ID\",\"expiresIn\":\"8h\"}}";

            TestUtils.GetProtectedHttpResponseMessageMock(httpMessageHandlerMock)
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(response),
            })
            .Verifiable();

            var httpClient = TestUtils.GetMockedClient(httpMessageHandlerMock);

            var currentTimeStamp    = DateTime.Now;
            var existingAuthDetails = new AuthDetails {
                Token = "OLD_TOKEN", Timestamp = currentTimeStamp.AddSeconds(-10)
            };

            // ACT
            var result = await subject.Handle(existingAuthDetails, httpClient);

            // ASSERT
            result.Token.Should().Be("FRESH_SAMPLE_TOKEN");
            result.Timestamp.Should().HaveValue();

            httpMessageHandlerMock.Invocations.Should().HaveCount(1);
        }
Beispiel #3
0
        public static AuthRequest FromCloudIdentity(CloudIdentity identity)
        {
            var creds = new AuthDetails();

            if (string.IsNullOrWhiteSpace(identity.Password))
            {
                creds.APIKeyCredentials = new Credentials()
                {
                    Username = identity.Username, APIKey = identity.APIKey
                }
            }
            ;
            else
            {
                creds.PasswordCredentials = new Credentials()
                {
                    Username = identity.Username, Password = identity.Password
                }
            };

            var raxIdentity = identity as RackspaceCloudIdentity;

            if (raxIdentity != null)
            {
                creds.Domain = raxIdentity.Domain;
            }

            return(new AuthRequest {
                Credencials = creds
            });
        }
    }
Beispiel #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthRequest"/> class with the
        /// given identity.
        /// </summary>
        /// <param name="identity">The identity of the user to authenticate.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="identity"/> is <see langword="null"/>.</exception>
        /// <exception cref="NotSupportedException">If given <paramref name="identity"/> type is not supported.</exception>
        public AuthRequest(CloudIdentity identity)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            var credentials = new AuthDetails();

            if (string.IsNullOrEmpty(identity.Password))
            {
                credentials.APIKeyCredentials = new Credentials(identity.Username, null, identity.APIKey);
            }
            else
            {
                credentials.PasswordCredentials = new Credentials(identity.Username, identity.Password, null);
            }

            var raxIdentity = identity as RackspaceCloudIdentity;

            if (raxIdentity != null)
            {
                credentials.Domain = raxIdentity.Domain;
            }

            Credentials = credentials;
        }
Beispiel #5
0
        private Response AddPackage(AuthDetails user, Dictionary <string, object> payload)
        {
            // Package needs to consists of 5 cards
            if (!(payload["array"] is JArray rawCards) || rawCards.Count != 5)
            {
                return(Response.Status(Status.BadRequest));
            }
            // Get user and check if its an admin account
            var userSchema = db.GetUser(user.Username);

            if (userSchema is null)
            {
                return(Response.Status(Status.BadRequest));
            }
            if (userSchema.Role != Role.Admin)
            {
                return(Response.Status(Status.Forbidden));
            }
            // Parse given cards
            var cards = CardSchema.ParseRequest(rawCards);

            // Check if all cards were correctly parsed
            if (cards.Count != 5)
            {
                return(Response.Status(Status.BadRequest));
            }
            // Add package and return corresponding response
            var result = db.AddPackage(cards);

            return(Response.Status(result ? Status.Created : Status.Conflict));
        }
        public async Task <SdkResult> Handle(Request request, HttpClient httpClient = null)
        {
            using (httpClient != null ? httpClient : httpClient = new HttpClient())
            {
                this.authDetails = await this.authHandler.Handle(this.authDetails, httpClient);

                return(await CallApiEndpoint(httpClient, request));
            }
        }
Beispiel #7
0
        public void GetAuthenticateTockenDetailsTestAuthDetailsNull()
        {
            AuthDetails authDetails = null;

            ITwitterFeedAuth _twitterFeedAuth = new TwitterFeedAuth();
            var authResponse = _twitterFeedAuth.GetAuthenticateTockenDetails(authDetails);

            Assert.AreEqual(authResponse, null);
        }
 public static AuthRequest FromCloudIdentity(CloudIdentity identity)
 {
     var creds = new AuthDetails();
     if (string.IsNullOrWhiteSpace(identity.Password))
         creds.APIKeyCredentials = new Credentials() { Username = identity.Username, APIKey = identity.APIKey};
     else
         creds.PasswordCredentials = new Credentials(){Username = identity.Username, Password = identity.Password};
     return new AuthRequest { Credencials = creds };
 }
Beispiel #9
0
        public ucContactManager(AuthDetails LoginDetails)
        {
            InitializeComponent();

            _loginDetails = LoginDetails;

            UpdateCRUDStateControls(AppModuleCrudState.Brows);
            LoadCustomerRecords();
        }
Beispiel #10
0
 private Response PerformTrade(
     string storeId, AuthDetails user, Dictionary <string, object> payload
     )
 {
     if (payload.ContainsKey("value") && payload["value"] is string cardId)
     {
         var trade = db.GetTradingDeal(storeId);
         var card  = db.GetUserCard(cardId);
         if (trade is {} && card is {})
Beispiel #11
0
        public IHttpActionResult AddInvoData(invoice invoiceobj)
        {
            AuthDetails authdet = LoginUserDetails();

            invoiceobj.UpdatedBy = authdet.UserId;
            invoiceobj.CreatedBy = authdet.UserId;
            var result = service1.Add(invoiceobj);

            return(Ok(result));
        }
Beispiel #12
0
        public IHttpActionResult AddData(company companyobj)
        {
            AuthDetails authdet = LoginUserDetails();

            companyobj.UpdatedBy = authdet.UserId;
            companyobj.CreatedBy = authdet.UserId;
            var result = service.Add(companyobj);

            return(Ok(result));
        }
Beispiel #13
0
        public IHttpActionResult AddQuotData(quotation quotationobj)
        {
            AuthDetails authdet = LoginUserDetails();

            quotationobj.UpdatedBy = authdet.UserId;
            quotationobj.CreatedBy = authdet.UserId;
            var result = service1.Add(quotationobj);

            return(Ok(result));
        }
Beispiel #14
0
        public IHttpActionResult GetList(CompanySearch search)
        {
            AuthDetails authdet = LoginUserDetails();
            var         filters = new List <MySqlParameter>
            {
                datatableService.CreateSqlParameter("@pUserId", authdet.UserId, MySqlDbType.Int32)
            };
            var result = service.GetList(search, filters);

            return(Ok(result));
        }
Beispiel #15
0
        public IHttpActionResult AddData(template templateobj)
        {
            AuthDetails authdet = LoginUserDetails();

            templateobj.userid    = authdet.UserId;
            templateobj.CreatedBy = authdet.UserId;
            templateobj.UpdatedBy = authdet.UserId;
            var result = service.Add(templateobj);

            return(Ok(result));
        }
Beispiel #16
0
        public void NullUserIdInConstructor()
        {
            AuthDetails authDetails = new AuthDetails()
            {
                ConsumerKey       = ConfigurationManager.AppSettings["authConsumerKey"],
                ConsumerSecretKey = ConfigurationManager.AppSettings["authConsumerSecret"],
                AuthURL           = ConfigurationManager.AppSettings["authUrl"]
            };

            ITwitterFeedAuth _twitterFeedAuth = new TwitterFeedAuth();
            var authResponse = _twitterFeedAuth.GetAuthenticateTockenDetails(authDetails);
        }
Beispiel #17
0
        private void ActivateAppOptionControls(AppWorkspaceViewType WorkspaceViewtype, string TitleName = "")
        {
            switch (WorkspaceViewtype)
            {
            case AppWorkspaceViewType.Login:
                tabAppView.SelectedTab  = appViewLogin;
                tileButLogout.Visible   = false;
                tileButMainMenu.Visible = false;
                if (TitleName.Trim() == "")
                {
                    SetAppTitle("Login");
                }
                else
                {
                    SetAppTitle(TitleName);
                }

                txtLoginUserName.Text     = "";
                txtLoginUserPassword.Text = "";
                tlLoginInputGrid.Focus();
                txtLoginUserName.Focus();
                txtLoginUserName.Select();
                txtLoginUserName.Refresh();
                txtLoginUserName.Invalidate();

                _loginDetails = null;
                this.Refresh();
                break;

            case AppWorkspaceViewType.AppMenu:
                tabAppView.SelectedTab  = appViewMainMenu;
                tileButLogout.Visible   = true;
                tileButMainMenu.Visible = true;
                if (TitleName.Trim() == "")
                {
                    SetAppTitle("App Menu");
                }
                else
                {
                    SetAppTitle(TitleName);
                }
                break;

            case AppWorkspaceViewType.AppModule:
                tabAppView.SelectedTab  = appViewModule;
                tileButLogout.Visible   = true;
                tileButMainMenu.Visible = true;
                SetAppTitle(TitleName);
                break;
            }
        }
Beispiel #18
0
        public IHttpActionResult GetList(CustomerSearch search)
        {
            AuthDetails authdet = LoginUserDetails();
            var         filters = new List <MySqlParameter>
            {
                datatableService.CreateSqlParameter("@pUserId", authdet.UserId, MySqlDbType.Int32),
                datatableService.CreateSqlParameter("@pName", search.Name, MySqlDbType.VarChar),
                datatableService.CreateSqlParameter("@pMobile", search.Mobile, MySqlDbType.VarChar),
                datatableService.CreateSqlParameter("@pShop", search.Shop, MySqlDbType.VarChar)
            };
            var result = service.GetList(search, filters);

            return(Ok(result));
        }
Beispiel #19
0
        public void GetAuthenticateTockenDetailsTestAuthURLNull()
        {
            AuthDetails authDetails = new AuthDetails()
            {
                ConsumerKey       = ConfigurationManager.AppSettings["authConsumerKey"],
                ConsumerSecretKey = null,
                AuthURL           = ConfigurationManager.AppSettings["authUrl"]
            };

            ITwitterFeedAuth _twitterFeedAuth = new TwitterFeedAuth();
            var authResponse = _twitterFeedAuth.GetAuthenticateTockenDetails(authDetails);

            Assert.AreEqual(authResponse, null);
        }
Beispiel #20
0
 private Response AddTrade(AuthDetails user, Dictionary <string, object> payload)
 {
     if (payload.ContainsKey("Id") && payload["Id"] is string id &&
         payload.ContainsKey("CardToTrade") && payload["CardToTrade"] is string tradeId &&
         payload.ContainsKey("Type") && payload["Type"] is string wanted &&
         payload.ContainsKey("MinimumDamage") &&
         Convert.ToDouble(payload["MinimumDamage"]) is var minDamage)
     {
         return(Response.Status(db.AddTradingDeal(user.Username, new StoreSchema(id, tradeId, wanted, minDamage))
             ? Status.Created
             : Status.BadRequest));
     }
     return(Response.Status(Status.BadRequest));
 }
Beispiel #21
0
        public void GetAuthenticateTockenDetailsTest()
        {
            AuthDetails authDetails = new AuthDetails()
            {
                ConsumerKey       = ConfigurationManager.AppSettings["authConsumerKey"],
                ConsumerSecretKey = ConfigurationManager.AppSettings["authConsumerSecret"],
                AuthURL           = ConfigurationManager.AppSettings["authUrl"]
            };

            ITwitterFeedAuth _twitterFeedAuth = new TwitterFeedAuth();
            var authResponse = _twitterFeedAuth.GetAuthenticateTockenDetails(authDetails);

            Assert.IsNotNull(authDetails);
            Assert.IsTrue(authResponse.TokenType != null && authResponse.Accesstoken != null);
        }
Beispiel #22
0
 public async Task <AuthDetails> Handle(AuthDetails currentDetails, HttpClient httpClient)
 {
     if (currentDetails == null || currentDetails.Token == null || !currentDetails.Timestamp.HasValue)
     {
         return(await LoginToApi(httpClient));
     }
     else if (currentDetails.Timestamp.HasValue && DateTime.Now - currentDetails.Timestamp > tokenTimeout)
     {
         return(await LoginToApi(httpClient));
     }
     else
     {
         return(currentDetails);
     }
 }
Beispiel #23
0
        public async Task <AuthDetails> GetTokenForSocialLogin(SocialLoginCredentials loginCredentials)
        {
            var user = await this.userManager.FindByEmailAsync(loginCredentials.Email);

            //user dosent exist, create new user in DB and the related token
            if (user == null)
            {
                IdentityUser newUser = new IdentityUser
                {
                    UserName = loginCredentials.Name,
                    Email    = loginCredentials.Email
                };

                var createUser = await this.userManager.CreateAsync(newUser);

                if (createUser.Succeeded)
                {
                    AuthDetails authDetails = new AuthDetails
                    {
                        AccessToken = this.GenerateToken(newUser, "User"),
                        UserId      = newUser.Id,
                        UserRole    = "User",
                        UserName    = newUser.UserName
                    };

                    return(authDetails);
                }
                else
                {
                    throw new Exception("User cannot be created");
                }
            }
            else
            {
                var role = await this.userManager.IsInRoleAsync(user, "Admin") ? "Admin" : "User";

                //User exists, create the token
                AuthDetails authDetails = new AuthDetails
                {
                    AccessToken = this.GenerateToken(user, role),
                    UserId      = user.Id,
                    UserRole    = role,
                    UserName    = user.UserName
                };

                return(authDetails);
            }
        }
        public static AuthRequest FromCloudIdentity(CloudIdentity identity)
        {
            var creds = new AuthDetails();
            if (string.IsNullOrWhiteSpace(identity.Password))
                creds.APIKeyCredentials = new Credentials() { Username = identity.Username, APIKey = identity.APIKey};
            else
                creds.PasswordCredentials = new Credentials(){Username = identity.Username, Password = identity.Password};

            var raxIdentity = identity as RackspaceCloudIdentity;
            if (raxIdentity != null)
            {
                creds.Domain = raxIdentity.Domain;
            }

            return new AuthRequest { Credencials = creds };
        }
Beispiel #25
0
        private Response AcquirePackage(AuthDetails user)
        {
            var packageCost = 5;
            var userStats   = db.GetUserStats(user.Username);

            if (userStats is null)
            {
                return(Response.Status(Status.BadRequest));
            }
            if (userStats.Coins - packageCost < 0)
            {
                return(Response.Status(Status.BadRequest));
            }
            return(Response.Status(db.AcquirePackage(user.Username, packageCost)
                ? Status.Created : Status.BadRequest));
        }
Beispiel #26
0
        public async Task <object> Login([FromForm] AuthDetails details)
        {
            this._logger.LogInformation("Login requested: {0} - {1}", details.Username, details.Provider);
            AuthResults result = null;

            if (details.IsValid())
            {
                result = await Auth(details);
            }
            else
            {
                result         = new AuthResults();
                result.Message = "Invalid login data";
            }
            return(result);
        }
Beispiel #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthRequest"/> class with the
        /// given identity.
        /// </summary>
        /// <param name="identity">The identity of the user to authenticate.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="identity"/> is <c>null</c>.</exception>
        /// <exception cref="NotSupportedException">If given <paramref name="identity"/> type is not supported.</exception>
        public AuthRequest(CloudIdentity identity)
        {
            if (identity == null)
                throw new ArgumentNullException("identity");

            var credentials = new AuthDetails();
            if (string.IsNullOrEmpty(identity.Password))
                credentials.APIKeyCredentials = new Credentials(identity.Username, null, identity.APIKey);
            else
                credentials.PasswordCredentials = new Credentials(identity.Username, identity.Password, null);

            var raxIdentity = identity as RackspaceCloudIdentity;
            if (raxIdentity != null)
                credentials.Domain = raxIdentity.Domain;

            Credentials = credentials;
        }
        public async Task <IActionResult> Embed()
        {
            // Generate token for the signed in user
            var accessToken = await m_tokenAcquisition.GetAccessTokenForUserAsync(new string[] { PowerBiScopes.ReadDashboard, PowerBiScopes.ReadReport, PowerBiScopes.ReadWorkspace });

            // Get username of logged in user
            var userInfo = await m_graphServiceClient.Me.Request().GetAsync();

            var userName = userInfo.DisplayName;

            AuthDetails authDetails = new AuthDetails
            {
                UserName    = userName,
                AccessToken = accessToken
            };

            return(View(authDetails));
        }
Beispiel #29
0
        public AuthDetails LoginUserDetails()
        {
            var identity = (ClaimsIdentity)User.Identity;
            IEnumerable <Claim> claims  = identity.Claims;
            AuthDetails         authdet = new AuthDetails();
            var claim = claims.Where(w => w.Type == "UserId").FirstOrDefault();

            if (claim != null)
            {
                authdet.UserId = int.Parse(claim.Value);
            }
            claim = claims.Where(w => w.Type == "Username").FirstOrDefault();
            if (claim != null)
            {
                authdet.UserName = claim.Value;
            }
            return(authdet);
        }
Beispiel #30
0
 public IHttpActionResult AddData(InvoiceListAdd InvoObj)
 {
     if (InvoObj.invoice_itemsobj != null)
     {
         AuthDetails authdet = LoginUserDetails();
         foreach (var invo in InvoObj.invoice_itemsobj)
         {
             invo.UpdatedBy = authdet.UserId;
             invo.CreatedBy = authdet.UserId;
         }
         var result = service.AddItems(InvoObj.invoice_itemsobj);
         return(Ok(result));
     }
     else
     {
         return(Ok(0));
     }
 }
Beispiel #31
0
 public IHttpActionResult AddData(QuotataionListAdd QuoteObj)
 {
     if (QuoteObj.quotation_itemsobj != null)
     {
         AuthDetails authdet = LoginUserDetails();
         foreach (var quote in QuoteObj.quotation_itemsobj)
         {
             quote.UpdatedBy = authdet.UserId;
             quote.CreatedBy = authdet.UserId;
         }
         var result = service.AddItems(QuoteObj.quotation_itemsobj);
         return(Ok(result));
     }
     else
     {
         return(Ok(0));
     }
 }
Beispiel #32
0
        public void Initialize()
        {
            var authHandler = new Mock <IAuthHandler>();

            var fakeAuthDetails = new AuthDetails
            {
                Token     = "SAMPLE_TOKEN",
                Timestamp = DateTime.Now
            };

            authHandler.Setup(ah => ah.Handle(It.IsAny <AuthDetails>(), It.IsAny <HttpClient>()))
            .Returns(Task.FromResult(fakeAuthDetails));

            subject = RequestHandler.GetInstance(authHandler.Object);

            var sdk = SDK.GetInstance();

            sdk.SetEnvironment(EnvironmentName.Sandbox);
        }
Beispiel #33
0
        public ActionResult Embed()
        {
            try
            {
                var userName = ClaimsPrincipal.Current.FindFirst("name").Value;

                var accessToken = TokenManager.GetAccessToken(PowerBIPermissionScopes.ReadUserWorkspaces);

                AuthDetails authDetails = new AuthDetails
                {
                    UserName    = userName,
                    AccessToken = accessToken
                };

                return(View("embed", authDetails));
            }
            catch (Exception ex)
            {
                ErrorModel errorModel = Utils.GetErrorModel((HttpStatusCode)500, ex.ToString());
                return(View("Error", errorModel));
            }
        }