示例#1
0
        public async void when_registering_2_account_with_same_twitterId()
        {
            var twitterId = Guid.NewGuid();

            var sut        = new AccountServiceClient(BaseUrl, SessionId, new DummyPackageInfo(), null, null);
            var newAccount = new RegisterAccount
            {
                AccountId = Guid.NewGuid(),
                Phone     = "5145551234",
                Country   = new CountryISOCode("CA"),
                Email     = GetTempEmail(),
                Name      = "First Name Test",
                TwitterId = twitterId.ToString()
            };
            await sut.RegisterAccount(newAccount);

            var newAccount2 = new RegisterAccount
            {
                AccountId = Guid.NewGuid(),
                Phone     = "5145551234",
                Country   = new CountryISOCode("CA"),
                Email     = GetTempEmail(),
                Name      = "First Name Test",
                TwitterId = twitterId.ToString()
            };

            Assert.Throws <WebServiceException>(async() => await sut.RegisterAccount(newAccount2), "CreateAccount_AccountAlreadyExist");
        }
示例#2
0
        public async Task <ActionResult <AccountMessage> > AccountRegister(RegisterAccount account)
        {
            if (!ModelState.IsValid)
            {
                return(new AccountMessage()
                {
                    Success = false,
                    Message = "Unknown validation error"
                });
            }

            CaptchaCheck captcha = new CaptchaCheck(account.RecaptchaToken);

            if (!captcha.Verify())
            {
                return new AccountMessage()
                       {
                           Success = false,
                           Message = "Invalid captcha! Please refresh the page and try again."
                       }
            }
            ;

            return(await _accountService.Register(account));
        }
    }
        public ActionResult RegisterAccount(RegisterAccount model)
        {
            try
            {
                var user = new User
                {
                    Firstname  = model.Firstname,
                    Lastname   = model.Lastname,
                    Email      = model.Email,
                    Password   = model.Password,
                    Age        = model.Age,
                    Gender     = model.Gender,
                    PictureURL = "https://pbs.twimg.com/profile_images/1724449330/stick_man_by_minimoko94-d2zvfn8.png",
                    Searchable = model.Searchable
                };

                databas.addUser(user);
                databas.saveUser();
                return(RedirectToAction("LogInView", "Login"));
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#4
0
        public async Task <IActionResult> Register([FromBody] RegisterAccount account)
        {
            if (!ModelState.IsValid)
            {
                return(Ok(new AuthFailedResponse
                {
                    Errors = ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage))
                }));
            }

            var authResponse = await _identityService.RegisterAsync(account.Username, account.Email, account.Password);

            if (!authResponse.Success)
            {
                return(Ok(new AuthFailedResponse
                {
                    Errors = authResponse.Errors
                }));
            }

            return(Ok(new AuthSuccessResponse
            {
                Token = authResponse.Token,
                RefreshToken = authResponse.RefreshToken
            }));
        }
示例#5
0
        public async void when_updating_twitter_account_password()
        {
            var          sut       = new AccountServiceClient(BaseUrl, SessionId, new DummyPackageInfo(), null, null);
            const string password  = "******";
            var          accountId = Guid.NewGuid();
            var          twitterId = Guid.NewGuid();

            var newAccount = new RegisterAccount
            {
                AccountId = Guid.NewGuid(),
                Phone     = "5145551234",
                Country   = new CountryISOCode("CA"),
                Email     = GetTempEmail(),
                Name      = "First Name Test",
                TwitterId = twitterId.ToString()
            };
            await sut.RegisterAccount(newAccount);

            await new AuthServiceClient(BaseUrl, SessionId, new DummyPackageInfo(), null, null).AuthenticateTwitter(newAccount.TwitterId);
            var request = new UpdatePassword
            {
                AccountId       = accountId,
                CurrentPassword = password,
                NewPassword     = "******"
            };

            Assert.Throws <WebServiceException>(async() => await sut.UpdatePassword(request));
        }
示例#6
0
        public async Task <AccountMessage> Register(RegisterAccount _account)
        {
            Common.Models.Account accountUsername = _unitOfWorkAccountSearch.Account.GetByUsername(_account.Username);
            //Common.Models.Account accountEmail = await _dbContext.Account.FirstOrDefaultAsync(a => a.Username == _account.Username);

            if (accountUsername != null)
            {
                return(new AccountMessage()
                {
                    Success = false,
                    Message = "Username is already in use"
                });
            }

            Common.Models.Account acc = new Common.Models.Account()
            {
                Username = _account.Username,
                Password = Argon2.Hash(_account.Password)
            };

            _unitOfWorkAccount.Account.Add(acc);

            _unitOfWorkAccount.Save();

            return(new AccountMessage()
            {
                Success = true,
                Message = acc.GenerateJwt()
            });
        }
示例#7
0
        public async Task <ActionResult> Register(RegisterAccount model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    Year     = model.Year,
                    Name     = model.Name,
                    SurName  = model.SurName,
                    Password = model.Password,
                    Country  = model.Country
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Login", "Account"));
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return(View(model));
        }
        public ActionResult RegisterAccount(RegisterAccount model)
        {
            try
            {
                var user = new User
                {
                    Firstname  = model.Firstname,
                    Lastname   = model.Lastname,
                    Email      = model.Email,
                    Password   = model.Password,
                    Age        = model.Age,
                    Gender     = model.Gender,
                    PictureURL = model.PictureURL,
                    Searchable = model.Searchable
                };

                databas.addUser(user);
                databas.saveUser();
                return(RedirectToAction("Login", "Account"));
            }
            catch (Exception)
            {
                throw;
            }


            return(View());
        }
        private async Task CheckFacebookAccount()
        {
            using (this.Services().Message.ShowProgress())
            {
                var info = await _facebookService.GetUserInfo();

                var data = new RegisterAccount();
                data.FacebookId = info.Id;
                data.Email      = info.Email;
                data.Name       = Params.Get(info.Firstname, info.Lastname)
                                  .Where(n => n.HasValue()).JoinBy(" ");

                try
                {
                    await _accountService.GetFacebookAccount(info.Id);
                    await OnLoginSuccess();
                }
                catch (Exception)
                {
                    DoSignUp(new
                    {
                        facebookId = info.Id,
                        name       = Params.Get(info.Firstname, info.Lastname).Where(n => n.HasValue()).JoinBy(" "),
                        email      = info.Email,
                    });
                }
            }
        }
示例#10
0
        public OperationResult Register(RegisterAccount command)
        {
            var operation = new OperationResult();

            if (_accountRepository.Exist(x => x.Username == command.Username || x.Mobile == command.Mobile))
            {
                return(operation.Failed(ApplicationMessages.DuplicatedRecord));
            }

            var    ImageFolderName = Tools.ToFolderName(this.GetType().Name);
            string ImagePath;

            if (command.ProfilePhoto != null)
            {
                ImagePath = $"{ImageFolderName}/{command.Fname}-{command.Lname}";
            }
            else
            {
                ImagePath = $"{ImageFolderName}";
            }
            var filepath = _fileUploader.Upload(command.ProfilePhoto, ImagePath);
            var password = _passwordHasher.Hash(command.Password);

            var account = new Account(command.Fname, command.Lname, command.Username, password,
                                      command.Mobile, command.RoleId, filepath);

            _accountRepository.Create(account);
            _accountRepository.SaveChanges();
            return(operation.Succedded());
        }
示例#11
0
        public OperationResult Register(RegisterAccount command)
        {
            var operationResult = new OperationResult();

            if (string.IsNullOrWhiteSpace(command.Mobile) ||
                string.IsNullOrWhiteSpace(command.FullName) ||
                string.IsNullOrWhiteSpace(command.Username) ||
                string.IsNullOrWhiteSpace(command.Password) ||
                string.IsNullOrWhiteSpace(command.RePassword))
            {
                return(operationResult.Failed(ApplicationMessage.RegisterErrorMessage));
            }

            if (_accountRepo.Exists(c => c.Username == command.Username || c.Mobile == command.Mobile))
            {
                return(operationResult.Failed(ApplicationMessage.duplicated));
            }
            if (command.Password != command.RePassword)
            {
                return(operationResult.Failed(ApplicationMessage.PasswordsNotMatch));
            }

            var path        = $"ProfileImage";
            var Picturepath = _fileUploader.Upload(command.ProfilePicture, path);

            var password = PasswordHelper.EncodePasswordMd5(command.Password);

            var Account = new Account(command.FullName, command.Username, command.Mobile,
                                      password, command.RoleId, Picturepath);

            _accountRepo.Create(Account);
            _accountRepo.Save();
            return(operationResult.Succeeded("ثبت نام شما در فروشگاه انجام شد میتواند در فروشگاه لاگین کنید"));
        }
 public RegisterAccountTests()
 {
     validator = new RegisterAccountValidation();
     command   = new RegisterAccount(
         "testUser",
         "*****@*****.**",
         "123456");
 }
示例#13
0
        public IActionResult AddUser(RegisterAccount registerAccount)
        {
            registerAccount.Password    = "******";
            registerAccount.PayPassword = "******";
            var result = AccountService.AddUser(registerAccount, null);

            return(MyJson(result));
        }
        public GivenAnAccountIsRegistered()
        {
            Given($"a valid {nameof(RegisterAccount)} command",
                  () => _command = new RegisterAccount {
                FirstName = "Jony", LastName = "Swieboda"
            });

            When($"the command is handled by the account", () => SystemUnderTest = Account.Register(_command));
        }
        public IActionResult OnGetCreate()
        {
            var command = new RegisterAccount()
            {
                Roles = _roleApplication.List()
            };

            return(Partial("./Create", command));
        }
示例#16
0
 public RegisterAccountHandlerTests()
 {
     fakeAccountRepository = new Mock <IAccountRepository>();
     command = new RegisterAccount(
         "testUser",
         "*****@*****.**",
         "123456");
     identityResultSuccess = IdentityResult.Success;
     identityResultFailure = IdentityResult.Failed(new IdentityError());
 }
示例#17
0
        public ActionResult AddUser(RegisterAccount registerAccount)
        {
            registerAccount.Password    = "******";
            registerAccount.PayPassword = "******";
            var result = AccountService.AddUser(registerAccount, null);

            return(new MyJsonResult {
                Data = result
            });
        }
示例#18
0
        //[HttpPost("sign-up", Name = "PostRegister")]
        public async Task <IActionResult> Register(RegisterAccount account, string returnTo)
        {
            if (ModelState.IsValid)
            {
                User user = new User()
                {
                    UserName      = account.UserName,
                    Email         = account.Email,
                    FirstName     = account.FirstName,
                    LastName      = account.LastName,
                    RegisteredOn  = account.RegisteredOn,
                    PhotoFileName = "user_avatar.png",
                    GeneratedKey  = Guid.NewGuid().ToString("N"),
                    PhoneNumber   = account.PhoneNumberUser
                };

                var result = await _userManager.CreateAsync(user, account.Password);

                if (result.Succeeded)
                {
                    if (_userManager.Options.SignIn.RequireConfirmedEmail)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callBackUrl = Url.RouteUrl("ConfirmEmail", new { code, key = user.GeneratedKey },
                                                       Request.Scheme);

                        var message = $"<a href=\"{callBackUrl}\"> Confirm Email </a>";

                        await _emailSender.SendEmailAsync(user.Email, "Confirm Email", message);

                        return(View("SuccessRegister", user));
                    }
                    if (_userManager.Options.SignIn.RequireConfirmedPhoneNumber)
                    {
                        var token = await _userManager
                                    .GenerateChangePhoneNumberTokenAsync(user, user.PhoneNumber);

                        await _smsSender.SendSmsAsync(account.PhoneNumberUser, token);

                        return(View("ConfirmPhone", new Confirmphone  {
                            Returnto = returnTo, Username = account.UserName
                        }));
                    }

                    // await _signInManager.SignInAsync(user, false);

                    return(RedirectToLocal(returnTo));
                }

                this.AddErrors(result);
            }

            return(View(account));
        }
示例#19
0
        public IActionResult OnPostRegister(RegisterAccount command)
        {
            var result = _accountApplication.Register(command);

            if (result.IsSuccedded)
            {
                return(RedirectToPage("/Account"));
            }
            RegisterMessage = result.Message;
            return(RedirectToPage("/Account"));
        }
示例#20
0
        public static async Task <bool> RegisterAccountAsync(string userName, string email, string password)
        {
            RegisterAccount registerAccount = new RegisterAccount()
            {
                UserName = userName,
                Email    = email,
                Password = password
            };

            return(await HttpConnector.Instance.PostAsync <RegisterAccount, bool>("Api/Account/Register", registerAccount, true));
        }
        private async void OnRegistrationFinished(RegisterAccount data)
        {
            if (data == null)
            {
                return;
            }

            _registrationService.PrepareNewRegistration();

            //no confirmation required
            if (Settings.AccountActivationDisabled ||
                data.FacebookId.HasValue() ||
                data.TwitterId.HasValue() ||
                data.IsConfirmed)
            {
                var facebookId = data.FacebookId;
                var twitterId  = data.TwitterId;

                using (this.Services().Message.ShowProgress())
                {
                    try
                    {
                        if (facebookId.HasValue())
                        {
                            Func <Task> loginAction = () => _accountService.GetFacebookAccount(facebookId);
                            await loginAction.Retry(TimeSpan.FromSeconds(1), 5);                             //retry because the account is maybe not yet created server-side
                        }
                        else if (twitterId.HasValue())
                        {
                            Func <Task> loginAction = () => _accountService.GetTwitterAccount(twitterId);
                            await loginAction.Retry(TimeSpan.FromSeconds(1), 5);                             //retry because the account is maybe not yet created server-side
                        }
                        else
                        {
                            Email    = data.Email;
                            Password = data.Password;
                            Func <Task> loginAction = () => _accountService.SignIn(data.Email, data.Password);
                            await loginAction.Retry(TimeSpan.FromSeconds(1), 5); //retry because the account is maybe not yet created server-side
                        }

                        await OnLoginSuccess();
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                    }
                }
            }
            else
            {
                Email = data.Email;
            }
        }
        public async Task <ActionResult> Register(RegisterAccount model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (string.IsNullOrEmpty(model.IsTeacher))
                {
                    Student student = new Student {
                        IsBlocked = false, Name = model.Name, Surname = model.SurName, Email = model.Email
                    };

                    repository.Students.Create(student);
                }
                else
                {
                    TeacherList teacherList = new TeacherList {
                        Name = model.Name, Email = model.Email, Surname = model.SurName
                    };
                    repository.TeacherLists.Create(teacherList);
                }
                if (result.Succeeded)
                {
                    //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    // генерируем токен для подтверждения регистрации
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    // создаем ссылку для подтверждения
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code },
                                                 protocol: Request.Url.Scheme);
                    // отправка письма
                    await UserManager.SendEmailAsync(user.Id, "Подтверждение электронной почты",
                                                     "Для завершения регистрации перейдите по ссылке:: <a href=\""
                                                     + callbackUrl + "\">завершить регистрацию</a>");

                    return(View("DisplayEmail"));
                    // Дополнительные сведения о включении подтверждения учетной записи и сброса пароля см. на странице https://go.microsoft.com/fwlink/?LinkID=320771.
                    // Отправка сообщения электронной почты с этой ссылкой
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>");

                    // return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            WriteToInfo("-- User: "******" was registrated - action register, AccountController");
            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return(View(model));
        }
示例#23
0
        private RegisterDataEntity ConvertRegisterAccountToRegisterDataEntity(RegisterAccount entry)
        {
            var entity = new RegisterDataEntity();

            entity.UserId   = entry.UserId;
            entity.UserName = entry.UserName;
            entity.Password = entry.Password;
            entity.Name     = entry.Name;
            entity.Email    = entry.Email;

            return(entity);
        }
示例#24
0
        public void Handle(RegisterAccount command)
        {
            Repository.Save(new Account(command.Id, command.Email));

            ++counter;
            if ((System.DateTime.UtcNow - last).TotalSeconds > 1)
            {
                last = System.DateTime.UtcNow;
                System.Console.WriteLine(counter);
                counter = 0;
            }
        }
示例#25
0
        public ActionResult Register(RegisterAccount mode)
        {
            var entity = ConvertRegisterAccountToRegisterDataEntity(mode);

            if (ModelState.IsValid)
            {
                _entities.AddToRegisterDataEntities(entity);
                _entities.SaveChanges();
                ModelState.Clear();
                mode = null;
            }
            return(View(mode));
        }
        public async Task <IActionResult> Register(RegisterAccount account)
        {
            var user = new IdentityUser {
                UserName = account.Username, Email = account.Email
            };
            var result = await userManager.CreateAsync(user, account.Password);

            if (result.Succeeded)
            {
                await signInManager.SignInAsync(user, isPersistent : false);
            }
            return(Ok(result));
        }
示例#27
0
        protected async Task <Account> GetNewTwitterAccount()
        {
            var newAccount = new RegisterAccount {
                AccountId = Guid.NewGuid(), Phone = "5145551234", Country = new CountryISOCode("CA"), Email = GetTempEmail(), Name = "First Name Test", TwitterId = Guid.NewGuid().ToString(), Language = "en"
            };
            await AccountService.RegisterAccount(newAccount);

            var authResponse = await new AuthServiceClient(BaseUrl, null, new DummyPackageInfo(), null, null).AuthenticateTwitter(newAccount.TwitterId);

            SessionId = authResponse.SessionId;

            return(await AccountService.GetMyAccount());
        }
示例#28
0
        public RegisterViewModel(IAuthenticationService service, INavigationService navigation, ISettingsService settings)
        {
            this.service    = service;
            this.navigation = navigation;
            this.settings   = settings;
            Account         = new RegisterAccount();

            this.RegisterCommand = new RelayCommand(async() => await RegisterAsync());
            this.GoBackCommand   = new RelayCommand(() =>
            {
                navigation.GoBack();
            });
        }
示例#29
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="registerAccount">注册信息</param>
 public Account(RegisterAccount registerAccount)
     : base(Guid.NewGuid())
 {
     this.AccountName      = registerAccount.AccountName;
     this.AccountNO        = registerAccount.AccountNO;
     this.Mail             = registerAccount.Mail;
     this.Mobile           = registerAccount.Mobile;
     this.Password         = registerAccount.Password;
     this.PayPassword      = registerAccount.PayPassword;
     this.Status           = AccountStatus.Enabled;
     this.CreateTime       = DateTime.Now;
     this.IsAdmin          = false;
     this.VerificationCode = new VerificationCode(this);
 }
示例#30
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="registerAccount">注册信息</param>
        /// <returns>注册结果</returns>
        public static Result Register(RegisterAccount registerAccount)
        {
            Result result = new Result();

            try
            {
                // 创建用户对象 执行注册方法和创建验证码方法
                var account = new Account(registerAccount);
                account.Register();

                // 将领域对象转化成数据库实体对象
                var mAccount          = AccountBuilder.ToMAccount(account);
                var mVerificationCode = account.VerificationCode.ToMVerificationCode();

                // 通过工资单元持久化数据
                using (var unit = DbContext.CreateIPowerUnitOfWork())
                {
                    var accountesRepository        = DbContext.CreateIAccountesRepository(unit);
                    var verificationCodeRepository = DbContext.CreateIVerificationCodeRepository(unit);

                    accountesRepository.Add(mAccount);
                    verificationCodeRepository.Add(mVerificationCode);

                    unit.Complete();
                }

                result.IsSucceed = true;

                // 异步调用发送邮件的方法
                Task.Factory.StartNew(() =>
                {
                    RegisterSendMail(account);
                });
            }
            catch (CustomException ex)
            {
                result.IsSucceed = false;
                result.Message   = ex.Message;
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Message   = "注册失败";

                // 记录异常日志
                LogService.WriteLog(ex, "注册帐号");
            }
            return(result);
        }