Skip to content

Instantly share code, notes, and snippets.

@gistlyn
Last active February 14, 2024 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gistlyn/e2e8b9b94e448b4c24367b4390a2b30a to your computer and use it in GitHub Desktop.
Save gistlyn/e2e8b9b94e448b4c24367b4390a2b30a to your computer and use it in GitHub Desktop.
Use Redis Auth Repository (requires auth)
using ServiceStack;
using ServiceStack.Web;
using ServiceStack.Auth;
using ServiceStack.Configuration;
using ServiceStack.Redis;
[assembly: HostingStartup(typeof(MyApp.ConfigureAuthRepository))]
namespace MyApp
{
// Custom User Table with extended Metadata properties
public class AppUser : UserAuth
{
public string? ProfileUrl { get; set; }
public string? LastLoginIp { get; set; }
public DateTime? LastLoginDate { get; set; }
}
public class AppUserAuthEvents : AuthEvents
{
public override void OnAuthenticated(IRequest req, IAuthSession session, IServiceBase authService,
IAuthTokens tokens, Dictionary<string, string> authInfo)
{
var authRepo = HostContext.AppHost.GetAuthRepository(req);
using (authRepo as IDisposable)
{
var userAuth = (AppUser)authRepo.GetUserAuth(session.UserAuthId);
userAuth.ProfileUrl = session.GetProfileUrl();
userAuth.LastLoginIp = req.UserHostAddress;
userAuth.LastLoginDate = DateTime.UtcNow;
authRepo.SaveUserAuth(userAuth);
}
}
}
public class ConfigureAuthRepository : IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureServices(services => services.AddSingleton<IAuthRepository>(c =>
new RedisAuthRepository<AppUser, UserAuthDetails>(c.GetRequiredService<IRedisClientsManager>())))
.ConfigureAppHost(appHost => {
var authRepo = appHost.Resolve<IAuthRepository>();
authRepo.InitSchema();
// CreateUser(authRepo, "admin@email.com", "Admin User", "p@55wOrd", roles:new[]{ RoleNames.Admin });
}, afterConfigure: appHost =>
appHost.AssertPlugin<AuthFeature>().AuthEvents.Add(new AppUserAuthEvents()));
// Add initial Users to the configured Auth Repository
public void CreateUser(IAuthRepository authRepo, string email, string name, string password, string[] roles)
{
if (authRepo.GetUserAuthByUserName(email) == null)
{
var newAdmin = new AppUser { Email = email, DisplayName = name };
var user = authRepo.CreateUserAuth(newAdmin, password);
authRepo.AssignRoles(user, roles);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment