Ejemplo n.º 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);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// A Lambda function that adds a partner post.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> AddPartnerAsync(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var partner       = JsonConvert.DeserializeObject <Partner>(request?.Body);
            var partnerFromDb = await DDBContext.LoadAsync <Partner>(partner.PartnerEmail);

            if (partnerFromDb != null)
            {
                partner.Id = partnerFromDb.Id;
                partner.CreatedTimestamp = partnerFromDb.CreatedTimestamp;
            }
            else
            {
                partner.Id = Guid.NewGuid().ToString();
                partner.CreatedTimestamp = DateTime.Now;
                partner.CreatedBy        = request.RequestContext.Authorizer.Claims.GetValueOrDefault("email");
            }

            partner.ModifiedTimestamp = DateTime.Now;
            partner.ModifiedBy        = request.RequestContext.Authorizer.Claims.GetValueOrDefault("email");

            context.Logger.LogLine($"Saving partner with id {partner.Id}");
            await DDBContext.SaveAsync <Partner>(partner);

            if (partnerFromDb == null)
            {
                var adminProvider = new AmazonCognitoIdentityProviderClient();
                await adminProvider.AdminCreateUserAsync(new Amazon.CognitoIdentityProvider.Model.AdminCreateUserRequest
                {
                    DesiredDeliveryMediums = { "EMAIL" },
                    ForceAliasCreation     = false,
                    TemporaryPassword      = Guid.NewGuid().ToString("d").Substring(3, 10),
                    UserAttributes         = new List <Amazon.CognitoIdentityProvider.Model.AttributeType>
                    {
                        new Amazon.CognitoIdentityProvider.Model.AttributeType
                        {
                            Name = "email", Value = partner.PartnerEmail
                        },
                        new Amazon.CognitoIdentityProvider.Model.AttributeType
                        {
                            Name = "name", Value = partner.PartnerName
                        }
                    },
                    Username   = partner.PartnerEmail,
                    UserPoolId = "us-east-1_ixnBV2gJQ"
                }).ConfigureAwait(false);
            }

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = partner.Id.ToString(),
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }, { "Access-Control-Allow-Origin", "*" }
                }
            };

            return(response);
        }
        /// <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");
            }
        }
        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);
        }
Ejemplo n.º 5
0
        public string AdminCreateUser(Boundary.Requests.AdminCreateUserRequest createRequest)
        {
            AdminCreateUserRequest adminCreateUserRequest = new AdminCreateUserRequest
            {
                UserPoolId             = _connectionInfo.UserPoolId,
                Username               = createRequest.Email,
                DesiredDeliveryMediums = new List <string> {
                    "EMAIL"
                }
            };

            try
            {
                var response = _provider.AdminCreateUserAsync(adminCreateUserRequest).Result;
                return(response.User.Username);
            }
            catch (Exception e)
            {
                LoggingHandler.LogError(e.Message);
                LoggingHandler.LogError(e.StackTrace);
                throw;
            }
        }
Ejemplo n.º 6
0
        public async Task <Guid> CreateAsync(Profile profile)
        {
            var request = CreateUser(profile);

            AdminCreateUserResponse result = null;

            try
            {
                result = await _provider.AdminCreateUserAsync(request);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception: {e.Message}");
            }

            return(Guid.Parse(result.User.Attributes.FirstOrDefault(a => a.Name == "sub").Value));
        }
        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);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Used to Create User in cognito. other attributes can be provided but are not mandatory.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="email"></param>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public async Task <AdminCreateUserResponse> AdminCreateUserAsync(Real.AdminCreateUserRequest request)
        {
            AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(RegionEndpoint.GetBySystemName(REGION));

            AWSModels.AdminCreateUserRequest userRequest = new AWSModels.AdminCreateUserRequest();
            userRequest.Username               = request.Username;
            userRequest.UserPoolId             = POOL_ID;
            userRequest.DesiredDeliveryMediums = new List <string>()
            {
                "EMAIL"
            };
            userRequest.TemporaryPassword = PasswordGenerator.GeneratePassword(true, true, true, true, false, 6);
            userRequest.UserAttributes.Add(new AttributeType {
                Name = "email", Value = request.Email
            });
            userRequest.UserAttributes.Add(new AttributeType {
                Name = "phone_number", Value = request.PhoneNumber
            });

            AdminCreateUserResponse response = null;

            try
            {
                response = await provider.AdminCreateUserAsync(userRequest);
            }
            catch (CodeDeliveryFailureException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.CodeDeliveryFailureException, ex.StackTrace, ex.Message);
            }
            catch (InternalErrorException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.InternalErrorException, ex.StackTrace, ex.Message);
            }
            catch (InvalidLambdaResponseException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.InvalidLambdaResponseException, ex.StackTrace, ex.Message);
            }
            catch (InvalidParameterException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.InvalidParameterException, ex.StackTrace, ex.Message);
            }
            catch (InvalidUserPoolConfigurationException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.InvalidUserPoolConfigurationException, ex.StackTrace, ex.Message);
            }
            catch (PasswordResetRequiredException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.PasswordResetRequiredException, ex.StackTrace, ex.Message);
            }
            catch (ResourceNotFoundException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.ResourceNotFoundException, ex.StackTrace, ex.Message);
            }
            catch (TooManyRequestsException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.TooManyRequestsException, ex.StackTrace, ex.Message);
            }
            catch (UnexpectedLambdaException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.UnexpectedLambdaException, ex.StackTrace, ex.Message);
            }
            catch (UserLambdaValidationException ex)
            {
                if (ex.Message == "User account already exists")
                {
                    ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.UserNameExistsException, ex.StackTrace, ex.Message);
                }
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.UserLambdaValidationException, ex.StackTrace, ex.Message);
            }
            catch (UserNotConfirmedException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.UserNotConfirmedException, ex.StackTrace, ex.Message);
            }
            catch (UserNotFoundException ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.UserNotFoundException, ex.StackTrace, ex.Message);
            }
            catch (AmazonCognitoIdentityProviderException ex)
            {
                if (ex.Message == "User account already exists")
                {
                    ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.UserNameExistsException, ex.StackTrace, ex.Message);
                }

                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.AmazonCognitoIdentityProviderException, ex.StackTrace, ex.Message);
            }
            catch (Exception ex)
            {
                ThrowCustomException(CognitoActionType.AdminCreateUser, ExceptionConstants.ErrorException, ex.StackTrace, ex.Message);
            }
            return(response);
        }
        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);
            }
        }