public override bool Execute()
        {
            bool processed = false;

            string generalSiteDirectoryUrl      = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryUrl");
            string generalSiteDirectoryListName = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryListName");
            string generalSiteCollectionUrl     = RoleEnvironment.GetConfigurationSettingValue("General.SiteCollectionUrl");
            string generalMailSMTPServer        = RoleEnvironment.GetConfigurationSettingValue("General.MailSMTPServer");
            string generalMailUser             = RoleEnvironment.GetConfigurationSettingValue("General.MailUser");
            string generalMailUserPassword     = RoleEnvironment.GetConfigurationSettingValue("General.MailUserPassword");
            string generalMailSiteAvailable    = RoleEnvironment.GetConfigurationSettingValue("General.MailSiteAvailable");
            string generalEncryptionThumbPrint = RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint");

            //Decrypt mail password
            generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint);
            //On-Prem settings
            string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication");

            try
            {
                SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager();

                string tempSharePointUrl = this.SharePointProvisioningData.Url;
                string siteCollectionUrl = this.CreateOnPremises ? generalOnPremWebApplication : generalSiteCollectionUrl;

                // issue the final SharePoint url
                SharePointProvisioningData.Url = this.GetNextSiteCollectionUrl(generalSiteDirectoryUrl, generalSiteDirectoryListName, siteCollectionUrl);

                //update site directory status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, tempSharePointUrl, this.SharePointProvisioningData.Url, "Provisioning");

                //complete the site data
                this.SharePointProvisioningData.Template            = "PROJECTSITE#0";
                this.SharePointProvisioningData.SiteOwner           = this.SharePointProvisioningData.Owners[0];
                this.SharePointProvisioningData.Lcid                = 1033;
                this.SharePointProvisioningData.TimeZoneId          = 3;
                this.SharePointProvisioningData.StorageMaximumLevel = 100;
                this.SharePointProvisioningData.StorageWarningLevel = 80;

                //create the site collection
                this.AddSiteCollection(this.SharePointProvisioningData);

                // Update status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Available");

                // Send mail to owners
                List <String> mailTo        = new List <string>();
                string        ownerNames    = "";
                string        ownerAccounts = "";

                foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                {
                    mailTo.Add(owner.Email);

                    if (ownerNames.Length > 0)
                    {
                        ownerNames    = ownerNames + ", ";
                        ownerAccounts = ownerAccounts + ", ";
                    }
                    ownerNames    = ownerNames + owner.Name;
                    ownerAccounts = ownerAccounts + owner.Login;
                }

                // send email to notify the use of successful provisioning
                string mailBody = String.Format(generalMailSiteAvailable, this.SharePointProvisioningData.Title, this.SharePointProvisioningData.Url, ownerNames, ownerAccounts);
                MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site is ready to be used", mailBody);
            }
            catch (Exception ex)
            {
                new SiteDirectoryManager().UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Error during provisioning", ex);
            }

            return(processed);
        }
        /// <summary>
        /// Returns a SharePointOnline ClientContext object
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param>
        /// <param name="tenantUserPassword">Password of the user used to instantiate the ClientContext object</param>
        /// <returns>ClientContext to be used by CSOM code</returns>
        public ClientContext GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, string tenantUserPassword)
        {
            var spoPassword = EncryptionUtility.ToSecureString(tenantUserPassword);

            return(GetSharePointOnlineAuthenticatedContextTenant(siteUrl, tenantUser, spoPassword));
        }
Beispiel #3
0
    private void Useronline()
    {
        string text  = this.txtName.Value.Trim();
        string text2 = this.txtPwd.Value.Trim();
        string iP    = this.GetIP();

        if (!this.IsRuleByText(text) || !this.IsRuleByText(text2))
        {
            string script = "<script>jw.alert('对不起!用户名或者密码输入错误,请重新输入!');</script>";
            base.ClientScript.RegisterStartupScript(base.GetType(), "IsRule", script);
            return;
        }
        HttpCookie httpCookie = base.Request.Cookies["cbPass"];

        if (httpCookie != null && text2 == "justwin")
        {
            text2 = EncryptionUtility.Decryption(httpCookie.Value);
        }
        object obj   = userManageDb.ValidatorLoginAccess(text, text2);
        string text3 = (obj == null) ? string.Empty : obj.ToString();
        int    num   = this.IsReturnLogin(text3);

        if (string.IsNullOrEmpty(text3))
        {
            string script2 = "<script>jw.alert('系统提示', '对不起!用户名或者密码错误,请重新输入!');</script>";
            base.ClientScript.RegisterStartupScript(base.GetType(), "JavaScript", script2);
            return;
        }
        SysManageDb sysManageDb = new SysManageDb();

        this.Session["SysID"]  = sysManageDb.GetDefault().ToString();
        this.Session["yhdm"]   = text3;
        this.Session["yhdma"]  = text3;
        this.Session["SkinID"] = userManageDb.getUserSkin(text3);
        this.Session["SkinID"] = "4";
        this.Session["PmSet"]  = PmTypeAction.GetPmType(obj.ToString());
        this.Session["ptcs"]   = myxml.Getcs(base.Server.MapPath("/ptcs.txt"));
        this.Session["pttest"] = "notest";
        if (this.Session["pttest"].ToString() != "notest" && (this.Session["ptcs"] == null || Convert.ToInt32(this.Session["ptcs"]) >= 200))
        {
            string str     = "请找甲乙软件联系。";
            string script3 = string.Format("<script>jw.alert('试用已到期;如需要继续使用,\\r\\n'+'" + str + "');</script>", new object[0]);
            base.ClientScript.RegisterStartupScript(base.GetType(), "Startup", script3);
            return;
        }
        this.Session["OpModules"] = userManageDb.GetUserOpModules(this.Session["yhdm"].ToString());
        this.Session["CorpCode"]  = userManageDb.GetCorpCode(this.Session["yhdm"].ToString());
        HttpCookie httpCookie2 = new HttpCookie("LogName");

        httpCookie2.Values["key1"] = "zyg";
        httpCookie2.Expires        = DateTime.Now.AddHours(2.0);
        base.Response.Cookies.Add(httpCookie2);
        loginLogDb loginLogDb = new loginLogDb();

        loginLogDb.UserlLoginInfo(iP, this.Session["yhdm"].ToString());
        if (num == 0)
        {
            this.AddUserInfo(this.Session["yhdm"].ToString(), false);
        }
        else
        {
            base.Application.Lock();
            DataTable dataTable = (DataTable)base.Application["UserCodeCollection"];
            foreach (DataRow dataRow in dataTable.Rows)
            {
                if (dataRow["userCode"].ToString() == text3)
                {
                    dataRow["loginTime"] = DateTime.Now;
                    dataRow["endTime"]   = DateTime.Now;
                    dataRow["ip"]        = iP;
                    break;
                }
            }
            base.Application["UserCodeCollection"] = dataTable;
            base.Application.UnLock();
        }
        FormsAuthentication.RedirectFromLoginPage(text3, false);
        AduitAction.AddToLog(text3, "登录系统", iP, text);
        this.LogUserInfo();
        base.Response.Redirect("./SysFrame2/Desktop.aspx");
    }
Beispiel #4
0
 private void btnDecrypt_Click(object sender, EventArgs e)
 {
     txtEncryptedContent.Text = EncryptionUtility.Decrypt(txtTextToEncrypt.Text, txtThumbPrint.Text);
 }
Beispiel #5
0
        static TestCommon()
        {
#if NETSTANDARD2_0
            // Load configuration in a way that's compatible with a .Net Core test project as well
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = @"..\..\App.config" //Path to your config file
            };
            configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
#endif

            // Read configuration data
            TenantUrl  = AppSetting("SPOTenantUrl");
            DevSiteUrl = AppSetting("SPODevSiteUrl");

#if !ONPREMISES
            if (string.IsNullOrEmpty(TenantUrl))
            {
                throw new ConfigurationErrorsException("Tenant site Url in App.config are not set up.");
            }
#endif
            if (string.IsNullOrEmpty(DevSiteUrl))
            {
                throw new ConfigurationErrorsException("Dev site url in App.config are not set up.");
            }



            // Trim trailing slashes
            TenantUrl  = TenantUrl.TrimEnd(new[] { '/' });
            DevSiteUrl = DevSiteUrl.TrimEnd(new[] { '/' });

            if (!string.IsNullOrEmpty(AppSetting("SPOCredentialManagerLabel")))
            {
                var tempCred = Core.Utilities.CredentialManager.GetCredential(AppSetting("SPOCredentialManagerLabel"));

                UserName = tempCred.UserName;
                Password = tempCred.SecurePassword;

                // username in format domain\user means we're testing in on-premises
                if (tempCred.UserName.IndexOf("\\") > 0)
                {
                    string[] userParts = tempCred.UserName.Split('\\');
                    Credentials = new NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]);
                }
                else
                {
                    Credentials = new SharePointOnlineCredentials(tempCred.UserName, tempCred.SecurePassword);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(AppSetting("SPOUserName")) &&
                    !String.IsNullOrEmpty(AppSetting("SPOPassword")))
                {
                    UserName = AppSetting("SPOUserName");
                    var password = AppSetting("SPOPassword");

                    Password    = EncryptionUtility.ToSecureString(password);
                    Credentials = new SharePointOnlineCredentials(UserName, Password);
                }
                else if (!String.IsNullOrEmpty(AppSetting("OnPremUserName")) &&
                         !String.IsNullOrEmpty(AppSetting("OnPremDomain")) &&
                         !String.IsNullOrEmpty(AppSetting("OnPremPassword")))
                {
                    Password    = EncryptionUtility.ToSecureString(AppSetting("OnPremPassword"));
                    Credentials = new NetworkCredential(AppSetting("OnPremUserName"), Password, AppSetting("OnPremDomain"));
                }
                else if (!String.IsNullOrEmpty(AppSetting("AppId")) &&
                         !String.IsNullOrEmpty(AppSetting("AppSecret")))
                {
                    AppId     = AppSetting("AppId");
                    AppSecret = AppSetting("AppSecret");
                }
                else if (!String.IsNullOrEmpty(AppSetting("AppId")) &&
                         !String.IsNullOrEmpty(AppSetting("HighTrustIssuerId")))
                {
                    AppId = AppSetting("AppId");
                    HighTrustCertificatePassword = AppSetting("HighTrustCertificatePassword");
                    HighTrustCertificatePath     = AppSetting("HighTrustCertificatePath");
                    HighTrustIssuerId            = AppSetting("HighTrustIssuerId");

                    if (!String.IsNullOrEmpty(AppSetting("HighTrustCertificateStoreName")))
                    {
                        StoreName result;
                        if (Enum.TryParse(AppSetting("HighTrustCertificateStoreName"), out result))
                        {
                            HighTrustCertificateStoreName = result;
                        }
                    }
                    if (!String.IsNullOrEmpty(AppSetting("HighTrustCertificateStoreLocation")))
                    {
                        StoreLocation result;
                        if (Enum.TryParse(AppSetting("HighTrustCertificateStoreLocation"), out result))
                        {
                            HighTrustCertificateStoreLocation = result;
                        }
                    }
                    HighTrustCertificateStoreThumbprint = AppSetting("HighTrustCertificateStoreThumbprint").Replace(" ", string.Empty);
                }
                else
                {
                    throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up.");
                }
            }
        }
        protected override void ProcessRecord()
        {
            Uri tenantUri = null;

            if (string.IsNullOrEmpty(TenantUrl) && SPOnlineConnection.CurrentConnection != null)
            {
                HttpClient client   = new HttpClient();
                var        uri      = new Uri(SPOnlineConnection.CurrentConnection.Url);
                var        uriParts = uri.Host.Split('.');
                if (uriParts[0].ToLower().EndsWith("-admin"))
                {
                    tenantUri =
                        new Uri(
                            $"{uri.Scheme}://{uriParts[0].ToLower().Replace("-admin", "")}.{string.Join(".", uriParts.Skip(1))}{(!uri.IsDefaultPort ? ":" + uri.Port : "")}");
                }
                else
                {
                    tenantUri = new Uri($"{uri.Scheme}://{uri.Authority}");
                }
            }
            else if (!string.IsNullOrEmpty(TenantUrl))
            {
                tenantUri = new Uri(TenantUrl);
            }
            else
            {
                throw new InvalidOperationException("Either a connection needs to be made by Connect-PnPOnline or TenantUrl and Credentials needs to be specified");
            }

            var tenantId = Microsoft.SharePoint.Client.TenantExtensions.GetTenantIdByUrl(tenantUri.ToString());

            string body;
            string response;
            var    password = string.Empty;
            var    username = string.Empty;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(Credentials)))
            {
                password = EncryptionUtility.ToInsecureString(Credentials.Password);
                username = Credentials.UserName;
            }
            else if (SPOnlineConnection.CurrentConnection != null)
            {
                password = EncryptionUtility.ToInsecureString(SPOnlineConnection.CurrentConnection.PSCredential.Password);
                username = SPOnlineConnection.CurrentConnection.PSCredential.UserName;
            }
            else
            {
                throw new InvalidOperationException("Either a connection needs to be made by Connect-PnPOnline or Credentials needs to be specified");
            }

            if (!string.IsNullOrEmpty(Resource))
            {
                body     = $"grant_type=password&client_id={ClientId}&username={username}&password={password}&resource={Resource}";
                response = HttpHelper.MakePostRequestForString($"https://login.microsoftonline.com/{tenantId}/oauth2/token", body, "application/x-www-form-urlencoded");
            }
            else
            {
                var scopes = string.Join(" ", Scopes);
                body     = $"grant_type=password&client_id={ClientId}&username={username}&password={password}&scope={scopes}";
                response = HttpHelper.MakePostRequestForString($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token", body, "application/x-www-form-urlencoded");
            }
            var json        = JToken.Parse(response);
            var accessToken = json["access_token"].ToString();

            if (SetAsCurrent.IsPresent)
            {
                if (SPOnlineConnection.CurrentConnection != null)
                {
                    SPOnlineConnection.CurrentConnection.AccessToken = accessToken;
                }
                else
                {
                    throw new InvalidOperationException("-SetAsCurrent can only be used when connecting using Connect-PnPOnline");
                }
            }
            if (Decoded.IsPresent)
            {
                var decodedToken = new JwtSecurityToken(accessToken);
                WriteObject(decodedToken);
            }
            else
            {
                WriteObject(accessToken);
            }
        }
        //[Bind(Include = "Id,UserId,ReviewId,Title,Body,DateCreated,StateId")] Article article
        public ActionResult Edit([Bind(Include = "Id,UserId,ReviewId,DateCreated,StateId,FileName,Title")] Article article, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                try {
                    if (article.StateId == 1 || article.StateId == 3) // Unlocked states
                    {
                        EncryptionUtility   utility    = new EncryptionUtility();
                        SymmetricParameters parameters = utility.GenerateSymmetricParameters("123qwe", "ijbygcrz");
                        string userId = User.Identity.GetUserId();
                        // Public and private keys are generated during user registration, stored in UserKey table
                        string PublicKey  = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PublicKey;
                        string PrivateKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PrivateKey;

                        //Convert file into an array of bytes, results saved in memory
                        MemoryStream ms = new MemoryStream();
                        file.InputStream.Position = 0;
                        file.InputStream.CopyTo(ms);
                        ms.Position = 0;

                        //Signing Process
                        string signature = utility.GenerateSignature(ms.ToArray(), PrivateKey);

                        // Encryption Process
                        string encryptedSK   = utility.Encrypt(parameters.SecretKey, PublicKey);
                        string encryptedIV   = utility.Encrypt(parameters.IV, PublicKey);
                        string encryptedFile = utility.Encrypt(ms.ToArray(), parameters);

                        // Storage Process
                        string filePath         = Server.MapPath(@"\Files"); //File save location
                        string absoluteFilePath = filePath + @"\" + article.FileName;
                        // If same name of file present then delete that file first
                        if (System.IO.File.Exists(absoluteFilePath))
                        {
                            System.IO.File.Delete(absoluteFilePath);
                        }

                        //Build file data, Secret key and IV in file header
                        utility.WriteToFile(absoluteFilePath, utility.FileMerge(encryptedSK, encryptedIV, encryptedFile));

                        // Database Process
                        if (article.Review != null)
                        {
                            article.Review.Accepted = false;
                        }

                        article.StateId        = 1; // Revert back to pending
                        article.DateLastEdited = DateTime.Now;
                        article.Signature      = signature;

                        db.Entry(article).State = EntityState.Modified;
                        db.SaveChanges();

                        ViewBag.Message = "Upload & Encryption Successful";

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        ViewBag.Message = "Only Pending or Finished articles can be updated.";
                    }
                }
                catch
                {
                    return(RedirectToAction("Missing"));
                }
            }

            return(View(article));
        }
Beispiel #8
0
        private bool ProcessMessage(string message)
        {
            bool processed = true;

            SharePointProvisioningData sharePointProvisioningData = DeserializeData(message);

            if (sharePointProvisioningData.DataClassification.Equals("HBI", StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    // Determine the system connectivity mode based on the command line
                    // arguments: -http, -tcp or -auto  (defaults to auto)
                    ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

                    string serviceNamespace = RoleEnvironment.GetConfigurationSettingValue("General.SBServiceNameSpace");
                    string issuerName       = RoleEnvironment.GetConfigurationSettingValue("General.SBIssuerName");
                    string issuerSecret     = EncryptionUtility.Decrypt(RoleEnvironment.GetConfigurationSettingValue("General.SBIssuerSecret"), RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint"));

                    // create the service URI based on the service namespace
                    Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning");

                    // create the credentials object for the endpoint
                    TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();
                    sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

                    // create the channel factory loading the configuration
                    ChannelFactory <ISharePointProvisioningChannel> channelFactory = new ChannelFactory <ISharePointProvisioningChannel>("RelayEndpoint", new EndpointAddress(serviceUri));

                    // apply the Service Bus credentials
                    channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

                    // create and open the client channel
                    ISharePointProvisioningChannel channel = channelFactory.CreateChannel();
                    channel.Open();
                    channel.ProvisionSiteCollection(sharePointProvisioningData);
                    channel.Close();
                    channelFactory.Close();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    //log error
                }
            }
            else
            {
                try
                {
                    SiteProvisioningBase siteToProvision = null;
                    switch (sharePointProvisioningData.Template)
                    {
                    case SiteProvisioningTypes.ContosoCollaboration:
                        siteToProvision = new ContosoCollaboration();
                        break;

                    case SiteProvisioningTypes.ContosoProject:
                        siteToProvision = new ContosoProject();
                        break;
                    }

                    siteToProvision.SharePointProvisioningData = sharePointProvisioningData;
                    HookupAuthentication(siteToProvision);

                    // Provision the site collection
                    processed = siteToProvision.Execute();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    //log error
                }
            }
            // always return true to get the item of the queue...no retry mechanism foreseen
            return(true);
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, ClientAuthenticationMode authenticationMode = ClientAuthenticationMode.Default)
        {
            var context = new PnPClientContext(url.AbsoluteUri);

            context.RetryCount      = retryCount;
            context.Delay           = retryWait * 1000;
            context.ApplicationName = Properties.Resources.ApplicationName;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016 || SP2019
            context.DisableReturnValueCache = true;
#endif
            context.RequestTimeout = requestTimeout;

            context.AuthenticationMode = authenticationMode;

            if (authenticationMode == ClientAuthenticationMode.FormsAuthentication)
            {
                var formsAuthInfo = new FormsAuthenticationLoginInfo(credentials.UserName, EncryptionUtility.ToInsecureString(credentials.Password));
                context.FormsAuthenticationLoginInfo = formsAuthInfo;
            }

            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
#if !ONPREMISES
                    catch (NotSupportedException nox)
                    {
#if NETSTANDARD2_1
                        // Legacy auth is not supported with .NET Standard
                        throw nox;
#else
                        // legacy auth?
                        var authManager = new OfficeDevPnP.Core.AuthenticationManager();
                        context = PnPClientContext.ConvertFrom(authManager.GetAzureADCredentialsContext(url.ToString(), credentials.UserName, credentials.Password));
                        context.ExecuteQueryRetry();
#endif
                    }
#endif
                    catch (ClientRequestException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
                else
                {
                    // If current credentials should be used, use the DefaultNetworkCredentials of the CredentialCache. This has the same effect
                    // as using "UseDefaultCredentials" in a HttpClient.
                    context.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
            }
#if SP2013 || SP2016 || SP2019
            var connectionType = ConnectionType.OnPrem;
#else
            var connectionType = ConnectionType.O365;
#endif
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.Credentials);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.Credentials;
            return(spoConnection);
        }
        public IActionResult CustSignupProcess(CustomerModel model)
        {
            model.isActive   = true; // should be after user has validated their email. but temp for now
            model.VerifyCode = Guid.NewGuid().ToString();

            var exist = TheRepository.CheckEmailExist(model.emailAddress);

            if (exist)
            {
                TempData["exist"] = "Email Exists";
                return(View("CustSignup", model));
            }
            var customer = TheRepository.CreateCustomer(model);

            model.id                     = customer.id;
            model.emailConfirmed         = false;
            model.isRegistrationApproved = false;
            model.createdDate            = DateTime.Now;

            model.password = PasswordHash.PasswordHash.CreateHash(model.password).Replace("1000:", String.Empty);

            LoginModel login = new LoginModel
            {
                userName    = model.emailAddress,
                password    = model.password,
                userid      = customer.id,
                createdDate = DateTime.Now
            };

            var createdLogin = TheRepository.CreateLogin(login);

            var encryptedid = EncryptionUtility.Encrypt(createdLogin.id.ToString());

            //Send an authorisation email to the customer
            EmailInfo emailInfo   = new EmailInfo();
            var       callbackUrl = Url.Action("VerifyEmail", "CustomerSignup", new { userId = customer.id, code = model.VerifyCode }, Request.Scheme, Request.Host.Value + "/CustomerArea");

            emailInfo.Body       = $"Welcome from I NEED YOUR TIME. Click <a href='{callbackUrl}'>here</a> to confirm your email";
            emailInfo.emailType  = "WelcomeEmail";
            emailInfo.IsBodyHtml = true;
            emailInfo.Subject    = "Welcome to INYT";
            emailInfo.ToAddress  = model.emailAddress;
            //_emailManager.SendEmail(emailInfo);
            var model2 = new Emailmodel
            {
                Name = model.firstName,
                Body = emailInfo.Body
            };
            var renderedHTML = ControllerExtensions.RenderViewAsHTMLString(this, "_VerifyEmail.cshtml", model2);

            EmailManager.SendEmail2(model.emailAddress, "VerifyAccount", renderedHTML.Result);
            //SendSimpleMessage(String.Format("<strong>Welcome from I NEED YOUR TIME. Click <a href='CustomerSignup/ConfirmEmail/{0}'>here</a> to confirm your email", "*****@*****.**"), encryptedid).Content.ToString();

            //Send an email to the Administrator with the customer details
            //EmailInfo emailInfo = new EmailInfo();
            emailInfo.Body       = "New customer on INYT website";
            emailInfo.emailType  = "NewCustomerEmail";
            emailInfo.IsBodyHtml = true;
            emailInfo.Subject    = "New customer";
            emailInfo.ToAddress  = "*****@*****.**";
            _emailManager.SendEmail(emailInfo);
            var model_admin = new Emailmodel
            {
                Name = model.firstName,
                Body = emailInfo.Body
            };
            var renderedHTMLAdmin = ControllerExtensions.RenderViewAsHTMLString(this, "_AdminEmail.cshtml", model_admin);

            EmailManager.SendEmail2(model.emailAddress, "VerifyAccount", renderedHTMLAdmin.Result);

            //SendSimpleMessage("New customer on INYT website", "*****@*****.**").Content.ToString();

            return(View(model));
        }
        /// <summary>
        /// Constructs scan job
        /// </summary>
        /// <param name="options">Scanner options</param>
        /// <param name="jobName">Name of the job</param>
        /// <param name="jobVersion">Version of the job</param>
        public ScanJob(Options options, string jobName, string jobVersion) : base(jobName, jobVersion)
        {
            // Basic scan job configuration
            this.UseThreading    = true;
            this.MaximumThreads  = options.Threads;
            this.TenantAdminSite = options.TenantAdminSite;
            this.OutputFolder    = DateTime.Now.Ticks.ToString();
            this.Separator       = options.Separator;
            this.ExcludeOD4B     = !options.IncludeOD4B;
            this.CsvFile         = options.CsvFile;
            this.Tenant          = options.Tenant;
            this.Urls            = options.Urls;
            this.ClientTag       = ConstructClientTag(jobName);

            // Authentication setup
            this.AzureEnvironment = options.AzureEnvironment;

            if (options.AuthenticationTypeProvided() == AuthenticationType.AppOnly)
            {
                this.UseAppOnlyAuthentication(options.ClientID, options.ClientSecret);
            }
            else if (options.AuthenticationTypeProvided() == AuthenticationType.AzureADAppOnly)
            {
                if (!string.IsNullOrEmpty(options.StoredCertificate))
                {
                    // Did we get a three part certificate path (= local stored cert)
                    var certPath = options.StoredCertificate.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    if (certPath.Length == 3 && (certPath[1].Equals("CurrentUser", StringComparison.InvariantCultureIgnoreCase) || certPath[1].Equals("LocalMachine", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        // Load the Azure cert based upon this
                        string certThumbPrint = certPath[2].ToUpper();

                        Enum.TryParse(certPath[0], out StoreName storeName);
                        Enum.TryParse(certPath[1], out StoreLocation storeLocation);

                        var store = new X509Store(storeName, storeLocation);
                        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                        var certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbPrint, false);

                        store.Close();

                        foreach (var certificate in certificateCollection)
                        {
                            if (certificate.Thumbprint == certThumbPrint)
                            {
                                options.AzureCert = certificate;
                                break;
                            }
                        }
                    }

                    if (options.AzureCert == null)
                    {
                        Log($"No valid certificate found for provided path {options.StoredCertificate}", LogSeverity.Error);
                        throw new Exception($"No valid certificate found for provided path {options.StoredCertificate}");
                    }
                }
                else
                {
                    var certificatePassword = EncryptionUtility.ToSecureString(options.CertificatePfxPassword);
                    using (var certfile = System.IO.File.OpenRead(options.CertificatePfx))
                    {
                        var certificateBytes = new byte[certfile.Length];
                        certfile.Read(certificateBytes, 0, (int)certfile.Length);
                        var cert = new X509Certificate2(
                            certificateBytes,
                            certificatePassword,
                            X509KeyStorageFlags.Exportable |
                            X509KeyStorageFlags.MachineKeySet |
                            X509KeyStorageFlags.PersistKeySet);
                        options.AzureCert = cert;
                    }
                }

                this.UseAzureADAppOnlyAuthentication(options.ClientID, options.AzureTenant, options.AzureCert);
            }
            else if (options.AuthenticationTypeProvided() == AuthenticationType.Office365)
            {
                this.UseOffice365Authentication(options.User, options.Password);
            }
            else if (options.AuthenticationTypeProvided() == AuthenticationType.AccessToken)
            {
                this.UseAccessTokenAuthentication(options.AccessToken);
            }

            // Configure sites to scan
            if (!String.IsNullOrEmpty(this.Tenant))
            {
                this.AddSite($"https://{this.Tenant}.sharepoint.{SharePointDomain}*");
                this.AddSite($"https://{this.Tenant}-my.sharepoint.{SharePointDomain}*");
            }
            else if (this.Urls != null && this.Urls.Count > 0)
            {
                foreach (var url in this.Urls)
                {
                    this.AddSite(url.Trim());
                }
            }
            else if (!String.IsNullOrEmpty(this.CsvFile))
            {
                foreach (var row in LoadSitesFromCsv(this.CsvFile, this.Separator.ToCharArray().First()))
                {
                    this.AddSite(row[0].Trim()); //first column in the row contains url
                }
            }
            else
            {
                Log("No site selection specified, assume the job will use search to retrieve a list of sites");
            }

            this.StartTime = DateTime.Now;
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            // Determine the system connectivity mode based on the command line
            // arguments: -http, -tcp or -auto  (defaults to auto)
            ServiceBusEnvironment.SystemConnectivity.Mode = GetConnectivityMode(args);

            string serviceNamespace = ConfigurationManager.AppSettings["General.SBServiceNameSpace"];
            string issuerName       = ConfigurationManager.AppSettings["General.SBIssuerName"];
            string issuerSecret     = EncryptionUtility.Decrypt(ConfigurationManager.AppSettings["SBIssuerSecret"], ConfigurationManager.AppSettings["General.EncryptionThumbPrint"]);

            // create the service URI based on the service namespace
            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning");

            // create the credentials object for the endpoint
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            // create the channel factory loading the configuration
            ChannelFactory <ISharePointProvisioningChannel> channelFactory = new ChannelFactory <ISharePointProvisioningChannel>("RelayEndpoint", new EndpointAddress(serviceUri));

            // apply the Service Bus credentials
            channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

            // create and open the client channel
            ISharePointProvisioningChannel channel = channelFactory.CreateChannel();

            channel.Open();

            SharePointProvisioningData sharePointProvisioningData = new SharePointProvisioningData();

            sharePointProvisioningData.Title              = "Test site on-premises";
            sharePointProvisioningData.Url                = String.Format("{0}{1}", "https://bertonline.sharepoint.com/sites/", Guid.NewGuid().ToString());
            sharePointProvisioningData.Template           = "ContosoCollaboration";
            sharePointProvisioningData.Name               = "";
            sharePointProvisioningData.DataClassification = "HBI";

            SharePointUser[] owners = new SharePointUser[1];
            SharePointUser   owner  = new SharePointUser();

            owner.Login = "******";
            owner.Name  = "Kevin Cook";
            owner.Email = "*****@*****.**";
            owners[0]   = owner;
            sharePointProvisioningData.Owners = owners;

            channel.ProvisionSiteCollection(sharePointProvisioningData);

            //Console.WriteLine("Enter text to echo (or [Enter] to exit):");
            //string input = Console.ReadLine();
            //while (input != String.Empty)
            //{
            //    try
            //    {
            //        Console.WriteLine("Server echoed: {0}", channel.Echo(input));
            //    }
            //    catch (Exception e)
            //    {
            //        Console.WriteLine("Error: " + e.Message);
            //    }
            //    input = Console.ReadLine();
            //}
            Console.ReadLine();
            channel.Close();
            channelFactory.Close();
        }
Beispiel #13
0
 private string GetApiKey()
 {
     return(_apiKeyEncrypted && ApiKey != null
     ? EncryptionUtility.DecryptString(ApiKey)
     : ApiKey);
 }
        public void ListItemProvider_Test_GetItems_Integration()
        {
            using (AuthenticationManager authManager = new AuthenticationManager(Common.User, EncryptionUtility.ToSecureString(Common.UserPassword)))
            {
                using (ClientContext context = authManager.GetContext(Common.SiteUrl))
                {
                    MockExecutorFactory factory = UnitTestClientContextHelper.BuildExecutorFactory(true, "./../../../MockResponses/ListItemProvider_Test_GetItems_Integration.json");
                    context.WebRequestExecutorFactory = factory;

                    ListItemProvider provider = new ListItemProvider(context);
                    var myItems = provider.GetMyItems();

                    factory.SaveMockData();
                }
            }
        }
Beispiel #15
0
        public async Task GetTwitterResponseTest()
        {
            string formattedToken     = EncryptionUtility.DecodeBase64(_consumerKey) + ":" + EncryptionUtility.DecodeBase64(_consumerSecret);
            string formattedUrl       = string.Format(_searchUrl, "nature", 20);
            string authorizationToken = "Bearer " + await HttpUtility.GetTwitterBearerToken(_authorizationUrl, formattedToken);

            string response = await HttpUtility.GetTwitterSearchResponse(formattedUrl, authorizationToken);

            var twitterResponseResult = JsonConvert.DeserializeObject <TwitterSearchMetaData>(response);

            Assert.IsNotNull(twitterResponseResult);
        }
Beispiel #16
0
 public override string Transform(string value, string valueName, ICustomAttributeProvider property)
 {
     return(value == null
         ? null
         : EncryptionUtility.Decrypt(value));
 }
Beispiel #17
0
        /// <inheritdoc />
        public void SetEncryptedValue(string settingName, string value)
        {
            string encryptedValue = EncryptionUtility.EncryptString(value);

            SetValue(settingName, encryptedValue);
        }
 public static string MD5_16(string str)
 {
     return(EncryptionUtility.MD5(str).Substring(8, 16));
 }
        public ActionResult Download(string fileName)
        {
            bool isPublished = false;

            if (db.Articles.SingleOrDefault(a => a.FileName == fileName).StateId == 4)
            {
                isPublished = true;
            }
            bool advancedUser = false;

            if (User.IsInRole("Author") || User.IsInRole("MediaManager"))
            {
                advancedUser = true;
            }


            if (advancedUser == false && isPublished == false)
            {
                return(RedirectToAction("Missing"));
            }
            else
            {
                try
                {
                    EncryptionUtility utility = new EncryptionUtility();

                    SymmetricParameters parameters = new SymmetricParameters();
                    string userId = db.Articles.SingleOrDefault(a => a.FileName == fileName).UserId;
                    // Public and private keys are generated during user registration, stored in UserKey table
                    string publicKey  = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PublicKey;
                    string privateKey = db.UserKeys.SingleOrDefault(k => k.UserId == userId).PrivateKey;
                    string signature  = db.Articles.SingleOrDefault(a => a.FileName == fileName).Signature;

                    // Retrieval Process
                    string filePath      = Server.MapPath(@"\Files" + @"\" + fileName);
                    string encryptedFile = utility.ReadFromFile(filePath);

                    // Decryption Process
                    string[] splitString      = encryptedFile.Split(new string[] { "#CONTENT#" }, StringSplitOptions.None);
                    string[] keyiv            = splitString[0].Split(new string[] { "$KEY$" }, StringSplitOptions.None);
                    string   SK               = keyiv[0];
                    string   IV               = keyiv[1];
                    string   encryptedContent = splitString[1];

                    parameters.SecretKey = utility.Decrypt(SK, privateKey);
                    parameters.IV        = utility.Decrypt(IV, privateKey);

                    //Decrypt file using Secret key and IV
                    byte[] decryptedFile = utility.Decrypt(encryptedContent, parameters);

                    bool verify = utility.VerifySignature(decryptedFile, publicKey, signature);

                    ViewBag.isValid = verify.ToString();
                    return(File(decryptedFile, System.Net.Mime.MediaTypeNames.Application.Octet, "Article"));
                }
                catch
                {
                    return(RedirectToAction("Missing"));
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// We want to base the lock name off of the full path of the package, however, the Mutex looks for files on disk if a path is given.
        /// Additionally, it also fails if the string is longer than 256 characters. Therefore we obtain a base-64 encoded hash of the path.
        /// </summary>
        /// <seealso href="http://social.msdn.microsoft.com/forums/en-us/clr/thread/D0B3BF82-4D23-47C8-8706-CC847157AC81"/>
        private static string GenerateUniqueToken(IPackageManager packageManager, string packageId, SemanticVersion version)
        {
            var fullPath = packageManager.FileSystem.GetFullPath(packageManager.PathResolver.GetPackageFileName(packageId, version));

            return(EncryptionUtility.GenerateUniqueToken(fullPath));
        }
Beispiel #21
0
        private string CreateConfiguration(Provider provider, string connectionString, String defaultSchema)
        {
            string driver  = String.Empty;
            string dialect = String.Empty;

            try
            {
                string dbProvider = provider.ToString();

                NHibernateProvider _NHibernateProvider = new NHibernateProvider();
                driver  = Convert.ToString(_NHibernateProvider.GetConnectionDriver(dbProvider));
                dialect = Convert.ToString(_NHibernateProvider.GetDatabaseDialect(dbProvider));


                StringBuilder configBuilder = new StringBuilder();
                XmlTextWriter configWriter  = new XmlTextWriter(new StringWriter(configBuilder));

                configWriter.Formatting = Formatting.Indented;
                configWriter.WriteStartElement("configuration");
                configWriter.WriteStartElement("hibernate-configuration", "urn:nhibernate-configuration-2.2");
                configWriter.WriteStartElement("session-factory");
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "connection.provider");
                configWriter.WriteString("NHibernate.Connection.DriverConnectionProvider");
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "connection.driver_class");
                configWriter.WriteString(driver);
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "connection.connection_string");

                string keyFile = string.Format("{0}{1}.{2}.key",
                                               _settings["AppDataPath"], _settings["ProjectName"], _settings["ApplicationName"]);
                configWriter.WriteString(EncryptionUtility.Encrypt(connectionString, keyFile));

                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "proxyfactory.factory_class");
                configWriter.WriteString("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "default_schema");
                configWriter.WriteString(defaultSchema);
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "dialect");
                configWriter.WriteString(dialect);
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "show_sql");
                configWriter.WriteString("true");
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteStartElement("property");
                configWriter.WriteAttributeString("name", "command_timeout");
                configWriter.WriteString("0");
                configWriter.WriteEndElement(); // end property element
                configWriter.WriteEndElement(); // end session-factory element
                configWriter.WriteEndElement(); // end hibernate-configuration element
                configWriter.WriteEndElement(); // end configuration element
                configWriter.Close();

                return(configBuilder.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Test Aes and AOS");
            User _selectedUser = null;
            User _sendUser     = null;
            var  IV            = System.Text.ASCIIEncoding.ASCII.GetBytes("adfqsffafdsfsqdf");

            //Try aes encryption
            try
            {
                Console.Write("Enter userName:  "******"Naam persoon: {0}", _selectedUser.getUserName()));
                }
                else
                {
                    Console.WriteLine(String.Format("Could not load user"));
                    Console.WriteLine(String.Format("Creating user {0}", _name));

                    //lets take a new CSP with a new 2048 bit rsa key pair
                    RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048);

                    //how to get the private key
                    var privKey = csp.ExportParameters(true);

                    //and the public key ...
                    var pubKey = csp.ExportParameters(false);

                    // user aanmaken
                    _selectedUser = new User(_name, privKey, pubKey);

                    string pubKeyString = EncryptionUtility.keyToString(pubKey);

                    string privKeyString = EncryptionUtility.keyToString(privKey);

                    Console.WriteLine(String.Format("Saving keys"));
                    string _nameFile = string.Format("{0}-RSAPrivKey.dat", _name);
                    FileUtility.saveByte(privKeyString, _nameFile);
                    _nameFile = string.Format("{0}-RSAPubKey.dat", _name);
                    FileUtility.saveByte(pubKeyString, _nameFile);
                }


                //Ask to send message to... or read message
                int    inputvalue = 0;
                string value;
                do
                {
                    Console.WriteLine("press 1 to send a message");
                    Console.WriteLine("Press 2 to read a message");
                    Console.WriteLine("Press 0 to close this program");
                    Console.Write("Enter input value:  "); // Prompt
                    value      = Console.ReadLine();       // Get string form message
                    inputvalue = Convert.ToInt32(value);
                    //declare file name variable for switch case
                    string _fileNamePriv;
                    string _fileNamePub;
                    string _messageFile;
                    string _aesKeyFile;
                    string _hashFile;
                    switch (inputvalue)
                    {
                    case 1:
                        Console.Write("Send message to?: ");
                        _name         = Console.ReadLine();                                                        // name of the user
                        _fileNamePriv = string.Format("{0}-RSAPrivKey.dat", _name);                                // RSAPrivate key filename
                        _fileNamePub  = string.Format("{0}-RSAPubKey.dat", _name);                                 // RSAPublic key filename
                        if (FileUtility.CheckFileExist(_fileNamePub) && FileUtility.CheckFileExist(_fileNamePriv)) //Checking if the Pub en Priv exist
                        {
                            Console.Write("Message to send: ");
                            string message = Console.ReadLine();

                            _sendUser = FileUtility.loadUser(_name);                                //user gegevesn laden
                            EncryptionUtility.aosEncryption(message, _selectedUser, _sendUser, IV); // Aos excryption doen.
                        }
                        else
                        {
                            Console.WriteLine(string.Format("Could not find {0} ", _name));
                            Console.WriteLine("");
                        }
                        break;

                    case 2:
                        //Show a list of all message files
                        FileUtility.loadfileList(_selectedUser);     // Show file lists

                        Console.Write("select message by number: ");
                        int _fileNumber = Convert.ToInt32(Console.ReadLine());
                        //Load all the file names into the memory
                        _messageFile = string.Format("{0}-MessageFile-{1}.dat", _selectedUser.getUserName(), _fileNumber);
                        _aesKeyFile  = string.Format("{0}-EncryptedAesKey-{1}.dat", _selectedUser.getUserName(), _fileNumber);
                        _hashFile    = string.Format("{0}-EncryptedHash-{1}.dat", _selectedUser.getUserName(), _fileNumber);
                        if (FileUtility.CheckFileExist(_messageFile) && FileUtility.CheckFileExist(_aesKeyFile))
                        {
                            Console.WriteLine("You selected file: {0}", _messageFile);
                            //select the user that wrote the text to you
                            Console.Write("Select user: "******"{0}-RSAPrivKey.dat", _name);
                            _fileNamePub  = string.Format("{0}-RSAPubKey.dat", _name);
                            //check if those keys exists
                            if (FileUtility.CheckFileExist(_fileNamePub) && FileUtility.CheckFileExist(_fileNamePriv))
                            {
                                //load the user into the system
                                _sendUser = FileUtility.loadUser(_name);

                                //Get AES key
                                byte[] _aesKeyBytes = EncryptionUtility.decryptFileWithRSA(_aesKeyFile, _selectedUser.getPrivKey());
                                //Decrypt message
                                string _message = EncryptionUtility.decryptMessage(_messageFile, _aesKeyBytes, IV);

                                //Hash stuff
                                EncryptionUtility.checkHash(_hashFile, _sendUser, _message);

                                //Show decrypted message
                                Console.WriteLine("Decrypted message: {0}", _message);
                            }
                            else
                            {
                                Console.WriteLine(string.Format("Could not find {0} ", _name));
                                Console.WriteLine("");
                            }
                        }
                        break;
                    }
                } while (!(inputvalue == 0));
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
            Console.ReadKey();
        }
Beispiel #23
0
        /// <summary>
        /// 加密的操作类
        /// </summary>
        /// <param name="timeliness">时限</param>
        /// <param name="encryptString">encryptString</param>
        /// <param name="key">key</param>
        /// <param name="iv">向量</param>
        /// <returns></returns>
        private static string EncryptTokenForCookie(string encryptString, string key, string iv)
        {
            string tonkenStr = encryptString;

            return(EncryptionUtility.SymmetricEncrypt(SymmetricEncryptType.DES, tonkenStr, iv, key));
        }
        internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, PSCredential credentials, PSHost host, bool currentCredentials, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, ClientAuthenticationMode authenticationMode = ClientAuthenticationMode.Default)
        {
            var context = new PnPClientContext(url.AbsoluteUri);

            context.RetryCount      = retryCount;
            context.Delay           = retryWait * 1000;
            context.ApplicationName = Properties.Resources.ApplicationName;
#if !ONPREMISES
            context.DisableReturnValueCache = true;
#elif SP2016
            context.DisableReturnValueCache = true;
#endif
            context.RequestTimeout = requestTimeout;

            context.AuthenticationMode = authenticationMode;

            if (authenticationMode == ClientAuthenticationMode.FormsAuthentication)
            {
                var formsAuthInfo = new FormsAuthenticationLoginInfo(credentials.UserName, EncryptionUtility.ToInsecureString(credentials.Password));
                context.FormsAuthenticationLoginInfo = formsAuthInfo;
            }

            if (!currentCredentials)
            {
                try
                {
                    SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(credentials.UserName, credentials.Password);
                    context.Credentials = onlineCredentials;
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                    catch (ServerException)
                    {
                        context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    }
                }
                catch (ArgumentException)
                {
                    // OnPrem?
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                    try
                    {
                        context.ExecuteQueryRetry();
                    }
                    catch (ClientRequestException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                    catch (ServerException ex)
                    {
                        throw new Exception("Error establishing a connection", ex);
                    }
                }
            }
            else
            {
                if (credentials != null)
                {
                    context.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
                }
            }
            var connectionType = ConnectionType.OnPrem;
            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, credentials, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
            spoConnection.ConnectionMethod = Model.ConnectionMethod.Credentials;
            return(spoConnection);
        }
        public override bool Execute()
        {
            bool processed = false;

            string generalSiteDirectoryUrl      = GetConfiguration("General.SiteDirectoryUrl");
            string generalSiteDirectoryListName = GetConfiguration("General.SiteDirectoryListName");
            string generalSiteCollectionUrl     = GetConfiguration("General.SiteCollectionUrl");
            string generalMailSMTPServer        = GetConfiguration("General.MailSMTPServer");
            string generalMailUser             = GetConfiguration("General.MailUser");
            string generalMailUserPassword     = GetConfiguration("General.MailUserPassword");
            string generalMailSiteAvailable    = GetConfiguration("General.MailSiteAvailable");
            string generalEncryptionThumbPrint = GetConfiguration("General.EncryptionThumbPrint");

            //Decrypt mail password
            generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint);
            string contosoCollaborationPromotedSiteName = GetConfiguration("ContosoCollaboration.PromotedSiteName");
            string contosoCollaborationPromotedSiteUrl  = GetConfiguration("ContosoCollaboration.PromotedSiteUrl");
            string contosoCollaborationThemeName        = GetConfiguration("ContosoCollaboration.ThemeName");
            //On-Prem settings
            string generalOnPremWebApplication = GetConfiguration("General.OnPremWebApplication");

            try
            {
                SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager();
                //FeatureManager featureManager = new FeatureManager();
                //ListManager listManager = new ListManager();
                //PageManager pageManager = new PageManager();
                //SecurityManager securityManager = new SecurityManager();
                //NavigationManager navigationManager = new NavigationManager();
                //BrandingManager brandingManager = new BrandingManager();


                string tempSharePointUrl = this.SharePointProvisioningData.Url;
                string siteCollectionUrl = this.CreateOnPremises ? generalOnPremWebApplication : generalSiteCollectionUrl;

                // issue the final SharePoint url
                SharePointProvisioningData.Url = this.GetNextSiteCollectionUrl(generalSiteDirectoryUrl, generalSiteDirectoryListName, siteCollectionUrl);

                //update site directory status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, tempSharePointUrl, this.SharePointProvisioningData.Url, "Provisioning");

                //complete the site data
                this.SharePointProvisioningData.Template            = "STS#0";
                this.SharePointProvisioningData.SiteOwner           = this.SharePointProvisioningData.Owners[0];
                this.SharePointProvisioningData.Lcid                = 1033;
                this.SharePointProvisioningData.TimeZoneId          = 3;
                this.SharePointProvisioningData.StorageMaximumLevel = 100;
                this.SharePointProvisioningData.StorageWarningLevel = 80;

                //create the site collection
                this.AddSiteCollection(this.SharePointProvisioningData);

                //enable features
                // Document ID Service (DocID) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("b50e3104-6812-424f-a011-cc90e6327318"));
                // Search Server Web Parts and Templates (SearchMaster) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("9c0834e1-ba47-4d49-812b-7d4fb6fea211"));
                // Workflows (Workflows) site collection feature
                this.CreatedSiteContext.Site.ActivateFeature(new Guid("0af5989a-3aea-4519-8ab0-85d91abe39ff"));
                // Metadata Navigation and Filtering (MetaDataNav) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("7201d6a4-a5d3-49a1-8c19-19c4bac6e668"));
                // Community Site Feature (CommunitySite) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("961d6a9c-4388-4cf2-9733-38ee8c89afd4"));
                // Project Functionality (ProjectFunctionality) site feature
                this.CreatedSiteContext.Web.ActivateFeature(new Guid("e2f2bb18-891d-4812-97df-c265afdba297"));

                // Picture library called Media
                this.CreatedSiteContext.Web.CreateList(Microsoft.SharePoint.Client.ListTemplateType.PictureLibrary, "Media", false);
                // Promoted Links library called Links
                this.CreatedSiteContext.Web.CreateList(new Guid("192efa95-e50c-475e-87ab-361cede5dd7f"), 170, "Links", false);

                // Update existing list settings for the documents library and the blog post library
                this.CreatedSiteContext.Web.UpdateListVersioning("Documents", true);

                //Remove the "Project Summary" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Project Summary", "home.aspx");
                //Remove the "Get started with your site" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Get started with your site", "home.aspx");
                //Remove the "Documents" web part
                this.CreatedSiteContext.Web.DeleteWebPart("SitePages", "Documents", "home.aspx");

                //Add links web part to the home page
                Guid          linksID         = this.CreatedSiteContext.Web.GetListID("Links");
                WebPartEntity promotedLinksWP = new WebPartEntity();
                promotedLinksWP.WebPartXml   = WpPromotedLinks(linksID, string.Format("{0}{1}/Lists/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "Links"), string.Format("{0}{1}/SitePages/{2}", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Name, "home.aspx"), "$Resources:core,linksList");
                promotedLinksWP.WebPartIndex = 2;
                promotedLinksWP.WebPartTitle = "Links";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", promotedLinksWP, "home.aspx", 2, 2, false);

                //Add html to the home page wiki
                this.CreatedSiteContext.Web.AddHtmlToWikiPage("SitePages", "Hello <strong>SharePoint Conference</strong> from spc403<br/><br/><br/>", "home.aspx", 1, 1);

                //add additional pages
                string siteMembersPage = "site members.aspx";
                string siteMembersUrl  = this.CreatedSiteContext.Web.AddWikiPage("Site Pages", siteMembersPage);
                this.CreatedSiteContext.Web.AddLayoutToWikiPage("SitePages", WikiPageLayout.TwoColumns, siteMembersPage);
                //Add site members web parts
                WebPartEntity wpSiteUsers = new WebPartEntity();
                wpSiteUsers.WebPartXml   = WpSiteUsers("Site owners", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Owners")));
                wpSiteUsers.WebPartIndex = 0;
                wpSiteUsers.WebPartTitle = "Site owners";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, false);

                wpSiteUsers.WebPartXml   = WpSiteUsers("Site visitors", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Visitors")));
                wpSiteUsers.WebPartIndex = 1;
                wpSiteUsers.WebPartTitle = "Site visitors";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 1, true);

                wpSiteUsers.WebPartXml   = WpSiteUsers("Site members", this.CreatedSiteContext.Web.GetGroupID(String.Format("{0} {1}", this.SharePointProvisioningData.Title, "Members")));
                wpSiteUsers.WebPartIndex = 0;
                wpSiteUsers.WebPartTitle = "Site members";
                this.CreatedSiteContext.Web.AddWebPartToWikiPage("SitePages", wpSiteUsers, siteMembersPage, 1, 2, false);

                //Update the quick launch navigation
                //First delete all quicklaunch entries
                this.CreatedSiteContext.Web.DeleteAllQuickLaunchNodes();

                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,nav_Home", null, "", NavigationType.QuickLaunch);
                //csomService.AddNavigationNode(this.SiteToProvision, "$Resources:core,BlogQuickLaunchTitle", new Uri(this.BlogSite.Url), "News & Trending", true);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,DiscussionsTab", new Uri(string.Format("{0}/Lists/Community%20Discussion/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                string notebookPath = string.Format("{0}/SiteAssets/{1} Notebook", this.SharePointProvisioningData.Url, this.SharePointProvisioningData.Title);
                notebookPath = HttpUtility.UrlPathEncode(notebookPath, false).Replace("/", "%2F");
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,SiteNotebookLink", new Uri(string.Format("{0}/_layouts/15/WopiFrame.aspx?sourcedoc={1}&action=editnew", this.SharePointProvisioningData.Url, notebookPath)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,taskList", new Uri(string.Format("{0}/Lists/Tasks/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,calendarList", new Uri(string.Format("{0}/Lists/Calendar/calendar.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,shareddocuments_Title_15", new Uri(string.Format("{0}/Shared Documents/Forms/AllItems.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,linksList", new Uri(string.Format("{0}/Lists/Links/Tiles.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,GrpMedia", new Uri(string.Format("{0}/Media/Forms/Thumbnails.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:spscore,Members_QuickLaunch", new Uri(string.Format("{0}/{1}", this.SharePointProvisioningData.Url, siteMembersUrl)), "", NavigationType.QuickLaunch);
                this.CreatedSiteContext.Web.AddNavigationNode("$Resources:core,category_SiteContents", new Uri(string.Format("{0}/_layouts/15/viewlsts.aspx", this.SharePointProvisioningData.Url)), "", NavigationType.QuickLaunch);

                // Insert demo promoted links list item
                if (contosoCollaborationPromotedSiteName.Length > 0 || contosoCollaborationPromotedSiteUrl.Length > 0)
                {
                    AddPromotedSiteLink(this.CreatedSiteContext, this.CreatedSiteContext.Web, "Links", contosoCollaborationPromotedSiteName, contosoCollaborationPromotedSiteUrl);
                }

                if (!this.CreateOnPremises)
                {
                    // add owners to site collection administrators
                    List <UserEntity> adminLogins = new List <UserEntity>();

                    int i = 0;
                    foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                    {
                        adminLogins.Add(new UserEntity()
                        {
                            Email     = owner.Email,
                            LoginName = owner.Login,
                            Title     = owner.Name,
                        });
                        i++;
                    }

                    Tenant tenant = new Tenant(this.AppOnlyClientContext);
                    tenant.AddAdministrators(adminLogins, new Uri(this.SharePointProvisioningData.Url), true);

                    // Everyone reader
                    this.CreatedSiteContext.Web.AddReaderAccess();
                }

                // Apply themes
                string themeRoot      = Path.Combine(this.AppRootPath, String.Format(@"Themes\{0}", contosoCollaborationThemeName));
                string spColorFile    = Path.Combine(themeRoot, string.Format("{0}.spcolor", contosoCollaborationThemeName));
                string spFontFile     = Path.Combine(themeRoot, string.Format("{0}.spfont", contosoCollaborationThemeName));
                string backgroundFile = Path.Combine(themeRoot, string.Format("{0}bg.jpg", contosoCollaborationThemeName));
                string logoFile       = Path.Combine(themeRoot, string.Format("{0}logo.png", contosoCollaborationThemeName));

                // Deploy theme files to root web, if they are not there and set it as active theme for the site
                string themeColorFileString       = "";
                string themeFontFileString        = "";
                string themeBackgroundImageString = "";

                if (!String.IsNullOrEmpty(themeRoot))
                {
                    themeColorFileString = this.CreatedSiteContext.Web.UploadThemeFile(themeRoot).ServerRelativeUrl;
                }
                if (!String.IsNullOrEmpty(spColorFile))
                {
                    themeFontFileString = this.CreatedSiteContext.Web.UploadThemeFile(spColorFile).ServerRelativeUrl;
                }

                if (!String.IsNullOrWhiteSpace(backgroundFile))
                {
                    themeBackgroundImageString = this.CreatedSiteContext.Web.UploadThemeFile(backgroundFile).ServerRelativeUrl;
                }

                this.CreatedSiteContext.Web.CreateComposedLookByUrl(contosoCollaborationThemeName, themeColorFileString, themeFontFileString, themeBackgroundImageString, String.Empty);
                this.CreatedSiteContext.Web.SetComposedLookByUrl(contosoCollaborationThemeName);

                //Seems to be broken at the moment...to be investigated
                //brandingManager.SetSiteLogo(this.CreatedSiteContext, this.CreatedSiteContext.Web, logoFile);

                // Update status
                siteDirectoryManager.UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Available");

                // Send mail to owners
                List <String> mailTo        = new List <string>();
                string        ownerNames    = "";
                string        ownerAccounts = "";

                foreach (SharePointUser owner in this.SharePointProvisioningData.Owners)
                {
                    mailTo.Add(owner.Email);

                    if (ownerNames.Length > 0)
                    {
                        ownerNames    = ownerNames + ", ";
                        ownerAccounts = ownerAccounts + ", ";
                    }
                    ownerNames    = ownerNames + owner.Name;
                    ownerAccounts = ownerAccounts + owner.Login;
                }

                // send email to notify the use of successful provisioning
                string mailBody = String.Format(generalMailSiteAvailable, this.SharePointProvisioningData.Title, this.SharePointProvisioningData.Url, ownerNames, ownerAccounts);
                MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site is ready to be used", mailBody);
            }
            catch (Exception ex)
            {
                //log error
                new SiteDirectoryManager().UpdateSiteDirectoryStatus(this.SiteDirectorySiteContext, this.SiteDirectorySiteContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryListName, this.SharePointProvisioningData.Url, "Error during provisioning", ex);
            }

            return(processed);
        }
Beispiel #26
0
        public void GetBase64EncodedValueTest()
        {
            var result = EncryptionUtility.Base64Encode("photo search");

            Assert.AreEqual(result, "cGhvdG8gc2VhcmNo");
        }
        protected override void ProcessRecord()
        {
            Uri tenantUri = null;

            if (string.IsNullOrEmpty(TenantUrl) && PnPConnection.CurrentConnection != null)
            {
                HttpClient client   = new HttpClient();
                var        uri      = new Uri(PnPConnection.CurrentConnection.Url);
                var        uriParts = uri.Host.Split('.');
                if (uriParts[0].ToLower().EndsWith("-admin"))
                {
                    tenantUri =
                        new Uri(
                            $"{uri.Scheme}://{uriParts[0].ToLower().Replace("-admin", "")}.{string.Join(".", uriParts.Skip(1))}{(!uri.IsDefaultPort ? ":" + uri.Port : "")}");
                }
                else
                {
                    tenantUri = new Uri($"{uri.Scheme}://{uri.Authority}");
                }
            }
            else if (!string.IsNullOrEmpty(TenantUrl))
            {
                tenantUri = new Uri(TenantUrl);
            }
            else
            {
                throw new InvalidOperationException("Either a connection needs to be made by Connect-PnPOnline or TenantUrl and Credentials needs to be specified");
            }

            var    tenantId = Microsoft.SharePoint.Client.TenantExtensions.GetTenantIdByUrl(tenantUri.ToString());
            string password;
            string username;

            if (ParameterSpecified(nameof(Credentials)))
            {
                password = EncryptionUtility.ToInsecureString(Credentials.Password);
                username = Credentials.UserName;
            }
            else if (PnPConnection.CurrentConnection != null)
            {
                password = EncryptionUtility.ToInsecureString(PnPConnection.CurrentConnection.PSCredential.Password);
                username = PnPConnection.CurrentConnection.PSCredential.UserName;
            }
            else
            {
                throw new InvalidOperationException("Either a connection needs to be made by Connect-PnPOnline or Credentials needs to be specified");
            }

            GenericToken token = null;

            if (ParameterSpecified(nameof(Resource)) && !string.IsNullOrEmpty(Resource))
            {
                token = GenericToken.AcquireV1Token(tenantId, ClientId, username, password, Resource);
            }

            if (ParameterSpecified(nameof(Scopes)) && Scopes.Count > 0)
            {
                token = GenericToken.AcquireV2Token(tenantId, ClientId, username, password, Scopes.ToArray());
            }

            if (SetAsCurrent.IsPresent)
            {
                if (PnPConnection.CurrentConnection != null)
                {
                    if (token == null)
                    {
                        throw new InvalidOperationException($"-{nameof(SetAsCurrent)} can't be performed as no valid token could be retrieved");
                    }

                    PnPConnection.CurrentConnection.AddToken(Enums.TokenAudience.Other, token);
                }
                else
                {
                    throw new InvalidOperationException($"-{nameof(SetAsCurrent)} can only be used when having an active connection using Connect-PnPOnline");
                }
            }

            if (Decoded.IsPresent)
            {
                WriteObject(token.ParsedToken);
            }
            else
            {
                WriteObject(token.AccessToken);
            }
        }
Beispiel #28
0
        public async Task GetBearerTokenTest()
        {
            string formattedToken     = EncryptionUtility.DecodeBase64(_consumerKey) + ":" + EncryptionUtility.DecodeBase64(_consumerSecret);
            string formattedUrl       = string.Format(_searchUrl, "nature", 20);
            string authorizationToken = "Bearer " + await HttpUtility.GetTwitterBearerToken(_authorizationUrl, formattedToken);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(authorizationToken));
        }
        public async Task <IActionResult> GetCASSContactByToken(string code)
        {
            var id = EncryptionUtility.DecryptStringHex(code, _encryptionKey);

            if (!string.IsNullOrEmpty(id))
            {
                MicrosoftDynamicsCRMcontact userContact = null;
                try
                {
                    var userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);
                    userContact = await _dynamicsClient.GetContactById(userSettings.ContactId);
                }
                catch (ArgumentNullException)
                {
                    // anonymous
                }

                var contactId = Guid.Parse(id);
                // query the Dynamics system to get the contact record.
                var contact = await _dynamicsClient.GetContactById(contactId);

                if (userContact == null)
                {
                    return(new JsonResult(new CASSPublicContact
                    {
                        Id = contact.Contactid,
                        token = code,
                        shortName = contact.Firstname.First() + " " + contact.Lastname,
                        IsWrongUser = false
                    }));
                }

                if (contact != null &&
                    userContact.Firstname != null &&
                    contact.Firstname.StartsWith(userContact.Firstname.Substring(0, 1), true,
                                                 CultureInfo.CurrentCulture) &&
                    userContact.Lastname != null && userContact.Lastname.ToLower() == contact.Lastname.ToLower() &&
                    userContact.Birthdate != null && userContact.Birthdate.Value.Date.ToShortDateString() ==
                    contact.Birthdate.Value.Date.ToShortDateString()
                    )
                {
                    return(new JsonResult(new CASSPrivateContact
                    {
                        Id = contact.Contactid,
                        token = code,
                        shortName = contact.Firstname + " " + contact.Lastname,
                        dateOfBirth = contact.AdoxioDateofbirthshortdatestring,
                        gender = ((ViewModels.Gender?)contact.AdoxioGendercode).ToString(),
                        streetAddress = contact.Address1Line1,
                        city = contact.Address1City,
                        province = contact.Address1Stateorprovince,
                        postalCode = contact.Address1Postalcode,
                        country = contact.Address1Country
                    }));
                }
                return(new JsonResult(new CASSPublicContact
                {
                    Id = contact.Contactid,
                    token = code,
                    shortName = contact.Firstname.First() + " " + contact.Lastname,
                    IsWrongUser = true
                }));
            }

            return(BadRequest());
        }
Beispiel #30
0
 public UserServices(APITesterDBContext context, IMapper mapper, EncryptionUtility encryption)
 {
     _context    = context;
     _mapper     = mapper;
     _encryption = encryption;
 }