Exemplo n.º 1
0
        static async Task <int> Main(string[] args)
        {
            MxReturnCode <int> rc = new MxReturnCode <int>($"{Program.WebAppName} v{Program.WebAppVersion}", 1);

            rc.Init(Assembly.GetExecutingAssembly(), "*****@*****.**", null, null, null, MxMsgs.SupportedCultures);

            Console.WriteLine(rc.GetInvokeDetails());

            var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("local.settings.json")
                         .Build();
            var conn = config?["ConnectionStrings:DefaultConnection"];  //03-12-18

            if (conn == null)
            {
                rc.SetError(2010101, MxError.Source.AppSetting, "config not built or ConnectionStrings:DefaultConnection not found");
            }
            else
            {
                using (IAdminRepo repo = new AdminRepo(conn))
                {
                    rc += await repo.GetUrdCountAsync();
                }
                if (rc.IsSuccess(true))
                {
                    Console.WriteLine($"Roles found = {rc.GetResult()}");
                    rc.SetResult(0);
                }
            }
            Console.WriteLine(rc.IsError(true) ? rc.GetErrorUserMsg() : $"Hello World!");
            Console.WriteLine(rc.IsError(true) ? rc.GetErrorTechMsg(): "no error");

            return(rc.GetResult());
        }
Exemplo n.º 2
0
        public async static Task <bool> IsExistsUser(ISysRepository repo, UserManager <IdentityUser> userManager, string email)
        {
            MxReturnCode <bool> rc = new MxReturnCode <bool>("IdentityDb.CreateUser()", false);

            if ((repo == null) || (userManager == null) || (email == null))
            {
                rc.SetError(3160201, MxError.Source.Param, "repo, userManager or email is null", MxMsgs.MxErrUnexpected);
            }
            else
            {
                try
                {
                    //check identity
                    var result = await repo.GetUserAsync(email);

                    rc += result;
                    if (result.IsSuccess())
                    {
                        rc.SetResult(true);
                    }
                    else
                    {
                        rc.SetResult(false);
                    }
                }
                catch (Exception e)
                {
                    rc.SetError(3160202, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
                }
            }
            return(rc.GetResult());
        }
Exemplo n.º 3
0
        public async static Task <bool> IsExistsRole(IAdminRepository repo, RoleManager <IdentityRole> roleManager, string gdprRolename)
        {
            MxReturnCode <bool> rc = new MxReturnCode <bool>("IdentityDb.IsExistsRole()", false);

            if ((repo == null) || (roleManager == null) || (gdprRolename == null))
            {
                rc.SetError(3160401, MxError.Source.Param, "repo, roleManager or rolename is null", MxMsgs.MxErrUnexpected);
            }
            else
            {
                try
                {
                    var identityRolename = AdminRepository.GetIdentityRolename(gdprRolename);
                    //check identity
                    var result = await repo.GetRoleAsync(gdprRolename);

                    rc += result;
                    if (result.IsSuccess())
                    {
                        rc.SetResult(true);
                    }
                    else
                    {
                        rc.SetResult(false);
                    }
                }
                catch (Exception e)
                {
                    rc.SetError(3160402, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
                }
            }
            return(rc.GetResult());
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnGetAsync(string msgJson)
        {
            MxReturnCode <IActionResult> rc = new MxReturnCode <IActionResult>("Index.OnGetAsync()", Page());

            try
            {
                using (IAdminRepository repository = new AdminRepository(_conn))
                {
                    var resCnt = await repository.GetRoleCountAsync();

                    rc += resCnt;
                    if (rc.IsSuccess())
                    {
                        URDCount = String.Format("URD Count = {0}", resCnt.GetResult());
                        SetPageStatusMsg("Database access ok", ExistingMsg.Keep);
                        rc.SetResult(Page());
                    }
                }
            }
            catch (Exception e)
            {
                rc.SetError(3130101, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
            }
            if (rc.IsError())
            {
                _logger.LogError(rc.GetErrorTechMsg());
                SetPageStatusMsg(rc.GetErrorUserMsgHtml(Startup.WebAppName, WebErrorHandling.GetMxRcReportToEmailBody()), ExistingMsg.Overwrite);
            }
            return(rc.GetResult());
        }
Exemplo n.º 5
0
        public async Task <IActionResult> OnGetAsync()
        {
            MxReturnCode <IActionResult> rc = new MxReturnCode <IActionResult>("Index.OnGetAsync()", Page());

            var userID = "[nobody logged-in]";
            var msg    = "unknown error";

            try
            {
                var loggedInUser = await _userManager.GetUserAsync(User);

                userID = loggedInUser?.Id ?? "[nobody logged-in]";
                msg    = $"{loggedInUser?.UserName ?? "nobody"} is logged-in. ";
                if (loggedInUser?.EmailConfirmed == false)
                {
                    msg += "Check your emails to complete your registration";
                }

                using (IAdminRepo repo = new AdminRepo(_config?.GetConnectionString("DefaultConnection")))
                {
                    var resCnt = await repo.GetUrdCountAsync();

                    rc += resCnt;
                    if (rc.IsError())
                    {
                        DatabaseStatus = "Database access failed";
                    }
                    else
                    {
                        DatabaseStatus = $"Database access ok, Role Count = {resCnt.GetResult()}";
                        rc.SetResult(Page());
                    }
                }
            }
            catch (Exception e)
            {
                rc.SetError(3040101, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
            }
            if (rc.IsError(true))
            {
                SetPageStatusMsg(rc.GetErrorUserMsgHtml(userID), ExistingMsg.Overwrite);
            }
            else
            {
                SetPageStatusMsg(msg, ExistingMsg.Overwrite);
            }

            return(rc.GetResult());
        }
Exemplo n.º 6
0
        static async Task <int> Main(string[] args)  //03-12-18 made async and returns int not void
        {
            MxUserMsg.Init(Assembly.GetExecutingAssembly(), MxMsgs.SupportedCultures);
            MxReturnCode <int> rc = new MxReturnCode <int>("Main()", -1, "*****@*****.**");

            try                                                     //03-12-18
            {
                IWebHost host = CreateWebHostBuilder(args).Build(); //calls Startup.ConfigureServices()
                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;
                    if (services == null)
                    {
                        rc.SetError(3130101, MxError.Source.Sys, "scope.ServiceProvider is null");
                    }
                    else
                    {
                        var userManager = services.GetRequiredService <UserManager <IdentityUser> >();
                        var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();
                        var config      = services.GetRequiredService <IConfiguration>();
                        if ((userManager == null) || (roleManager == null) || (config == null))
                        {
                            rc.SetError(3130102, MxError.Source.Sys, "userManager or roleManager or config is null");
                        }
                        else
                        {
                            var result = await SeedDb.EnsureDataPresentAsync(config, userManager, roleManager);

                            rc += result;
                            if (result.IsSuccess())
                            {
                                host.Run();         //calls Startup.Configure()
                                rc.SetResult(0);    //success - webapp has completed
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                rc.SetError(3010103, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
            }
            return(rc.GetResult());  //03-12-18
        }
Exemplo n.º 7
0
        static async Task <int> Main(string[] args)  //03-12-18 made async and returns int not void
        {
            MxReturnCode <int> rc = new MxReturnCode <int>("Main()", -1);

            try
            {
                IWebHost host = CreateWebHostBuilder(args).Build();      //calls Startup.ConfigureServices()
                using (var scope = host?.Services?.CreateScope())
                {
                    var services = scope.ServiceProvider;
                    if (services == null)
                    {
                        rc.SetError(3050101, MxError.Source.Sys, "scope.ServiceProvider is null");
                    }
                    else
                    {
                        var mxIdentitySeedDb = services.GetRequiredService <IMxIdentitySeedDb>();
                        if (mxIdentitySeedDb == null)
                        {
                            rc.SetError(3050102, MxError.Source.Sys, "mxIdentityDb is null");
                        }
                        else
                        {
                            rc = await mxIdentitySeedDb.SetupAsync();

                            if (rc.IsSuccess(true))
                            {
                                host.Run();      //calls Startup.Configure()
                                rc.SetResult(0); //success - webapp has completed
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                rc.SetError(3050103, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
            }
            return(rc.GetResult());
        }
Exemplo n.º 8
0
        static async Task <int> Main(string[] args) //Uses Dapper/Gdpr.Domain Repository classes to access the database
        {
            MxUserMsg.Init(Assembly.GetExecutingAssembly(), MxMsgs.SupportedCultures);

            MxReturnCode <int> rc = new MxReturnCode <int>(string.Format("{0} v{1}", "ReturnCodeApp()", GetVersion()), 1, "*****@*****.**");

            var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("local.settings.json")
                         .Build();
            var conn = config?["ConnectionStrings:DefaultConnection"];  //03-12-18

            if (conn == null)
            {
                rc.SetError(2010101, MxError.Source.AppSetting, "config not built or ConnectionStrings:DefaultConnection not found");
            }
            else
            {
                using (IAdminRepository repository = new AdminRepository(conn))
                {
                    rc += await repository.GetRoleCountAsync();
                }
                if (rc.IsSuccess())
                {
                    Console.WriteLine(@"URD Count = {0}", rc.GetResult());
                }
            }
            if (rc.IsError())
            {
                Console.WriteLine(rc.GetErrorUserMsg());
                Console.WriteLine(rc.GetErrorTechMsg());
            }
            else
            {
                Console.WriteLine("ends ok");
            }

            return(rc.IsSuccess() ? 0 : -1);
        }
Exemplo n.º 9
0
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            MxReturnCode <IActionResult> rc = new MxReturnCode <IActionResult>("Account.ExternalLogin.OnGetCallbackAsync()", RedirectToPage("./Login", new { ReturnUrl = returnUrl }));

            returnUrl = returnUrl ?? Url.Content("~/");
            if ((returnUrl == null) || (remoteError != null))
            {
                rc.SetError(3020101, MxError.Source.Service, $"Error from external provider: {remoteError}");
            }
            else
            {
                try
                {
                    var info = await _signInManager.GetExternalLoginInfoAsync();

                    if (info == null)
                    {
                        rc.SetError(3020102, MxError.Source.Service, "Error loading external login information.");
                    }
                    else
                    {   // Sign in the user with this external login provider if the user already has a login.
                        var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : false);

                        if (result.Succeeded)
                        {
                            SetPageStatusMsg($"Welcome {info.Principal.Identity.Name} you have been authenticated by {info.LoginProvider}", ExistingMsg.Overwrite);
                            rc.SetResult(LocalRedirect(returnUrl));
                        }
                        else if (result.IsLockedOut)
                        {
                            rc.SetError(3020103, MxError.Source.Sys, "user account locked out", MxMsgs.MxErrAccountLockout);
                        }
                        else if (result.RequiresTwoFactor)
                        {
                            SetPageStatusMsg($"Welcome {info.Principal.Identity.Name} you have been authenticated by {info.LoginProvider}", ExistingMsg.Overwrite);
                            rc.SetResult(LocalRedirect($"~/Identity/Account/LoginWith2fa?ReturnUrl={returnUrl ?? "%2f"}"));
                        }
                        else
                        { // If the user does not have an account, then ask the user to create an account.
                            ReturnUrl     = returnUrl;
                            LoginProvider = info.LoginProvider;
                            if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                            {
                                Input = new InputModel
                                {
                                    Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                                };
                                ProviderEmail = info.Principal.FindFirstValue(ClaimTypes.Email);
                            }
                            rc.SetResult(Page());
                        }
                    }
                }
                catch (Exception e)
                {
                    rc.SetError(3020104, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
                }
            }
            if (rc.IsError(true))
            {
                SetPageStatusMsg(rc.GetErrorUserMsgHtml(), ExistingMsg.Overwrite);
            }

            return(rc.GetResult());
        }
Exemplo n.º 10
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            MxReturnCode <IActionResult> rc = new MxReturnCode <IActionResult>("Account.ExternalLogin.OnPostConfirmationAsync()", RedirectToPage("./Login", new { ReturnUrl = returnUrl }));

            try
            {      // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    rc.SetError(3090201, MxError.Source.Sys, "Error loading external login information during confirmation.");
                }
                else
                {
                    if (ModelState.IsValid == false)
                    {
                        rc.SetError(3090202, MxError.Source.Data, WebErrorHandling.GetModelStateErrors(ModelState, WebErrorHandling.FormValidationErrorPreamble));
                    }
                    else
                    {
                        var providerEmail = ProviderEmail;
                        if (providerEmail != Input.Email)
                        {
                            rc.SetError(3090203, MxError.Source.Sys, $"{providerEmail} from provider != {Input.Email} from form", MxMsgs.MxErrUnexpected);
                        }
                        else
                        {
                            IdentityUser user = null;
                            if (await _userManager.FindByEmailAsync(providerEmail) == null)
                            {
                                user = new IdentityUser {
                                    UserName = providerEmail, Email = providerEmail, EmailConfirmed = true
                                };
                                var result = await _userManager.CreateAsync(user);

                                if (result.Succeeded == false)
                                {
                                    rc.SetError(3090204, MxError.Source.Sys, WebErrorHandling.GetIdentityErrors(result, $"cannot create user account for {providerEmail}"));
                                }
                            }
                            if (rc.GetErrorCode() != 3090204)
                            {
                                if ((user = await _userManager.FindByEmailAsync(providerEmail)) == null)
                                {
                                    rc.SetError(3090205, MxError.Source.Sys, $"Unable to load user {providerEmail}", MxMsgs.MxErrUnexpected, true);
                                }
                                else
                                {
                                    var result = await _userManager.AddLoginAsync(user, info);

                                    if (result.Succeeded == false)
                                    {
                                        rc.SetError(3090206, MxError.Source.Sys, WebErrorHandling.GetIdentityErrors(result, $"cannot add  {info.LoginProvider} login  for {providerEmail}"));
                                    }
                                    else
                                    {
                                        await _signInManager.SignInAsync(user, isPersistent : false);

                                        SetPageStatusMsg($"Welcome {info.Principal.Identity.Name} you have been authenticated by {info.LoginProvider}", ExistingMsg.Overwrite);
                                        rc.SetResult(LocalRedirect(returnUrl));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                rc.SetError(3090207, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
            }
            if (rc.IsError(true))
            {
                SetPageStatusMsg(rc.GetErrorUserMsgHtml(), ExistingMsg.Overwrite);
            }

            return(rc.GetResult());
        }
Exemplo n.º 11
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            MxReturnCode <IActionResult> rc = new MxReturnCode <IActionResult>("Account.Manage.Register.OnPostAsync()", Page());

            string userId = null;

            returnUrl = returnUrl ?? Url.Content("~/");
            if (!ModelState.IsValid)
            {
                rc.SetError(3010101, MxError.Source.User, WebErrorHandling.GetModelStateErrors(ModelState, WebErrorHandling.FormValidationErrorPreamble));
            }
            else
            {
                try
                {
                    if (await ValidateForm() == false)
                    {
                        rc.SetError(3010102, MxError.Source.User, WebErrorHandling.GetModelStateErrors(ModelState, WebErrorHandling.FormValidationErrorPreamble));
                    }
                    else
                    {
                        var user = new IdentityUser {
                            UserName = Input.Email, Email = Input.Email
                        };
                        var result = await _userManager.CreateAsync(user, Input.Password);

                        if (result.Succeeded == false)
                        {
                            rc.SetError(3010103, MxError.Source.Sys, WebErrorHandling.GetIdentityErrors(result, $"cannot register user {Input.Email}"));
                        }
                        else
                        {
                            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                            var callbackUrl = Url.Page(
                                "/Account/ConfirmEmail",
                                pageHandler: null,
                                values: new { userId = user.Id, code = code },
                                protocol: Request.Scheme);

                            await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                              $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                            userId = user?.Id;
                            await _signInManager.SignInAsync(user, isPersistent : false);

                            rc.SetResult(LocalRedirect(returnUrl));
                        }
                    }
                }
                catch (Exception e)
                {
                    rc.SetError(3010104, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true);
                }
            }
            if (rc.IsError(true))
            {
                SetPageStatusMsg(rc.GetErrorUserMsgHtml(userId), ExistingMsg.Overwrite);
            }

            return(rc.GetResult());
        }