-
Notifications
You must be signed in to change notification settings - Fork 1
/
Configure.AuthRepository.cs
58 lines (53 loc) · 2.3 KB
/
Configure.AuthRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using ServiceStack;
using ServiceStack.Web;
using ServiceStack.Auth;
using ServiceStack.Configuration;
[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 InMemoryAuthRepository<AppUser, UserAuthDetails>()))
.ConfigureAppHost(appHost => {
var authRepo = appHost.Resolve<IAuthRepository>();
authRepo.InitSchema();
// CreateUser(authRepo, "[email protected]", "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);
}
}
}
}