예제 #1
0
        public UserCreateResponse CreateUser(UserCreateRequest createRequest)
        {
            var response         = new UserCreateResponse();
            var validationErrors = _validation.createRequestValidation.Validate(createRequest);
            var DBErrors         = new List <DatabaseErrors>();

            if (validationErrors.Count != 0 && validationErrors != null)
            {
                response.ValidationErrors = validationErrors;
            }
            else
            {
                try
                {
                    var user = AddUserToDB(createRequest);
                    response.User = user;
                }
                catch (NullReferenceException)
                {
                    DBErrors.Add(DatabaseErrors.DB_CONNECTION_FAILED);
                }
                response.DBErrors = DBErrors;
            }

            return(response);
        }
예제 #2
0
 public void Complete(UserCreateResponse response)
 {
     File.AppendAllLines(FileName, new[] {
         "complete",
         "id: " + response.UserId
     });
 }
        public UserCreateResponse Handle(UserCreateRequest request)
        {
            presenter.Progress(10); // 10% 経過

            var username      = request.UserName;
            var duplicateUser = userRepository.FindByUserName(username);

            presenter.Progress(30); // 30% 経過

            if (duplicateUser != null)
            {
                throw new Exception("duplicated");
            }

            presenter.Progress(50); // 50% 経過

            var user = new User(username);

            presenter.Progress(80); // 80% 経過

            userRepository.Save(user);

            var response = new UserCreateResponse(user.Id);

            presenter.Complete(response);

            return(response); // 同じレスポンスを
        }
예제 #4
0
        public static async Task <HttpResponseMessage> Create(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "users")] HttpRequest req,
            ExecutionContext context,
            ILogger log)
        {
            init(context);

            log.LogInformation(req.ContentType);

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = null;

            try
            {
                data = JsonConvert.DeserializeObject(requestBody);
            }
            catch (JsonReaderException)
            {
                return(Responses.BadRequest("invalid Body"));
            }

            string name        = data?.name;
            string description = data?.description;

            var request = new UserCreateRequest(name, description);
            UserCreateResponse response = await new UserCreateUseCase().execute(request);

            return(Responses.Created(JsonConvert.SerializeObject(response.User)));
        }
예제 #5
0
        public UserCreateResponse Create([FromBody] UserCreateRequest request)
        {
            var response = new UserCreateResponse();

            response.Id = _facade.Create(request.User);

            return(response);
        }
예제 #6
0
 public async Task <ActionResult> Create([FromBody] UserCreateRequest rq)
 {
     try
     {
         UserCreateResponse rs = await(new UserCreateService(Context, _userRepo)).RunAsync(rq);
         return(new ApiActionResult(Context.Request, rs));
     }
     catch (Exception ex)
     {
         return(new ApiActionResult(Context.Request, ex));
     }
 }
예제 #7
0
        public async Task <Models.User> Create(UserCreateResponse response)
        {
            var user = new Models.User
            {
                PublicId = response.PublicId,
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return(user);
        }
        public async Task NullBody_Fails()
        {
            // Arrange
            UserCreateRequest req = null;

            // Act
            HttpResponseMessage res = await this.client.PostJsonAsync(LOGIN_URL, req);

            UserCreateResponse result = await res.ReadJsonResponseAsync <UserCreateResponse>();

            // Assert
            // Not matching the whole object since we don't want to validate message content, not i18n or l10n safe
            result.Errors.Should().HaveCount(1);
            result.Errors.FirstOrDefault().Field.Should().BeNullOrEmpty();
            ((int)(res.StatusCode)).Should().Be(422);
        }
예제 #9
0
        /// <summary>
        /// Creates a new USER record.  Generates a temporary password and
        /// returns it as part of the response.
        /// If a User already exists for the specified email, an exception is throw
        /// please check for existence before calling this if you do not intent
        /// to create a user.
        /// </summary>
        /// <returns></returns>
        public UserCreateResponse CreateUser(UserDetail userDetail)
        {
            // see if this user already exists
            UserDetail existingUser = this.GetUserDetail(userDetail.Email);

            if (existingUser != null)
            {
                // USER ALREADY EXISTS ... return what we already have
                // NO we better return an error so that someone cannot just overwrite the account
                // prompt them to recover the password if the account already exists
                throw new ApplicationException("This user already exists. To recover a password user the forgot password link on the login page.");
            }


            // generate and hash a temporary password
            string temporaryPassword = System.Web.Security.Membership.GeneratePassword(10, 2);
            string hashedPassword;
            string salt;

            PasswordHash.HashPassword(temporaryPassword, out hashedPassword, out salt);


            // create new records for USER and USER_DETAIL_INFORMATION
            using (var db = new CSET_Context())
            {
                var u = new USERS()
                {
                    PrimaryEmail          = userDetail.Email,
                    FirstName             = userDetail.FirstName,
                    LastName              = userDetail.LastName,
                    Password              = hashedPassword,
                    Salt                  = salt,
                    IsSuperUser           = false,
                    PasswordResetRequired = true
                };
                db.USERS.Add(u);
                db.SaveChanges();

                UserCreateResponse resp = new UserCreateResponse
                {
                    UserId            = u.UserId == 0?1:u.UserId,
                    PrimaryEmail      = u.PrimaryEmail,
                    TemporaryPassword = temporaryPassword
                };
                return(resp);
            }
        }
예제 #10
0
        public UserCreate(UserCreateRequest request)
        {
            if (request != null)
            {
                if (string.IsNullOrWhiteSpace(request.Email) || !EmailHelper.IsValidEmail(request.Email))
                {
                    Response = new UserCreateResponse
                    {
                        Type = UserCreateResponseType.EmailNotValid
                    };
                    return;
                }

                //TODO: Password regex check (force min 10 characters etc)
                if (string.IsNullOrWhiteSpace(request.Password))
                {
                    Response = new UserCreateResponse
                    {
                        Type = UserCreateResponseType.PasswordTooWeak
                    };
                    return;
                }

                using (var dbContext = new ApplicationDbContext())
                {
                    if (dbContext.Users.Any(aUser => aUser.Email.ToLower().Trim() == request.Email.ToLower().Trim()))
                    {
                        Response = new UserCreateResponse
                        {
                            Type = UserCreateResponseType.EmailExists
                        };
                        return;
                    }
                    var user = new User();
                    user.Set(request);
                    dbContext.Users.Add(user);
                    dbContext.SaveChanges();

                    Response = new UserCreateResponse
                    {
                        Identifier = user.Identifier,
                        Type       = UserCreateResponseType.Success,
                    };
                }
            }
        }
        private async Task Run_Fails(UserCreateRequest req, string ErrorFieldName)
        {
            // Arrange
            const bool expectedSuccess = false;

            // Act
            HttpResponseMessage res = await this.client.PostJsonAsync(LOGIN_URL, req);

            UserCreateResponse result = await res.ReadJsonResponseAsync <UserCreateResponse>();

            // Assert
            // Not matching the whole object since we don't want to validate message content, not i18n or l10n safe
            result.Success.Should().Be(expectedSuccess);
            result.Errors.Count.Should().BeInRange(1, 2); // valid and maybe required
            result.Errors.ForEach(e => e.Field.Should().Be(ErrorFieldName));
            ((int)(res.StatusCode)).Should().Be(422);
        }
예제 #12
0
        internal UserCreateResponse CheckUserExists(UserDetail userDetail)
        {
            UserDetail         existingUser = this.GetUserDetail(userDetail.Email);
            UserCreateResponse resp         = new UserCreateResponse();

            if (existingUser != null)
            {
                resp.IsExisting   = true;
                resp.UserId       = existingUser.UserId;
                resp.PrimaryEmail = userDetail.Email;
            }
            else
            {
                resp.IsExisting = false;
            }
            return(resp);
        }
예제 #13
0
        /// <summary>
        /// Creates a new user and sends them an email containing a temporary password.
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool CreateUserSendEmail(CreateUser info)
        {
            try
            {
                // Create the USER and USER_DETAIL_INFORMATION records for this new user
                UserManager um = new UserManager();
                UserDetail ud = new UserDetail()
                {
                    UserId = info.UserId,
                    Email = info.PrimaryEmail,
                    FirstName = info.FirstName,
                    LastName = info.LastName
                };
                UserCreateResponse userCreateResponse = um.CreateUser(ud);

                db.USER_SECURITY_QUESTIONS.Add(new USER_SECURITY_QUESTIONS()
                {
                    UserId = userCreateResponse.UserId,
                    SecurityQuestion1 = info.SecurityQuestion1,
                    SecurityQuestion2 = info.SecurityQuestion2,
                    SecurityAnswer1 = info.SecurityAnswer1,
                    SecurityAnswer2 = info.SecurityAnswer2
                });

                db.SaveChanges();
                
                // Send the new temp password to the user
                NotificationManager nm = new NotificationManager(info.AppCode);
                nm.SendPasswordEmail(userCreateResponse.PrimaryEmail, info.FirstName, info.LastName, userCreateResponse.TemporaryPassword);

                return true;
            }
            catch (ApplicationException app)
            {
                throw new CSETApplicationException("This account already exists. Please request a new password using the Forgot Password link if you have forgotten your password.", app);
            }
            catch (DbUpdateException due)
            {
                throw new CSETApplicationException("This account already exists. Please request a new password using the Forgot Password link if you have forgotten your password.", due);
            }
            catch (Exception e)
            {
                return false;
            }
        }
예제 #14
0
        /// <summary>
        /// Creates user asynchronously.
        /// </summary>
        /// <param name="request">The <see cref="UserCreateRequest" /> instance.</param>
        /// <returns>Returns the <see cref="UserCreateResponse" /> instance.</returns>
        public async Task <UserCreateResponse> CreateUserAsync(UserCreateRequest request)
        {
            await this._builder.BuildAsync(request);

            var handler = this._handlers.SingleOrDefault(p => p.CanHandle(request));

            if (handler == null)
            {
                return(await Task.FromResult(default(UserCreateResponse)));
            }

            var ev = handler.CreateEvent(request) as UserCreatedEvent;

            PopulateBaseProperties(ev);

            UserCreateResponse response;

            try
            {
                await this._processor.ProcessEventsAsync(new[] { ev });

                response = new UserCreateResponse()
                {
                    Data = new UserResponseData()
                    {
                        Title    = ev.Title,
                        Username = ev.Username,
                        Email    = ev.Email,
                    }
                };
            }
            catch (Exception ex)
            {
                response = new UserCreateResponse()
                {
                    Error = new ResponseError()
                    {
                        Message    = ex.Message,
                        StackTrace = ex.StackTrace,
                    }
                };
            }

            return(await Task.FromResult(response));
        }
        public async Task ValidUser_Succeeds()
        {
            // Arrange
            UserCreateRequest req = new UserCreateRequest {
                Email    = VALID_EMAIL,
                Password = VALID_PASSWORD
            };
            const bool expectedSuccess = true;

            // Act
            HttpResponseMessage res = await this.client.PostJsonAsync(LOGIN_URL, req);

            UserCreateResponse result = await res.ReadJsonResponseAsync <UserCreateResponse>();

            // Assert
            // Not matching the whole object since we don't want to validate message content, not i18n or l10n safe
            result.UserId.Should().BeGreaterThan(0);
            result.Success.Should().Be(expectedSuccess);
            ((int)(res.StatusCode)).Should().Be(200);
        }
예제 #16
0
        public IActionResult LoginUser([FromBody] LoginRequest loginRequest)
        {
            var optionUser = _userService.LogInByCredentials(loginRequest.Username, loginRequest.Password);

            return(optionUser.Match <IActionResult>(
                       Some: user =>
            {
                var token = _jwtIssuer.GenerateToken(user);
                var userCreateResponse = new UserCreateResponse(token);
                return Ok(userCreateResponse);
            },
                       None: Ok(new
            {
                errors = new
                {
                    passwordError = "Invalid password.",
                    commonError = "There are errors with some fields bellow."
                }
            })));
        }
예제 #17
0
        public async Task <ActionResult <UserCreateResponse> > Create([FromRoute] string username)
        {
            if (!UserNameRX.IsMatch(username))
            {
                return(BadRequest(new ErrorModel()
                {
                    Code = 400,
                    Message = "Invalid username pattern"
                }));
            }

            if (await db.Users.CountAsync(u => u.Username == username) > 0)
            {
                return(BadRequest(new ErrorModel()
                {
                    Code = 400,
                    Message = "Username already exists"
                }));
            }

            var(token, hash) = masterTokens.Generate();

            var user = new User()
            {
                Username      = username,
                MasterKeyHash = hash,
            };

            db.Add(user);
            await db.SaveChangesAsync();

            var res = new UserCreateResponse()
            {
                Id        = user.Id,
                TimeStamp = user.TimeStamp,
                Username  = user.Username,
                MasterKey = token,
            };

            return(Ok(res));
        }
예제 #18
0
        public async Task <IActionResult> Create(AccountCreateModel Model)
        {
            if (!this.ModelState.IsValid)
            {
                return(View(Model ?? new AccountCreateModel())); // Fix your errors please
            }

            UserCreateResponse createResponse = await this.userRepository.CreateUserAsync(new UserCreateRequest {
                Email    = Model.Email,
                Password = Model.Password
            });

            if (!createResponse.Success)
            {
                foreach (var error in createResponse.Errors)
                {
                    this.ModelState.AddModelError(error.Field, error.Message);
                }
                return(View(Model));
            }

            return(RedirectToAction("CreateSuccess"));
        }
예제 #19
0
        public IActionResult CreateUser([FromBody] UserCreateRequest userCreateRequest)
        {
            var userForm = new UserForm(userCreateRequest.Username, userCreateRequest.Password);

            _userService.CreateUser(userForm);

            var optionUser = _userService.LogInByCredentials(userForm.Username, userForm.Password);

            return(optionUser.Match <IActionResult>(
                       Some: user =>
            {
                var token = _jwtIssuer.GenerateToken(user);
                var userCreateResponse = new UserCreateResponse(token);
                return Ok(userCreateResponse);
            },
                       None: Ok(new
            {
                errors = new
                {
                    usernameError = "Username already taken.",
                    commonError = "There are errors with some fields bellow."
                }
            })));
        }
 public void Complete(UserCreateResponse response)
 {
     Console.WriteLine("complete");
     Console.WriteLine("created id: " + response.UserId);
 }
        public void Complete(UserCreateResponse response)
        {
            var message = new UserCreateCompleteModel(response.UserId);

            MessageBus.Instance.Send(message);
        }
예제 #22
0
        /// <summary>
        /// Emulates credential authentication without requiring credentials.
        /// The Windows file system is consulted to see if a certain file was placed there
        /// during the stand-alone install process.
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public static LoginResponse AuthenticateStandalone(Login login)
        {
            int    userIdSO       = 100;
            string primaryEmailSO = "";

            // Read the file system for the LOCAL-INSTALLATION file put there at install time
            if (!IsLocalInstallation(login.Scope))
            {
                return(null);
            }


            String name = WindowsIdentity.GetCurrent().Name;

            name           = string.IsNullOrWhiteSpace(name) ? "Local" : name;
            primaryEmailSO = name;
            using (var db = new CSET_Context())
            {
                //check for legacy default email for local installation and set to new standard
                var userOrg = db.USERS.Where(x => x.PrimaryEmail == primaryEmailSO + "@myorg.org").FirstOrDefault();
                if (userOrg != null)
                {
                    string tmp = userOrg.PrimaryEmail.Split('@')[0];
                    userOrg.PrimaryEmail = tmp;
                    if (db.USERS.Where(x => x.PrimaryEmail == tmp).FirstOrDefault() == null)
                    {
                        db.SaveChanges();
                    }
                    primaryEmailSO = userOrg.PrimaryEmail;
                }

                var user = db.USERS.Where(x => x.PrimaryEmail == primaryEmailSO).FirstOrDefault();
                if (user == null)
                {
                    UserManager um = new UserManager();
                    UserDetail  ud = new UserDetail()
                    {
                        Email     = primaryEmailSO,
                        FirstName = name,
                        LastName  = ""
                    };
                    UserCreateResponse userCreateResponse = um.CreateUser(ud);

                    db.SaveChanges();
                    //update the userid 1 to the new user
                    var tempu = db.USERS.Where(x => x.PrimaryEmail == primaryEmailSO).FirstOrDefault();
                    if (tempu != null)
                    {
                        userIdSO = tempu.UserId;
                    }
                    determineIfUpgradedNeededAndDoSo(userIdSO);
                }
                else
                {
                    userIdSO = user.UserId;
                }
            }

            if (string.IsNullOrEmpty(primaryEmailSO))
            {
                return(null);
            }


            // Generate a token for this user
            string token = TransactionSecurity.GenerateToken(userIdSO, login.TzOffset, -1, null, null, login.Scope);

            // Build response object
            LoginResponse resp = new LoginResponse
            {
                Token            = token,
                Email            = primaryEmailSO,
                UserFirstName    = name,
                UserLastName     = "",
                IsSuperUser      = false,
                ResetRequired    = false,
                ExportExtension  = IOHelper.GetExportFileExtension(login.Scope),
                ImportExtensions = IOHelper.GetImportFileExtensions(login.Scope)
            };


            return(resp);
        }
 public void Complete(UserCreateResponse response)
 {
 }
예제 #24
0
        /// <summary>
        /// Creates or updates the rows necessary to attach a Contact to an Assessment.
        /// Creates a new User based on email.
        /// Creates or overwrites the ASSESSMENT_CONTACTS connection.
        /// Creates a new Contact if needed.  If a Contact already exists for the email, no
        /// changes are made to the Contact row.
        /// </summary>
        public ContactDetail CreateAndAddContactToAssessment(ContactCreateParameters newContact)
        {
            int          assessmentId = Auth.AssessmentForUser();
            TokenManager tm           = new TokenManager();
            string       app_code     = tm.Payload(Constants.Token_Scope);

            NotificationManager nm = new NotificationManager();

            ASSESSMENT_CONTACTS existingContact = null;

            using (var db = new CSET_Context())
            {
                // See if the Contact already exists
                existingContact = db.ASSESSMENT_CONTACTS.Where(x => x.UserId == newContact.UserId && x.Assessment_Id == assessmentId).FirstOrDefault();
                if (existingContact == null)
                {
                    // Create Contact
                    var c = new ASSESSMENT_CONTACTS()
                    {
                        FirstName        = newContact.FirstName,
                        LastName         = newContact.LastName,
                        PrimaryEmail     = newContact.PrimaryEmail,
                        Assessment_Id    = assessmentId,
                        AssessmentRoleId = newContact.AssessmentRoleId,
                        Title            = newContact.Title,
                        Phone            = newContact.Phone
                    };

                    // Include the userid if such a user exists
                    USERS user = db.USERS.Where(u => !string.IsNullOrEmpty(u.PrimaryEmail) &&
                                                u.PrimaryEmail == newContact.PrimaryEmail)
                                 .FirstOrDefault();
                    if (user != null)
                    {
                        c.UserId = user.UserId;
                    }

                    db.ASSESSMENT_CONTACTS.AddOrUpdate(c, x => x.Assessment_Contact_Id);


                    // If there was no USER record for this new Contact, create one
                    if (user == null)
                    {
                        UserDetail userDetail = new UserDetail
                        {
                            Email                 = newContact.PrimaryEmail,
                            FirstName             = newContact.FirstName,
                            LastName              = newContact.LastName,
                            IsSuperUser           = false,
                            PasswordResetRequired = true
                        };
                        UserManager        um   = new UserManager();
                        UserCreateResponse resp = um.CheckUserExists(userDetail);
                        if (!resp.IsExisting)
                        {
                            resp = um.CreateUser(userDetail);

                            // Send this brand-new user an email with their temporary password (if they have an email)
                            if (!string.IsNullOrEmpty(userDetail.Email))
                            {
                                if (!UserAuthentication.IsLocalInstallation(app_code))
                                {
                                    nm.SendInviteePassword(userDetail.Email, userDetail.FirstName, userDetail.LastName, resp.TemporaryPassword);
                                }
                            }
                        }
                        c.UserId = resp.UserId;
                    }

                    db.SaveChanges();

                    AssessmentUtil.TouchAssessment(assessmentId);

                    existingContact = c;
                }
            }

            // Flip the 'invite' flag to true, if they are a contact on the current Assessment
            ContactsManager cm = new ContactsManager();

            cm.MarkContactInvited(newContact.UserId, assessmentId);

            // Tell the user that they have been invited to participate in an Assessment (if they have an email)
            if (!string.IsNullOrEmpty(newContact.PrimaryEmail))
            {
                if (!UserAuthentication.IsLocalInstallation(app_code))
                {
                    nm.InviteToAssessment(newContact);
                }
            }

            // Return the full list of Contacts for the Assessment
            return(new ContactDetail
            {
                FirstName = existingContact.FirstName,
                LastName = existingContact.LastName,
                PrimaryEmail = existingContact.PrimaryEmail,
                AssessmentId = existingContact.Assessment_Id,
                AssessmentRoleId = existingContact.AssessmentRoleId,
                Invited = existingContact.Invited,
                UserId = existingContact.UserId ?? null,
                Title = existingContact.Title,
                Phone = existingContact.Phone
            });
        }