/// <summary> /// Register user using specific information. /// </summary> /// <param name="model"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public virtual async Task <RegisterUserResult> RegisterUserAsync(RegisterViewModel model, CancellationToken cancellationToken) { // Check user duplicate. var users = _unitOfWork.Users.Search(); var user = await users.FirstOrDefaultAsync(x => x.Email.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase), cancellationToken); if (user != null) { throw new Exception(HttpMessages.UserAlreadyExist); } using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { #region Initialize user user = new User(); user.Email = model.Email; user.LastName = model.LastName; user.FirstName = model.FirstName; // Mark account as pending. user.Status = UserStatuses.Pending; // Hash the password for user protection. user.Password = _profileService.HashPassword(model.Password); _unitOfWork.Users.Insert(user); #endregion #region Initialize token // Find list of profile activation tokens. var profileActivationTokens = _unitOfWork.ProfileActivationTokens.Search(); profileActivationTokens = profileActivationTokens.Where(x => x.Email.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase)); var profileActivationToken = new ProfileActivationToken(); profileActivationToken.Email = model.Email; profileActivationToken.Token = Guid.NewGuid().ToString("D"); profileActivationToken.CreatedTime = 0; // Delete previous activation token and add the new one. _unitOfWork.ProfileActivationTokens.Remove(profileActivationTokens); _unitOfWork.ProfileActivationTokens.Insert(profileActivationToken); #endregion var registerResult = new RegisterUserResult(); registerResult.Email = user.Email; registerResult.Token = profileActivationToken.Token; await _unitOfWork.CommitAsync(); transactionScope.Complete(); return(registerResult); } }
//[ValidateModelState(typeof(CreateUserRequest), "createUserModel")] //TODO: Implement public async Task <IHttpActionResult> Register(CreateUserRequest createUserModel) { RegisterUserRequest registerRequest = new RegisterUserRequest { CreateUser = createUserModel }; RegisterUserResult registerResult = await RegisterUserCommand.ExecuteAsync(registerRequest); if (!registerResult.IdentityResult.Succeeded) { //TODO: Translate errors returned to client return(GetErrorResult(registerResult.IdentityResult)); } //send confirmation email (TODO: Use Domain Event) string code = registerResult.EmailConfirmationCode; ApplicationUser user = registerResult.User; var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }) + @"&zumo-api-version=2.0.0"); await AppUserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); Uri locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id })); return(Created(locationHeader, TheModelFactory.Create(user))); }
public async Task <RegisterUserResult> RegisterUserAsync(User user, string callbackUrl) { var registerUserResult = new RegisterUserResult(); var identity = _mapper.Map <IdentityUser>(user); var result = await _userManager.CreateAsync(identity, user.Password); if (result.Succeeded) { if (_userManager.Options.SignIn.RequireConfirmedAccount) { var code = await _userManager.GenerateEmailConfirmationTokenAsync(identity); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); callbackUrl = $"{callbackUrl}?userId={identity.Id}&code={code}"; await _emailService.SendAsync(user.Email, EmailsContent.ConfirmEmailSubject, string.Format(EmailsContent.ConfirmEmailMessage, HtmlEncoder.Default.Encode(callbackUrl))); registerUserResult.EmailConfirmationRequired = true; } else { await _signInManager.SignInAsync(identity, isPersistent : false); } } else { registerUserResult.RegistrationErrors = result.Errors.Select(error => error.Description); } return(registerUserResult); }
public RegisterUserResult RegisterChatUser(string chatUserName, string password) { IChatData chatData = new StaticChatData(); var result = new RegisterUserResult(); if (chatData.IsUserWithGivenNameExist(chatUserName)) { result.ServiceMessage = "Пользователь с таким именем уже существует.\\nПопробуйте другое имя."; result.RedirectUrl = "#/register"; return(result); } try { chatData.AddChatUser( new ChatUser( chatData.GetIdForNewUser(), chatUserName, password ) ); } catch (Exception) { if (!chatData.IsUserWithGivenNameExist(chatUserName)) { result.ServiceMessage = "При регистрации пользователя произошла ошибка.\\nПопробуйте ещё раз."; result.RedirectUrl = "#/register"; return(result); } } result.ServiceMessage = "Пользователь успешно зарегистрирован.\\n" + "Введите указанные данные для входа в чат."; result.RedirectUrl = "#/login"; return(result); }
private void Act() { _result = _subject.Handle(new RegisterUser { Email = _email }, CancellationToken.None).GetAwaiter().GetResult(); }
public async Task <RegisterUserResult> DoRegister(RegisterUserInfo request) { try { if (!Misc.IsValideEmailAdress(request.Mail)) { throw new Exception("Invalid eMail!"); } if (!Misc.IsValideUserName(request.UserName)) { throw new Exception( "Invalid User Name, only letters and digits allowed, minimum length is 3 char and maximum length is 15 char!"); } if (request.Password.Length < 8 || request.Password.Length > 32) { throw new Exception("Password minimum length is 8 char, maximum length is 32 char!"); } if (!Misc.IsValidePassword(request.Password)) { throw new Exception("Invalid password, character ' and \" are not allowed!"); } if (request.VerifyKey.Length != 32) { throw new Exception("Invalid Verify Key!"); } var lastSendTime = (DateTime.UtcNow - _lastTime).TotalSeconds; if (lastSendTime <= 90) { throw new Exception( $"You need to wait at least 90 seconds before to try again! Last try was {lastSendTime} seconds ago."); } dynamic requestInfo = request; var result = await DataExchange.DoDataExchange((object)requestInfo); RegisterUserResult retVal = result.ToObject <RegisterUserResult>(); if (retVal.Result) { _lastTime = DateTime.UtcNow; } return(retVal); } catch (Exception e) { return(new RegisterUserResult(false, e.Message)); } }
public async Task <IActionResult> Register([FromBody] UserCredentialsDTO userCredentialsDTO) { ApiResponse <LoginResponse> apiResponse = new ApiResponse <LoginResponse>(); try { IAppUser newAppUser = new AppUser() { Email = userCredentialsDTO.Email, Password = userCredentialsDTO.Password, Ipv4 = HttpUtils.GetUserIp(HttpContext) }; RegisterUserResult registerUserResult = await this._authenticationService.RegisterUserAsync(newAppUser); if (registerUserResult.State != RegisterUserState.Success) { apiResponse.Error = true; apiResponse.Message = registerUserResult.State.Switch(new Dictionary <RegisterUserState, Func <string> >() { { RegisterUserState.EmailExists, () => Resource_ResponseMessages_en.EmailExists }, { RegisterUserState.PasswordTooSmall, () => Resource_ResponseMessages_en.PasswordTooSmall }, { RegisterUserState.InvalidEmail, () => Resource_ResponseMessages_en.InvalidEmail } }, () => Resource_ResponseMessages_en.Unknown ); return(BadRequest(apiResponse)); } apiResponse.Message = Resource_ResponseMessages_en.RegisterSuccess; apiResponse.EndpointResult = new LoginResponse(this._jWTService.Generate(newAppUser)); return(Ok(apiResponse)); } catch (DbException e) { apiResponse.Error = true; apiResponse.Message = Resource_ResponseMessages_en.Unknown; // TODO: Error handling. return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented))); } catch (Exception e) { apiResponse.Error = true; apiResponse.Message = Resource_ResponseMessages_en.Unknown; // TODO: Error handling. return(Problem(statusCode: 500, detail: Newtonsoft.Json.JsonConvert.SerializeObject(e, Newtonsoft.Json.Formatting.Indented))); } }
public RegisterUserResult RegisterUser(RegisterUser registerUser, string path) { var response = new RegisterUserResult(); XmlDocument doc = new XmlDocument(); doc.Load(path); doc.GetElementsByTagName("RsaId").Item(0).InnerText = registerUser.RsaId; doc.GetElementsByTagName("UserName").Item(0).InnerText = registerUser.UserName; doc.GetElementsByTagName("Password").Item(0).InnerText = registerUser.Password; doc.GetElementsByTagName("emailaddress").Item(0).InnerText = registerUser.Email; doc.GetElementsByTagName("dob").Item(0).InnerText = registerUser.DateOfBirth; doc.GetElementsByTagName("mobile").Item(0).InnerText = registerUser.Mobile; //payload of xml document(Conversion to xml document) var stringPayload = new XmlConverter.XmlConverter().ToXml(doc); //econding of xml document to UTF-8 var encodedString = new UTF8Encoding().GetString(stringPayload); //replaces xml document footers var httpContent = new StringContent(encodedString, Encoding.UTF8, "text/xml"); using (var httpClient = new HttpClient()) { // Do the actual request and await the response var httpResponse = httpClient.PostAsync("http://41.216.173.228/RoboService/UserServicing.asmx?op=RegisterUser", httpContent); // If the response contains content we want to read it! if (httpResponse.Result.Content != null) { if (httpResponse.Result.IsSuccessStatusCode) { //convert back to xml string var stringData = httpResponse.Result.Content.ReadAsStringAsync().Result; XmlDocument resultDoc = new XmlDocument(); resultDoc.LoadXml(stringData); response.responsecode = resultDoc.GetElementsByTagName("responsecode").Item(0).InnerText; response.responsemessage = resultDoc.GetElementsByTagName("responsemessage").Item(0).InnerText; response.comment = resultDoc.GetElementsByTagName("comment").Item(0).InnerText; } } } return(response); }
/// <summary> /// 顔認証対象者情報登録 /// </summary> /// <param name="userID">登録する顔認証対象者ID</param> /// <param name="userName">>登録する顔認証対象者名</param> /// <returns>顔認証対象者登録結果</returns> private static async Task <RegisterUserResult> RegisterUser(string userID, string userName) { var result = new RegisterUserResult { ResultStatus = ResultStatus.Failed }; var param = new RegisterUserParam { UserID = userID, UserName = userName, UserState = "enabled", }; var reqJson = JsonConvert.SerializeObject(param); using (var content = CreateJsonContent(reqJson)) { content.Headers.Add("X-NECCP-Tenant-ID", TenantID); content.Headers.Add("apiKey", ManageApiKey); using (var response = await client.PostAsync(NfcManageUri + "users", content)) { string resultJson = await response.Content.ReadAsStringAsync(); DumpResult(response, resultJson, reqJson); switch (response.StatusCode) { case HttpStatusCode.Created: result = JsonConvert.DeserializeObject <RegisterUserResult>(resultJson); result.ResultStatus = ResultStatus.Success; break; case HttpStatusCode.Conflict: result.ResultStatus = ResultStatus.Conflict; break; } } } return(result); }
public async Task <RegisterUserResult> RegisterUserAsync(IAppUser appUser) { RegisterUserResult registerUserResult = new RegisterUserResult(); registerUserResult.User = null; if (!String.IsNullOrEmpty(appUser.Password) && appUser.Password.Length < _appSettings.Password_MinLength) { registerUserResult.State = RegisterUserState.PasswordTooSmall; return(registerUserResult); } if (String.IsNullOrEmpty(appUser.Email) || !this._emailValidatorService.IsValid(appUser.Email)) { registerUserResult.State = RegisterUserState.InvalidEmail; return(registerUserResult); } // TODO: Check if it's a temporary email or a spam email. if (await _appUserStore.EmailExistsAsync(appUser.Email)) { registerUserResult.State = RegisterUserState.EmailExists; return(registerUserResult); } appUser.UserName = StringUtils.GenerateRandomString(8); appUser.Email = this._sanitizerService.SanitizeHTML(appUser.Email); appUser.Password = await _passwordService.HashPasswordAsync(appUser.Password); await _appUserStore.CreateAsync(appUser as AppUser); appUser.Id = await _appUserStore.GetLastInsertedUserId(); registerUserResult.State = RegisterUserState.Success; registerUserResult.User = appUser; return(registerUserResult); }
/// <summary> /// add user as an asynchronous operation. /// </summary> /// <param name="dto">The dto.</param> /// <returns>Task<UserDto>.</returns> public async Task <RegisterUserResult> RegisterUserAsync(UserDto dto) { var result = new RegisterUserResult(); if (dto == null) { result.status = RegisterUserResultType.InvalidAccount; return(result); } var ex = await FirstOrDefaultAsync(i => i.name == dto.name || (i.telephone == dto.telephone && !string.IsNullOrEmpty(i.telephone))); if (ex != null) { if (ex.name == dto.name) { result.status = RegisterUserResultType.ExistAccount; return(result); } else { result.status = RegisterUserResultType.ExistTelephone; return(result); } } var user = Mapper.Map <UserDto, User>(dto); var dbUser = await base.InsertAsync(user); await UnitOfWork.CommitAsync(); if (dbUser != null) { result.status = RegisterUserResultType.Success; return(result); } result.status = RegisterUserResultType.Fail; return(result); }
// processes the Http request for a user registration public async Task <IdentityResult> RegisterUser(RegisterBindingModel registerUser) { Trace.WriteLine(string.Format("Start registering user with e-mail: '{0}'", registerUser.Email)); var user = _automapper.Map <UserAccount>(registerUser); if (ProfileImageSelected(registerUser.Profile.Image)) { user.ProfileImage = Guid.NewGuid().ToString("N"); } RegisterUserResult result = await _repository.RegisterUser(user); if (result.IdentityResult.Succeeded) { // send confirmation e-mail await SendConfirmationEmail(result.UserId); // store the profile picture in Azure cloud storage StoreProfileImage(registerUser.Profile.Image, user.ProfileImage, result.UserId); } return(result.IdentityResult); }
/// <summary> /// Register User Internal /// </summary> /// <param name="model"></param> /// <returns></returns> internal async Task <RegisterUserResult> RegisterInternal(RegisterGeneralModel model) { var userResult = new RegisterUserResult(); using (IUnitOfWork unitOfWork = UnitOfWork.Create()) { var checkUserEmail = unitOfWork.UserRepository.GetAll().FirstOrDefault(a => a.Email == model.Email || a.UserName == model.Email); if (checkUserEmail != null) { userResult.AddError(HttpStatusCode.BadRequest, 10, "This email is already taken ***"); return(userResult); } unitOfWork.BeginTransaction(); //Create user record var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), FirstName = model.FirstName ?? string.Empty, LastName = model.LastName ?? string.Empty, UserName = model.Email, Email = model.Email, //AvatarFileId = model.AvatarFileId, HasTempPassword = true, CreatedById = DbConstants.AdminUserId, CreatedDate = DateTime.Now }; if (!string.IsNullOrEmpty(model.UserName)) { var names = model.UserName.Split(' '); user.FirstName = names[0]; user.LastName = names.Length > 1 ? names[1] : ""; } if (!string.IsNullOrEmpty(model.Password)) { user.PasswordHash = new PasswordHasher().HashPassword(model.Password); } user.AutopilotTrack = true; user.SecurityStamp = Guid.NewGuid().ToString(); #region Need To redo { ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = factory.GetScheduler(); JobDataMap dataMap = new JobDataMap(); dataMap["registermodel"] = model; dataMap["userId"] = user.Id; dataMap["OperationType"] = "Registration"; var job = JobBuilder.Create <UpdateContactJob>() .WithIdentity("UpdateContactJob").UsingJobData(dataMap) .Build(); var jobKey = new JobKey("UpdateContactJob"); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1") .StartAt(DateTime.Now) .ForJob(jobKey) .Build(); if (!scheduler.CheckExists(jobKey)) { scheduler.ScheduleJob(job, trigger); } scheduler.Start(); } #endregion unitOfWork.UserRepository.Insert(user); await unitOfWork.SaveAsync(); ApplicationUserRole userRole = new ApplicationUserRole(); userRole.RoleId = DataLayer.DbConstants.CustomerUserRole; userRole.UserId = user.Id; unitOfWork.UserRoleRepository.Insert(userRole); await unitOfWork.SaveAsync(); Address address = new Address(); address.CreatedById = user.Id; address.CreatedDate = DateTime.Now; unitOfWork.AddressRepository.Insert(address); await unitOfWork.SaveAsync(); CustomerDetails customer = new CustomerDetails(); customer.Id = Guid.NewGuid(); customer.CreatedById = user.Id; customer.CreatedDate = DateTime.Now; customer.UserId = user.Id; customer.ContactPhone = model.ContactPhone; customer.AddressId = address.Id; customer.ModifiedReason = "created"; unitOfWork.CustomerDetailsRepository.Insert(customer); await unitOfWork.SaveAsync(); if (!string.IsNullOrEmpty(model.Provider) && !string.IsNullOrEmpty(model.ExternalAccessToken)) { var loginInfo = await this.SignInManager.AuthenticationManager.GetExternalLoginInfoAsync(); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(loginInfo.ExternalIdentity as ClaimsIdentity); ApplicationUserLogin userLogin = new ApplicationUserLogin(); userLogin.UserId = user.Id; userLogin.ProviderKey = loginInfo.Login.ProviderKey; userLogin.LoginProvider = loginInfo.Login.LoginProvider; unitOfWork.UserLoginRepository.Insert(userLogin); await unitOfWork.SaveAsync(); } unitOfWork.CommitTransaction(); if (model.Provider == null) { //Senf verification Email { string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = string.Format("{0}/#/confirm-email?userId={1}&code={2}", Url.Link("Default", new { controller = "account" }), user.Id, Uri.EscapeDataString(code)); await EmailNitificationHelper.Create().SendConfirmationEmail(user, UserManager, callbackUrl); } } userResult.UserId = user.Id; return(userResult); } }