private static void ConfigureMembershipReboot(IAppBuilder app)
        {
            var cookieOptions = new CookieAuthenticationOptions
            {
                AuthenticationType = MembershipRebootOwinConstants.AuthenticationType
            };
            Func<IDictionary<string, object>, UserAccountService> uaFunc = env =>
            {
                var appInfo = new OwinApplicationInformation(
                    env,
                    "Test",
                    "Test Email Signature",
                    "/Login",
                    "/Register/Confirm/",
                    "/Register/Cancel/",
                    "/PasswordReset/Confirm/");

                var config = new MembershipRebootConfiguration();
                var emailFormatter = new EmailMessageFormatter(appInfo);
                // uncomment if you want email notifications -- also update smtp settings in web.config
                config.AddEventHandler(new EmailAccountEventsHandler(emailFormatter));

                var svc = new UserAccountService(config, new DefaultUserAccountRepository());
                svc.TwoFactorAuthenticationPolicy = new OwinCookieBasedTwoFactorAuthPolicy(env);
                return svc;
            };
            Func<IDictionary<string, object>, AuthenticationService> authFunc = env =>
            {
                return new OwinAuthenticationService(cookieOptions.AuthenticationType, uaFunc(env), env);
            };

            app.UseMembershipReboot(cookieOptions, uaFunc, authFunc);
        }
        public ValidationResult Validate(UserAccountService service, UserAccount account, string value)
        {
            if (String.IsNullOrWhiteSpace(value))
            {
                return new ValidationResult(Resources.ValidationMessages.PasswordRequired);
            }
            
            if (value.Length < this.MinimumLength)
            {
                return new ValidationResult(String.Format(Resources.ValidationMessages.PasswordLength, this.MinimumLength));
            }

            var upper = value.Any(x => Char.IsUpper(x));
            var lower = value.Any(x => Char.IsLower(x));
            var digit = value.Any(x => Char.IsDigit(x));
            var other = value.Any(x => !Char.IsUpper(x) && !Char.IsLower(x) && !Char.IsDigit(x));

            var vals = new bool[] { upper, lower, digit, other };
            var matches = vals.Where(x => x).Count();
            if (matches < this.MinimumNumberOfComplexityRules)
            {
                return new ValidationResult(String.Format(Resources.ValidationMessages.PasswordComplexityRules, this.MinimumNumberOfComplexityRules));
            }

            return null;
        }
 public static void CreateLocalAccount( IDocumentStore masterStore,string email,string password ,UserAccountService userAccountService)
 {
     if (userAccountService == null) return;
     var account=userAccountService.CreateAccount(null, password, email);
     account.RequiresPasswordReset = true;
     userAccountService.Update(account);
 }
 public static IUserService Factory(string connString)
 {
     var repo = new DefaultUserAccountRepository(connString);
     var userAccountService = new UserAccountService(config, repo);
     var userSvc = new MembershipRebootUserService<UserAccount>(userAccountService, repo);
     return userSvc;
 }
 public HomeController(
     ClaimsBasedAuthenticationService claimsBasedAuthenticationService,
     UserAccountService userAccountService)
 {
     this.claimsBasedAuthenticationService = claimsBasedAuthenticationService;
     this.userAccountService = userAccountService;
 }
 public HomeController(
     AuthenticationService AuthenticationService,
     UserAccountService userAccountService)
 {
     this.AuthenticationService = AuthenticationService;
     this.userAccountService = userAccountService;
 }
 public static IUserService Factory()
 {
     var repo = new DefaultUserAccountRepository();
     var userAccountService = new UserAccountService(config, repo);
     var userSvc = new UserService<UserAccount>(userAccountService, repo);
     return userSvc;
 }
 public static IUserManager Create()
 {
     var repo = new DefaultUserAccountRepository();
     repo.QueryFilter = RelationalUserAccountQuery.Filter;
     repo.QuerySort = RelationalUserAccountQuery.Sort;
     var svc = new UserAccountService(config, repo);
     return new UserManager<UserAccount>(svc, repo, repo);
 }
 public IdentityRepository()
 {
     var settings = SecuritySettings.FromConfiguration();
     settings.RequireAccountVerification = false;
     var config = new MembershipRebootConfiguration(settings);
     this.userSvc = new UserAccountService(config, new BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository());
     this.groupSvc = new GroupService(new BrockAllen.MembershipReboot.Ef.DefaultGroupRepository());
 }
            public void Test(UserAccountService<HierarchicalUserAccount> service,
                string username, string password, string certThumb)
            {
                string email = $"{username}@example.com";
                var account = service.CreateAccount(username, password, email);

                service.AddCertificate(account.ID, certThumb, username);
            }
 public void Dispose()
 {
     if (this.userService != null)
     {
         this.userService.Dispose();
         this.userService = null;
     }
 }
 public void Dispose()
 {
     if (this.UserAccountService != null)
     {
         this.UserAccountService.Dispose();
         this.UserAccountService = null;
     }
 }
            public void CanAuthenticateAnAccount(UserAccountService<HierarchicalUserAccount> service,
                string username, string password)
            {
                string email = $"{username}@example.com";
                service.CreateAccount(username, password, email);

                service.Authenticate(username, password).ShouldBe(true);
            }
 public AccountController(
     AuthenticationService<NhUserAccount> authenticationService,
     ISession session,
     UserAccountService<NhUserAccount> userAccountService)
 {
     this.authenticationService = authenticationService;
     this.session = session;
     this.userAccountService = userAccountService;
 }
Example #15
0
        public virtual void SignIn(TAccount account, string method, bool persistent = false)
        {
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }
            if (String.IsNullOrWhiteSpace(method))
            {
                throw new ArgumentNullException("method");
            }

            if (!account.IsLoginAllowed || account.IsAccountClosed)
            {
                throw new ValidationException(UserAccountService.GetValidationMessage(MembershipRebootConstants.ValidationMessages.LoginNotAllowed));
            }

            if (!account.IsAccountVerified && UserAccountService.Configuration.RequireAccountVerification)
            {
                throw new ValidationException(UserAccountService.GetValidationMessage(MembershipRebootConstants.ValidationMessages.AccountNotVerified));
            }

            if (account.RequiresTwoFactorAuthToSignIn() ||
                account.RequiresPasswordReset ||
                this.UserAccountService.IsPasswordExpired(account))
            {
                Tracing.Verbose("[AuthenticationService.SignIn] detected account requires two factor or password reset to sign in: {0}", account.ID);
                IssuePartialSignInToken(account, method);
                return;
            }

            // gather claims
            var claims = GetAllClaims(account, method);

            // get custom claims from properties
            var cmd = new MapClaimsFromAccount <TAccount> {
                Account = account
            };

            this.UserAccountService.ExecuteCommand(cmd);
            if (cmd.MappedClaims != null)
            {
                claims.AddRange(cmd.MappedClaims);
            }

            // create principal/identity
            var id = new ClaimsIdentity(claims, method);
            var cp = new ClaimsPrincipal(id);

            // claims transform
            if (this.ClaimsAuthenticationManager != null)
            {
                cp = ClaimsAuthenticationManager.Authenticate(String.Empty, cp);
            }

            // issue cookie
            IssueToken(cp, persistentCookie: persistent);
        }
 protected override IIdentityManagerService CreateIdentityManager()
 {
     var config = new MembershipRebootConfiguration<TestUserAccount>();
     config.RequireAccountVerification = false;
     config.PasswordHashingIterationCount = 100;
     
     var repository = new TestUserAccountRepository();
     userAccountService = new UserAccountService<TestUserAccount>(config, repository);
     return new IdentityManagerService<TestUserAccount>(userAccountService, repository);
 }
Example #17
0
        public static void RemoveClaims <TAccount>(this UserAccountService <TAccount> svc, Guid accountID, IEnumerable <Claim> claims)
            where TAccount : UserAccount
        {
            if (svc == null)
            {
                throw new ArgumentNullException("account");
            }

            svc.RemoveClaims(accountID, new UserClaimCollection(claims));
        }
Example #18
0
        public static void UpdateClaims <TAccount>(this UserAccountService <TAccount> svc, Guid accountID, IEnumerable <Claim> additions = null, IEnumerable <Claim> deletions = null)
            where TAccount : UserAccount
        {
            if (svc == null)
            {
                throw new ArgumentNullException("account");
            }

            svc.UpdateClaims(accountID, new UserClaimCollection(additions), new UserClaimCollection(deletions));
        }
Example #19
0
        public static void ConfigureTwoFactorAuthenticationPolicy <TAccount>(this UserAccountService <TAccount> svc, ITwoFactorAuthenticationPolicy policy)
            where TAccount : UserAccount
        {
            if (svc == null)
            {
                throw new ArgumentNullException("account");
            }

            svc.AddCommandHandler(new TwoFactorAuthPolicyCommandHandler(policy));
        }
 public static void CreateLocalAccount(IDocumentStore masterStore, string email, string password)
 {
     
     
     var accountRepo = new RavenUserAccountRepository(masterStore);
     var userAccountService = new UserAccountService(accountRepo)
     {
         Configuration = MembershipRebootConfig.Create()
     };
     CreateLocalAccount(masterStore, email, password, userAccountService);
 }
Example #21
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         this.userAccountService.TryDispose();
         this.userAccountService = null;
         this.authenticationService.TryDispose();
         this.authenticationService = null;
     }
     base.Dispose(disposing);
 }
            public void CanCreateANewUserAccount(UserAccountService<HierarchicalUserAccount> service,
                string username, string password)
            {
                string email = $"{username}@example.com";
                var account = service.CreateAccount(username, password, email);

                var fromDb = service.GetByID(account.ID);

                fromDb.ShouldNotBe(null);
                fromDb.Username.ShouldBe(username);
                fromDb.Email.ShouldBe(email);
            }
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (this.userAccountService != null)
         {
             this.userAccountService.Dispose();
             this.userAccountService = null;
         }
     }
     base.Dispose(disposing);
 }
        public IIdentityManagerService Create()
        {
            var db = new DefaultMembershipRebootDatabase(this.connString);
            var userrepo = new DefaultUserAccountRepository(db);
            var usersvc = new UserAccountService<RelationalUserAccount>(config, userrepo);

            var grprepo = new DefaultGroupRepository(db);
            var grpsvc = new GroupService<RelationalGroup>(config.DefaultTenant, grprepo);

            var svc = new MembershipRebootIdentityManagerService<RelationalUserAccount, RelationalGroup>(usersvc, userrepo, grpsvc, grprepo);
            return new DisposableIdentityManagerService(svc, db);
        }
 /// <summary>
 /// Load your modules or register your services here!
 /// </summary>
 /// <param name="kernel">The kernel.</param>
 private static void RegisterServices(IKernel kernel)
 {
     var config = MembershipRebootConfig.Create();
     kernel.Bind<IUserAccountRepository<CustomUserAccount>>().To<CustomRepository>().InRequestScope();
     kernel.Bind<AuthenticationService<CustomUserAccount>>().To<SamAuthenticationService<CustomUserAccount>>();
     kernel.Bind<UserAccountService<CustomUserAccount>>().ToMethod(ctx =>
         {
             var svc = new UserAccountService<CustomUserAccount>(config, ctx.Kernel.Get<IUserAccountRepository<CustomUserAccount>>());
             svc.TwoFactorAuthenticationPolicy = new AspNetCookieBasedTwoFactorAuthPolicy<CustomUserAccount>();
             return svc;
         });
 }
 public IIdentityManagerService Create()
 {
     var userrepo = new DefaultUserAccountRepository(this.connString);
     userrepo.QueryFilter = RelationalUserAccountQuery.Filter;
     userrepo.QuerySort = RelationalUserAccountQuery.Sort;
     var usersvc = new UserAccountService<RelationalUserAccount>(config, userrepo);
     
     var grprepo = new DefaultGroupRepository(this.connString);
     var grpsvc = new GroupService<RelationalGroup>(grprepo);
     
     var svc = new MembershipRebootIdentityManagerService<RelationalUserAccount, RelationalGroup>(usersvc, userrepo, grpsvc, grprepo);
     return new DisposableIdentityManagerService(svc, userrepo);
 }
        public IdentityRepository()
        {
            var settings = SecuritySettings.FromConfiguration();
            settings.RequireAccountVerification = false;
            settings.PasswordHashingIterationCount = 50000;
            var config = new MembershipRebootConfiguration(settings);
            var uarepo = new BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository();
            this.userSvc = new UserAccountService(config, uarepo);
            this.userQuery = uarepo;

            var grpRepo = new BrockAllen.MembershipReboot.Ef.DefaultGroupRepository();
            this.groupSvc = new GroupService(config.DefaultTenant, grpRepo);
            this.groupQuery = grpRepo;
        }
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            var config = MembershipRebootConfig.Create();
            var policy = new AspNetCookieBasedTwoFactorAuthPolicy(debugging: true);
            kernel.Bind<UserAccountService>().ToMethod(ctx =>
            {
                var svc = new UserAccountService(config, ctx.Kernel.Get<IUserAccountRepository>());
                svc.TwoFactorAuthenticationPolicy = policy;
                return svc;
            });
            kernel.Bind<AuthenticationService>().To<SamAuthenticationService>();

            RegisterEntityFramework(kernel);
            //RegisterMongoDb(kernel);
            //RegisterRavenDb(kernel);
        }
        public void Send(Message msg)
        {

            var accountRepo = new RavenUserAccountRepository(MasterStore);
            var userAccountService = new UserAccountService(accountRepo)
            {
                Configuration = MembershipRebootConfig.Create()
            };
            string user = msg.To;// think this is probably e-mail address...
            UserAccount account;
            account = userAccountService.GetByEmail(user);
            // who the message is to will give us org and user- query masterdb by username
            using (var session = MasterStore.OpenSession())
            {
            }
                var notify = new Notification
                {

                    //need url to put in here.
                    Body =
                        String.Format("Your temporary Illuminate passowrd is : {0} \n Please follow the instructions at {1} to change your password and login to Illuminate", password),
                    SendDate = DateTime.Now,
                    Title = string.Format("Your temporary Illuminate password"),
                    From = EmailRecipient.GetIlluminateRecipient(),
                    NotificationRecipients = new NotificationRecipient[]
                                                                              {
                                                                                  new NotificationRecipient
                                                                                      {

                                                                                          NotificationDeliveryTypes =
                                                                                          
                                                                                              NotificationDeliveryTypes
                                                                                                  .Email,
                                                                                      
                                                                                          Users = new List<SimpleUser>{OrgUser.ToSimpleUser()}

                                                                                      }
                                                                              },
                };

                using (var orgSession = OrgStore.OpenSession())
                {
                orgSession.Store(notify);
                orgSession.SaveChanges();
            }
        }
        private void InitDb()
        {
            using (var db = new BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository())
            {
                var svc = new UserAccountService(db);
                if (svc.GetByUsername("admin") == null)
                {
                    var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
                    svc.VerifyAccount(account.VerificationKey);

                    account = svc.GetByID(account.ID);
                    account.AddClaim(ClaimTypes.Role, "Administrator");
                    account.AddClaim(ClaimTypes.Role, "Manager");
                    account.AddClaim(ClaimTypes.Country, "USA");
                    svc.Update(account);
                }
            }
        }
 public StudentsController(UserAccountService<CustomUserAccount> userAccountService)
 {
     db = new CustomDb();
     this.userAccountService = userAccountService;
     try
     {
         var findacc = db.Users.Find(1); //find admin user
         if (findacc == null)
         {
             //add admin user
             var acc = this.userAccountService.CreateAccount("admin", "adminx", "*****@*****.**");
             this.userAccountService.AddClaim(acc.ID, Constants.ClaimTypes.Role, "Admin");
         }
     }
     catch (Exception e)
     {
         //admin exist
     }
 }
        public async Task Invoke(IDictionary<string, object> env)
        {
            var ctx = new OwinContext(env);

            using (var db = new BrockAllen.MembershipReboot.Ef.DefaultUserAccountRepository())
            {
                var settings = SecuritySettings.FromConfiguration();
                var mrConfig = new MembershipRebootConfiguration(settings);
                mrConfig.ConfigureCookieBasedTwoFactorAuthPolicy(new OwinCookieBasedTwoFactorAuthPolicy(env));

                var appInfo = new OwinApplicationInformation(env,
                    "Test", "Test Email Signature",
                    "/Login",
                    "/Register/Confirm/",
                    "/Register/Cancel/",
                    "/PasswordReset/Confirm/",
                    "/ChangeEmail/Confirm/");

                var emailFormatter = new EmailMessageFormatter(appInfo);
                if (settings.RequireAccountVerification)
                {
                    // uncomment if you want email notifications -- also update smtp settings in web.config
                    mrConfig.AddEventHandler(new EmailAccountCreatedEventHandler(emailFormatter));
                }
                // uncomment if you want email notifications -- also update smtp settings in web.config
                mrConfig.AddEventHandler(new EmailAccountEventsHandler(emailFormatter));

                var uaSvc = new UserAccountService(mrConfig, db);
                var anSvc = new OwinAuthenticationService(uaSvc, env);
                try
                {
                    ctx.SetUserAccountService(uaSvc);
                    ctx.SetAuthenticationService(anSvc);

                    await next(env);
                }
                finally
                {
                    ctx.SetUserAccountService(null);
                    ctx.SetAuthenticationService(null);
                }
            }
        }
Example #33
0
        protected override void OnApplicationStarted()
        {
            //hook into the fed auth config created event do we can do some extra steps
            FederatedAuthentication.FederationConfigurationCreated += FederatedAuthentication_FederationConfigurationCreated;
            XmlConfigurator.Configure(); //configure logging
            Logger = LogManager.GetLogger("Illuminate");
            Logger.Information("Illuminate Web Application Started");

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteTable.Routes.MapHubs();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Logger.Information("About to create master store when starting Illuminate");
            DataBase = IlluminateDatabase.Create(new DocumentStore { ConnectionStringName = "RavenServer" });
            Logger.Information("Created master store when starting Illuminate");
            Mappings.Initialise();
            BinderConfig.RegisterBinders();

            var accountRepoStore = new DocumentStore {ConnectionStringName = "RavenServer"};
            accountRepoStore.Initialize();
            var accountRepo = new RavenUserAccountRepository(accountRepoStore);
            UserAccountService = new UserAccountService(accountRepo)
            {
                Configuration = MembershipRebootConfig.Create()
            };
            RebootAuthenticationService = new SamAuthenticationService(UserAccountService);
            //in DEBUG mode attach raven profiler so we can profile all org stores if needed
#if DEBUG
            foreach (var store in DataBase.GetAllOrgStores().Where(store => store.Identifier.EndsWith("halethorpe")))
            {
                Raven.Client.MvcIntegration.RavenProfiler.InitializeFor(store);
            }
            //Raven.Client.MvcIntegration.RavenProfiler.InitializeFor(DataBase.MasterStore);
#endif
            //task manager does some stuff as background processes
            Logger.Information("about to initialize taskmanager when starting Illuminate");
            TaskManager.Initialize(new IlluminateRegistry());
            Logger.Information("Initialized taskmanager when starting Illuminate");
            
        }
        private static void ConfigureMembershipReboot(IAppBuilder app)
        {
            System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
            var cookieOptions = new CookieAuthenticationOptions
            {
                AuthenticationType = MembershipRebootOwinConstants.AuthenticationType
            };

            var appInfo = new OwinApplicationInformation(
                app,
                "Test",
                "Test Email Signature",
                "/Login",
                "/Register/Confirm/",
                "/Register/Cancel/",
                "/PasswordReset/Confirm/");

            var config = new MembershipRebootConfiguration();
            var emailFormatter = new EmailMessageFormatter(appInfo);
            // uncomment if you want email notifications -- also update smtp settings in web.config
            config.AddEventHandler(new EmailAccountEventsHandler(emailFormatter));

            Func<IDictionary<string, object>, UserAccountService> uaFunc = env =>
            {
                var svc = new UserAccountService(config, new DefaultUserAccountRepository());
                var debugging = false;
#if DEBUG
                debugging = true;
#endif
                svc.ConfigureTwoFactorAuthenticationCookies(env, debugging);
                return svc;
            };
            Func<IDictionary<string, object>, AuthenticationService> authFunc = env =>
            {
                return new OwinAuthenticationService(cookieOptions.AuthenticationType, uaFunc(env), env);
            };

            app.UseMembershipReboot(cookieOptions, uaFunc, authFunc);
        }
Example #35
0
        public ValidationResult Validate(UserAccountService <TAccount> service, TAccount account, string value)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            var list = new List <ValidationResult>();

            foreach (var item in this)
            {
                var result = item.Validate(service, account, value);
                if (result != null && result != ValidationResult.Success)
                {
                    return(result);
                }
            }
            return(null);
        }
        public virtual void SignIn(TAccount account, string method, bool persistent = false)
        {
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }
            if (String.IsNullOrWhiteSpace(method))
            {
                throw new ArgumentNullException("method");
            }

            if (!account.IsLoginAllowed || account.IsAccountClosed)
            {
                throw new ValidationException(UserAccountService.GetValidationMessage("LoginNotAllowed"));
            }

            if (!account.IsAccountVerified && UserAccountService.Configuration.RequireAccountVerification)
            {
                throw new ValidationException(UserAccountService.GetValidationMessage("AccountNotVerified"));
            }

            if (account.RequiresTwoFactorAuthToSignIn() ||
                account.RequiresPasswordReset ||
                this.UserAccountService.IsPasswordExpired(account))
            {
                Tracing.Verbose("[AuthenticationService.SignIn] detected account requires two factor or password reset to sign in: {0}", account.ID);
                IssuePartialSignInToken(account, method);
                return;
            }

            // gather claims
            var claims = GetBasicClaims(account, method);

            // get the rest
            if (!String.IsNullOrWhiteSpace(account.Email))
            {
                claims.Add(new Claim(ClaimTypes.Email, account.Email));
            }
            if (!String.IsNullOrWhiteSpace(account.MobilePhoneNumber))
            {
                claims.Add(new Claim(ClaimTypes.MobilePhone, account.MobilePhoneNumber));
            }
            var x509 = from c in account.Certificates
                       select new Claim(ClaimTypes.X500DistinguishedName, c.Subject);

            claims.AddRange(x509);
            var otherClaims =
                (from uc in account.Claims
                 select new Claim(uc.Type, uc.Value)).ToList();

            claims.AddRange(otherClaims);

            // get custom claims from properties
            var cmd = new MapClaimsFromAccount <TAccount> {
                Account = account
            };

            this.UserAccountService.ExecuteCommand(cmd);
            if (cmd.MappedClaims != null)
            {
                claims.AddRange(cmd.MappedClaims);
            }

            // create principal/identity
            var id = new ClaimsIdentity(claims, method);
            var cp = new ClaimsPrincipal(id);

            // claims transform
            if (this.ClaimsAuthenticationManager != null)
            {
                cp = ClaimsAuthenticationManager.Authenticate(String.Empty, cp);
            }

            // issue cookie
            IssueToken(cp, persistentCookie: persistent);
        }
Example #37
0
 public AuthenticationService(UserAccountService <TAccount> userService, ClaimsAuthenticationManager claimsAuthenticationManager)
 {
     this.UserAccountService          = userService;
     this.ClaimsAuthenticationManager = claimsAuthenticationManager;
 }
Example #38
0
 public AuthenticationService(UserAccountService <TAccount> userService)
     : this(userService, null)
 {
 }
Example #39
0
        public void SignInWithLinkedAccount(
            string tenant,
            string providerName,
            string providerAccountID,
            IEnumerable <Claim> claims,
            out TAccount account)
        {
            account = null;

            if (!UserAccountService.Configuration.MultiTenant)
            {
                tenant = UserAccountService.Configuration.DefaultTenant;
            }

            if (String.IsNullOrWhiteSpace(tenant))
            {
                throw new ArgumentException("tenant");
            }
            if (String.IsNullOrWhiteSpace(providerName))
            {
                throw new ArgumentException("providerName");
            }
            if (String.IsNullOrWhiteSpace(providerAccountID))
            {
                throw new ArgumentException("providerAccountID");
            }
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            var user = GetCurentPrincipal();

            if (user != null && user.Identity.IsAuthenticated)
            {
                // already logged in, so use the current user's account
                account = this.UserAccountService.GetByID(user.GetUserID());
            }
            else
            {
                // see if there's already an account mapped to this provider
                account = this.UserAccountService.GetByLinkedAccount(tenant, providerName, providerAccountID);
                if (account == null)
                {
                    // no account associated, so create one
                    // we need email
                    var email = claims.GetValue(ClaimTypes.Email);
                    if (String.IsNullOrWhiteSpace(email))
                    {
                        throw new ValidationException(UserAccountService.GetValidationMessage(MembershipRebootConstants.ValidationMessages.AccountCreateFailNoEmailFromIdp));
                    }

                    // guess at a name to use
                    var name = claims.GetValue(ClaimTypes.Name);
                    if (name == null ||
                        this.UserAccountService.UsernameExists(tenant, name))
                    {
                        name = email;
                    }
                    else
                    {
                        name = name.Replace(" ", "");
                    }

                    // check to see if email already exists
                    if (this.UserAccountService.EmailExists(tenant, email))
                    {
                        throw new ValidationException(UserAccountService.GetValidationMessage(MembershipRebootConstants.ValidationMessages.LoginFailEmailAlreadyAssociated));
                    }

                    // auto-gen a password, they can always reset it later if they want to use the password feature
                    // this is slightly dangerous if we don't do email account verification, so if email account
                    // verification is disabled then we need to be very confident that the external provider has
                    // provided us with a verified email
                    account = this.UserAccountService.CreateAccount(tenant, name, null, email);
                }
            }

            if (account == null)
            {
                throw new Exception("Failed to locate account");
            }

            // add/update the provider with this account
            this.UserAccountService.AddOrUpdateLinkedAccount(account, providerName, providerAccountID, claims);

            // log them in if the account if they're verified
            if (account.IsAccountVerified || !UserAccountService.Configuration.RequireAccountVerification)
            {
                // signin from the account
                // if we want to include the provider's claims, then perhaps this
                // should be done in the claims transformer
                this.SignIn(account, providerName);
            }
        }
Example #40
0
        public void SignInWithLinkedAccount(
            string tenant,
            string providerName,
            string providerAccountID,
            IEnumerable <Claim> claims,
            out TAccount account)
        {
            account = null;

            if (!UserAccountService.Configuration.MultiTenant)
            {
                tenant = UserAccountService.Configuration.DefaultTenant;
            }

            if (String.IsNullOrWhiteSpace(tenant))
            {
                throw new ArgumentException("tenant");
            }
            if (String.IsNullOrWhiteSpace(providerName))
            {
                throw new ArgumentException("providerName");
            }
            if (String.IsNullOrWhiteSpace(providerAccountID))
            {
                throw new ArgumentException("providerAccountID");
            }
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            Tracing.Information("[AuthenticationService.SignInWithLinkedAccount] tenant: {0}, provider: {1}, id: {2}", tenant, providerName, providerAccountID);

            var user = GetCurentPrincipal();

            if (user != null && user.Identity.IsAuthenticated)
            {
                // already logged in, so use the current user's account
                Tracing.Verbose("[AuthenticationService.SignInWithLinkedAccount] user already logged in as: {0}", user.Identity.Name);
                account = this.UserAccountService.GetByID(user.GetUserID());
            }
            else
            {
                // see if there's already an account mapped to this provider
                account = this.UserAccountService.GetByLinkedAccount(tenant, providerName, providerAccountID);
                if (account == null)
                {
                    Tracing.Verbose("[AuthenticationService.SignInWithLinkedAccount] linked account not found");

                    // no account associated, so create one
                    // we need email
                    var email = claims.GetValue(ClaimTypes.Email);
                    if (String.IsNullOrWhiteSpace(email))
                    {
                        throw new ValidationException(UserAccountService.GetValidationMessage(MembershipRebootConstants.ValidationMessages.AccountCreateFailNoEmailFromIdp));
                    }

                    // check to see if email already exists
                    if (this.UserAccountService.EmailExists(tenant, email))
                    {
                        throw new ValidationException(UserAccountService.GetValidationMessage(MembershipRebootConstants.ValidationMessages.LoginFailEmailAlreadyAssociated));
                    }

                    // guess at a username to use
                    var name = claims.GetValue(ClaimTypes.Name);
                    // remove whitespace
                    if (name != null)
                    {
                        name = ParseValidUsername(name);
                    }

                    // check to see if username already exists
                    if (String.IsNullOrWhiteSpace(name) || this.UserAccountService.UsernameExists(tenant, name))
                    {
                        // try use email for name then
                        name = email.Substring(0, email.IndexOf('@'));
                        name = ParseValidUsername(name);

                        if (this.UserAccountService.UsernameExists(tenant, name))
                        {
                            // gen random username -- this isn't ideal but
                            // they should always be able to change it later
                            name = Guid.NewGuid().ToString("N");
                        }
                    }

                    // create account without password -- user can verify their email and then
                    // do a password reset to assign password
                    Tracing.Verbose("[AuthenticationService.SignInWithLinkedAccount] creating account: {0}, {1}", name, email);
                    account = this.UserAccountService.CreateAccount(tenant, name, null, email);

                    // update account with external claims
                    var cmd = new MapClaimsToAccount <TAccount> {
                        Account = account, Claims = claims
                    };
                    this.UserAccountService.ExecuteCommand(cmd);
                    this.UserAccountService.Update(account);
                }
                else
                {
                    Tracing.Verbose("[AuthenticationService.SignInWithLinkedAccount] linked account found: {0}", account.ID);
                }
            }

            if (account == null)
            {
                throw new Exception("Failed to locate account");
            }

            // add/update the provider with this account
            this.UserAccountService.AddOrUpdateLinkedAccount(account, providerName, providerAccountID, claims);

            // log them in if the account if they're verified
            if (account.IsAccountVerified || !UserAccountService.Configuration.RequireAccountVerification)
            {
                Tracing.Verbose("[AuthenticationService.SignInWithLinkedAccount] signing user in: {0}", account.ID);
                // signin from the account
                // if we want to include the provider's claims, then perhaps this
                // should be done in the claims transformer
                this.SignIn(account, providerName);
            }
            else
            {
                Tracing.Error("[AuthenticationService.SignInWithLinkedAccount] user account not verified, not allowed to login: {0}", account.ID);
            }
        }
 public ClaimsBasedAuthenticationService(UserAccountService userService)
 {
     this.userService = userService;
 }
Example #42
0
 public ValidationResult Validate(UserAccountService <TAccount> service, TAccount account, string value)
 {
     return(func(service, account, value));
 }
Example #43
0
 public AuthenticationService(UserAccountService userService)
 {
     this.UserAccountService = userService;
 }
 public SamAuthenticationService(UserAccountService userService)
     : base(userService)
 {
 }