예제 #1
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ExpenseLogContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //---https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = utils.GetAppSetting("EL_GOOGLE_AUTH_CLIENT_ID"),
                ClientSecret = utils.GetAppSetting("EL_GOOGLE_AUTH_CLIENT_SECRET")
            });
        }
예제 #2
0
        public async Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();
            var apiKey           = utils.GetAppSetting("EL_SENDGRID_API_KEY");
            var client           = new SendGridClient(apiKey);
            var from             = new EmailAddress(utils.GetAppSetting("EL_MAIL_SENDER", "*****@*****.**"));
            var subject          = message.Subject;
            var to               = new EmailAddress(message.Destination);
            var plainTextContent = message.Body;
            var htmlContent      = $"<strong>{message.Body}</strong>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response         = await client.SendEmailAsync(msg);

            return;
        }
예제 #3
0
        private string GetRequestParameter(string paramName)
        {
            string result = String.Empty;

            if (System.Web.HttpContext.Current.Request.Params[paramName] != null)
            {
                ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();
                result = utils.Decrypt(System.Web.HttpContext.Current.Request.Params[paramName].Trim());
            }

            if (result == String.Empty)
            {
                throw new Exception($"HttpContext.Current.Request Parameter '{paramName}' is null or empty.");
            }

            return(result);
        }
        private void SetVariables2ViewBag(ExpenseRecord expenseRecord = null)
        {
            //--- Get current user
            string userId = User.Identity.GetUserId();

            //--- Set User ID
            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();
            ViewBag.UserID = utils.Encrypt(userId);

            //--- Set attachmentUploadWebAPIUrl
            string webAPIUri = utils.GetAppSetting("EL_EXPENSE_LOG_WEB_API_URI");
            Uri    uri       = new Uri(new Uri(webAPIUri), "/api/attachment/upload");

            ViewBag.AttachmentUploadWebAPIUrl = uri.ToString();

            //--- Set Lists
            SetViewBagSelectLists(userId, expenseRecord);
        }
        private async Task <bool> DeleteAttachmentFilesAsync(IEnumerable <string> attachments)
        {
            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();

            string attachmentNameListJson = utils.Encrypt(JsonConvert.SerializeObject(attachments));

            using (HttpClient client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    content.Add(new StringContent(attachmentNameListJson, Encoding.UTF8, "application/json"), "attachmentNameList");
                    string requestUri = $"{utils.GetAppSetting("EL_EXPENSE_LOG_WEB_API_URI")}api/attachment/delete";

                    HttpResponseMessage result = await client.PostAsync(requestUri, content);

                    return(result.StatusCode == System.Net.HttpStatusCode.OK);
                }
            }
        }
예제 #6
0
        public string Get(string id, string name)
        {
            string result = "Invalid parameters";

            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();

            if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(name))
            {
                if (id.StartsWith("encrypt", StringComparison.CurrentCultureIgnoreCase))
                {
                    result = utils.Encrypt(name);
                }
                else
                if (id.StartsWith("decrypt", StringComparison.CurrentCultureIgnoreCase))
                {
                    result = utils.Decrypt(name);
                }
            }

            return(result);
        }
예제 #7
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            //--- Enable CORS (Cross Origin Resource Sharing)
            //--- Read more here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
            //--- Restrict who can access that WebAPI
            ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();
            string corsOrigins           = utils.GetAppSetting("EL_CORS_ORIGINS"); //--- gets comma separated list
            var    cors = new EnableCorsAttribute(corsOrigins, "*", "*");

            config.EnableCors(cors);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
예제 #8
0
        private void InitializeCloudBlobContainer()
        {
            if (_CloudBlobContainer == null)
            {
                ExpenseLogCommon.Utils utils = new ExpenseLogCommon.Utils();
                //--- Retrieve storage account information from connection string
                //--- How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(utils.GetAppSetting("EL_STORAGE_CONNECTION_STRING"));

                //--- Create a blob client for interacting with the blob service.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                _CloudBlobContainer = blobClient.GetContainerReference(utils.GetAppSetting("EL_STORAGE_BLOB_CONTAINER_NAME"));
                _CloudBlobContainer.CreateIfNotExists();

                //--- To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate
                //--- access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions
                //--- to allow public access to blobs in this container. Comment the line below to not use this approach and to use SAS. Then you can view the image
                //--- using: https://[InsertYourStorageAccountNameHere].blob.core.windows.net/webappstoragedotnet-imagecontainer/FileName
                _CloudBlobContainer.SetPermissions(new BlobContainerPermissions {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
            }
        }