private static bool Authenticate(Context context) { return(Authentications.Windows() || Authentications.Try( context: context, loginId: Forms.Data("Users_LoginId"), password: Forms.Data("Users_Password").Sha512Cng())); }
public ActionResult Login(string returnUrl) { var context = new Context(); var log = new SysLogModel(context: context); if (Sessions.LoggedIn()) { if (QueryStrings.Bool("new")) { Authentications.SignOut(); } log.Finish(context: context); return(base.Redirect(Locations.Top())); } var html = UserUtilities.HtmlLogin( context: context, returnUrl: returnUrl, message: Request.QueryString["expired"] == "1" && !Request.IsAjaxRequest() ? Messages.Expired().Text : string.Empty); ViewBag.HtmlBody = html; log.Finish(context: context, responseSize: html.Length); return(View()); }
private static bool WindowsAuthenticated(Context context) { return(Authentications.Windows() && !context.LoginId.IsNullOrEmpty() && (!Parameters.Authentication.RejectUnregisteredUser || context.Authenticated)); }
public async Task <IActionResult> LoginAsync(Authentications authentication) { //authenticate using the manager var usr = AuthenticateManager.GetAuthentication(authentication.Username, authentication.Password); if (authentication == null) { return(View()); } var claims = new List <Claim>() { new Claim(ClaimTypes.Name, usr.Username), new Claim("FullName", usr.Username), }; var claimsIdentity = new ClaimsIdentity(claims, "Cookies"); await HttpContext.SignInAsync("Cookies", new ClaimsPrincipal(claimsIdentity)); if (TempData["ReturnUrl"] == null) { return(RedirectToAction("Index", "Home")); } else { return(Redirect(TempData["ReturnUrl"].ToString())); } }
public ActionResult Login(string returnUrl) { var log = new SysLogModel(); if (Sessions.LoggedIn()) { if (Libraries.Requests.QueryStrings.Bool("new")) { Authentications.SignOut(); } else { log.Finish(); return(base.Redirect(Locations.Top())); } } var html = UserUtilities.HtmlLogin( returnUrl, Request.QueryString["expired"] == "1" && !Request.IsAjaxRequest() ? Messages.Expired().Html : string.Empty); ViewBag.HtmlBody = html; log.Finish(html.Length); return(View()); }
private static void Sync(string pattern) { try { var directorySearcher = DirectorySearcher( Parameters.Authentication.LdapSyncUser, Parameters.Authentication.LdapSyncPassword); directorySearcher.Filter = pattern; var results = directorySearcher.FindAll(); foreach (SearchResult result in results) { var entry = result.Entry( Parameters.Authentication.LdapSyncUser, Parameters.Authentication.LdapSyncPassword); if (Authentications.Windows()) { UpdateOrInsert(NetBiosName(entry), entry); } else { UpdateOrInsert( entry.Property(Parameters.Authentication.LdapSearchProperty), entry); } } } catch (Exception e) { new SysLogModel(e); } }
private static void Sync( Context context, ParameterAccessor.Parts.Ldap ldap, string pattern, DateTime synchronizedTime) { var logs = new Logs() { new Log("pattern", pattern) }; try { var directorySearcher = DirectorySearcher( ldap.LdapSyncUser, ldap.LdapSyncPassword, ldap); directorySearcher.Filter = pattern; directorySearcher.PageSize = 1000; var results = directorySearcher.FindAll(); logs.Add("results", results.Count.ToString()); foreach (SearchResult result in results) { DirectoryEntry entry = result.Entry( ldap.LdapSyncUser, ldap.LdapSyncPassword); if (Enabled(entry, ldap)) { logs.Add("entry", entry.Path); if (Authentications.Windows()) { UpdateOrInsert( context: context, loginId: NetBiosName( context: context, entry: entry, ldap: ldap), entry: entry, ldap: ldap, synchronizedTime: synchronizedTime); } else { UpdateOrInsert( context: context, loginId: entry.Property( context: context, name: ldap.LdapSearchProperty), entry: entry, ldap: ldap, synchronizedTime: synchronizedTime); } } } } catch (Exception e) { new SysLogModel(context: context, e: e, logs: logs); } }
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDistributedMemoryCache(); services.AddMvc().AddSessionStateTempDataProvider(); services.AddSession(); var mvcBuilder = services.AddMvc( options => { options.Filters.Add(new HandleErrorExAttribute()); options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); options.Filters.Add(new CheckContextAttributes()); if (Parameters.Service.RequireHttps) { options.Filters.Add(new Microsoft.AspNetCore.Mvc.RequireHttpsAttribute()); } }); if (Authentications.SAML()) { services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => o.LoginPath = new PathString("/users/login")) .AddSaml2(options => { Saml.SetSPOptions(options); }); } else { services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => o.LoginPath = new PathString("/users/login")); } var extensionDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "ExtendedLibraries"); if (Directory.Exists(extensionDirectory)) { foreach (var assembly in Directory.GetFiles(extensionDirectory, "*.dll").Select(dll => Assembly.LoadFrom(dll)).ToArray()) { mvcBuilder.AddApplicationPart(assembly); } } services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = int.MaxValue; }); services.Configure <IISServerOptions>(options => { options.AllowSynchronousIO = true; options.MaxRequestBodySize = long.MaxValue; }); services.Configure <KestrelServerOptions>(options => { options.AllowSynchronousIO = true; options.Limits.MaxRequestBodySize = long.MaxValue; }) .Configure <KestrelServerOptions>(configuration.GetSection("Kestrel")); services.AddHealthChecks(); }
public async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync( HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation) { var stream = await actionContext?.Request?.Content?.ReadAsStreamAsync(); if (stream == null) { return(await Task.FromResult(actionContext.Request.CreateResponse( statusCode: HttpStatusCode.BadRequest, value: new { Message = Displays.BadRequest( context: new Context( sessionStatus: false, sessionData: false, item: false)) }, mediaType: "application/json"))); } var reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8); var requestData = await reader.ReadToEndAsync(); stream.Position = 0; var context = new Context( sessionStatus: false, sessionData: false, item: false, apiRequestBody: requestData); if (!context.ContractSettings.AllowedIpAddress(context.UserHostAddress)) { return(await Task.FromResult(actionContext.Request.CreateResponse( statusCode: HttpStatusCode.Forbidden, value: new { Message = Displays.InvalidIpAddress(context) }, mediaType: "application/json"))); } if (Parameters.Security.TokenCheck && HttpContext.Current?.User?.Identity?.IsAuthenticated == true) { var data = await actionContext.Request?.Content?.ReadAsStringAsync(); var api = data?.Deserialize <Api>(); if (api?.Token != Authentications.Token()) { return(await Task.FromResult(actionContext.Request.CreateResponse( statusCode: HttpStatusCode.BadRequest, value: new { Message = Displays.BadRequest(context: context) }, mediaType: "application/json"))); } } return(await continuation()); }
public string Authenticate(string returnUrl) { var log = new SysLogModel(); var json = Authentications.SignIn(returnUrl); log.Finish(json.Length); return(json); }
public void OnAuthorization(AuthorizationFilterContext filterContext) { if (Sessions.LoggedIn() && Contract.OverDeadline()) { Authentications.SignOut(); filterContext.Result = new RedirectResult(Locations.Login() + "?expired=1"); } }
/// <summary> /// Fixed: /// </summary> public string Authenticate(Context context, string returnUrl) { var log = new SysLogModel(context: context); var json = Authentications.SignIn(context: context, returnUrl: returnUrl); log.Finish(context: context, responseSize: json.Length); return(json); }
public ActionResult Logout(string returnUrl) { var log = new SysLogModel(); Authentications.SignOut(); var url = Locations.Login(); log.Finish(); return(Redirect(url)); }
/// <summary> /// Fixed: /// </summary> public string Logout(Context context, string returnUrl) { var log = new SysLogModel(context: context); Authentications.SignOut(context: context); var url = Locations.Login(context: context); log.Finish(context: context); return(url); }
private void InitializeSession() { Sessions.Set("StartTime", DateTime.Now); Sessions.Set("LastAccessTime", Sessions.Get <DateTime>("StartTime")); Sessions.Set("SessionGuid", Strings.NewGuid()); if (Sessions.LoggedIn()) { //TODO Ldap //if (Authentications.Windows()) //{ // Ldap.UpdateOrInsert(HttpContext.Current.User.Identity.Name); //} var userId = Sessions.UserId(); var tenantId = Rds.ExecuteScalar_int(statements: Rds.SelectUsers( column: Rds.UsersColumn().TenantId(), where : Rds.UsersWhere().UserId(userId))); Sessions.SetTenantId(tenantId); StatusesInitializer.Initialize(tenantId); var userModel = new UserModel( SiteSettingsUtilities.UsersSiteSettings(), userId); if (userModel.AccessStatus == Databases.AccessStatuses.Selected && !userModel.Disabled) { userModel.SetSession(); } else { Authentications.SignOut(); SetAnonymouseSession(); var request = AspNetCoreHttpContext.Current.Request; var url = $"{request.Scheme}://{request.Host.Value}{request.Path.Value}{request.QueryString.Value}"; AspNetCoreHttpContext.Current.Response.Redirect(url); } } else { SetAnonymouseSession(); } var @base = AspNetCoreHttpContext.Current.Request.PathBase; switch (@base.Value.ToLower()) { case "~/backgroundtasks/do": case "~/reminderschedules/remind": break; default: new SysLogModel().Finish(); break; } }
public static Error.Types OnDeleting(SiteSettings ss, SiteModel siteModel) { if (ss.Title != Forms.Data("DeleteSiteTitle") || !Authentications.Try( Forms.Data("Users_LoginId"), Forms.Data("Users_Password").Sha512Cng())) { return(Error.Types.IncorrectSiteDeleting); } return(ss.CanManageSite() ? Error.Types.None : Error.Types.HasNotPermission); }
public string Authenticate(string returnUrl) { var context = new Context(); var log = new SysLogModel(context: context); var json = Authentications.SignIn( context: context, returnUrl: Url.IsLocalUrl(returnUrl) ? returnUrl : string.Empty); log.Finish( context: context, responseSize: json.Length); return(json); }
public override void Cancel() { if (ObjectState != ObjectStates.None) { _provider = OriginalValues._provider; _server = OriginalValues._server; _userName = OriginalValues._userName; _password = OriginalValues._password; _port = OriginalValues._port; _path = OriginalValues._path; _authentication = OriginalValues._authentication; _timeout = OriginalValues._timeout; ObjectState = ObjectStates.None; } }
public void OnAuthorization(AuthorizationContext filterContext) { var context = new Context( sessionStatus: false, sessionData: false, item: false); if (context.Controller != "errors" && Parameters.SyntaxErrors?.Any() == true) { filterContext.Result = new RedirectResult( Locations.ParameterSyntaxError(context: context)); } if (context.Authenticated && !context.ContractSettings.AllowedIpAddress(context.UserHostAddress)) { Authentications.SignOut(context: context); filterContext.Result = new RedirectResult( Locations.InvalidIpAddress(context: context)); return; } if (context.Authenticated && context.ContractSettings.OverDeadline(context: context)) { Authentications.SignOut(context: context); filterContext.Result = new RedirectResult( Locations.Login(context: context) + "?expired=1"); return; } if (!context.LoginId.IsNullOrEmpty()) { if (!context.Authenticated) { if (Authentications.Windows()) { filterContext.Result = new EmptyResult(); return; } else { Authentications.SignOut(context: context); filterContext.Result = new RedirectResult( Locations.Login(context: context)); return; } } } SiteInfo.Reflesh(context: context); }
private static HtmlBuilder HiddenData( this HtmlBuilder hb, Context context, SiteSettings ss = null, ServerScriptModelRow scriptValues = null) { return(!context.Ajax ? hb .Hidden(controlId: "ApplicationPath", value: Locations.Get(context: context)) .Hidden( controlId: "Token", value: Authentications.Token(), _using: Parameters.Security.TokenCheck) .Hidden(controlId: "Language", value: context.Language) .Hidden(controlId: "DeptId", value: context.DeptId.ToString()) .Hidden(controlId: "UserId", value: context.UserId.ToString()) .Hidden(controlId: "LoginId", value: context.LoginId) .Hidden(controlId: "Publish", value: "1", _using: context.Publish) .Hidden(controlId: "TableName", value: ss?.ReferenceType) .Hidden(controlId: "Controller", value: context.Controller) .Hidden(controlId: "Action", value: context.Action) .Hidden(controlId: "Id", value: context.Id.ToString()) .Hidden(controlId: "TenantId", value: context.TenantId.ToString()) .Hidden(controlId: "SiteId", value: ss?.SiteId.ToString()) .Hidden(controlId: "JoinedSites", value: ss?.JoinedSsHash ?.Select(o => new { SiteId = o.Key, o.Value.ReferenceType, o.Value.Title }) .ToJson()) .HiddenSiteSettings( context: context, ss: ss) .HiddenServerScript( context: context, ss: ss, scriptValues: scriptValues) .ExtendedSql(context: context) .Hidden( controlId: "Log", value: (new { Log = context.GetLog() }).ToJson()) .Hidden( controlId: "data-validation-maxlength-type", value: Parameters.Validation.MaxLengthCountType) .Hidden( controlId: "data-validation-maxlength-regex", value: Parameters.Validation.SingleByteCharactorRegexClient) : hb); }
protected void Session_Start() { Session["StartTime"] = DateTime.Now; Session["LastAccessTime"] = Session["StartTime"]; Session["SessionGuid"] = Strings.NewGuid(); if (Sessions.LoggedIn()) { if (Authentications.Windows()) { Ldap.UpdateOrInsert(HttpContext.Current.User.Identity.Name); } var userId = Sessions.UserId(); var tenantId = Rds.ExecuteScalar_int(statements: Rds.SelectUsers( column: Rds.UsersColumn().TenantId(), where : Rds.UsersWhere().UserId(userId))); Sessions.SetTenantId(tenantId); StatusesInitializer.Initialize(tenantId); var userModel = new UserModel( SiteSettingsUtilities.UsersSiteSettings(), userId); if (userModel.AccessStatus == Databases.AccessStatuses.Selected && !userModel.Disabled) { userModel.SetSession(); } else { Authentications.SignOut(); SetAnonymousSession(); Response.Redirect(HttpContext.Current.Request.Url.ToString()); } } else { SetAnonymousSession(); } switch (Request.AppRelativeCurrentExecutionFilePath.ToLower()) { case "~/backgroundtasks/do": case "~/reminderschedules/remind": break; default: new SysLogModel().Finish(); break; } }
private static string LoginId( Context context, ParameterAccessor.Parts.Ldap ldap, SearchResult result) { var loginId = Authentications.Windows(context: context) ? NetBiosName( context: context, result: result, ldap: ldap) : result.Property( context: context, name: ldap.LdapSearchProperty); return(loginId); }
private static string LoginId( Context context, ParameterAccessor.Parts.Ldap ldap, LdapEntry entry) { var loginId = Authentications.Windows(context: context) ? NetBiosName( context: context, entry: entry, ldap: ldap) : entry.Property( context: context, name: ldap.LdapSearchProperty); return(loginId); }
protected void Session_Start() { var context = new Context(); Session["StartTime"] = DateTime.Now; Session["LastAccessTime"] = Session["StartTime"]; Session["SessionGuid"] = Strings.NewGuid(); if (Sessions.LoggedIn()) { if (Authentications.Windows()) { Ldap.UpdateOrInsert( context: context, loginId: context.LoginId); } var userModel = GetUser(context: context); context = userModel.GetContext(); StatusesInitializer.Initialize(context: context); if (userModel.AccessStatus == Databases.AccessStatuses.Selected && !userModel.Disabled) { userModel.SetSession(); } else { Authentications.SignOut(); SetAnonymousSession(); Response.Redirect(HttpContext.Current.Request.Url.ToString()); } } else { SetAnonymousSession(); } switch (Request.AppRelativeCurrentExecutionFilePath.ToLower()) { case "~/backgroundtasks/do": case "~/reminderschedules/remind": break; default: new SysLogModel(context: context).Finish(context: context); break; } }
public ActionResult Login(string returnUrl, string ssocode = "") { var context = new Context(); var log = new SysLogModel(context: context); if ((Parameters.Authentication.Provider == "SAML-MultiTenant") && (ssocode != string.Empty)) { var tenant = new TenantModel().Get( context: context, ss: SiteSettingsUtilities.TenantsSiteSettings(context), where : Rds.TenantsWhere().Comments(ssocode)); if (tenant.AccessStatus == Databases.AccessStatuses.Selected) { Authentications.SignOut(context: context); var redirectUrl = Saml.SetIdpConfiguration(context, tenant.TenantId); if (redirectUrl != null) { return(new RedirectResult(redirectUrl)); } } return(new RedirectResult(Locations.InvalidSsoCode(context))); } if (context.Authenticated) { if (context.QueryStrings.Bool("new")) { Authentications.SignOut(context: context); } log.Finish(context: context); return(base.Redirect(Url.IsLocalUrl(returnUrl) ? returnUrl : Locations.Top(context: context))); } var html = UserUtilities.HtmlLogin( context: context, returnUrl: Url.IsLocalUrl(returnUrl) ? returnUrl : "", message: Request.QueryString["expired"] == "1" && !Request.IsAjaxRequest() ? Messages.Expired(context: context).Text : string.Empty); ViewBag.HtmlBody = html; log.Finish(context: context, responseSize: html.Length); return(View()); }
/// <summary> /// Fixed: /// </summary> public (string redirectUrl, string redirectResultUrl, string html) Login( Context context, string returnUrl, bool isLocalUrl, string ssocode = "") { var log = new SysLogModel(context: context); if (context.Authenticated) { if (context.QueryStrings.Bool("new")) { Authentications.SignOut(context: context); } log.Finish(context: context); return(isLocalUrl ? returnUrl : Locations.Top(context: context), null, null); } if ((Parameters.Authentication.Provider == "SAML-MultiTenant") && (ssocode != string.Empty)) { var tenant = new TenantModel().Get( context: context, ss: SiteSettingsUtilities.TenantsSiteSettings(context), where : Rds.TenantsWhere().Comments(ssocode)); if (tenant.AccessStatus == Databases.AccessStatuses.Selected) { var redirectUrl = Saml.SetIdpConfiguration(context, tenant.TenantId); if (redirectUrl != null) { return(null, redirectUrl, null); } } return(null, Locations.InvalidSsoCode(context), null); } var html = UserUtilities.HtmlLogin( context: context, returnUrl: isLocalUrl ? returnUrl : string.Empty, message: context.QueryStrings.ContainsKey("expired") && context.QueryStrings["expired"] == "1" && !context.Ajax ? Messages.Expired(context: context).Text : string.Empty); log.Finish(context: context, responseSize: html.Length); return(null, null, html); }
public ActionResult Challenge(string idp = "") { if (!Authentications.SAML()) { var context = new ContextImplement(); return(new RedirectResult( Pleasanter.Libraries.Responses.Locations.Login(context: context))); } return(new ChallengeResult(Saml2Defaults.Scheme, new AuthenticationProperties( items: string.IsNullOrEmpty(idp) ? null : new Dictionary <string, string> { ["idp"] = idp }) { RedirectUri = Url.Action(nameof(SsoSync)) })); }
public void OnAuthorization(AuthorizationContext filterContext) { if (Sessions.LoggedIn()) { var userModel = new UserModel().Get( ss: null, where : Rds.UsersWhere() .TenantId(Sessions.TenantId()) .UserId(Sessions.UserId()) .Disabled(0)); if (userModel.AccessStatus != Databases.AccessStatuses.Selected) { Authentications.SignOut(); filterContext.Result = new RedirectResult(Locations.Login()); } else { userModel.SetSession(); } } }
private static int UserIdentity() { var id = HttpContext.Current.Session["UserId"].ToInt(); if (id != 0) { return(id.ToInt()); } else { var name = HttpContext.Current?.User.Identity.Name; var userId = Authentications.Windows() && name != null ? Rds.ExecuteScalar_int(statements : Rds.SelectUsers( column: Rds.UsersColumn().UserId(), where : Rds.UsersWhere().LoginId(name))) : name.ToInt(); HttpContext.Current.Session["UserId"] = userId; return(userId); } }
public ActionResult Login(string returnUrl) { var log = new SysLogModel(); if (Sessions.LoggedIn()) { if (Libraries.Requests.QueryStrings.Bool("new")) { Authentications.SignOut(); } log.Finish(); return(base.Redirect(Locations.Top())); } var html = UserUtilities.HtmlLogin( returnUrl, (Request.Query.TryGetValue("expired", out var value) == true ? value.Any(v => v == "1") : false) && !Libraries.Requests.Request.IsAjaxRequest(Request) ? Messages.Expired().Text : string.Empty); ViewBag.HtmlBody = html; log.Finish(html.Length); return(View()); }