You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
services.SetupHangfire(env);// ---publicstaticclassHangfireConfig{publicstaticvoidSetupHangfire(thisIServiceCollectionservices,IWebHostEnvironmentenv){services.AddScoped<IJobContextAccessor,JobContextAccessor>();services.AddScoped<IJobWithUserContext,JobWithUserContext>();// if you want tags with sql server// var tagOptions = new TagsOptions() { TagsListStyle = TagsListStyle.Dropdown };// var hangfireConfig = new MemoryStorageOptions() { };services.AddHangfire(config =>{config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170).UseMemoryStorage().UseColouredConsoleLogProvider().UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings()// if you want tags with sql server// .UseTagsWithSql(tagOptions, hangfireConfig).UseActivator(newJobWithUserContextActivator(services.BuildServiceProvider().GetRequir
10BC0
edService<IServiceScopeFactory>()));});services.AddHangfireServer(options =>{options.WorkerCount=10;options.ServerName=$"PeakLims-{env.EnvironmentName}";if(Consts.HangfireQueues.List().Length>0){options.Queues=Consts.HangfireQueues.List();}});}}
publicstaticclassHangfireQueues{// public const string MyFirstQueue = "my-first-queue";publicstaticstring[]List(){returntypeof(HangfireQueues).GetFields(BindingFlags.Public|BindingFlags.Static|BindingFlags.FlattenHierarchy).Where(fi =>fi.IsLiteral&&!fi.IsInitOnly&&fi.FieldType==typeof(string)).Select(x =>(string)x.GetRawConstantValue()).ToArray();}}
Create the following files
namespacePeakLims.Resources.HangfireUtilities;usingHangfire.Client;usingHangfire.Common;publicclassCurrentUserFilterAttribute:JobFilterAttribute,IClientFilter{publicvoidOnCreating(CreatingContextcontext){varargue=context.Job.Args.FirstOrDefault(x =>xisIJobWithUserContext);if(argue==null)thrownewException($"This job does not implement the {nameof(IJobWithUserContext)} interface");varjobParameters=argueasIJobWithUserContext;varuser=jobParameters?.User;if(user==null)thrownewException($"A User could not be established");context.SetJobParameter("User",user);}publicvoidOnCreated(CreatedContextcontext){}}
@@ -0,0+1,23 @@
namespacePeakLims.Resources.HangfireUtilities;usingHangfire.Dashboard;publicclassHangfireAuthorizationFilter:IDashboardAsyncAuthorizationFilter{privatereadonlyIServiceProvider_serviceProvider;publicHangfireAuthorizationFilter(IServiceProviderserviceProvider){_serviceProvider=serviceProvider;}publicTask<bool>AuthorizeAsync(DashboardContextcontext){// TODO alt -- add login handling with cookie handling// var heimGuard = _serviceProvider.GetService<IHeimGuardClient>();// return await heimGuard.HasPermissionAsync(Permissions.HangfireAccess);varenv=_serviceProvider.GetService<IWebHostEnvironment>();returnTask.FromResult(env.IsDevelopment());}}
publicinterfaceICurrentUserService:IPeakLimsScopedService{
@@ -17,26+18,43 @@ publicinterfaceICurrentUserService:IPeakLimsScopedService
public sealedclassCurrentUserService:ICurrentUserService{privatereadonlyIHttpContextAccessor_httpContextAccessor;privatereadonlyIJobContextAccessor_jobContextAccessor;publicCurrentUserService(IHttpContextAccessorhttpContextAccessor,IJobContextAccessorjobContextAccessor){_httpContextAccessor=httpContextAccessor;_jobContextAccessor=jobContextAccessor;}publicClaimsPrincipal?User=>_httpContextAccessor.HttpContext?.User??CreatePrincipalFromJobContextUserId();publicstring?UserId=>User?.FindFirstValue(ClaimTypes.NameIdentifier);publicstring?Email=>User?.FindFirstValue(ClaimTypes.Email);publicstring?FirstName=>User?.FindFirstValue(ClaimTypes.GivenName);publicstring?LastName=>User?.FindFirstValue(ClaimTypes.Surname);publicstring?Username=>User?.Claims?.FirstOrDefault(x =>x.Typeis"preferred_username" or "username")?.Value;publicstring?ClientId=>User?.Claims?.FirstOrDefault(x =>x.Typeis"client_id" or "clientId")?.Value;publicboolIsMachine=>ClientId!=null;privateClaimsPrincipal?CreatePrincipalFromJobContextUserId(){varuserId=_jobContextAccessor?.UserContext?.User;if(string.IsNullOrEmpty(userId)){returnnull;}varclaims=new[]{newClaim(ClaimTypes.NameIdentifier,userId)};varidentity=newClaimsIdentity(claims,$"hangfirejob-{userId}");returnnewClaimsPrincipal(identity);}}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Additions and Updates
GetAllandJobfeaturesfakeanymoreBasePaginationParametersandExceptionsandValueObjectto api project (BasePaginationParameters.cs already exists (when scaffolding multiple bounded contexts) #124)Commandprop from feature scaffoldingFixed
.in project name (Using some characters in ProjectName breaks generated code #111)Adding Hangfire To an Existing Project
Install
Add this to your Infra Registration
Update
Program.csAdd queues to your consts
Create the following files
Add a permission to
PermissionsUpdate your CurrentUserService
Add this to your test fixture
Add this unit test to
CurrentUserServiceTestsThis discussion was created from the release v0.23.0.
Beta Was this translation helpful? Give feedback.
All reactions