// The remote server returned an error: (500) Internal Server Error.
        public void CreateAccount()
        {
            const string userName = "******";
            var client = GetClient();
            var item = new Account { UserName = userName };

            client.Add(item);
            client.UnitOfWork.Commit();
            string accountId = item.AccountId;

            //check
            client = GetClient();
            int count = client.Accounts.Where(x => x.AccountId == accountId).Count();
            Assert.Equal(count, 1);

            // clear base
            EndActionClearAccount(userName);
        }
        /// <summary>
        /// Determines whether the specified user name is authorized.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="account">The account.</param>
        /// <param name="types">The types.</param>
        /// <returns><c>true</c> if the specified user name is authorized; otherwise, <c>false</c>.</returns>
        public bool IsAuthorized(string userName, out Account account, params RegisterType[] types)
        {
            var isAuthorized = true;

            var usr = GetAccountByUserName(userName, types);

            if (usr == null)
            {
                isAuthorized = false;
            }
            else // check if user is approved and can access the store
            {
                // check state
                if (usr.AccountState != AccountState.Approved.GetHashCode())
                {
                    isAuthorized = false;
                }
            }

            account = null;
            if (isAuthorized)
            {
                account = usr;
            }

            return isAuthorized;
        }
        public void RemoveUncommitedRoleTest()
        {
            ISecurityRepository client = GetClient();

            var account = new Account() { UserName = "******" };
            var role = new Role() { Name = "testRole" };

            var roleAssignment = new RoleAssignment
            {
                Account = account,
                AccountId = account.AccountId,
                Role = role,
                RoleId = role.RoleId
            };

            client.Attach(account);

            // add role
            account.RoleAssignments.Add(roleAssignment);
            Assert.True(client.IsAttachedTo(roleAssignment));
 
            // remove uncommited role
            account.RoleAssignments.Remove(roleAssignment);
            client.Remove(roleAssignment);
            Assert.False(client.IsAttachedTo(roleAssignment));
        }
        public void CreateAccountWithNewRoleTest()
        {
            const string roleName = "testRole";
            const string userName = "******";
            ISecurityRepository client = GetClient();

            var role = new Role() { Name = roleName };

            var account = new Account() { UserName = userName };

            var roleAssignment = new RoleAssignment
            {
                Account = account,
                AccountId = account.AccountId,
                Role = role,
                RoleId = role.RoleId
            };


            // add role to account
            account.RoleAssignments.Add(roleAssignment);

            client.Add(role);
            client.Add(account);
            client.UnitOfWork.Commit();
            string accountId = account.AccountId;
            string roleId = role.RoleId;
            EndActionClearAccount(userName);
            EndActionClearRole(roleName);

            client = GetClient();
            int count = client.Accounts.Where(x => x.AccountId == accountId).Count();
            Assert.Equal(count, 1);
            count = client.Roles.Where(x => x.RoleId == roleId).Count();
            Assert.Equal(count, 1);
            count = client.RoleAssignments.Where(x => x.RoleId == roleId && x.AccountId == accountId).Count();
            Assert.Equal(count, 1);

        }
Ejemplo n.º 5
0
		/// <summary>
		/// Creates the account.
		/// </summary>
		/// <param name="account">The account.</param>
		public virtual void CreateAccount(Account account)
		{
			_securityRepository.Add(account);
		    SaveSecurityChanges();
		}
Ejemplo n.º 6
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider;
            string providerUserId;

            if (UserHelper.CustomerSession.IsRegistered ||
                !_oAuthSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToLocal(returnUrl);
            }

            if (ModelState.IsValid)
            {
                var user = _userClient.GetAccountByUserName(model.UserName.ToLower());

                //If user has local account then password must be correct in order to associate it with external account
                if (user != null && _oAuthSecurity.HasLocalAccount(user.AccountId.ToString(CultureInfo.InvariantCulture)))
                {
                    if (user.StoreId != UserHelper.CustomerSession.StoreId)
                    {
                        var store = StoreHelper.StoreClient.GetStoreById(user.StoreId);
                        var storeName = store != null ? store.Name : user.StoreId;
                        ModelState.AddModelError("", string.Format("This user name is already registered with store '{0}'. Use different user name or login to store '{0}'.", storeName).Localize());
                    }
                    else if (string.IsNullOrEmpty(model.NewPassword) || !_webSecurity.Login(model.UserName, model.NewPassword))
                    {
                        ModelState.AddModelError("", "This user name is already used. Use correct password or another user name.".Localize());
                    }
                }
                else
                {
                    //If there is any extrenal account associated with given user name, then we cannot allow 
                    //associate any more external logins, because someone could steal account by mapping his own external login
                    var externalAccounts = _oAuthSecurity.GetAccountsFromUserName(model.UserName);

                    if (externalAccounts.Count > 0)
                    {
                        ModelState.AddModelError("", "This user name is already associated with external account. Use different user name.".Localize());
                    }
                    else if (model.CreateLocalLogin)
                    {
                        if (string.IsNullOrEmpty(model.NewPassword) || !model.NewPassword.Equals(model.ConfirmPassword))
                        {
                            ModelState.AddModelError("", "You must specifiy a valid password.".Localize());
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    // Check if user already exists
                    if (user == null)
                    {
                        var id = Guid.NewGuid().ToString();
                        user = new Account
                        {
                            MemberId = id,
                            UserName = model.UserName,
                            StoreId = UserHelper.CustomerSession.StoreId,
                            RegisterType = RegisterType.GuestUser.GetHashCode(),
                            AccountState = AccountState.Approved.GetHashCode()
                        };

                        // Insert a new user into the database
                        _userClient.CreateAccount(user);

                        //Create contact
                        _userClient.CreateContact(new Contact
                        {
                            MemberId = id,
                            FullName = model.UserName
                        });
                    }
                    //Create internal login
                    if (model.CreateLocalLogin && !_oAuthSecurity.HasLocalAccount(user.AccountId.ToString(CultureInfo.InvariantCulture)))
                    {
                        _webSecurity.CreateAccount(model.UserName, model.NewPassword);
                    }

                    //Associate external login with user or create new
                    _oAuthSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);

                    if (_oAuthSecurity.Login(provider, providerUserId, false))
                    {
                        UserHelper.OnPostLogon(model.UserName);
                        return RedirectToLocal(returnUrl);
                    }

                    ModelState.AddModelError("", "Failed to login".Localize());
                }
            }

            ViewBag.ProviderDisplayName = _oAuthSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public async Task<string> CreateUserAndAccountAsync(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false)
        {

            var account = _securityRepository.Accounts.FirstOrDefault(x => x.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase));

            if (account != null)
            {
                throw new InvalidOperationException(string.Format("username {0} already taken", userName));
            }

            var user = new ApplicationUser
            {
                UserName = userName,
                Email = userName,
            };


            var result = await UserManager.CreateAsync(user, password);
            if (result.Succeeded)
            {
                IDictionary<string, object> values = propertyValues as RouteValueDictionary;

                if (values == null && propertyValues != null)
                {
                    var propertyValuesAsDictionary = propertyValues as IDictionary<string, object>;
                    values = propertyValuesAsDictionary != null ? new RouteValueDictionary(propertyValuesAsDictionary)
                                                                : new RouteValueDictionary(propertyValues);
                }

                account = new Account
                {
                    UserName = userName,
                    AccountId = user.Id
                };

                if (values != null)
                {
                    foreach (var prop in account.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(prop => values.ContainsKey(prop.Name)))
                    {
                        prop.SetValue(account, values[prop.Name]);
                    }
                }

                _securityRepository.Add(account);
                _securityRepository.UnitOfWork.Commit();

                if (requireConfirmationToken)
                {
                    return await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                }
            }

            return null;
        }
 public AccountRolesStepViewModel(IRepositoryFactory<ISecurityRepository> repositoryFactory, ISecurityEntityFactory entityFactory, Account item)
     : base(repositoryFactory, entityFactory, item)
 {
 }
        public CreateAccountViewModel(IViewModelsFactory<IAccountOverviewStepViewModel> overviewVmFactory, IViewModelsFactory<IAccountRolesStepViewModel> rolesVmFactory, Account item)
        {
			var itemParameter = new KeyValuePair<string, object>("item", item);
			RegisterStep(overviewVmFactory.GetViewModelInstance(itemParameter));
			RegisterStep(rolesVmFactory.GetViewModelInstance(itemParameter));
		}
Ejemplo n.º 10
0
	    private int AddAccount(string name)
	    {
			var  client = GetRepository();
			var account = new Account { UserName = name };
			client.Add(account);
			client.UnitOfWork.Commit();
			return account.AccountId;
	    }
        public async Task<ActionResult> ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {

            var info = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (UserHelper.CustomerSession.IsRegistered || info == null)
            {
                return RedirectToLocal(returnUrl);
            }

            if (ModelState.IsValid)
            {
                var user = _userClient.GetAccountByUserName(model.Email.ToLower());
                var appUser = await UserManager.FindByNameAsync(model.Email);

                //TODO: there is no guarantee that user is connected by userName
                if (user != null && appUser == null || user == null && appUser != null ||
                    user != null && user.AccountId != appUser.Id)
                {
                    return View("ExternalLoginFailure");
                }

                //If user has local account then password must be correct in order to associate it with external account
                if (appUser != null && await UserManager.HasPasswordAsync(appUser.Id))
                {
                    if (user.StoreId != UserHelper.CustomerSession.StoreId)
                    {
                        var store = StoreHelper.StoreClient.GetStoreById(user.StoreId);
                        var storeName = store != null ? store.Name : user.StoreId;
                        ModelState.AddModelError("", string.Format("This user name is already registered with store '{0}'. Use different user name or login to store '{0}'.", storeName).Localize());
                    }
                    else if (string.IsNullOrEmpty(model.NewPassword) || await _identitySecurity.LoginAsync(model.Email, model.NewPassword) != SignInStatus.Success)
                    {
                        ModelState.AddModelError("", "This user name is already used. Use correct password or another user name.".Localize());
                    }
                }
                else if (model.CreateLocalLogin && (string.IsNullOrEmpty(model.NewPassword) || !model.NewPassword.Equals(model.ConfirmPassword)))
                {
                    ModelState.AddModelError("", "You must specifiy a valid password.".Localize());
                }

                if (ModelState.IsValid)
                {
                    // Check if user already exists
                    if (user == null)
                    {
                        var id = Guid.NewGuid().ToString();
                        user = new Account
                        {
                            MemberId = id,
                            UserName = model.Email,
                            StoreId = UserHelper.CustomerSession.StoreId,
                            RegisterType = RegisterType.GuestUser.GetHashCode(),
                            AccountState = AccountState.Approved.GetHashCode()
                        };

                        // Insert a new user into the database
                        _userClient.CreateAccount(user);

                        //Create contact
                        _userClient.CreateContact(new Contact
                        {
                            MemberId = id,
                            FullName = model.Email
                        });
                    }

                    if (appUser == null)
                    {
                        var result = await _identitySecurity.CreateAccountAsync(model.Email, model.CreateLocalLogin ? model.NewPassword : null);
                        if (result.Succeeded)
                        {
                            appUser = await UserManager.FindByNameAsync(model.Email);
                            result = await UserManager.AddLoginAsync(appUser.Id, info.Login);
                            if (result.Succeeded)
                            {
                                await SignInManager.SignInAsync(appUser, isPersistent: false, rememberBrowser: false);
                                await UserHelper.OnPostLogonAsync(model.Email);
                                return RedirectToLocal(returnUrl);
                            }
                        }
                        AddErrors(result);
                    }
                }
            }

            ViewBag.ProviderDisplayName = info.Login.LoginProvider;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }