forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppHost.cs
More file actions
398 lines (344 loc) · 14.8 KB
/
Copy pathAppHost.cs
File metadata and controls
398 lines (344 loc) · 14.8 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//#define HTTP_LISTENER
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Net;
using System.Threading;
using Funq;
using Raven.Client;
using Raven.Client.Document;
using ServiceStack.Admin;
using ServiceStack.Auth;
using ServiceStack.Authentication.OAuth2;
using ServiceStack.Authentication.OpenId;
using ServiceStack.Authentication.RavenDb;
using ServiceStack.Caching;
using ServiceStack.Configuration;
using ServiceStack.Data;
using ServiceStack.DataAnnotations;
using ServiceStack.FluentValidation;
using ServiceStack.Logging;
using ServiceStack.MiniProfiler;
using ServiceStack.MiniProfiler.Data;
using ServiceStack.OrmLite;
using ServiceStack.Razor;
using ServiceStack.Text;
using ServiceStack.Web;
#if HTTP_LISTENER
namespace ServiceStack.Auth.Tests
#else
namespace ServiceStack.AuthWeb.Tests
#endif
{
#if HTTP_LISTENER
public class AppHost : AppHostHttpListenerBase
#else
public class AppHost : AppHostBase
#endif
{
public static ILog Log = LogManager.GetLogger(typeof(AppHost));
public AppHost()
: base("Test Auth", typeof(AppHost).Assembly) { }
public override void Configure(Container container)
{
Plugins.Add(new RazorFormat());
Plugins.Add(new ServerEventsFeature());
container.Register(new DataSource());
var UsePostgreSql = false;
if (UsePostgreSql)
{
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(
"Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
PostgreSqlDialect.Provider) {
ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
});
}
else
{
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider) {
ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
});
}
using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
db.DropAndCreateTable<Rockstar>();
db.Insert(Rockstar.SeedData);
}
JsConfig.EmitCamelCaseNames = true;
//Register a external dependency-free
container.Register<ICacheClient>(new MemoryCacheClient());
//Configure an alt. distributed persistent cache that survives AppDomain restarts. e.g Redis
//container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
//Enable Authentication an Registration
ConfigureAuth(container);
//Create your own custom User table
using (var db = container.Resolve<IDbConnectionFactory>().Open())
db.DropAndCreateTable<UserTable>();
SetConfig(new HostConfig {
DebugMode = true,
AddRedirectParamsToQueryString = true,
});
}
private void ConfigureAuth(Container container)
{
//Enable and register existing services you want this host to make use of.
//Look in Web.config for examples on how to configure your oauth providers, e.g. oauth.facebook.AppId, etc.
var appSettings = new AppSettings();
//Register all Authentication methods you want to enable for this web app.
Plugins.Add(new AuthFeature(
() => new CustomUserSession(), //Use your own typed Custom UserSession type
new IAuthProvider[] {
//new AspNetWindowsAuthProvider(this) {
// LoadUserAuthFilter = LoadUserAuthInfo,
// AllowAllWindowsAuthUsers = true
//},
new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
new TwitterAuthProvider(appSettings), //Sign-in with Twitter
new FacebookAuthProvider(appSettings), //Sign-in with Facebook
new DigestAuthProvider(appSettings), //Sign-in with Digest Auth
new BasicAuthProvider(), //Sign-in with Basic Auth
new GoogleOpenIdOAuthProvider(appSettings), //Sign-in with Google OpenId
new YahooOpenIdOAuthProvider(appSettings), //Sign-in with Yahoo OpenId
new OpenIdOAuthProvider(appSettings), //Sign-in with Custom OpenId
new GoogleOAuth2Provider(appSettings), //Sign-in with Google OAuth2 Provider
new LinkedInOAuth2Provider(appSettings), //Sign-in with LinkedIn OAuth2 Provider
new GithubAuthProvider(appSettings), //Sign-in with GitHub OAuth Provider
new YandexAuthProvider(appSettings), //Sign-in with Yandex OAuth Provider
new VkAuthProvider(appSettings), //Sign-in with VK.com OAuth Provider
new OdnoklassnikiAuthProvider(appSettings), //Sign-in with Odnoklassniki OAuth Provider
}));
#if HTTP_LISTENER
//Required for DotNetOpenAuth in HttpListener
OpenIdOAuthProvider.OpenIdApplicationStore = new InMemoryOpenIdApplicationStore();
#endif
//Provide service for new users to register so they can login with supplied credentials.
Plugins.Add(new RegistrationFeature());
//override the default registration validation with your own custom implementation
Plugins.Add(new CustomRegisterPlugin());
var authRepo = CreateOrmLiteAuthRepo(container, appSettings);
//var authRepo = CreateRavenDbAuthRepo(container, appSettings);
//AuthProvider.ValidateUniqueUserNames = false;
try
{
authRepo.CreateUserAuth(new CustomUserAuth
{
Custom = "CustomUserAuth",
DisplayName = "Credentials",
FirstName = "First",
LastName = "Last",
FullName = "First Last",
Email = "demis.bellot@gmail.com",
}, "test");
authRepo.CreateUserAuth(new CustomUserAuth
{
Custom = "CustomUserAuth",
DisplayName = "Credentials",
FirstName = "First",
LastName = "Last",
FullName = "First Last",
UserName = "mythz",
}, "test");
}
catch (Exception ignoreExistingUser) {}
Plugins.Add(new RequestLogsFeature());
}
private static IUserAuthRepository CreateRavenDbAuthRepo(Container container, AppSettings appSettings)
{
container.Register<IDocumentStore>(c =>
new DocumentStore { Url = "http://macbook:8080/" });
var documentStore = container.Resolve<IDocumentStore>();
documentStore.Initialize();
container.Register<IAuthRepository>(c =>
new RavenDbUserAuthRepository<CustomUserAuth,CustomUserAuthDetails>(c.Resolve<IDocumentStore>()));
return (IUserAuthRepository)container.Resolve<IAuthRepository>();
}
private static IUserAuthRepository CreateOrmLiteAuthRepo(Container container, AppSettings appSettings)
{
//Store User Data into the referenced SqlServer database
container.Register<IAuthRepository>(c =>
new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
//Use OrmLite DB Connection to persist the UserAuth and AuthProvider info
var authRepo = (OrmLiteAuthRepository) container.Resolve<IAuthRepository>();
//If using and RDBMS to persist UserAuth, we must create required tables
if (appSettings.Get("RecreateAuthTables", false))
authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
else
authRepo.InitSchema(); //Create only the missing tables
return authRepo;
}
public void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
if (userSession == null)
return;
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
var user = UserPrincipal.FindByIdentity(pc, userSession.UserAuthName);
tokens.DisplayName = user.DisplayName;
tokens.Email = user.EmailAddress;
tokens.FirstName = user.GivenName;
tokens.LastName = user.Surname;
tokens.FullName = (String.IsNullOrWhiteSpace(user.MiddleName))
? "{0} {1}".Fmt(user.GivenName, user.Surname)
: "{0} {1} {2}".Fmt(user.GivenName, user.MiddleName, user.Surname);
tokens.PhoneNumber = user.VoiceTelephoneNumber;
}
}
catch (MultipleMatchesException mmex)
{
Log.Error("Multiple windows user info for '{0}'".Fmt(userSession.UserAuthName), mmex);
}
catch (Exception ex)
{
Log.Error("Could not retrieve windows user info for '{0}'".Fmt(tokens.DisplayName), ex);
}
}
}
public class CustomUserAuth : UserAuth
{
public string Custom { get; set; }
}
public class CustomUserAuthDetails : UserAuthDetails
{
public string Custom { get; set; }
}
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
if (password == "test")
return true;
throw HttpError.Unauthorized("Custom Error Message");
}
public override object Authenticate(IServiceBase authService, IAuthSession session, Authenticate request)
{
try
{
return base.Authenticate(authService, session, request);
}
catch (Exception ex)
{
return ex;
}
}
}
//Provide extra validation for the registration process
public class CustomRegisterPlugin : IPlugin
{
public class CustomRegistrationValidator : RegistrationValidator
{
public CustomRegistrationValidator()
{
RuleSet(ApplyTo.Post, () =>
{
RuleFor(x => x.UserName).Must(x => false)
.WithMessage("CustomRegistrationValidator is fired");
});
}
}
public void Register(IAppHost appHost)
{
appHost.RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
}
}
public class CustomUserSession : AuthUserSession
{
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
var jsv = authService.Request.Dto.Dump();
"OnAuthenticated(): {0}".Print(jsv);
}
public override void OnRegistered(IRequest httpReq, IAuthSession session, IServiceBase service)
{
"OnRegistered()".Print();
}
}
public class DataSource
{
public string[] Items = new[] { "Eeny", "meeny", "miny", "moe" };
}
public class UserTable
{
public int Id { get; set; }
public string CustomField { get; set; }
}
[Route("/channels/{Channel}/chat")]
public class PostChatToChannel : IReturn<ChatMessage>
{
public string From { get; set; }
public string ToUserId { get; set; }
public string Channel { get; set; }
public string Message { get; set; }
public string Selector { get; set; }
}
public class ChatMessage
{
public long Id { get; set; }
public string FromUserId { get; set; }
public string FromName { get; set; }
public string DisplayName { get; set; }
public string Message { get; set; }
public string UserAuthId { get; set; }
public bool Private { get; set; }
}
[Route("/channels/{Channel}/raw")]
public class PostRawToChannel : IReturnVoid
{
public string From { get; set; }
public string ToUserId { get; set; }
public string Channel { get; set; }
public string Message { get; set; }
public string Selector { get; set; }
}
public class ServerEventsService : Service
{
private static long msgId;
public IServerEvents ServerEvents { get; set; }
public object Any(PostChatToChannel request)
{
var sub = ServerEvents.GetSubscriptionInfo(request.From);
if (sub == null)
throw HttpError.NotFound("Subscription {0} does not exist".Fmt(request.From));
var msg = new ChatMessage
{
Id = Interlocked.Increment(ref msgId),
FromUserId = sub.UserId,
FromName = sub.DisplayName,
Message = request.Message,
};
if (request.ToUserId != null)
{
msg.Private = true;
ServerEvents.NotifyUserId(request.ToUserId, request.Selector, msg);
var toSubs = ServerEvents.GetSubscriptionInfosByUserId(request.ToUserId);
foreach (var toSub in toSubs)
{
msg.Message = "@{0}: {1}".Fmt(toSub.DisplayName, msg.Message);
ServerEvents.NotifySubscription(request.From, request.Selector, msg);
}
}
else
{
ServerEvents.NotifyChannel(request.Channel, request.Selector, msg);
}
return msg;
}
public void Any(PostRawToChannel request)
{
var sub = ServerEvents.GetSubscriptionInfo(request.From);
if (sub == null)
throw HttpError.NotFound("Subscription {0} does not exist".Fmt(request.From));
if (request.ToUserId != null)
{
ServerEvents.NotifyUserId(request.ToUserId, request.Selector, request.Message);
}
else
{
ServerEvents.NotifyChannel(request.Channel, request.Selector, request.Message);
}
}
}
}