protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); // Grab the user's login information from Identity AppUserState appUserState = new AppUserState(); if (User is ClaimsPrincipal) { var user = User as ClaimsPrincipal; var claims = user.Claims.ToList(); var userStateString = GetClaim(claims, "userState"); //var name = GetClaim(claims, ClaimTypes.Name); //var id = GetClaim(claims, ClaimTypes.NameIdentifier); if (!string.IsNullOrEmpty(userStateString)) { appUserState.FromString(userStateString); } } AppUserState = appUserState; ViewData["UserState"] = AppUserState; ViewData["ErrorDisplay"] = ErrorDisplay; }
public ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { var user = Helpers.User.ValidateAuthentication(model.UserName, model.Password); if (user == null) { ModelState.AddModelError("", "Login failed!"); return(View("Login", model)); } if (user.IsActive == false) { ModelState.AddModelError("", "Inactive account!"); return(View("Login", model)); } AppUserState appUserState = new AppUserState(user); IdentitySignin(appUserState, appUserState.UserId.ToString(), model.RememberMe); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Home")); } return(View("Login", model)); }
/// <inheritdoc /> /// <summary> /// ErrorDisplay control that holds page level error information /// </summary> protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); if (!SettingsManager.Settings.Any()) { SettingsManager.Initiase(Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "inReachWeb")); } // Grab the user's login information from Identity var appUserState = new AppUserState(); if (User is ClaimsPrincipal) { var ucl = ClaimsPrincipal.Current.Claims.ToList().FirstOrDefault(c => c.Type == "userState"); var userStateString = ucl?.Value; Logger.Info($"ucl {userStateString}"); if (!string.IsNullOrEmpty(userStateString)) { appUserState.FromString(userStateString); } } AppUserState = appUserState; Logger.Info($"initialise user is {AppUserState.Name}"); }
public ActionResult LogOn(string email, string password, bool rememberMe, string returnUrl, bool emailPassword) { if (emailPassword) { if (ModelState.ContainsKey("emailpassword")) ModelState.Remove("emailpassword"); return EmailPassword(email); } var user = busUser.ValidateUserAndLoad(email, password); if (user == null) { ErrorDisplay.ShowError(busUser.ErrorMessage); return View(ViewModel); } AppUserState appUserState = new AppUserState() { Email = user.Email, Name = user.Name, UserId = user.Id, Theme = user.Theme, IsAdmin = user.IsAdmin }; //IssueAuthTicket(appUserState, rememberMe); IdentitySignin(appUserState, user.OpenId, rememberMe); if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); return RedirectToAction("New", "Snippet", null); }
public void IdentitySignin(AppUserState appUserState, string providerKey = null, bool isPersistent = false) { var claims = new List <Claim>(); // create *required* claims claims.Add(new Claim(ClaimTypes.NameIdentifier, appUserState.UserId)); claims.Add(new Claim(ClaimTypes.Name, appUserState.UserName)); // serialized AppUserState object claims.Add(new Claim("userState", appUserState.ToString())); claims.Add(new Claim("LoginUserId", appUserState.UserId)); claims.Add(new Claim("EmployeeId", appUserState.EmployeeId.ToString())); claims.Add(new Claim("LoginRoleId", appUserState.RoleId.ToString())); claims.Add(new Claim("LoginRoleName", appUserState.RoleName.ToString())); var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); // add to user here! AuthenticationManager.SignIn(new AuthenticationProperties() { AllowRefresh = true, IsPersistent = isPersistent, ExpiresUtc = DateTime.UtcNow.AddMinutes(30) }, identity); }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); // Grab the user's login information from Identity AppUserState objAppUserState = new AppUserState(); if (User is ClaimsPrincipal) { var user = User as ClaimsPrincipal; var claims = user.Claims.ToList(); var userStateString = GetClaim(claims, "userState"); ViewData["LoginUserId"] = GetClaim(claims, "LoginUserId"); ViewData["EmployeeId"] = GetClaim(claims, "EmployeeId"); ViewData["LoginRoleId"] = GetClaim(claims, "LoginRoleId"); ViewData["LoginRoleName"] = GetClaim(claims, "LoginRoleName"); if (!string.IsNullOrEmpty(userStateString)) { objAppUserState.FromString(userStateString); } } F_AppUserState = objAppUserState; ViewData["UserState"] = F_AppUserState; ViewData["ErrorDisplay"] = ErrorDisplay; }
//public Task JoinGroup(string groupName) //{ // return Groups.Add(Context.ConnectionId, groupName); //} //public Task LeaveGroup(string groupName) //{ // return Groups.Remove(Context.ConnectionId, groupName); //} public IEnumerable <ExecutiveDashboardTickerModel> getExecutiveDasboardData(AppUserState appUserState) { ExecutiveDashboardTickerModel model = new ExecutiveDashboardTickerModel { AppUserState = appUserState }; return(_executiveDashboardTicker.GetDashboardTickerData(model)); }
public override Task OnConnected() { FingerprintsModel.AppUserState appUserState = new AppUserState { Name = Context.User.Identity.Name, ConnectionId = Context.ConnectionId, }; _connections.Add(appUserState.Name, appUserState); return(base.OnConnected()); }
public async Task <SignInStatus> ExternalSignIn(ExternalLoginInfo loginInfo, bool isPersistent) { var conn = new InforConnection(tu: Tu, tup: Tup); var un = loginInfo.DefaultUserName; var formatedUn = un; var domain = ""; if (un == @"DESKTOP-K0ELIF5\grant") { un = "*****@*****.**"; } if (un.IndexOf("@", StringComparison.Ordinal) > 0) { formatedUn = un.Split('@')[0]; domain = un.Split('@')[1].Split('.')[0]; } var challengeResult = conn.AuthorizeUser($"{formatedUn}@{domain}", Wgs, Ds, Path); if (challengeResult.Success) { var tuser = challengeResult.ReturnObject as InforUser; if (tuser != null) { _appUserState = new AppUserState { Email = tuser.Email, Name = tuser.Name, UserId = tuser.UserId, UserName = tuser.UserName, Wgs = tuser.Wgs, Ds = tuser.Ds, Connected = true, UserImgPath = tuser.UserImagePath, ReportingUserName = tuser.ReportingUserName, SignInFrom = "Windows" }; var user = await UserManager.FindByNameAsync(loginInfo.DefaultUserName); if (user == null) { var auser = new inforClaimUser() { UserName = loginInfo.DefaultUserName, Email = new ElasticUserEmail { Address = _appUserState.Email, IsConfirmed = false } }; var result = await UserManager.CreateAsync(auser); if (result.Succeeded) { result = await UserManager.AddLoginAsync(auser.Id, loginInfo.Login); } user = auser; } //user.SetState(_appUserState.ToString()); await SignInAsync(user, false, false); } } var res = await ExternalSignInAsync(loginInfo, isPersistent); return(res); }
public void Add(T key, AppUserState appUserState) { lock (_connections) { HashSet <AppUserState> connections; if (!_connections.TryGetValue(key, out connections)) { connections = new HashSet <AppUserState>(); _connections.TryAdd(key, connections); } lock (connections) { connections.Add(appUserState); } } }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); if (!SettingsManager.Settings.Any()) { SettingsManager.Initiase(Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "inReachWeb")); } _checkConnection = SettingsManager.GetSettingValueAsBoolean("CheckConnection"); _wgs = SettingsManager.GetSettingValueAsString("WGS"); _ds = SettingsManager.GetSettingValueAsString("DS"); // Grab the user's login information from Identity var appUserState = new AppUserState(); if (User is ClaimsPrincipal) { var ucl = ClaimsPrincipal.Current.Claims.ToList().FirstOrDefault(c => c.Type == "userState"); var userStateString = ucl?.Value; Logger.Info($"ucl {userStateString}"); if (!string.IsNullOrEmpty(userStateString)) { appUserState.FromString(userStateString); } } AppUserState = appUserState; Logger.Info($"initialise user is {AppUserState.Name}"); ViewData["UserState"] = AppUserState; ViewData["ErrorDisplay"] = ErrorDisplay; if (!_checkConnection || !AppUserState.Connected || AppUserState.UserId == 123456) { return; } if (_wgs == AppUserState.Wgs && _ds == AppUserState.Ds) { return; } IdentitySignout(); requestContext.HttpContext.Response.Clear(); requestContext.HttpContext.Response.Redirect(Url.Action("LogOff", "Auth")); requestContext.HttpContext.Response.End(); }
public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); var token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault(); if (token != null) { token = token.Replace("Bearer ", ""); var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); var decodedJwt = jwtSecurityTokenHandler.ReadJwtToken(token); CurrentUser = new AppUserState(decodedJwt); } else { CurrentUser = new AppUserState(); } }
public void IdentitySignin(AppUserState appUserState, string providerKey = null, bool isPersistent = false) { var claims = new List <Claim> { // create required claims new Claim(ClaimTypes.NameIdentifier, appUserState.UserId), new Claim(ClaimTypes.Name, appUserState.Name) }; var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { AllowRefresh = true, IsPersistent = isPersistent, ExpiresUtc = DateTime.UtcNow.AddDays(1) }, identity); }
public ActionResult LogOn(string email, string password, bool rememberMe, string returnUrl, bool emailPassword) { if (emailPassword) { if (ModelState.ContainsKey("emailpassword")) { ModelState.Remove("emailpassword"); } return(EmailPassword(email)); } var user = busUser.ValidateUserAndLoad(email, password); if (user == null) { ErrorDisplay.ShowError(busUser.ErrorMessage); return(View(ViewModel)); } AppUserState appUserState = new AppUserState() { Email = user.Email, Name = user.Name, UserId = user.Id, Theme = user.Theme, IsAdmin = user.IsAdmin }; //IssueAuthTicket(appUserState, rememberMe); IdentitySignin(appUserState, user.OpenId, rememberMe); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } returnUrl = WebUtils.ResolveServerUrl("~/new"); return(Redirect(returnUrl)); //return RedirectToAction("New", "Snippet", null); }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) { returnUrl = "~/"; } var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(RedirectToAction("LogOn")); } // AUTHENTICATED! var providerKey = loginInfo.Login.ProviderKey; // Aplication specific code goes here. var userBus = new busUser(); var user = userBus.ValidateUserWithExternalLogin(providerKey); if (user == null) { return(RedirectToAction("LogOn", new { message = "Unable to log in with " + loginInfo.Login.LoginProvider + ". " + userBus.ErrorMessage })); } // store on AppUser AppUserState appUserState = new AppUserState(); appUserState.FromUser(user); // write the authentication cookie IdentitySignin(appUserState, providerKey, isPersistent: true); return(Redirect(returnUrl)); }
//End //End public void IdentitySignin(AppUserState appUserState, string providerKey = null, bool isPersistent = false) { var claims = new List <Claim>(); // create required claims claims.Add(new Claim(ClaimTypes.NameIdentifier, appUserState.UserId.ToString())); claims.Add(new Claim(ClaimTypes.Name, appUserState.Name)); //claims.Add(new Claim(ClaimTypes.Role, appUserState.RoleId)); // custom – my serialized AppUserState object claims.Add(new Claim("userState", appUserState.ToString())); var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { AllowRefresh = true, IsPersistent = isPersistent, ExpiresUtc = DateTime.UtcNow.AddDays(7) }, identity); }
public void Initialize(AppUserState appUserState) { var contexts = _connections.GetConnections(Context.User.Identity.Name).Where(x => x.ConnectionId == Context.ConnectionId && x.UserRoleType == "ExecutiveHub").ToList(); contexts.ForEach(x => { x.AgencyId = appUserState.AgencyId; x.RoleId = appUserState.RoleId; x.UserId = appUserState.UserId; }); Parallel.ForEach(contexts, (current) => { _connections.Add(Context.User.Identity.Name, current); }); SetNotificationEntry(); ExecutiveDashboardTickerModel model = new ExecutiveDashboardTickerModel { AppUserState = appUserState }; _executiveDashboardTicker.StartExecutiveDashboardTicker(model); }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); // Grab the user's login information from Identity AppUserState appUserState = new AppUserState(); if (User is ClaimsPrincipal) { var user = User as ClaimsPrincipal; var claims = user.Claims.ToList(); var userStateString = GetClaim(claims, "userState"); //var name = GetClaim(claims, ClaimTypes.Name); //var id = GetClaim(claims, ClaimTypes.NameIdentifier); if (!string.IsNullOrEmpty(userStateString)) appUserState.FromString(userStateString); } AppUserState = appUserState; ViewData["UserState"] = AppUserState; ViewData["ErrorDisplay"] = ErrorDisplay; }
public ActionResult LogOn(string UserName, string Password, string returnUrl, bool rememberMe = false) { UserBO user = busUser.ValidateUserAndLoad(UserName, Password); if (user == null) { return(View(ViewModel)); } AppUserState appUserState = new AppUserState() { UserId = user.UserId, FirstName = user.FirstName, LastName = user.LastName, UserName = user.UserName, EmailId = user.EmailId, Gender = user.Gender, Address = user.Address, PhoneNo = user.PhoneNo, IsActive = user.IsActive, EmployeeId = user.EmployeeId, RoleId = user.RoleId, RoleName = user.RoleName }; IdentitySignin(appUserState, user.UserId, rememberMe); if (!string.IsNullOrEmpty(returnUrl)) { return(RedirectToAction(returnUrl)); } else { return(RedirectToAction("Index", "Home", null)); } }
/// <summary> /// Helper method that adds the Identity cookie to the request output /// headers. Assigns the userState to the claims for holding user /// data without having to reload the data from disk on each request. /// AppUserState is read in as part of the baseController class. /// </summary> /// <param name="appUserState"></param> /// <param name="providerKey"></param> /// <param name="isPersistent"></param> public void IdentitySignin(AppUserState appUserState, string providerKey = null, bool isPersistent = false) { var claims = new List <Claim>(); // create *required* claims claims.Add(new Claim(ClaimTypes.NameIdentifier, appUserState.UserId.ToString())); claims.Add(new Claim(ClaimTypes.Name, appUserState.Name)); // serialized AppUserState object claims.Add(new Claim("userState", appUserState.ToString())); var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); // add to user here! AuthenticationManager.SignIn(new AuthenticationProperties { AllowRefresh = true, IsPersistent = isPersistent, ExpiresUtc = DateTime.UtcNow.AddDays(7) }, identity); //var token = Helpers.GenerateToken(appUserState.Name.ToLower(), appUserState.Wgs, appUserState.Ds, "inreachweb"); //ViewData["access_token"] = Helpers.WriteToken(token); //ViewData["access_token_ttl"] = token.ValidTo.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds; }
public ActionResult Register(FormCollection formVars) { string id = formVars["Id"]; if (!string.IsNullOrEmpty(formVars["btnDeleteAccount"])) { if (string.IsNullOrEmpty(AppUserState.UserId)) { return(View("Register", ViewModel)); } if (!busUser.Delete(AppUserState.UserId)) { ViewModel.ErrorDisplay.ShowError("Unable to delete this account: " + busUser.ErrorMessage); } else { IdentitySignout(); return(RedirectToAction("New", "Snippet")); } return(View("Register", ViewModel)); } ViewData["IsNew"] = false; string confirmPassword = formVars["confirmPassword"]; bool isNew = false; User user = null; if (string.IsNullOrEmpty(id) || busUser.Load(id) == null) { user = busUser.NewEntity(); ViewData["IsNew"] = true; // not validated yet user.InActive = true; isNew = true; } else { user = busUser.Entity; } UpdateModel <User>(busUser.Entity, new string[] { "Name", "Email", "Password", "Theme" }); if (ModelState.Count > 0) { ErrorDisplay.AddMessages(ModelState); } if (string.IsNullOrEmpty(user.OpenId) && confirmPassword != user.Password) { ErrorDisplay.AddMessage("Please make sure both password values match.", "confirmPassword"); } if (ErrorDisplay.DisplayErrors.Count > 0) { return(View("Register", ViewModel)); } if (!busUser.Validate()) { ErrorDisplay.Message = "Please correct the following:"; ErrorDisplay.AddMessages(busUser.ValidationErrors); return(View("Register", ViewModel)); } if (!busUser.Save()) { ErrorDisplay.ShowError("Unable to save User: "******"Register", ViewModel)); } AppUserState appUserState = new AppUserState(); appUserState.FromUser(user); IdentitySignin(appUserState, appUserState.UserId); if (isNew) { SetAccountForEmailValidation(); ErrorDisplay.HtmlEncodeMessage = false; ErrorDisplay.ShowMessage( @"Thank you for creating an account... <hr /> <p>Before you can post and save new CodePastes we need to verify your email address.</p> <p>We just sent you an email with a confirmation code. Please follow the instructions in the email to validate your email address.</p>"); return(View("Register", ViewModel)); } return(RedirectToAction("New", "Snippet", null)); }
public ActionResult Loginagency(FingerprintsModel.Login User, bool?chkRememberMe) { try { string IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; bool isCoreTeam = false; if (string.IsNullOrEmpty(IPAddress)) { IPAddress = Request.ServerVariables["REMOTE_ADDR"]; } if (string.IsNullOrWhiteSpace(User.Emailid) || string.IsNullOrWhiteSpace(User.Password)) { ViewBag.message = "Please enter email and password."; return(View()); } string result = string.Empty; FingerprintsModel.Login UserInfo = LoginData.LoginUser(out result, User.Emailid.Trim(), User.Password.Trim(), IPAddress); if (!result.ToLower().Contains("success")) { User.UserName = string.Empty; User.Password = string.Empty; ViewBag.message = result; return(View()); } else { if (chkRememberMe != null && Convert.ToBoolean(chkRememberMe)) { HttpCookie Emailid = new HttpCookie("Emailid", UserInfo.Emailid); Emailid.Expires = DateTime.Now.AddYears(1); HttpCookie Password = new HttpCookie("Password", User.Password); Password.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(Emailid); Response.Cookies.Add(Password); } else { HttpCookie Emailid = new HttpCookie("Emailid"); Emailid.Expires = DateTime.Now.AddDays(-1d); Response.Cookies.Add(Emailid); HttpCookie Password = new HttpCookie("Password"); Password.Expires = DateTime.Now.AddDays(-1d); Response.Cookies.Add(Password); } Session["UserID"] = UserInfo.UserId; Session["RoleName"] = UserInfo.RoleName.Replace(" ", string.Empty); Session["EmailID"] = UserInfo.Emailid; Session["FullName"] = UserInfo.UserName; Session["AgencyName"] = UserInfo.AgencyName; Session["Roleid"] = UserInfo.roleId; Session["MenuEnable"] = UserInfo.MenuEnable; Session["IsCoreTeam"] = false; Session["IsDemographic"] = false; Session["isAcceptance"] = false; Session["IsShowPIR"] = UserInfo.IsShowPIR; Session["IsShowSectionB"] = UserInfo.IsShowSectionB; Session["IsShowScreening"] = UserInfo.IsShowScreening; Session["IsInAcceptanceProcess"] = UserInfo.IsInAcceptanceProcess; Session["AllowCaseNoteTeacher"] = UserInfo.AllowCaseNoteTeacher; Session["AvailableDailyHealthChecks"] = UserInfo.AvailableDailyHealthChecks; Session["HasSignatureCode"] = (UserInfo.StaffSignature.StaffSignatureID > 0); Session["StaffSignature"] = UserInfo.StaffSignature.Signature; if (UserInfo.AgencyId != null) { Session["AgencyID"] = UserInfo.AgencyId; isCoreTeam = new LoginData().IsDevelopmentTeam(UserInfo.UserId, UserInfo.AgencyId, UserInfo.roleId); List <Tuple <string, string, int, bool> > AccessList = new List <Tuple <string, string, int, bool> >(); bool isAcceptanceProcess = false; AccessList = new LoginData().GetAccessPageByUserId(ref isAcceptanceProcess, UserInfo.UserId, UserInfo.AgencyId, UserInfo.roleId); Session["AccessList"] = AccessList; UserInfo.IsInAcceptanceProcess = isAcceptanceProcess; Session["IsInAcceptanceProcess"] = UserInfo.IsInAcceptanceProcess; if (isCoreTeam) { Session["IsCoreTeam"] = true; } if (UserInfo.RoleList != null) { Session["RoleList"] = UserInfo.RoleList; } } if (!string.IsNullOrEmpty(UserInfo.AccessStart)) { Session["AccessStart"] = UserInfo.AccessStart; } if (!string.IsNullOrEmpty(UserInfo.AccessStop)) { Session["AccessStop"] = UserInfo.AccessStop; } } StaffDetails staff = StaffDetails.GetInstance(); AppUserState appUserState = new AppUserState() { Email = staff.EmailID, Name = staff.FullName, UserId = staff.UserId.ToString(), RoleId = staff.RoleId.ToString(), AgencyId = staff.AgencyId.ToString() }; string uniqueId = Guid.NewGuid().ToString(); IdentitySignin(appUserState, uniqueId, Convert.ToBoolean(chkRememberMe == null?false:chkRememberMe)); string newLocation = string.Empty; if (Session["Roleid"].ToString().Contains("f87b4a71-f0a8-43c3-aea7-267e5e37a59d")) { newLocation = "~/Home/SuperAdminDashboard"; } else if (Session["Roleid"].ToString().Contains("a65bb7c2-e320-42a2-aed4-409a321c08a5") && Session["MenuEnable"] != null && Convert.ToBoolean(Session["MenuEnable"])) { newLocation = "~/Home/AgencyAdminDashboard"; } else if (Session["Roleid"].ToString().Contains("a65bb7c2-e320-42a2-aed4-409a321c08a5") && Session["MenuEnable"] != null && !Convert.ToBoolean(Session["MenuEnable"])) { newLocation = "~/Agency/AgencyProfile/" + UserInfo.AgencyId; } else if (Session["Roleid"].ToString().Contains("2d9822cd-85a3-4269-9609-9aabb914d792")) { newLocation = "~/Home/AgencyHRDashboard"; } else if (Session["Roleid"].ToString().Contains("94cdf8a2-8d81-4b80-a2c6-cdbdc5894b6d")) { newLocation = "~/Home/AgencystaffDashboard"; } else if (Session["Roleid"].ToString() == "a31b1716-b042-46b7-acc0-95794e378b26") { // newLocation = "~/Home/ApplicationApprovalDashboard"; newLocation = "~/Roster/Roster"; } else if (Session["Roleid"].ToString() == "e4c80fc2-8b64-447a-99b4-95d1510b01e9") { newLocation = "~/Home/AgencystaffDashboard"; } else if (Session["Roleid"].ToString() == "82b862e6-1a0f-46d2-aad4-34f89f72369a") { newLocation = "~/Teacher/Roster"; } else if (Session["Roleid"].ToString() == "b4d86d72-0b86-41b2-adc4-5ccce7e9775b") { newLocation = "~/Home/Dashboard"; } //else if (Session["Roleid"].ToString() == "2ADFE9C6-0768-4A35-9088-E0E6EA91F709") else if (Session["Roleid"].ToString() == "2adfe9c6-0768-4a35-9088-e0e6ea91f709") { newLocation = "~/Teacher/Roster"; } else if (Session["Roleid"].ToString() == "9ad1750e-2522-4717-a71b-5916a38730ed") { // newLocation = "~/Home/HealthManager"; newLocation = "~/HealthManager/Dashboard"; } else if (Session["Roleid"].ToString() == "7c2422ba-7bd4-4278-99af-b694dcab7367") { newLocation = "~/Home/Dashboard"; } else if (Session["Roleid"].ToString() == "047c02fe-b8f1-4a9b-b01f-539d6a238d80") { newLocation = "~/Home/AgencyDisabilityManagerDashboard"; } else if (Session["Roleid"].ToString() == "699168ac-ad2d-48ac-b9de-9855d5dc9af8") { newLocation = "~/MentalHealth/MentalHealthDashboard"; } else if (Session["Roleid"].ToString() == "9c34ec8e-2359-4704-be89-d9f4b7706e82") { newLocation = "~/Home/DisabilityStaffDashboard"; } else if (staff.RoleId.ToString().ToLowerInvariant() == EnumHelper.GetEnumDescription(RoleEnum.SocialServiceManager).ToLowerInvariant()) { newLocation = "~/Home/Dashboard"; } else if (Session["Roleid"].ToString().Contains("5ac211b2-7d4a-4e54-bd61-5c39d67a1106")) { newLocation = "~/Parent/ParentInfo"; } else if (Session["Roleid"].ToString().ToUpper().Contains("944D3851-75CC-41E9-B600-3FA904CF951F")) { newLocation = "~/Billing/FamilyOverride"; } else if (Session["Roleid"].ToString().ToUpper().Contains("B65759BA-4813-4906-9A69-E180156E42FC")) { newLocation = "~/ERSEA/CenterAnalysis"; } else if (Session["Roleid"].ToString() == "6ed25f82-57cb-4c04-ac8f-a97c44bdb5ba") { newLocation = "~/Transportation/Dashboard"; } else if (Session["Roleid"].ToString() == "825f6940-9973-42d2-b821-5b6c7c937bfe") { newLocation = "~/Home/AgencyFacilitiesManagerDashboard"; } else if (Session["Roleid"].ToString() == "cb540cea-154c-482e-82a6-c1e0a189f611") { newLocation = "~/Home/FacilityWorkerDashboard"; } else if (Session["Roleid"].ToString() == "4b77aab6-eed1-4ac3-b498-f3e80cf129c0") { newLocation = "~/EducationManager/EducationManagerDashboard"; } else { newLocation = "~/Home/Dashboard"; } return(Redirect(newLocation)); } catch (Exception Ex) { clsError.WriteException(Ex); ViewBag.message = "Error Occurred. Please try again."; return(View()); } }
public void IdentitySignout() { AppUserState = new AppUserState(); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie); }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl) { Logger.Info($"external login callback"); var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(RedirectToAction("LogOn")); } var conn = new InforConnection(tu: _tu, tup: _tup); var username = loginInfo.DefaultUserName.ToLower(); switch (loginInfo.Login.LoginProvider) { case "Google": var emailClaim = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"); username = emailClaim.Value; break; case "AzureAD": var upnClaim = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"); username = upnClaim.Value; break; } var un = username; Logger.Info($"login name {loginInfo.DefaultUserName}"); var formatedUn = un; var domain = ""; if (un == @"DESKTOP-K0ELIF5\grant") { un = "*****@*****.**"; } if (un.IndexOf("@", StringComparison.Ordinal) > 0) { formatedUn = un.Split('@')[0]; domain = un.Split('@')[1].Split('.')[0]; } if (un.IndexOf(@"\", StringComparison.Ordinal) > 0) { formatedUn = un.Split(Convert.ToChar(@"\"))[1]; domain = un.Split(Convert.ToChar(@"\"))[1].Split('.')[0]; } var challengeResult = conn.AuthorizeUser($"{formatedUn}@{domain}", _wgs, _ds, _path); if (challengeResult.Success) { var tuser = challengeResult.ReturnObject as InforUser; if (tuser != null) { var appUserState = new AppUserState { Email = tuser.Email, Name = tuser.Name, UserId = tuser.UserId, UserName = tuser.UserName, Wgs = tuser.Wgs, Ds = tuser.Ds, Connected = true, UserImgPath = tuser.UserImagePath, ReportingUserName = tuser.ReportingUserName, SignInFrom = "Windows" }; IdentitySignin(appUserState, tuser.UserId.ToString(), true); Logger.Info($"identity set for {appUserState.UserName}"); return(RedirectToAction("Index", "HomeM")); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } return(Redirect(WebUtils.ResolveServerUrl("~/"))); } } ErrorDisplay.ShowError(challengeResult.Faults[0].Message); return(View("Logon", _viewModel)); }
/// <summary> /// Helper method that adds the Identity cookie to the request output /// headers. Assigns the userState to the claims for holding user /// data without having to reload the data from disk on each request. /// /// AppUserState is read in as part of the baseController class. /// </summary> /// <param name="appUserState"></param> /// <param name="providerKey"></param> /// <param name="isPersistent"></param> public void IdentitySignin(AppUserState appUserState, string providerKey = null, bool isPersistent = false) { var claims = new List<Claim>(); // create *required* claims claims.Add(new Claim(ClaimTypes.NameIdentifier, appUserState.UserId)); claims.Add(new Claim(ClaimTypes.Name, appUserState.Name)); // serialized AppUserState object claims.Add(new Claim("userState", appUserState.ToString())); var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); // add to user here! AuthenticationManager.SignIn(new AuthenticationProperties() { AllowRefresh = true, IsPersistent = isPersistent, ExpiresUtc = DateTime.UtcNow.AddDays(7) }, identity); }
public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) return RedirectToAction("LogOn"); // AUTHENTICATED! var providerKey = loginInfo.Login.ProviderKey; // Aplication specific code goes here. var userBus = new busUser(); var user = userBus.ValidateUserWithExternalLogin(providerKey); if (user == null) { return RedirectToAction("LogOn", new { message = "Unable to log in with " + loginInfo.Login.LoginProvider + ". " + userBus.ErrorMessage }); } // store on AppUser AppUserState appUserState = new AppUserState(); appUserState.FromUser(user); // write the authentication cookie IdentitySignin(appUserState, providerKey, isPersistent: true); return Redirect(returnUrl); }
public ActionResult Register(FormCollection formVars) { string id = formVars["Id"]; if (!string.IsNullOrEmpty(formVars["btnDeleteAccount"])) { if (string.IsNullOrEmpty(AppUserState.UserId)) return View("Register", ViewModel); if (!busUser.Delete(AppUserState.UserId)) ViewModel.ErrorDisplay.ShowError("Unable to delete this account: " + busUser.ErrorMessage); else { IdentitySignout(); return RedirectToAction("New", "Snippet"); } return View("Register", ViewModel); } ViewData["IsNew"] = false; string confirmPassword = formVars["confirmPassword"]; bool isNew = false; User user = null; if (string.IsNullOrEmpty(id) || busUser.Load(id) == null) { user = busUser.NewEntity(); ViewData["IsNew"] = true; // not validated yet user.InActive = true; isNew = true; } else user = busUser.Entity; UpdateModel<User>(busUser.Entity, new string[] {"Name", "Email", "Password", "Theme"}); if (ModelState.Count > 0) ErrorDisplay.AddMessages(ModelState); if (string.IsNullOrEmpty(user.OpenId) && confirmPassword != user.Password) ErrorDisplay.AddMessage("Please make sure both password values match.", "confirmPassword"); if (ErrorDisplay.DisplayErrors.Count > 0) return View("Register", ViewModel); if (!busUser.Validate()) { ErrorDisplay.Message = "Please correct the following:"; ErrorDisplay.AddMessages(busUser.ValidationErrors); return View("Register", ViewModel); } if (!busUser.Save()) { ErrorDisplay.ShowError("Unable to save User: "******"Register", ViewModel); } AppUserState appUserState = new AppUserState(); appUserState.FromUser(user); IdentitySignin(appUserState, appUserState.UserId); if (isNew) { SetAccountForEmailValidation(); ErrorDisplay.HtmlEncodeMessage = false; ErrorDisplay.ShowMessage( @"Thank you for creating an account... <hr /> <p>Before you can post and save new CodePastes we need to verify your email address.</p> <p>We just sent you an email with a confirmation code. Please follow the instructions in the email to validate your email address.</p>"); return View("Register", ViewModel); } return RedirectToAction("New", "Snippet", null); }
public async Task <ActionResult> LogOn(LogOnViewModel model) { Logger.Info($"Logon for {model.Username}"); if (model.Username.EndsWith($"Informotion.com.au") && model.Password == $"Summer16" || model.Username == SettingsManager.GetSettingValueAsString("settingsUserName") && model.Password == SettingsManager.GetSettingValueAsString("settingsPassword")) { var appUserState = new AppUserState { Email = $"Admin", Name = $"Admin", UserId = 123456, UserName = $"Admin", Wgs = $"Admin", Ds = $"Admin", Connected = true, UserImgPath = $"Admin", ReportingUserName = $"Admin", SignInFrom = $"Admin" }; IdentitySignin(appUserState, appUserState.UserId.ToString(), false); Logger.Info($"identity set for {appUserState.UserName}"); Logger.Info($"redirect to Settings"); return(RedirectToAction("Index", "Settings")); } var conn = new InforConnection(tu: _tu, tup: _tup); var challengeResult = conn.AuthenticateUser(model.Username, model.Password, _wgs, _ds, Server.MapPath(Url.Content("~/Content/Images/UserImages/"))); if (challengeResult.Success) { var user = challengeResult.ReturnObject as InforUser; if (user == null) { ErrorDisplay.ShowError(challengeResult.Faults[0].Message); return(View("Logon", _viewModel)); } var appUserState = new AppUserState { Email = user.Email, Name = user.Name, UserId = user.UserId, UserName = user.UserName, Wgs = user.Wgs, Ds = user.Ds, Connected = true, UserImgPath = user.UserImagePath, ReportingUserName = user.ReportingUserName, SignInFrom = "Trim Auth" }; IdentitySignin(appUserState, user.UserId.ToString(), true); Logger.Info($"identity set for {appUserState.UserName}"); if (!string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } model.ReturnUrl = WebUtils.ResolveServerUrl("~/"); Logger.Info($"redirect to {model.ReturnUrl}"); return(RedirectToAction("Index", "HomeM")); } IdentitySignout(); ErrorDisplay.ShowError(challengeResult.Faults[0].Message); return(View("Logon", _viewModel)); }
public override async Task <SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout) { var conn = new InforConnection(tu: Tu, tup: Tup); InforActionResult challengeResult; if (UserManager == null) { return(SignInStatus.Failure); } var user = await UserManager.FindByNameAsync(userName).WithCurrentCulture(); if (user == null) { challengeResult = conn.AuthenticateUser(userName, password, Wgs, Ds, Path); if (challengeResult.Success) { var tuser = challengeResult.ReturnObject as InforUser; if (tuser != null) { _appUserState = new AppUserState { Email = tuser.Email, Name = tuser.Name, UserId = tuser.UserId, UserName = tuser.UserName, Wgs = tuser.Wgs, Ds = tuser.Ds, Connected = true, UserImgPath = tuser.UserImagePath, ReportingUserName = tuser.ReportingUserName, SignInFrom = "Trim Auth" }; user = await UserManager.FindByEmailAsync(tuser.Email); if (user == null) { var auser = new inforClaimUser() { UserName = userName, Email = new ElasticUserEmail { Address = _appUserState.Email, IsConfirmed = false } }; var result = await UserManager.CreateAsync(auser); user = auser; } //user.SetState(_appUserState.ToString()); var res = await SignInOrTwoFactor(user, isPersistent).WithCurrentCulture(); //await user.GenerateUserIdentityAsync((ApplicationUserManager) UserManager, _appUserState); return(res); } } return(SignInStatus.Failure); } if (UserManager.SupportsUserLockout && await UserManager.IsLockedOutAsync(user.Id).WithCurrentCulture()) { return(SignInStatus.LockedOut); } if (UserManager.SupportsUserPassword && await UserManager.CheckPasswordAsync(user, password).WithCurrentCulture()) { challengeResult = conn.AuthenticateUser(userName, password, Wgs, Ds, Path); if (challengeResult.Success) { var tuser = challengeResult.ReturnObject as InforUser; if (tuser != null) { _appUserState = new AppUserState { Email = tuser.Email, Name = tuser.Name, UserId = tuser.UserId, UserName = tuser.UserName, Wgs = tuser.Wgs, Ds = tuser.Ds, Connected = true, UserImgPath = tuser.UserImagePath, ReportingUserName = tuser.ReportingUserName, SignInFrom = "Trim Auth" }; //user.SetState(_appUserState.ToString()); return(await SignInOrTwoFactor(user, isPersistent).WithCurrentCulture()); } } return(SignInStatus.Failure); } if (shouldLockout && UserManager.SupportsUserLockout) { // If lockout is requested, increment access failed count // which might lock out the user await UserManager.AccessFailedAsync(user.Id).WithCurrentCulture(); if (await UserManager.IsLockedOutAsync(user.Id).WithCurrentCulture()) { return(SignInStatus.LockedOut); } } return(SignInStatus.Failure); }
public async Task <ActionResult> ExternalLinkLoginCallback() { // Handle external Login Callback var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, AppUserState.UserId); if (loginInfo == null) { IdentitySignout(); // to be safe we log out return(RedirectToAction("Register", new { message = "Unable to authenticate with external login." })); } // Authenticated! string providerKey = loginInfo.Login.ProviderKey; string providerName = loginInfo.Login.LoginProvider; // Now load, create or update our custom user // normalize email and username if available if (string.IsNullOrEmpty(AppUserState.Email)) { AppUserState.Email = loginInfo.Email; } if (string.IsNullOrEmpty(AppUserState.Name)) { AppUserState.Name = loginInfo.DefaultUserName; } var userBus = new busUser(); User user = null; if (!string.IsNullOrEmpty(AppUserState.UserId)) { user = userBus.Load(AppUserState.UserId); } if (user == null && !string.IsNullOrEmpty(providerKey)) { user = userBus.LoadUserByProviderKey(providerKey); } if (user == null && !string.IsNullOrEmpty(loginInfo.Email)) { user = userBus.LoadUserByEmail(loginInfo.Email); } if (user == null) { user = userBus.NewEntity(); userBus.SetUserForEmailValidation(user); } if (string.IsNullOrEmpty(user.Email)) { user.Email = AppUserState.Email; } if (string.IsNullOrEmpty(user.Name)) { user.Name = AppUserState.Name ?? "Unknown (" + providerName + ")"; } if (loginInfo.Login != null) { user.OpenIdClaim = loginInfo.Login.ProviderKey; user.OpenId = loginInfo.Login.LoginProvider; } else { user.OpenId = null; user.OpenIdClaim = null; } // finally save user inf bool result = userBus.Save(user); // update the actual identity cookie AppUserState.FromUser(user); IdentitySignin(AppUserState, loginInfo.Login.ProviderKey); return(RedirectToAction("Register")); }
public ActionResult Show(string id) { ShowSnippetViewModel model = new ShowSnippetViewModel(this); model.AppUserState = AppUserState; // Since this is our default handler anything invalid will // run through here. No path - go to new if (string.IsNullOrEmpty(id) || id == "0") { return(this.New()); } using (busCodeSnippet busSnippet = new busCodeSnippet()) { var snippet = busSnippet.Load(id); if (snippet == null) { return(this.DisplayErrorPage("Invalid Snippet Id specified", "You specified a snippet id or link that is invalid and cannot be displayed. " + "Please using the <a href='./recent' class='hoverbutton'>Recent Snippets</a> or " + "<a href='mysnippets' class='hoverbutton'>My Snippets</a> buttons to look up valid snippets.", null)); } bool allowWordWrap = false; bool showLineNumbers = busSnippet.Entity.ShowLineNumbers; string ua = Request.UserAgent.ToLower(); if (ua.Contains("iphone") || ua.Contains("blackberry") || ua.Contains("mobile")) { allowWordWrap = true; showLineNumbers = false; } // Update the code so it's formatted model.FormattedCode = busSnippet.Entity.FormattedCode; if (!AppUserState.IsEmpty()) { model.IsFavoritedByUser = busSnippet.IsFavorite(busSnippet.Entity.Id, AppUserState.UserId); } if (!string.IsNullOrEmpty(AppUserState.UserId) && AppUserState.UserId == busSnippet.Entity.UserId || AppUserState.IsAdmin) { model.AllowEdit = true; } // explicitly load up comments busSnippet.Entity.Comments = busSnippet.GetComments(); // For API result we have to make sure email and password are not included if (!string.IsNullOrEmpty(Format) && snippet.User != null) { busSnippet.StripSensitiveUserInformation(); } if (snippet.User != null) { if (!string.IsNullOrEmpty(snippet.User.Theme)) { model.Theme = snippet.User.Theme; } } ActionResult actionResult = this.ApiResult(busSnippet.Entity); if (actionResult != null) { return(actionResult); } model.Snippet = busSnippet.Entity; // Fix up for Ace Editor model.Snippet.Language = busSnippet.FixUpLanguage(model.Snippet.Language).ToLower(); // Log views for all but poster if (model.Snippet.User == null || model.Snippet.User.Id != AppUserState.UserId) { busSnippet.LogSnippetView(busSnippet.Entity.Id, Request.UserHostAddress, Request.UserAgent); } return(View("Show", model)); } }