-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathOAuthProvider.cs
59 lines (57 loc) · 2.47 KB
/
OAuthProvider.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
59
using System;
using System.Linq;
using System.Web;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Security;
using DevExpress.ExpressApp.Utils;
using DevExpress.ExpressApp.Web;
using Microsoft.Owin.Security;
using MySolution.Module.BusinessObjects;
using MySolution.Module.Web.Security;
namespace MySolution.Web.Security {
public class OAuthProvider : IAuthenticationProvider {
private readonly Type userType;
private readonly SecurityStrategyComplex security;
public bool CreateUserAutomatically { get; set; }
public OAuthProvider(Type userType, SecurityStrategyComplex security) {
Guard.ArgumentNotNull(userType, "userType");
this.userType = userType;
this.security = security;
}
public object Authenticate(IObjectSpace objectSpace) {
ApplicationUser user = null;
string userEmail = GetUserEmail();
if(!string.IsNullOrEmpty(userEmail)) {
user = (ApplicationUser)objectSpace.FindObject(userType, CriteriaOperator.Parse("OAuthAuthenticationEmails[Email = ?]", userEmail));
if(user == null && CreateUserAutomatically) {
user = (ApplicationUser)objectSpace.CreateObject(userType);
user.UserName = userEmail;
EmailEntity email = objectSpace.CreateObject<EmailEntity>();
email.Email = userEmail;
user.OAuthAuthenticationEmails.Add(email);
((CustomSecurityStrategyComplex)security).InitializeNewUser(objectSpace, user);
objectSpace.CommitChanges();
}
}
else {
WebApplication.Redirect(WebApplication.LogonPage);
}
if(user == null) {
throw new Exception("Login failed");
}
return user;
}
private string GetUserEmail() {
var authentication = HttpContext.Current.GetOwinContext().Authentication;
var externalLoginInfo = authentication.GetExternalLoginInfo();
if(externalLoginInfo != null) {
return externalLoginInfo.Email;
}
var email = authentication.User.Claims.Where(c => c.Type == Microsoft.Identity.Web.ClaimConstants.PreferredUserName).Select(c => c.Value).FirstOrDefault();
return email;
}
public void Setup(params object[] args) {
}
}
}