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()); }
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()); }
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()); }
private async Task <MxReturnCode <bool> > DeseedStdUrdRole(GdprSeedRepo gdprSeedRepo, string urdName, Guid wstId) { MxReturnCode <bool> rc = new MxReturnCode <bool>($"MxIdentityDb.DeseedStdUrdRole(name={urdName ?? "[null]"})"); if ((gdprSeedRepo == null) || (string.IsNullOrWhiteSpace(urdName)) || (gdprSeedRepo.GetStdGdprUrdCode(urdName) == UrdCodeStd.Undefined)) { rc.SetError(3060401, MxError.Source.Param, $"gdprSeedRepo is null or urdName={urdName ?? "[null]"} is invalid"); } else { var resUrdExists = await gdprSeedRepo.IsExistStdUrdAsync(urdName); rc += resUrdExists; if (rc.IsSuccess()) { if (resUrdExists.GetResult() == false) { var resCreate = await gdprSeedRepo.CreateStdUrdAsync(urdName, wstId); rc += resCreate; } if (rc.IsSuccess()) { var identityRoleName = gdprSeedRepo.XlatUrdNameToIdentityRoleName(urdName); if (await _roleManager.FindByNameAsync(identityRoleName) != null) { rc.SetResult(true); } else { var idres = await _roleManager.CreateAsync(new IdentityRole() { Name = identityRoleName }); if (idres.Succeeded) { rc.SetError(3060402, MxError.Source.Sys, $"unable to create Identity Role {identityRoleName ?? "[null]"}"); } else { rc.SetResult(true); } } } if (rc.IsError(true)) { await gdprSeedRepo.DeleteStdUrdAsync(urdName); } } } return(rc); }
public async static Task <MxReturnCode <bool> > CreateRole(IAdminRepository repo, RoleManager <IdentityRole> roleManager, Guid wst, string gdprRoleName) { MxReturnCode <bool> rc = new MxReturnCode <bool>("IdentityDb.CreateRole()"); var identityRoleName = AdminRepository.GetIdentityRolename(gdprRoleName); if ((repo == null) || (roleManager == null) || (gdprRoleName == null) || (identityRoleName == null)) { rc.SetError(3160301, MxError.Source.Param, "repo, roleManager or gdprRoleName is null", MxMsgs.MxErrUnexpected); } else { try { if (await roleManager.RoleExistsAsync(identityRoleName) == false) { IdentityResult result = await roleManager.CreateAsync(new IdentityRole { Name = identityRoleName }); if (result.Succeeded == false) { rc.SetError(3160302, MxError.Source.Sys, WebErrorHandling.GetIdentityErrors(result, $"cannot create role {identityRoleName}")); } } if (rc.GetErrorCode() == MxErrorLog.UnknownError) { //if gdprname exists - setresult //create GDPR records; WST + URD and WXR record for each role 1) Admin 2) Controller 3) Standard 4) Guest 5) System (Guest) 6) Ghost (Guest) //var resCnt = await repository.CreateGDPRRole(gdprRoleName != null ? gdprRoleName : identityRoleName); //rc += resCnt; //if (res.IsSuccess()) //{ // rc.SetResult(true); //} } } catch (Exception e) { rc.SetError(3160303, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true); } } if (rc.IsError()) { //var role = await roleManager.FindByNameAsync(identityRoleName); //if (role != null) // await roleManager.DeleteAsync(role); } return(rc); }
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); }
public async static Task <MxReturnCode <int> > CreateUser(ISysRepository repo, UserManager <IdentityUser> userManager, string gdprRoleName, string password, string email, string fullName) { MxReturnCode <int> rc = new MxReturnCode <int>("IdentityDb.CreateUser()", -1); if ((repo == null) || (userManager == null) || (gdprRoleName == null) || (password == null) || (email == null) || (fullName == null)) { rc.SetError(3160101, MxError.Source.Param, "repo, userManager, roleName, password, email, or fullname is null", MxMsgs.MxErrUnexpected); } else { try { if (await IsExistsUser(repo, userManager, email) == true) { rc.SetResult(0); } else { if (await userManager.FindByEmailAsync(email) == null) { IdentityUser user = new IdentityUser() { UserName = email, Email = email }; await userManager.CreateAsync(user, password); IdentityResult result = await userManager.AddToRoleAsync(user, gdprRoleName); if (result.Succeeded == false) { rc.SetError(3160102, MxError.Source.Sys, WebErrorHandling.GetIdentityErrors(result, $"cannot create role {gdprRoleName}")); } } if (rc.GetErrorCode() == MxErrorLog.UnknownError) { //if (await repository.IsGdprUserExists(email) ) //var resCnt = await repository.CreateGDPRUser(); //rc += resCnt; //if (res.IsSuccess()) //{ // rc.SetResult(true); //} } rc.SetResult(1); } } catch (Exception e) { rc.SetError(3160102, MxError.Source.Exception, e.Message, MxMsgs.MxErrUnknownException, true); } if (rc.IsError()) { var user = await userManager.FindByEmailAsync(email); if (user != null) { await userManager.DeleteAsync(user); } } } return(rc); }
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()); }
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()); }
public async Task <MxReturnCode <bool> > CreateUrdAsync(string name, int roleCode, UrdStatus roleStatus, string purpose, string description, Guid wstId) { MxReturnCode <bool> rc = new MxReturnCode <bool>("AdminRepository.CreateUrdAsync()"); if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(purpose) || string.IsNullOrWhiteSpace(description) || (GdprUrd.IsValidRoleCode(roleCode) == false) || (wstId == Guid.Empty)) { rc.SetError(1010201, MxError.Source.Param, $"name={name ?? "[null]"} or purpose or description null or empty, or roleCode {roleCode} is invalid, or wstId is empty"); } else { try { if ((rc += CheckConnection()).IsSuccess()) { GdprUrd role = new GdprUrd { Name = name, RoleCode = roleCode, Purpose = purpose, Description = description, Status = (int)roleStatus }; var sql = "INSERT INTO GdprUrd(Name, RoleCode, Status, Purpose, Description) VALUES(@Name, @RoleCode, @Status, @Purpose, @Description);"; var resultCreateUrd = await db.ExecuteAsync(sql, role); if (resultCreateUrd != 1) { rc.SetError(1010202, MxError.Source.Data, $"unable to create role={name}"); } else { var resGetUrd = await GetUrdAsync(name); rc += resGetUrd; if ((rc.IsError()) || (resGetUrd.GetResult() == null)) { rc.SetError(1010203, MxError.Source.Data, $"unable to access new role={name}"); } { GdprWxr wxr = new GdprWxr { UrdId = resGetUrd.GetResult().Id, WstId = wstId }; sql = "INSERT INTO GdprWxr(@UrdId, WstId) VALUES(@UrdId, @WstId);"; var resultCreateWxr = await db.ExecuteAsync(sql, wxr); if (resultCreateWxr != 1) { rc.SetError(1010204, MxError.Source.Data, $"unable to create WXR for role={name}, WstId={wstId}"); } else { rc.SetResult(true); } } } } } catch (Exception e) { rc.SetError(1010205, MxError.Source.Exception, e.Message, MxMsgs.MxErrDbQueryException); } } return(rc); }
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()); }