Esempio n. 1
0
        protected virtual async Task <AuthenticateResult> ProcessNewExternalAccountAsync(string tenant, string provider, string providerId, IEnumerable <Claim> claims)
        {
            var user = await TryGetExistingUserFromExternalProviderClaimsAsync(provider, claims);

            if (user == null)
            {
                user = await InstantiateNewAccountFromExternalProviderAsync(provider, providerId, claims);

                var email = claims.GetValue(Constants.ClaimTypes.Email);

                user = userAccountService.CreateAccount(
                    tenant,
                    Guid.NewGuid().ToString("N"),
                    null, email,
                    null, null,
                    user);
            }

            userAccountService.AddOrUpdateLinkedAccount(user, provider, providerId);

            var result = await AccountCreatedFromExternalProviderAsync(user.ID, provider, providerId, claims);

            if (result != null)
            {
                return(result);
            }

            return(await SignInFromExternalProviderAsync(user.ID, provider));
        }
Esempio n. 2
0
        public IActionResult InviteUsers(InviteUsersViewModel values)
        {
            if (string.IsNullOrWhiteSpace(Tenant))
            {
                return(View("Error"));
            }

            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Please correct validation errors");
                return(View(values));
            }

            try
            {
                _userAccountService.CreateAccount(Tenant, values.Email, null, values.Email);
            }
            catch (ValidationException ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(View());
            }

            ModelState.Clear();
            return(View(new InviteUsersViewModel
            {
                Message =
                    $"We've sent {values.FirstName}'s invitation to join the <strong>{Tenant}</strong> team! Tell {values.FirstName} to be on the look out for the email at {values.Email}."
            }));
        }
        /// <summary>
        /// Registers user (typically with default claims)
        /// </summary>
        /// <param name="userRegistration">User registration details</param>
        /// <param name="createAdmin">Grant user admin rights</param>
        /// <returns>ID of registered user</returns>
        public Guid RegisterUserAccount(UserRegistrationDTO userRegistration, bool createAdmin = false)
        {
            using (UnitOfWorkProvider.Create())
            {
                var userClaims = new List <Claim>();

                if (createAdmin)
                {
                    userClaims.Add(new Claim(ClaimTypes.Role, Claims.Admin));
                }
                else
                {
                    // for the moment there is just Player role left
                    userClaims.Add(new Claim(ClaimTypes.Role, Claims.Player));
                }
                var account = coreService.CreateAccount(userRegistration.UserName, userRegistration.Password, userRegistration.Email, null, null);


                AutoMapper.Mapper.Map(userRegistration, account);

                foreach (var claim in userClaims)
                {
                    coreService.AddClaim(account.ID, claim.Type, claim.Value);
                }

                coreService.Update(account);

                return(account.ID);
            }
        }
 private void InitDatabase()
 {
     var svc = new UserAccountService(new EFUserAccountRepository(), null, null);
     if (svc.GetByUsername("admin") == null)
     {
         var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
         svc.VerifyAccount(account.VerificationKey);
         account.AddClaim(ClaimTypes.Role, "Administrator");
         svc.Update(account);
     }
 }
Esempio n. 5
0
 protected void btRegister_Click(object sender, EventArgs e)
 {
     UserAccountService uas = new UserAccountService();
     if (uas.UserExists(txtUserName.Text) || txtPassword.Text != txtConfirm.Text)
         lblResult.Text = "UserName already exists or Password Mistach";
     else
     {
         uas.CreateAccount(txtUserName.Text, txtPassword.Text);
         Response.Redirect("Login.aspx");
     }
 }
 private void InitDatabase()
 {
     var svc = new UserAccountService(new DefaultUserAccountRepository(SecuritySettings.Instance.ConnectionStringName), null, null);
     if (svc.GetByUsername("admin") == null)
     {
         var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
         svc.VerifyAccount(account.VerificationKey);
         account.AddClaim(ClaimTypes.Role, "Administrator");
         svc.Update(account);
     }
 }
        private void InitDatabase()
        {
            var svc = new UserAccountService(new MembershipRebootConfiguration(), new CustomRepository());

            if (svc.GetByUsername("admin") == null)
            {
                var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
                svc.VerifyAccount(account.VerificationKey);
                account.AddClaim(ClaimTypes.Role, "Administrator");
                svc.Update(account);
            }
        }
        private void InitDatabase()
        {
            var svc = new UserAccountService(new MembershipRebootConfiguration(new DefaultUserAccountRepository(SecuritySettings.Instance.ConnectionStringName)));

            if (svc.GetByUsername("admin") == null)
            {
                var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
                svc.VerifyAccount(account.VerificationKey);
                account.AddClaim(ClaimTypes.Role, "Administrator");
                svc.Update(account);
            }
        }
        private void InitDatabase()
        {
            var svc = new UserAccountService(new EFUserAccountRepository(), null, null);

            if (svc.GetByUsername("admin") == null)
            {
                var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
                svc.VerifyAccount(account.VerificationKey);
                account.AddClaim(ClaimTypes.Role, "Administrator");
                svc.SaveChanges();
            }
        }
        public async Task <UserManagementResult <string> > CreateUserAsync(string username, string password, IEnumerable <Claim> claims)
        {
            string[] exclude         = { ClaimTypes.Username, ClaimTypes.Password, ClaimTypes.Email };
            var      otherProperties = claims.Where(x => !exclude.Contains(x.Type)).ToArray();

            try
            {
                var metadata = await GetMetadataAsync();

                var createProps = metadata.UserMetadata.GetCreateProperties();

                var account = new TAccount();
                foreach (var prop in otherProperties)
                {
                    var result = SetUserProperty(createProps, account, prop.Type, prop.Value);
                    if (result.Errors.Any())
                    {
                        return(new UserManagementResult <string>(result.Errors.ToArray()));
                    }
                }

                if (_userAccountService.Configuration.EmailIsUsername)
                {
                    account = _userAccountService.CreateAccount(null, null, password, username, account: account);
                }
                else
                {
                    var emailClaim = claims.SingleOrDefault(x => x.Type == ClaimTypes.Email);
                    var email      = emailClaim?.Value;

                    account = _userAccountService.CreateAccount(null, username, password, email, account: account);
                }

                return(new UserManagementResult <string>(account.ID.ToString("D")));
            }
            catch (ValidationException ex)
            {
                return(new UserManagementResult <string>(new string[] { ex.Message }));
            }
        }
        protected virtual async Task <ExternalAuthenticateResult> ProcessNewExternalAccountAsync(string provider, string providerId, IEnumerable <Claim> claims)
        {
            var acct = userAccountService.CreateAccount(Guid.NewGuid().ToString("N"), null, null);

            userAccountService.AddOrUpdateLinkedAccount(acct, provider, providerId);

            var result = await AccountCreatedFromExternalProviderAsync(acct.ID, provider, providerId, claims);

            if (result != null)
            {
                return(result);
            }

            return(await SignInFromExternalProviderAsync(acct.ID, provider));
        }
Esempio n. 12
0
 private void InitDatabase()
 {
     using (var svc = new UserAccountService(new DefaultUserAccountRepository()))
     {
         if (svc.GetByUsername("admin") == null)
         {
             var account = svc.CreateAccount("admin", "admin123", "*****@*****.**");
             svc.VerifyAccount(account.VerificationKey);
             account.AddClaim(ClaimTypes.Role, "Administrator");
             account.AddClaim(ClaimTypes.Role, "Manager");
             account.AddClaim(ClaimTypes.Country, "USA");
             svc.Update(account);
         }
     }
 }
Esempio n. 13
0
        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);
                }
            }
        }
Esempio n. 14
0
        public IActionResult Create(CreateAccountInputModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    HierarchicalUserAccount account = _userAccountService.CreateAccount(model.Username, PasswordGenerator.GeneratePasswordOfLength(16), model.Email);
                    _userAccountService.SetConfirmedEmail(account.ID, account.Email);
                    _userAccountService.ResetPassword(account.ID);
                    AddClaims(account.ID, model);

                    return(View("Success", model));
                }
                catch (ValidationException ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            return(Create());
        }
Esempio n. 15
0
        public void CreateAccount_CreatesAccountInRepository()
        {
            var result = subject.CreateAccount("test", "test", "*****@*****.**");

            Assert.AreSame(repository.Get(result.ID), result);
        }
Esempio n. 16
0
 public void CreateUser(string userName, string password, string email = null)
 {
     userSvc.CreateAccount(userName, password, email);
 }
Esempio n. 17
0
        /// <summary>
        /// Creates a new user account in both MembershipReboot database and in the MapHive meta database;
        /// sends out a confirmation email if email account and template are provided
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TAccount"></typeparam>
        /// <param name="userAccountService"></param>
        /// <param name="dbCtx"></param>
        /// <param name="emailAccount"></param>
        /// <param name="emailTemplate"></param>
        /// <returns></returns>
        protected internal virtual async Task <T> CreateAsync <T, TAccount>(DbContext dbCtx, UserAccountService <TAccount> userAccountService, IEmailAccount emailAccount = null, IEmailTemplate emailTemplate = null)
            where T : MapHiveUserBase
            where TAccount : RelationalUserAccount
        {
            T output;

            //need to validate the model first
            await ValidateAsync(dbCtx);

            //make sure the email is ALWAYS lower case
            Email = Email.ToLower();

            //check if the email is already used or not; throw validation feedback exception if so
            //Note - could do it in the mh meta, but both dbs must be in sync anyway
            var emailInUse = userAccountService.GetByEmail(Email) != null;

            if (emailInUse)
            {
                throw Validation.Utils.GenerateValidationFailedException(nameof(Email), ValidationErrors.EmailInUse);
            }

            //user account exists in two places - mbr and mh databases. Therefore need to handle them both properly wrapped into transactions

            DbContext mbrDbCtx = GetMembershipRebootDbCtx(userAccountService);

            System.Data.Common.DbTransaction mbrTrans = null;

            System.Data.Common.DbTransaction mhTrans = null;


            //since this method wraps the op on 2 dbs into transactions, it must handle connections manually and take care of closing it aftwerwards
            //it is therefore required to clone contexts with independent conns so the base contexts can be reused
            var clonedMhDbCtx  = dbCtx.Clone(contextOwnsConnection: false);
            var clonedMbrDbCtx = mbrDbCtx.Clone(false);

            try
            {
                //open the connections as otherwise will not be able to begin transaction
                await clonedMbrDbCtx.Database.Connection.OpenAsync();

                await clonedMhDbCtx.Database.Connection.OpenAsync();

                //begin the transaction and set the transaction object back on the db context so it uses it
                mbrTrans = clonedMbrDbCtx.Database.Connection.BeginTransaction();
                clonedMbrDbCtx.Database.UseTransaction(mbrTrans);

                mhTrans = clonedMhDbCtx.Database.Connection.BeginTransaction();
                clonedMhDbCtx.Database.UseTransaction(mhTrans);


                //first create a membership reboot account
                //wire up evt too, to intercept what mbr is trying to say...
                AccountCreatedEvent <TAccount> e = null;

                userAccountService.Configuration.AddEventHandler(new MembershipRebootEventHandlers.AccountCreatedEventHandler <TAccount>(
                                                                     (evt) =>
                {
                    e = evt;
                }));
                var newMbrAccount = userAccountService.CreateAccount(this.Email, Cartomatic.Utils.Crypto.Generator.GenerateRandomString(10), this.Email);

                //so can next pass some data to the mh meta user object
                this.Uuid = newMbrAccount.ID;

                //mbr work done, so can create the user within the mh metadata db
                output = await base.CreateAsync <T>(clonedMhDbCtx);

                //looks like we're good to go, so can commit
                mbrTrans.Commit();
                mhTrans.Commit();


                var opFeedback = new Dictionary <string, object>
                {
                    { nameof(e.InitialPassword), e.InitialPassword },
                    { nameof(e.VerificationKey), e.VerificationKey }
                };

                //if email related objects have been provided, send the account created email
                if (emailAccount != null && emailTemplate != null)
                {
                    EmailSender.Send(
                        emailAccount, emailTemplate.Prepare(opFeedback), Email
                        );
                }

                //finally the user created event
                UserCreated?.Invoke(
                    this,
                    new Events.OpFeedbackEventArgs
                {
                    OperationFeedback = opFeedback
                }
                    );
            }
            catch (Exception ex)
            {
                mbrTrans?.Rollback();
                mhTrans?.Rollback();

                throw Validation.Utils.GenerateValidationFailedException(ex);
            }
            finally
            {
                //try to close the connections as they were opened manually and therefore may not have been closed!
                clonedMhDbCtx.Database.Connection.CloseConnection(dispose: true);
                clonedMbrDbCtx.Database.Connection.CloseConnection(dispose: true);

                mbrTrans?.Dispose();
                mhTrans?.Dispose();
            }

            return(output);
        }
Esempio n. 18
0
        private static void TestClientService()
        {
            List <ClientDTO> list = new List <ClientDTO>();
            IUserAccountRepository <Riganti.Utils.Infrastructure.EntityFramework.UserAccount> uar = Container.Resolve <IUserAccountRepository <Riganti.Utils.Infrastructure.EntityFramework.UserAccount> >();

            uar.GetByUsername("me");
            userAccountService = new UserAccountService <Riganti.Utils.Infrastructure.EntityFramework.UserAccount>(uar);
            userAccountService.CreateAccount("Padge", "12345", "*****@*****.**");
            userAccountService.CreateAccount("Matt", "12345", "*****@*****.**");
            userAccountService.CreateAccount("Mike", "12345", "*****@*****.**");
            var mattAccount  = userAccountService.GetByUsername("Matt");
            var mikeAccount  = userAccountService.GetByUsername("Mike");
            var padgeAccount = userAccountService.GetByUsername("Padge");

            clientService = Container.Resolve <IClientService>();

            //Create
            clientService.CreateClient(mattAccount.ID, new ClientDTO {
                FirstName = "Mattthew", LastName = "Tuck"
            });
            clientService.CreateClient(padgeAccount.ID, new ClientDTO {
                FirstName = "Padge", LastName = "Padgey"
            });
            clientService.CreateClient(mikeAccount.ID, new ClientDTO {
                FirstName = "Mike", LastName = "Sufferer"
            });

            //GetClientByEmail
            ClientDTO matt  = clientService.GetClientByEmail("*****@*****.**");
            ClientDTO mike  = clientService.GetClientByEmail("*****@*****.**");
            ClientDTO padge = clientService.GetClientByEmail("*****@*****.**");

            list.Add(matt);
            list.Add(mike);
            Console.WriteLine(list.Count() == 2 ? "ClientService - TestGetClientByEmail - OK" : "ClientService - TestGetClientByEmail - FAIL");

            clientID2 = padge.ID;
            clientID  = matt.ID;


            //GetClientById
            ClientDTO matthew = clientService.GetClient(matt.ID);

            Console.WriteLine(matthew.FirstName == "Mattthew" && matthew.LastName == "Tuck" ?
                              "ClientService - Test02 - OK" : "ClientService - Test02 - FAIL");

            //ListAllClients
            var clients = clientService.ListAllClients(1);

            Console.WriteLine(clients.TotalResultCount == 3 ? "ClientService - TestListAllClients - OK" : "ClientService - TestListAllClients - FAIL");

            //EditClient
            matthew.FirstName = "Matthew";
            matthew.LastName  = "Lord";
            clientService.EditClient(matthew, matthew.SonglistIDs);
            ClientDTO mattFromDB = clientService.GetClient(matthew.ID);

            Console.WriteLine(mattFromDB.FirstName == "Matthew" && mattFromDB.LastName == "Lord" ?
                              "ClientService - TestEditClient - OK" : "ClientService - TestEditClient - FAIL");

            //DeleteClient
            clientService.DeleteClient(mike.ID);
            ClientDTO mikeFromDB = clientService.GetClientByEmail("*****@*****.**");

            Console.WriteLine(mikeFromDB == null ? "ClientService - TestDeleteClient - OK" : "ClientService - TestDeleteClient - FAIL");
        }