コード例 #1
0
        /// <summary>
        /// This send the temporary code again to the admin created user which is now not activate
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task <bool> ResendTemporaryPasssword(Real.ResendTemporaryCodeRequest request)
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(RegionEndpoint.GetBySystemName(REGION));

            AdminCreateUserRequest userRequest = new AdminCreateUserRequest();

            userRequest.Username               = request.Username;
            userRequest.UserPoolId             = POOL_ID;
            userRequest.DesiredDeliveryMediums = new List <string>()
            {
                "EMAIL"
            };
            userRequest.MessageAction     = MessageActionType.RESEND;
            userRequest.TemporaryPassword = PasswordGenerator.GeneratePassword(true, true, true, true, false, 6);

            try
            {
                AdminCreateUserResponse response = await provider.AdminCreateUserAsync(userRequest);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
            return(true);
        }
コード例 #2
0
        public AuthenticationCreateUserTests() : base()
        {
            AdminCreateUserRequest createUserRequest = new AdminCreateUserRequest()
            {
                TemporaryPassword = "******",
                Username          = "******",
                UserAttributes    = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    },
                },
                ValidationData = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    }
                },
                UserPoolId = pool.PoolID
            };

            AdminCreateUserResponse createReponse = provider.AdminCreateUserAsync(createUserRequest).Result;

            user = new CognitoUser("User5", pool.ClientID, pool, provider);
        }
        /// <summary>
        /// Signs up the user with the specified parameters using an asynchronous call end triggers a temporary password sms or email message.
        /// </summary>
        /// <param name="userID">The userID of the user being created</param>
        /// <param name="userAttributes">The user attributes of the user being created</param>
        /// <param name="validationData">The validation data of the user being created</param>
        /// <returns>Returns the delivery details for the sign up request</returns>
        public Task AdminSignupAsync(string userID,
                                     IDictionary <string, string> userAttributes,
                                     IDictionary <string, string> validationData)
        {
            AdminCreateUserRequest signUpUserRequest = CreateAdminSignUpRequest(userID, userAttributes, validationData);

            return(Provider.AdminCreateUserAsync(signUpUserRequest));
        }
コード例 #4
0
        /// <summary>
        /// Creates a new User
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task <UserRegisterResult> CreateUserAsync(UserInfo userInfo)
        {
            AdminCreateUserRequest adminCreateUserRequest = new AdminCreateUserRequest()
            {
                Username               = userInfo.Email,
                UserPoolId             = _appConfigInfo.AWSPoolId,
                DesiredDeliveryMediums = new List <string> {
                    "EMAIL"
                },
                UserAttributes = new List <AttributeType>
                {
                    new AttributeType
                    {
                        Name  = "name",
                        Value = userInfo.FirstName
                    },
                    new AttributeType
                    {
                        Name  = "family_name",
                        Value = userInfo.LastName
                    },
                    new AttributeType
                    {
                        Name  = "email",
                        Value = userInfo.Email
                    },
                    new AttributeType()
                    {
                        Name  = "custom:Role",
                        Value = userInfo.Role
                    },
                    new AttributeType()
                    {
                        Name  = "custom:Groups",
                        Value = string.Join(",", userInfo.Groups)
                    }
                }
            };

            try
            {
                var userCreateResult = await _provider.AdminCreateUserAsync(adminCreateUserRequest);

                return(new UserRegisterResult
                {
                    UserName = userCreateResult.User.Username,
                    UserStatus = userCreateResult.User.UserStatus
                });
            }
            catch (UsernameExistsException)
            {
                throw new CcsSsoException("USERNAME_EXISTS");
            }
        }
コード例 #5
0
        public UserDomain AddUser(AdminCreateUserRequest requestData, string subId)
        {
            // POST /users

            UserDomain userDomain = null;

            var userEntity = new User()
            {
                CreatedAt = requestData.CreatedAt.HasValue
                    ? requestData.CreatedAt
                    : DateTime.UtcNow,
                Email  = requestData.Email,
                Name   = requestData.Name,
                Status = requestData.Status,
                SubId  = subId
            };

            try
            {
                // add the user
                Context.Users.Add(userEntity);
                Context.SaveChanges();

                if (requestData.OrganisationId.HasValue)
                {
                    AssociateUserWithOrganisation(userEntity.Id, requestData.OrganisationId.Value);
                }

                if (requestData.Roles != null)
                {
                    var validatedRoles = UserRoleValidator.ToValidList(requestData.Roles);
                    AddRolesToUser(userEntity.Id, validatedRoles);
                }

                // refresh the user domain object
                userDomain = GetUserById(userEntity.Id);
            }
            catch (DbUpdateException dbe)
            {
                HandleDbUpdateException(dbe);
            }
            catch (Exception e)
            {
                LoggingHandler.LogError(e.Message);
                LoggingHandler.LogError(e.StackTrace);
                throw;
            }

            return(userDomain);
        }
コード例 #6
0
        async Task <bool> ILoginProvider.CreateLogin(User user)
        {
            var createUserRequest = new AdminCreateUserRequest
            {
                UserPoolId = _settngs.UserPoolId,
                Username   = user.Email,
            };

            var attributes = new[]
            {
                new AttributeType
                {
                    Name  = AuthPolicy.EmailClaimName,
                    Value = user.Email
                },
                new AttributeType
                {
                    Name  = AuthPolicy.FamilyClaimName,
                    Value = user.FamlyId
                },
                new AttributeType
                {
                    Name  = AuthPolicy.ChurchIdClaimName,
                    Value = user.ChurchId
                },
                new AttributeType
                {
                    Name  = AuthPolicy.UserRoleClaimName,
                    Value = user.Role.ToString()
                },
                new AttributeType
                {
                    Name  = "email_verified",
                    Value = "true"
                }
            };

            createUserRequest.UserAttributes.AddRange(attributes);

            try
            {
                await _client.AdminCreateUserAsync(createUserRequest);
            }
            catch (UsernameExistsException)
            {
                _logger.LogInformation($"Failed to create user with loginId {user.Email}");
                return(false);
            }
            return(true);
        }
コード例 #7
0
        public static void CreateUser(string username)
        {
            var provider = new AmazonCognitoIdentityProviderClient();

            var createUserRequest = new AdminCreateUserRequest
            {
                MessageAction     = "SUPPRESS",
                Username          = username,
                TemporaryPassword = Constants.TemporaryPassword,
                UserPoolId        = PoolId
            };

            provider.AdminCreateUser(createUserRequest);
        }
コード例 #8
0
        public IActionResult Create([FromBody] AdminCreateUserRequest userCreateRequest)
        {
            if (!userCreateRequest.IsValid())
            {
                return(BadRequest("Invalid details provided"));
            }

            try
            {
                return(Created("Created", _createUserRequestUseCase.AdminExecute(userCreateRequest)));
            }
            catch (UseCaseException e)
            {
                return(BadRequest(e));
            }
        }
コード例 #9
0
ファイル: UserService.cs プロジェクト: bigroly/A2.API
        public async Task <bool> CreateUser(User user)
        {
            AdminCreateUserRequest cognitoCreateUserRequest = new AdminCreateUserRequest()
            {
                UserPoolId             = _config.GetValue <string>("Cognito:PoolId"),
                Username               = user.EmailAddress,
                DesiredDeliveryMediums = new List <string> {
                    "EMAIL"
                }
            };

            await _cognito.AdminCreateUserAsync(cognitoCreateUserRequest);

            await CognitoPutUser(user);

            return(true);
        }
コード例 #10
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (var client = new AmazonCognitoIdentityProviderClient(awsAccessKeyId: "AccessKey", awsSecretAccessKey: "SecretKey", RegionEndpoint.USEast1))
            {
                var cognitoRequest = new AdminCreateUserRequest
                {
                    Username           = "******",
                    UserPoolId         = "POOLID",
                    TemporaryPassword  = "******",
                    ForceAliasCreation = true,
                    UserAttributes     = new List <AttributeType>()
                };
                var email = new AttributeType
                {
                    Name  = "email",
                    Value = "*****@*****.**"
                };
                var CustomAttribute = new AttributeType
                {
                    Name  = "custom:ACustomType",
                    Value = "Value"
                };
                var verified = new AttributeType
                {
                    Name  = "email_verified",
                    Value = "true"
                };
                cognitoRequest.UserAttributes.Add(CustomAttribute);
                cognitoRequest.UserAttributes.Add(email);
                cognitoRequest.UserAttributes.Add(verified);


                try
                {
                    var response = client.AdminCreateUserAsync(cognitoRequest);
                    var reply    = await response;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error:" + ex.Message);
                }
            }
        }
コード例 #11
0
        public UserResponse AdminExecute(AdminCreateUserRequest createRequestData)
        {
            UserResponse response = null;
            string       subId;

            // check for currently active user with the same email address (prevents 2 active
            // users with the same email address in the database which can cause problems
            // elsewhere, e.g. 'login user')
            var user = _usersGateway.GetUserByEmail(createRequestData.Email, UserStatus.Active);

            if (user != null)
            {
                throw new UseCaseException()
                      {
                          UserErrorMessage = "An active user with the supplied email address is already registered"
                      }
            }
            ;

            try
            {
                subId = _authGateway.AdminCreateUser(createRequestData);
            }
            catch (AmazonCognitoIdentityProviderException e)
            {
                LoggingHandler.LogError(e.Message);
                LoggingHandler.LogError(e.StackTrace);
                return(null);
            }

            if (subId != null)
            {
                var userDomain = _usersGateway.AddUser(createRequestData, subId);

                if (userDomain != null)
                {
                    response = userDomain.ToResponse();
                }
                response.SetPasswordRequired = true;
            }

            return(response);
        }
コード例 #12
0
        /// <summary>
        /// Lambda to create user in coognito
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <AdminCreateUserResponse> FunctionHandler(AdminCreateUserRequest request, ILambdaContext context)
        {
            LambdaLogger.Log(request.ToString <AdminCreateUserRequest>());
            try
            {
                if (request.IsRequestValid())
                {
                    var response = await _cognitoService.AdminCreateUserAsync(request);

                    return(new AdminCreateUserResponse()
                    {
                        StatusCode = 200, StatusMessage = "success", Payload = response
                    });
                }
                throw new Exception("Invalid Request");
            }
            catch (Exception ex)
            {
                return(new AdminCreateUserResponse()
                {
                    StatusCode = 400, StatusMessage = "error", Payload = ex.Message
                });
            }
        }
 public void AdminCreateUserAsync(AdminCreateUserRequest request, AmazonServiceCallback <AdminCreateUserRequest, AdminCreateUserResponse> callback, AsyncOptions options = null)
 {
     throw new System.NotImplementedException();
 }
コード例 #14
0
        public async Task <(bool, UserType)> FindOrCreateUser(string email, string name, string country, string ipAddress, ADUser adUser = null, bool shouldUpdateAdUser = true)
        {
            email = email.ToLower();
            var request = new ListUsersRequest
            {
                UserPoolId = Configurations.Cognito.CognitoPoolId,
                Filter     = $"email = \"{email}\"",
            };

            var usersResponse = await provider.ListUsersAsync(request);

            if (usersResponse.Users.Count > 0)
            {
                var user = usersResponse.Users.First();
                // dont return passcode property to client
                user.Attributes.Remove(user.Attributes.Find(x => x.Name == "custom:authChallenge"));
                return(true, user);
            }
            else
            {
                var adUserExisting = false;
                if (adUser == null)
                {
                    // create AD User if needed
                    var(existing, newAdUser) = await ADUser.FindOrCreate(email, name, country, ipAddress);

                    adUser         = newAdUser;
                    adUserExisting = existing;
                }
                else
                {
                    adUserExisting = true;
                }

                if (adUser == null)
                {
                    throw new Exception($"can not create ad user {email}");
                }

                // update new properties
                if (adUserExisting && shouldUpdateAdUser)
                {
                    var updateParams = new Dictionary <string, dynamic>();
                    if (!string.IsNullOrWhiteSpace(country))
                    {
                        updateParams["country"] = country;
                        adUser.Country          = country;
                    }

                    if (!string.IsNullOrWhiteSpace(ipAddress))
                    {
                        updateParams["streetAddress"] = ipAddress;
                        adUser.IPAddress = ipAddress;
                    }

                    // enable account if needed
                    if (!adUser.AccountEnabled)
                    {
                        updateParams["accountEnabled"] = true;
                        adUser.AccountEnabled          = true;
                    }

                    if (updateParams.Count > 0)
                    {
                        await adUser.Update(updateParams);
                    }
                }

                // then create cognito user
                var attributes = new List <AttributeType>();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    attributes.Add(new AttributeType()
                    {
                        Name = "name", Value = name
                    });
                }

                if (!string.IsNullOrWhiteSpace(country))
                {
                    attributes.Add(new AttributeType()
                    {
                        Name = "custom:country", Value = country
                    });
                }
                else if (!string.IsNullOrWhiteSpace(adUser.Country))
                {
                    attributes.Add(new AttributeType()
                    {
                        Name = "custom:country", Value = adUser.Country
                    });
                }

                if (!string.IsNullOrWhiteSpace(ipAddress))
                {
                    attributes.Add(new AttributeType()
                    {
                        Name = "custom:ipAddress", Value = ipAddress
                    });
                }
                else if (!string.IsNullOrWhiteSpace(adUser.IPAddress))
                {
                    attributes.Add(new AttributeType()
                    {
                        Name = "custom:ipAddress", Value = adUser.IPAddress
                    });
                }

                // set custom user id from b2c
                attributes.Add(new AttributeType()
                {
                    Name = "preferred_username", Value = adUser.ObjectId
                });
                attributes.Add(new AttributeType()
                {
                    Name = "email", Value = email
                });

                // create new user with temp password
                var createRequest = new AdminCreateUserRequest
                {
                    UserPoolId        = Configurations.Cognito.CognitoPoolId,
                    Username          = email,
                    UserAttributes    = attributes,
                    TemporaryPassword = TokenService.GeneratePassword(Guid.NewGuid().ToString()),
                    MessageAction     = MessageActionType.SUPPRESS,
                };

                UserType newUser;
                try
                {
                    var createUserResponse = await provider.AdminCreateUserAsync(createRequest);

                    newUser = createUserResponse.User;
                }
                catch (UsernameExistsException ex)
                {
                    // TODO will remove later (after fixing from client)
                    Logger.Log?.LogError($"user name exist {ex.Message}");
                    // user exist in other request, just get it from cognito after few second
                    Task.Delay(5 * 1000).Wait();
                    usersResponse = await provider.ListUsersAsync(request);

                    newUser = usersResponse.Users.First();
                }

                // then change its password
                var changePasswordRequest = new AdminSetUserPasswordRequest
                {
                    UserPoolId = Configurations.Cognito.CognitoPoolId,
                    Username   = newUser.Username,
                    Password   = TokenService.GeneratePassword(email),
                    Permanent  = true
                };

                await provider.AdminSetUserPasswordAsync(changePasswordRequest);


                if (!adUserExisting)
                {
                    // add cognito user into group new
                    await UpdateUserGroup(newUser.Username, "new");

                    if (shouldUpdateAdUser)
                    {
                        // add ad user into group new
                        var newGroup = await ADGroup.FindByName("new");

                        var addResult = await newGroup.AddUser(adUser.ObjectId);

                        if (!addResult)
                        {
                            throw new Exception($"can not add ad user {email} into new group");
                        }
                    }
                }
                else
                {
                    // add cognito user into group from b2c
                    var groupName = await adUser.GroupName();

                    if (!string.IsNullOrWhiteSpace(groupName))
                    {
                        await UpdateUserGroup(newUser.Username, groupName);
                    }
                    else
                    {
                        Logger.Log?.LogError($"user {email} does not have group");
                    }
                }

                // dont return passcode property to client
                newUser.Attributes.Remove(newUser.Attributes.Find(x => x.Name == "custom:authChallenge"));
                return(false, newUser);
            }
        }
コード例 #15
0
 public static bool IsValid(this AdminCreateUserRequest userCreateRequest)
 {
     return((!string.IsNullOrWhiteSpace(userCreateRequest.Email)) &&
            (!string.IsNullOrWhiteSpace(userCreateRequest.Name)));
 }