/// <summary> /// Internal constructor to initialize a provider, user pool, and user for testing /// Created user info: Username = User 5, Password = PassWord1!, Email = [email protected] /// </summary> public MfaAuthenticationTests() { //Delete pool created by BaseAuthenticationTestClass if (pool != null) { provider.DeleteUserPoolAsync(new DeleteUserPoolRequest() { UserPoolId = pool.PoolID }).Wait(); } UserPoolPolicyType passwordPolicy = new UserPoolPolicyType(); List <SchemaAttributeType> requiredAttributes = new List <SchemaAttributeType>(); List <string> verifiedAttributes = new List <string>(); var creds = FallbackCredentialsFactory.GetCredentials(); var region = FallbackRegionFactory.GetRegionEndpoint(); provider = new AmazonCognitoIdentityProviderClient(creds, region); AdminCreateUserConfigType adminCreateUser = new AdminCreateUserConfigType() { UnusedAccountValidityDays = 8, AllowAdminCreateUserOnly = false }; passwordPolicy.PasswordPolicy = new PasswordPolicyType() { MinimumLength = 8, RequireNumbers = true, RequireSymbols = true, RequireUppercase = true, RequireLowercase = true }; SchemaAttributeType emailSchema = new SchemaAttributeType() { Required = true, Name = CognitoConstants.UserAttrEmail, AttributeDataType = AttributeDataType.String }; SchemaAttributeType phoneSchema = new SchemaAttributeType() { Required = true, Name = CognitoConstants.UserAttrPhoneNumber, AttributeDataType = AttributeDataType.String }; requiredAttributes.Add(emailSchema); requiredAttributes.Add(phoneSchema); verifiedAttributes.Add(CognitoConstants.UserAttrEmail); verifiedAttributes.Add(CognitoConstants.UserAttrPhoneNumber); //Create Role for MFA using (var managementClient = new AmazonIdentityManagementServiceClient()) { CreateRoleResponse roleResponse = managementClient.CreateRoleAsync(new CreateRoleRequest() { RoleName = "TestRole_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"), AssumeRolePolicyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow" + "\",\"Principal\":{\"Service\":\"cognito-idp.amazonaws.com\"},\"Action\":\"sts:AssumeRole\",\"Condition" + "\":{\"StringEquals\":{\"sts:ExternalId\":\"8327d096-57c0-4fb7-ad24-62ea8fc692c0\"}}}]}" }).Result; roleName = roleResponse.Role.RoleName; roleArn = roleResponse.Role.Arn; //Create and attach policy for role CreatePolicyResponse createPolicyResponse = managementClient.CreatePolicyAsync(new CreatePolicyRequest() { PolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect\": \"Allow\",\"Action" + "\": [\"sns:publish\"],\"Resource\": [\"*\"]}]}", PolicyName = "Cognito_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"), }).Result; policyName = createPolicyResponse.Policy.PolicyName; policyArn = createPolicyResponse.Policy.Arn; managementClient.AttachRolePolicyAsync(new AttachRolePolicyRequest() { PolicyArn = policyArn, RoleName = roleName }).Wait(); } //Create user pool and client CreateUserPoolRequest createPoolRequest = new CreateUserPoolRequest { PoolName = "mfaTestPool_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"), Policies = passwordPolicy, Schema = requiredAttributes, AdminCreateUserConfig = adminCreateUser, MfaConfiguration = "ON", AutoVerifiedAttributes = verifiedAttributes, SmsConfiguration = new SmsConfigurationType { SnsCallerArn = roleArn, ExternalId = "8327d096-57c0-4fb7-ad24-62ea8fc692c0" } }; //Build in buffer time for role/policy to be created CreateUserPoolResponse createPoolResponse = null; string bufferExMsg = "Role does not have a trust relationship allowing Cognito to assume the role"; while (true) { try { createPoolResponse = provider.CreateUserPoolAsync(createPoolRequest).Result; break; } catch (Exception ex) { if (string.Equals(bufferExMsg, ex.InnerException.Message)) { System.Threading.Thread.Sleep(3000); } else { throw ex; } } } UserPoolType poolCreated = createPoolResponse.UserPool; CreateUserPoolClientResponse clientResponse = provider.CreateUserPoolClientAsync(new CreateUserPoolClientRequest() { ClientName = "App1", UserPoolId = poolCreated.Id, GenerateSecret = false, }).Result; UserPoolClientType clientCreated = clientResponse.UserPoolClient; this.pool = new CognitoUserPool(poolCreated.Id, clientCreated.ClientId, provider, ""); SignUpRequest signUpRequest = new SignUpRequest() { ClientId = clientCreated.ClientId, Password = "******", Username = "******", UserAttributes = new List <AttributeType>() { new AttributeType() { Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**" }, new AttributeType() { Name = CognitoConstants.UserAttrPhoneNumber, Value = "+15555555555" } }, ValidationData = new List <AttributeType>() { new AttributeType() { Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**" }, new AttributeType() { Name = CognitoConstants.UserAttrPhoneNumber, Value = "+15555555555" } } }; SignUpResponse signUpResponse = provider.SignUpAsync(signUpRequest).Result; AdminConfirmSignUpRequest confirmRequest = new AdminConfirmSignUpRequest() { Username = "******", UserPoolId = poolCreated.Id }; AdminConfirmSignUpResponse confirmResponse = provider.AdminConfirmSignUpAsync(confirmRequest).Result; this.user = new CognitoUser("User5", clientCreated.ClientId, pool, provider); }
public async Task <int> SignUp([FromBody] SignUpRequest request) { return(await Mediator.Send(_mapper.Map <SignUpCommand>(request))); }
public SignUpInResult SignUp(SignUpRequest request) { return(BaseInvokeCheckModel(request, () => { var responseBuilder = ResponseBuilder <SignUpInResult> .Fail(); if (!_inviteService.IsInviteValid(request.VerificationCode)) { return responseBuilder.SetInfoAndBuild("Verification code is wrong"); } if (_dbContext.Users.Any(x => x.Email == request.Email)) { return responseBuilder.SetInfoAndBuild("User with this email already registered"); } if (_dbContext.Users.Any(x => x.VerificationCode == request.VerificationCode)) { return responseBuilder.SetInfoAndBuild("This invite already used"); } string salt = Crypto.GenerateSalt(); string passwordHah = Crypto.HashPassword(request.Password + salt); var dataUser = UserMapper.ToData.FromRequest(request, (user) => { user.Id = Guid.NewGuid(); user.IsUploadingAudio = false; user.PasswordHash = passwordHah; user.PasswordSalt = salt; user.RegisterDate = DateTime.Now; }); var dataAuthToken = new DataModel.AuthToken() { Id = Guid.NewGuid(), DateExpired = DateTime.Now.AddDays(AuthTokenDaysExpired), UserId = dataUser.Id, IsActive = true, }; var playlist = new DataModel.Playlist() { Id = Guid.NewGuid(), IsGeneral = true, OwnerId = dataUser.Id, OrderValue = 0, }; _dbContext.AuthTokens.Add(dataAuthToken); _dbContext.Users.Add(dataUser); _dbContext.Playlists.Add(playlist); _dbContext.SaveChanges(); return ResponseBuilder <SignUpInResult> .SuccessBuild(new SignUpInResult() { User = UserMapper.ToApi.FromData(dataUser), AuthToken = AuthTokenMapper.ToApi.FromData(dataAuthToken), }); })); }
public async Task <IActionResult> Register([FromBody] SignUpRequest register) { await _accountService.SignUpAsync(register); return(Created("", true)); }
public SignUpResponse SignUp([FromBody] SignUpRequest request) { return(_signUpService.SignUp(request)); }
public ResponseData CreateAccount(SignUpRequest userSignUp) { ResponseData responseData = _userRepository.CreateAccount(userSignUp); return(responseData); }
public SignUpInResult SignUp([FromBody] SignUpRequest request) { return(_authService.SignUp(request)); }
public static SignUpDto Map(this SignUpRequest request) => new SignUpDto(request.Username, request.Password, request.PasswordConfirmation, request.Email);
public async Task <IActionResult> SignUp(SignUpRequest request) { return(CreatedAtAction(nameof(Get), new { }, await _userService.SignUpAsync(request))); }
public async Task <HttpResponseMessage> SignUp(SignUpRequest signUpRequest) { return(await Helper.GenerateCompany()); }
public static MessageResponse SignUp(DatabaseManager databaseManager, EncryptionHelper encryptionHelper, SignUpRequest request) { request.User.IsVerified = false; return(User.AddUser(databaseManager, encryptionHelper, request)); }
public async Task <ActionResult <SignInResponse> > SignUp([FromBody] SignUpRequest request) { var result = await _authenticationService.SignUp(request); return(Ok(result)); }
public async Task CreateAccount([FromBody] SignUpRequest request) { await userAccessModule.ExecuteCommandAsync(new CreateUser { Username = request.Username, Password = request.Password, Email = request.Email }); }
public async Task <SignUpResponse> CreateOrganizationWithAdmin(SignUpRequest request) { var response = new SignUpResponse(); var user = await _userRepository.Select(x => x.Email == request.Email); if (user.IsExist()) { response.ErrorMessages.Add("email_already_exist"); response.Status = ResponseStatus.Invalid; return(response); } var organization = await _organizationRepository.Select(x => x.Name == request.OrganizationName); if (organization.IsExist()) { response.ErrorMessages.Add("organization_name_already_exist"); response.Status = ResponseStatus.Invalid; return(response); } organization = _organizationFactory.CreateEntityFromRequest(request, _cryptoHelper.GetKeyAsString(), _cryptoHelper.GetIVAsString()); var salt = _cryptoHelper.GetSaltAsString(); var passwordHash = _cryptoHelper.Hash(request.Password, salt); user = _userFactory.CreateEntityFromRequest(request, organization, salt, passwordHash); var english = await _languageRepository.Select(x => x.IsoCode2Char == "en"); user.LanguageId = english.Id; user.LanguageUid = english.Uid; user.LanguageName = english.Name; user.LanguageIconUrl = english.IconUrl; var loginLog = _userLoginLogFactory.CreateEntityFromRequest(request, user); var integration = _integrationFactory.CreateDefault(organization); var integrationClient = _integrationClientFactory.CreateEntity(integration); var project = _projectFactory.CreateDefault(organization); var(uowResult, insertedOrganization, insertedUser) = await _signUpUnitOfWork.DoWork(organization, user, loginLog, integration, integrationClient, project); if (uowResult) { // todo:send welcome email // todo:send email log _cacheManager.UpsertUserCache(insertedUser, _userFactory.MapCurrentUser(insertedUser)); _cacheManager.UpsertOrganizationCache(insertedOrganization, _organizationFactory.MapCurrentOrganization(insertedOrganization)); response.Status = ResponseStatus.Success; return(response); } response.SetFailed(); return(response); }
private async Task <AuthEventEnum> NextChallenge(AuthEventEnum lastAuthEventEnum = AuthEventEnum.AuthChallenge) { try { if (!HasChallenge) { switch (CurrentAuthProcess) { case AuthProcessEnum.None: return(AuthEventEnum.Alert_NothingToDo); case AuthProcessEnum.ResettingPassword: CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.PasswordResetDone); case AuthProcessEnum.SigningUp: if (HasChallenge) { return(AuthEventEnum.AuthChallenge); } if (!IsLoginFormatOk) { AuthChallengeList.Add(AuthChallengeEnum.Login); } else if (!IsPasswordFormatOk) { AuthChallengeList.Add(AuthChallengeEnum.Password); } else if (!IsEmailFormatOk) { AuthChallengeList.Add(AuthChallengeEnum.Email); } if (HasChallenge) { return(AuthEventEnum.AuthChallenge); } if (!IsCodeVerified) { // Request Auth Code var signUpRequest = new SignUpRequest() { ClientId = clientId, Password = password, Username = login }; signUpRequest.UserAttributes.Add( new AttributeType() { Name = "email", Value = email }); // This call may throw an exception var result = await providerClient.SignUpAsync(signUpRequest).ConfigureAwait(false); if (!AuthChallengeList.Contains(AuthChallengeEnum.Code)) { AuthChallengeList.Add(AuthChallengeEnum.Code); } return(AuthEventEnum.AuthChallenge); } CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.SignedUp); case AuthProcessEnum.SigningIn: if (authFlowResponse != null && authFlowResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) // Update Passsword { if (!AuthChallengeList.Contains(AuthChallengeEnum.NewPassword)) { AuthChallengeList.Add(AuthChallengeEnum.NewPassword); } authFlowResponse = null; return(AuthEventEnum.AuthChallenge); } // Grab JWT from login to User Pools to extract User Pool Identity //var token = new JwtSecurityToken(jwtEncodedString: CognitoUser.SessionTokens.IdToken); //UpIdentity = token.Claims.First(c => c.Type == "sub").Value; // JWT sub cliam contains User Pool Identity //// Note: creates Identity Pool identity if it doesn't exist Credentials = CognitoUser.GetCognitoAWSCredentials(identityPoolId, regionEndpoint); IsSignedIn = true; CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.SignedIn); case AuthProcessEnum.UpdatingEmail: if (!IsCodeVerified) { AuthChallengeList.Add(AuthChallengeEnum.Code); return(AuthEventEnum.VerificationCodeSent); } CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.EmailUpdateDone); case AuthProcessEnum.UpdatingPassword: await CognitoUser.ChangePasswordAsync(password, newPassword).ConfigureAwait(false); CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.PasswordUpdateDone); case AuthProcessEnum.UpdatingPhone: CurrentAuthProcess = AuthProcessEnum.None; ClearSensitiveFields(); return(AuthEventEnum.PhoneUpdateDone); } } } catch (UsernameExistsException) { return(AuthEventEnum.Alert_LoginAlreadyUsed); } catch (InvalidParameterException) { return(AuthEventEnum.Alert_InternalProcessError); } catch (InvalidPasswordException) { return(AuthEventEnum.Alert_PasswordFormatRequirementsFailed); } catch (TooManyRequestsException) { return(AuthEventEnum.Alert_TooManyAttempts); } catch (TooManyFailedAttemptsException) { return(AuthEventEnum.Alert_TooManyAttempts); } catch (PasswordResetRequiredException) { return(AuthEventEnum.Alert_PasswordResetRequiredException); } catch (Exception e) { Debug.WriteLine($"SignUp() threw an exception {e}"); return(AuthEventEnum.Alert_Unknown); } return(lastAuthEventEnum); }
public async Task <IActionResult> SignUp([FromBody] SignUpRequest request) { var result = await UserService.SignUpAsync(request); return(this.ToResult(result)); }
public SignUpResponse SignUp(SignUpRequest request) { return(m_AccountManager.SignUp(request)); }
public void SignUpAsync(SignUpRequest data, Action <ResponseBase, Exception> callback) { RpcRoot.JsonRpc.PostAsync(RpcRoot.OfficialServerHost, RpcRoot.OfficialServerPort, _controllerName, nameof(IUserController.SignUp), data, callback); }
public async Task <SignUpResult> SignUp(SignUpRequest signUpRequest) { try { ValidateSignUpOrSignInInput(signUpRequest.Username, signUpRequest.Password); if (signUpRequest.Profile != null) { ValidateProfile(signUpRequest.Profile); } if (string.IsNullOrEmpty(signUpRequest.Email)) { throw new Errors.EmailNotValid(); } if (!Config.RememberMeOptions.ContainsKey(signUpRequest.RememberMe)) { throw new RememberMeValueNotValid(); } var username = signUpRequest.Username.ToLower(); var email = signUpRequest.Email.ToLower(); var appId = _config.AppId; var seed = Utils.GenerateSeed(); var(sessionId, creationDate, userId) = await GenerateKeysAndSignUp(username, signUpRequest.Password, seed, email, signUpRequest.Profile); var session = new SignInSession { Username = username, SessionId = sessionId, CreationDate = creationDate.ToString(CultureInfo.InvariantCulture) }; var seedString = Convert.ToBase64String(seed); _localData.SaveSeedString(signUpRequest.RememberMe, appId, username, seedString); _localData.SignInSession(signUpRequest.RememberMe, username, sessionId, creationDate.ToString(CultureInfo.InvariantCulture)); await ConnectWebSocket(session, seedString, signUpRequest.RememberMe); return(new SignUpResult { Username = username, UserId = userId, Email = email, Profile = signUpRequest.Profile, }); } catch (Exception ex) { if (!(ex is IError e)) { throw new UnknownServiceUnavailable(ex); } switch (e.Name) { case "ParamsMustBeObject": case "UsernameMissing": case "UsernameAlreadyExists": case "UsernameCannotBeBlank": case "UsernameMustBeString": case "UsernameTooLong": case "PasswordMissing": case "PasswordCannotBeBlank": case "PasswordTooShort": case "PasswordTooLong": case "PasswordMustBeString": case "EmailNotValid": case "ProfileMustBeObject": case "ProfileCannotBeEmpty": case "ProfileHasTooManyKeys": case "ProfileKeyMustBeString": case "ProfileKeyTooLong": case "ProfileValueMustBeString": case "ProfileValueCannotBeBlank": case "ProfileValueTooLong": case "RememberMeValueNotValid": case "TrialExceededLimit": case "AppIdNotSet": case "AppIdNotValid": case "UserAlreadySignedIn": case "ServiceUnavailable": throw; default: throw new UnknownServiceUnavailable(ex); } } }
public SignUpResponse SignUpUser(SignUpRequest request) { return(_usersDataAccess.SignUpUser(request)); }
public async Task <RequestResult> UpdateInfomation(SignUpRequest updateRequest) { //Tìm kiếm xem Customer có tồn tại hay không var customer = _context.Customers.Find(updateRequest.Id); if (customer != null) //Có tồn tại { if (customer.IsActive == 1) //Tài khoản không bị khoá { //kiểm tra xem Email mới có bị trùng với một tài khoản khác hay không var checkMail = _context.Customers.SingleOrDefault(x => x.Email == updateRequest.Email && x.Id != updateRequest.Id); if (checkMail != null) //Email đã tồn tại { return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Email is registed by other customer." }); } else { //kiểm tra xem Phone mới có bị trùng với một tài khoản khác hay không var checkPhone = _context.Customers.SingleOrDefault(x => x.Phone == updateRequest.Phone && x.Id != updateRequest.Id); if (checkPhone != null) //Phone đã tồn tại { return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Phone is registed by other customer." }); } else //Email và Phone mới không trùng { customer.Name = updateRequest.Name; customer.Email = updateRequest.Email; customer.Phone = updateRequest.Phone; //customer.Password = updateRequest.Password; customer.Address = updateRequest.Address; customer.ModifiedDate = DateTime.Now; _context.Customers.Update(customer); _context.SaveChanges(); return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Success, Content = JsonConvert.SerializeObject(customer) }); } } } else { return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Account is deactivated." }); } } else { return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Invalid information." }); } }
public Result <ServiceResponse> SignUp(SignUpRequest request) { return(this.UseConnection("Default", connection => { request.CheckNotNull(); Check.NotNullOrWhiteSpace(request.Email, "email"); Check.NotNullOrEmpty(request.Password, "password"); UserRepository.ValidatePassword(request.Email, request.Password, true); Check.NotNullOrWhiteSpace(request.DisplayName, "displayName"); if (connection.Exists <UserRow>( UserRow.Fields.Username == request.Email | UserRow.Fields.Email == request.Email)) { throw new ValidationError("EmailInUse", Texts.Validation.EmailInUse); } using (var uow = new UnitOfWork(connection)) { string salt = null; var hash = UserRepository.GenerateHash(request.Password, ref salt); var displayName = request.DisplayName.TrimToEmpty(); var email = request.Email; var username = request.Email; var fld = UserRow.Fields; var userModel = new UserRow { Username = username, Source = "sign", DisplayName = displayName, Email = email, PasswordHash = hash, PasswordSalt = salt, IsActive = 0, InsertDate = DateTime.Now, InsertUserId = 1, LastDirectoryUpdate = DateTime.Now }; var userId = (int)connection.InsertAndGetID(userModel); userModel.UserId = userId; var tenant = new TenantRow { TenantName = request.TenantName, CurrencyId = 1, SubscriptionRequired = true }; tenant.TenantId = Int32.Parse(connection.InsertAndGetID(tenant).ToString()); var offer = connection.ById <OffersRow>(request.OfferId); //Insert First subscription directly after you know the TenantId var subscriptionId = (int)connection.InsertAndGetID(new SubscriptionsRow { // TODO Get local string Name = string.Format("{0} - {1}", offer.Name, request.TenantName), OfferId = offer.OfferId, TenantId = Int32.Parse(tenant.TenantId.ToString()), SubscriptionEndDate = DateTime.Now.AddMonths(12), Enabled = 1, IsActive = 1, InsertUserId = userId, InsertDate = DateTime.Now, ActivatedOn = DateTime.Now, FreeDaysFromOffer = offer.MaximumSubscriptionTime ?? 0 }); tenant.SubscriptionId = subscriptionId; //Update Tenant SubscriptionId .. Is it Needet? connection.UpdateById(tenant, ExpectedRows.One); var userRoleId = (int)connection.InsertAndGetID(new UserRoleRow { UserId = userId, RoleId = offer.RoleId }); userModel.TenantId = tenant.TenantId ?? 2; connection.UpdateById(userModel, ExpectedRows.One); byte[] bytes; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(DateTime.UtcNow.AddHours(3).ToBinary()); bw.Write(userId); bw.Flush(); bytes = ms.ToArray(); } var token = Convert.ToBase64String(HttpContext.RequestServices .GetDataProtector("Activate").Protect(bytes)); var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ?? Request.GetBaseUri().ToString(); var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t="); activateLink = activateLink + Uri.EscapeDataString(token); var emailModel = new ActivateEmailModel(); emailModel.Username = username; emailModel.DisplayName = displayName; emailModel.ActivateLink = activateLink; var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString(); var emailBody = TemplateHelper.RenderViewToString(HttpContext.RequestServices, MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel); Common.EmailHelper.Send(emailSubject, emailBody, email); uow.Commit(); UserRetrieveService.RemoveCachedUser(userId, username); return new ServiceResponse(); } })); }
public async Task <RequestResult> SignUp(SignUpRequest signUpRequest) { var cus = _context.Customers.FirstOrDefault(x => x.Email == signUpRequest.Email); if (cus != null) { return new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Email is existed." } } ; cus = _context.Customers.FirstOrDefault(x => x.Phone == signUpRequest.Phone); if (cus != null) { return new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Phone is existed." } } ; Customer customer = new Customer() { Id = 0, Name = signUpRequest.Name, Email = signUpRequest.Email, Phone = signUpRequest.Phone, Password = signUpRequest.Password, Address = signUpRequest.Address, LoginAttemptCount = 0, ModifiedDate = DateTime.Now, IsActive = 1 }; _context.Customers.Add(customer); await _context.SaveChangesAsync(); cus = _context.Customers.FirstOrDefault(x => x.Email == signUpRequest.Email && x.Phone == signUpRequest.Phone); SignUpRequest response = new SignUpRequest(); if (cus != null) { response.Id = cus.Id; response.Name = cus.Name; response.Email = cus.Email; response.Phone = cus.Phone; response.Password = cus.Password; response.Address = cus.Address; return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Success, Content = JsonConvert.SerializeObject(response) }); } else { return(new RequestResult { StatusCode = DataAccess.Models.Enum.StatusCode.Failed, Content = "Invalid information." }); } }
public Result <ServiceResponse> SignUp(SignUpRequest request) { return(this.UseConnection("Default", connection => { request.CheckNotNull(); Check.NotNullOrWhiteSpace(request.Email, "email"); Check.NotNullOrEmpty(request.Password, "password"); UserRepository.ValidatePassword(request.Email, request.Password, true); Check.NotNullOrWhiteSpace(request.DisplayName, "displayName"); if (connection.Exists <UserRow>( UserRow.Fields.Username == request.Email | UserRow.Fields.Email == request.Email)) { throw new ValidationError("EmailInUse", Texts.Validation.CantFindUserWithEmail); } using (var uow = new UnitOfWork(connection)) { string salt = null; var hash = UserRepository.GenerateHash(request.Password, ref salt); var displayName = request.DisplayName.TrimToEmpty(); var email = request.Email; var username = request.Email; var fld = UserRow.Fields; var userId = (int)new SqlInsert(fld.TableName) .Set(fld.Username, username) .Set(fld.Source, "sign") .Set(fld.DisplayName, displayName) .Set(fld.Email, email) .Set(fld.PasswordHash, hash) .Set(fld.PasswordSalt, salt) .Set(fld.IsActive, 0) .Set(fld.InsertDate, DateTime.Now) .Set(fld.InsertUserId, 1) .Set(fld.LastDirectoryUpdate, DateTime.Now) .ExecuteAndGetID(connection); byte[] bytes; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(DateTime.UtcNow.AddHours(3).ToBinary()); bw.Write(userId); bw.Flush(); bytes = ms.ToArray(); } var token = Convert.ToBase64String(MachineKey.Protect(bytes, "Activate")); var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ?? Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/"); var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t="); activateLink = activateLink + Uri.EscapeDataString(token); var emailModel = new ActivateEmailModel(); emailModel.Username = username; emailModel.DisplayName = displayName; emailModel.ActivateLink = activateLink; var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString(); var emailBody = TemplateHelper.RenderTemplate( MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel); var message = new MailMessage(); message.To.Add(email); message.Subject = emailSubject; message.Body = emailBody; message.IsBodyHtml = true; var client = new SmtpClient(); if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(client.PickupDirectoryLocation)) { var pickupPath = Server.MapPath("~/App_Data"); pickupPath = Path.Combine(pickupPath, "Mail"); Directory.CreateDirectory(pickupPath); client.PickupDirectoryLocation = pickupPath; } uow.Commit(); UserRetrieveService.RemoveCachedUser(userId, username); client.Send(message); return new ServiceResponse(); } })); }
public async Task <BaseResponse> SignUpUser(SignUpRequest signUpRequest) { return(await _ICommonRepository.SignUpUser(signUpRequest)); }
public SignUpResponse SignUp(SignUpRequest signUpRequest) { throw new NotImplementedException(); }
public async void SignUptoCognito(int _clientid, string _username, string _password, string _email) { // If the REgEx Formats are Respected, we proceed to Adhesion OR We Return an Error Format if (SecurityCheck.CheckUserPattern(_username)) { if (SecurityCheck.CheckPasswordPattern(_password)) { if (SecurityCheck.CheckEmailPattern(_email)) { SignUpRequest signUpRequest = new SignUpRequest() { ClientId = Constants.CLIENTAPP_ID, Username = _username, Password = _password, SecretHash = CognitoHashCalculator.GetSecretHash(_username, Constants.CLIENTAPP_ID, Constants.NeokySecret) }; List <AttributeType> attributes = new List <AttributeType>() { new AttributeType() { Name = "email", Value = _email } }; // Send SignupRequest signUpRequest.UserAttributes = attributes; try { SignUpResponse result = await Server.cognitoManagerServer.provider.SignUpAsync(signUpRequest); if (result.HttpStatusCode == System.Net.HttpStatusCode.OK) { ServerSend.SignUpStatusReturn(_clientid, Constants.ADHESION_OK); } } catch (Exception e) { switch (e.GetType().ToString()) { case "Amazon.CognitoIdentityProvider.Model.UsernameExistsException": ServerSend.SignUpStatusReturn(_clientid, Constants.ADHESION_ALREADY_EXIST); break; default: NlogClass.target.WriteAsyncLogEvent(new AsyncLogEventInfo(new LogEventInfo(LogLevel.Error, "SignUpClientToCognito", "Client ID : " + _clientid.ToString() + " | New Exception | Code : " + e.GetType().ToString() + " | Exeption : " + e.Message), NlogClass.exceptions.Add)); ServerSend.SignUpStatusReturn(_clientid, Constants.ADHESION_KO); break; } } } else { ServerSend.SignUpStatusReturn(_clientid, Constants.ADHESION_FORMAT_EMAIL_KO); } } else { ServerSend.SignUpStatusReturn(_clientid, Constants.ADHESION_FORMAT_PASSWORD_KO); } } else { ServerSend.SignUpStatusReturn(_clientid, Constants.ADHESION_FORMAT_USERNAME_KO); } }
public Result<ServiceResponse> SignUp(SignUpRequest request) { return this.UseConnection("Default", connection => { request.CheckNotNull(); Check.NotNullOrWhiteSpace(request.Email, "email"); Check.NotNullOrEmpty(request.Password, "password"); UserRepository.ValidatePassword(request.Email, request.Password, true); Check.NotNullOrWhiteSpace(request.DisplayName, "displayName"); if (connection.Exists<UserRow>( UserRow.Fields.Username == request.Email | UserRow.Fields.Email == request.Email)) { throw new ValidationError("EmailInUse", Texts.Validation.CantFindUserWithEmail); } using (var uow = new UnitOfWork(connection)) { string salt = null; var hash = UserRepository.GenerateHash(request.Password, ref salt); var displayName = request.DisplayName.TrimToEmpty(); var email = request.Email; var username = request.Email; var fld = UserRow.Fields; var userId = (int)new SqlInsert(fld.TableName) .Set(fld.Username, username) .Set(fld.Source, "sign") .Set(fld.DisplayName, displayName) .Set(fld.Email, email) .Set(fld.PasswordHash, hash) .Set(fld.PasswordSalt, salt) .Set(fld.IsActive, 0) .Set(fld.InsertDate, DateTime.Now) .Set(fld.InsertUserId, 1) .Set(fld.LastDirectoryUpdate, DateTime.Now) .ExecuteAndGetID(connection); byte[] bytes; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(DateTime.UtcNow.AddHours(3).ToBinary()); bw.Write(userId); bw.Flush(); bytes = ms.ToArray(); } var token = Convert.ToBase64String(MachineKey.Protect(bytes, "Activate")); var externalUrl = Config.Get<EnvironmentSettings>().SiteExternalUrl ?? Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/"); var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t="); activateLink = activateLink + Uri.EscapeDataString(token); var emailModel = new ActivateEmailModel(); emailModel.Username = username; emailModel.DisplayName = displayName; emailModel.ActivateLink = activateLink; var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString(); var emailBody = TemplateHelper.RenderTemplate( MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel); var message = new MailMessage(); message.To.Add(email); message.Subject = emailSubject; message.Body = emailBody; message.IsBodyHtml = true; var client = new SmtpClient(); if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(client.PickupDirectoryLocation)) { var pickupPath = Server.MapPath("~/App_Data"); pickupPath = Path.Combine(pickupPath, "Mail"); Directory.CreateDirectory(pickupPath); client.PickupDirectoryLocation = pickupPath; } uow.Commit(); UserRetrieveService.RemoveCachedUser(userId, username); client.Send(message); return new ServiceResponse(); } }); }
public async Task <IActionResult> SignUp([FromBody] SignUpRequest signUpRequest) { var result = await _authService.SignUpAsync(signUpRequest); return(Ok(result)); }
public Result <ServiceResponse> SignUp(SignUpRequest request) { return(this.UseConnection("Default", connection => { request.CheckNotNull(); Check.NotNullOrWhiteSpace(request.Email, "email"); Check.NotNullOrEmpty(request.Password, "password"); UserRepository.ValidatePassword(request.Email, request.Password, true); Check.NotNullOrWhiteSpace(request.DisplayName, "displayName"); if (connection.Exists <UserRow>( UserRow.Fields.Username == request.Email | UserRow.Fields.Email == request.Email)) { throw new ValidationError("EmailInUse", Texts.Validation.EmailInUse); } using (var uow = new UnitOfWork(connection)) { string salt = null; var hash = UserRepository.GenerateHash(request.Password, ref salt); var displayName = request.DisplayName.TrimToEmpty(); var email = request.Email; var username = request.Email; var fld = UserRow.Fields; var userId = (int)connection.InsertAndGetID(new UserRow { Username = username, Source = "sign", DisplayName = displayName, Email = email, PasswordHash = hash, PasswordSalt = salt, IsActive = 0, InsertDate = DateTime.Now, InsertUserId = 1, LastDirectoryUpdate = DateTime.Now }); byte[] bytes; using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(DateTime.UtcNow.AddHours(3).ToBinary()); bw.Write(userId); bw.Flush(); bytes = ms.ToArray(); } var token = Convert.ToBase64String(HttpContext.RequestServices .GetDataProtector("Activate").Protect(bytes)); var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ?? Request.GetBaseUri().ToString(); var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t="); activateLink = activateLink + Uri.EscapeDataString(token); var emailModel = new ActivateEmailModel(); emailModel.Username = username; emailModel.DisplayName = displayName; emailModel.ActivateLink = activateLink; var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString(); var emailBody = TemplateHelper.RenderViewToString(HttpContext.RequestServices, MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel); Common.EmailHelper.Send(emailSubject, emailBody, email); uow.Commit(); UserRetrieveService.RemoveCachedUser(userId, username); return new ServiceResponse(); } })); }
public async Task <JsonResult> OnPutSignUp([FromBody] SignUpRequest SignUpRequest) { Logger.LogDebug("New user request: {} {} {}", SignUpRequest.Email, SignUpRequest.Name, SignUpRequest.University); if (await _UserManager.FindByEmailAsync(SignUpRequest.Email) != null) { Logger.LogInformation("New user {}, already exists!", SignUpRequest.Email); return(new JsonResult(new SignUpResult { UserName = SignUpRequest.Email, Message = "User already exists!", Success = false })); } User newUser = new User { Email = SignUpRequest.Email, Name = SignUpRequest.Name, SecurityStamp = Guid.NewGuid().ToString(), UserName = SignUpRequest.Email, University = SignUpRequest.University, Comments = new List <Comment>(), Orders = new List <Order>() }; var createResult = await _UserManager.CreateAsync(newUser, SignUpRequest.Password); if (createResult.Succeeded) { var addToRoleResult = await _UserManager.AddToRoleAsync(newUser, Role.User); if (!addToRoleResult.Succeeded) { await _UserManager.DeleteAsync(newUser); return(new JsonResult(new SignUpResult { UserName = SignUpRequest.Email, Message = "User " + SignUpRequest.Email + " couldn't be added to Role!", Success = false })); } } else { bool valid = true; foreach (var validator in _UserManager.PasswordValidators) { if (!(await validator.ValidateAsync(_UserManager, newUser, SignUpRequest.Password)).Succeeded) { valid = false; } } if (!valid) { return(new JsonResult(new SignUpResult { UserName = SignUpRequest.Email, Message = "User password is not complex enough!", Success = false })); } return(new JsonResult(new SignUpResult { UserName = SignUpRequest.Email, Message = "User " + SignUpRequest.Email + " couldn't be created!", Success = false })); } await _context.SaveChangesAsync(); Logger.LogInformation("New user has been created {}!", SignUpRequest.Email); return(new JsonResult(new SignUpResult { UserName = SignUpRequest.Email, Message = "User " + SignUpRequest.Email + " has been created!", Success = true })); }