public async Task<IActionResult> Start(RegistrationModel model) {
            var token = Guid.NewGuid().ToString();

            _logger.Log(x => x.Information, () => string.Format("Starting registration process - {0} ", new { model.Name, token }));

            var registrationRequest = _database.RegistrationRequests.Add(model.Name, model.Consented, token);

            await _database.SaveChangesAsync();

            var requestUri = Request.GetUri();
            var redirectUri = requestUri.ToString().Replace(requestUri.Segments.Last(), "");

            redirectUri += "complete";

            var authorizationRequest = OnboardingUrl.FormatUrlWith(
                _settings.ClientID,
                GraphUrl,
                redirectUri,
                registrationRequest.Token
            );

            if(model.Consented) {
                authorizationRequest += "&prompt={0}".FormatUrlWith("admin_consent");
            }
            else {
                return View("RegistrationError", new RegistrationErrorModel("Consent Not Given", "You Must Give Consent"));
            }

            return Redirect(authorizationRequest);
        }
 public RegistrationResponse RegisterDevice(string ChannelUri, short DeviceType)
 {
   // Get the body. This will be the devices channel URI
   RegistrationModel model = new RegistrationModel();
   string pinCode = model.SaveDeviceRegistration(ChannelUri);
   return new RegistrationResponse() { PinCode = pinCode };
 }
 public ActionResult Index(RegistrationModel model)
 {
     if (ModelState.IsValid)
     {
         return View(model);
     }
     List<RegistrationModel> list = Session[Storage.DbKey] as List<RegistrationModel> ?? new List<RegistrationModel>();
     list.Add(model);
     Session[Storage.DbKey] = list;
     return RedirectToAction("List" , "User");
 }
 public bool IsValid(RegistrationModel registrationModel)
 {
     if (String.IsNullOrEmpty(registrationModel.Username))
     {
         return false;
     }
     if (registrationModel.Username.Contains('_'))
     {
         return false;
     }
     return true;
 }
    public ActionResult AccessCode(RegistrationCheck check)
    {
      RegistrationModel model = new RegistrationModel();
      string pinCode = GetPin(check);
      DeviceRegistration deviceRegistration = model.GetRegistration(GetPin(check));

      if (deviceRegistration != null)
      {
        check.ChannelUri = deviceRegistration.ChannelUri;
      }

      return RedirectToAction("Information", new { pinCode = pinCode });
    }
 public bool IsValid(RegistrationModel registrationModel)
 {
     if (String.IsNullOrEmpty(registrationModel.Email))
     {
         return false;
     }
     if (!registrationModel.Email.Contains('@'))
     {
         return false;
     }
     if (!registrationModel.Email.Contains('.'))
     {
         return false;
     }
     return true;
 }
 public bool IsValid(RegistrationModel registrationModel)
 {
     if (String.IsNullOrEmpty(registrationModel.Password))
     {
         return false;
     }
     if (registrationModel.Password.Length < MinimumLength)
     {
         return false;
     }
     if (!Capital.IsMatch(registrationModel.Password) || !Lowercase.IsMatch(registrationModel.Password))
     {
         return false;
     }
     return true;
 }
        public async Task<IHttpActionResult> Register(RegistrationModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new AppStoreUser() { UserName = model.Email, Email = model.Email };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }
    public void PinGeneration()
    {
      RegistrationModel model = new RegistrationModel();

      List<string> generatedPins = new List<string>();

      for (int i = 0; i < 10000; i++)
      {
        string newPin = model.GeneratePin();

        if (generatedPins.Contains(newPin))
        {
          Assert.Fail("Duplication pin found at index " + i);
          return;
        }

        generatedPins.Add(newPin);
      }
    }
Example #10
0
        public async Task <IHttpActionResult> Register(RegistrationModel model)
        {
            // 1. Server Side Validation
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // 2. Pass the registration onto AuthRepository
            var result = await _repo.RegisterUser(model);

            // 3. Check to see that the registration was successful
            if (result.Succeeded)
            {
                return(Ok());
            }
            else
            {
                return(BadRequest("Registration form was invalid."));
            }
        }
        public Task RegisterUser(RegistrationModel registrationModel)
        {
            if (registrationModel == null)
            {
                throw new ArgumentNullException(nameof(registrationModel));
            }
            if (string.IsNullOrEmpty(registrationModel.FirstName))
            {
                throw new ArgumentNullException(nameof(registrationModel.FirstName));
            }
            if (string.IsNullOrEmpty(registrationModel.Username))
            {
                throw new ArgumentNullException(nameof(registrationModel.Username));
            }
            if (string.IsNullOrEmpty(registrationModel.Password))
            {
                throw new ArgumentNullException(nameof(registrationModel.Password));
            }

            return(RegisterUserAsync(registrationModel));
        }
        public void Test1()
        {
            //Arrange
            RegistrationModel temp     = new RegistrationModel();
            string            name     = "testName";
            string            surname  = "testSurname";
            string            email    = "*****@*****.**";
            string            password = "******";

            //Act
            temp.Name     = name;
            temp.Surname  = surname;
            temp.Email    = email;
            temp.Password = password;

            //Assert
            Assert.Equal(name, temp.Name);
            Assert.Equal(surname, temp.Surname);
            Assert.Equal(email, temp.Email);
            Assert.Equal(password, temp.Password);
        }
        public async Task <IActionResult> Register([FromBody] RegistrationModel registration)
        {
            var newUser = new User
            {
                UserName  = registration.Email,
                Email     = registration.Email,
                FirstName = registration.FirstName,
                LastName  = registration.LastName
            };
            var result = await _userManager.CreateAsync(newUser, registration.Password);

            if (result.Succeeded)
            {
                return(Ok(newUser.ToApiModel()));
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
            return(BadRequest(ModelState));
        }
        public async Task <IActionResult> Create([FromBody] RegistrationModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.ToDictionary()));
            }

            var result = await _authServices.Registration(model);

            if (!result.Succeeded && result.Errors.Any())
            {
                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError(err.Code, err.Description);
                }

                return(BadRequest(ModelState.ToDictionary()));
            }

            return(Ok());
        }
        private async Task <ApplicationUser> CreateNewUser(RegistrationModel registrationModel)
        {
            var user = await _userManager.FindByEmailAsync(registrationModel.Username);

            if (user == null)
            {
                user = MapToNewUser(registrationModel);
                var createResult = await _userManager.CreateAsync(user, registrationModel.Password);

                if (!createResult.Succeeded)
                {
                    ProcessErrors("Creating new user failed.", createResult);
                }
            }
            else
            {
                throw new InvalidOperationException($"Unable to create user with email {registrationModel.Username} as it already exists.");
            }

            return(user);
        }
Example #16
0
 /// <summary>
 /// Registration by registration model
 /// </summary>
 /// <param name="model">Model for the registration with main data</param>
 /// <returns>Result of the registration</returns>
 public async System.Threading.Tasks.Task Registration(RegistrationModel model)
 {
     var appUser = new User
     {
         UserName = model.UserName,
         Email = model.Email,
         FullName = model.FullName
     };
     var result = await this._userManager.CreateAsync(appUser, model.Password);
     if (result.Succeeded)
     {
         var user = await this._userManager.FindByNameAsync(appUser.UserName);
         await this._userManager.AddToRoleAsync(user, Roles.NormalWebsiteRole);
         this._logger.LogInformation($"{user.UserName}'s registration was successfully with e-mail {user.Email}");
         this._notificationService.AddSystemNotificationByType(SystemNotificationType.Registration, user);
     }
     else
     {
         throw new MessageException(this._utilsService.ErrorsToString(result.Errors));
     }
 }
Example #17
0
        private void Search_Student_Details()
        {
            Reset_Controls();
            if (string.IsNullOrEmpty(txtRegistrationNo.Text))
            {
                MessageBox.Show("Registration Number is required.", "Student TC", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                StudentRegistration registration       = new StudentRegistration();
                RegistrationModel   _registrationModel = new RegistrationModel();
                _registrationModel = registration.Get_Student_Detail(Convert.ToInt64(txtRegistrationNo.Text));

                if (_registrationModel.RegistrationNo == null)
                {
                    _registrationModel = registration.Get_InActive_Student_Detail(Convert.ToInt64(txtRegistrationNo.Text));
                }

                if (_registrationModel.RegistrationNo != null)
                {
                    lblStudentNameValue.Text    = _registrationModel.FullName;
                    lblClassValue.Text          = _registrationModel.ClassSection;
                    lblStudentNameValue.Visible = true;
                    lblClassValue.Visible       = true;
                    lblStudentName.Visible      = true;
                    lblClass.Visible            = true;
                    panelInfo.Visible           = true;
                    _class_ID   = _registrationModel.CurrentClass;
                    _section_ID = _registrationModel.CurrentSection;
                    _student_ID = (long)_registrationModel.StudentID;
                    Get_Student_TC_Details();
                }
                else
                {
                    MessageBox.Show("Invalid Registration Number.", "Student TC", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Reset_Controls();
                    txtRegistrationNo.Text = string.Empty;
                }
            }
        }
Example #18
0
        public bool RegistrateUser(RegistrationModel registrationModel)
        {
            User existingUser;

            try
            {
                existingUser = Find(registrationModel.Email);
            }
            catch
            {
                existingUser = null;
            }

            if (existingUser != null)
            {
                return(false);
            }
            var user = new User
            {
                Name     = registrationModel.Name,
                Email    = registrationModel.Email,
                Password = SecurityManager.GetHashString(registrationModel.Password),
                Status   = UserStatus.Unconfirmed
            };


            try
            {
                Data.Users.Add(user);
                Data.SaveChanges();
                SendConfirmationMail(user);
            }
            catch
            {
                Data.Users.Remove(user);
                return(false);
            }

            return(true);
        }
Example #19
0
      public ActionResult Register(RegistrationModel info)
      {
          using (BusinessLogicLayer.ContextBll ctx = new BusinessLogicLayer.ContextBll())
          {
              if (!ModelState.IsValid)
              {
                  return(View(info));
              }
              BusinessLogicLayer.UserBLL user = ctx.FindUserByEmail(info.EMail);
              if (user != null)
              {
                  info.Message = $"The Email Address '{info.EMail}' already exists in the database";
                  return(View(info));
              }
              user = new BusinessLogicLayer.UserBLL();

              user.EmailAdderess = info.EMail;
              //user.Password = System.Web.Helpers.Crypto.
              //    GenerateSalt(Constants.SaltSize);
              user.Password = info.Password;
              user.Hash     = System.Web.Helpers.Crypto.
                              HashPassword(info.Password);
              // + user.Hash
              user.RoleID = 3;
              string GetUntil(string text, string limiter = "@")
              {
                  int charLocation = text.IndexOf(limiter, StringComparison.Ordinal);

                  return(text.Substring(0, charLocation));
              }

              user.Name = GetUntil(info.EMail);  // extract all letters befor @

              ctx.CreateUser(user);
              Session["AUTHUsername"] = (user.EmailAdderess);
              Session["AUTHRoles"]    = user.Role;
              Session["AUTHTYPE"]     = "HASHED";
              return(RedirectToAction("Index"));
          }
      }
Example #20
0
        public ActionResult Index(RegistrationModel registrationModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Registration reg = new Registration();
                    registrationModel.UserType = "O";
                    int _uid = reg.Createuser(registrationModel);

                    if (_uid == -1)
                    {
                        ViewBag.Message = "Email Already Exist, Please Enter some Different Email Id.";
                        return(View());
                    }
                    else if (_uid == 1)
                    {
                        Session["UserId"]   = _uid;
                        Session["UserName"] = registrationModel.UserName;
                        ViewBag.UserName    = Session["UserName"].ToString();
                        ViewBag.Message     = "Welcome " + Session["UserName"].ToString();

                        return(RedirectToAction("Index", "Dashboard", new { @pageNo = 0 }));
                    }
                    else
                    {
                        ViewBag.Message = "Internal Error Occurred, Please Try After Some Time.";
                        return(View());
                    }
                }
                else
                {
                    return(View(registrationModel));
                }
            }catch (Exception ex)
            {
                ViewBag.Message = "Some Problem at User Registration, Please try again.";
                return(RedirectToAction("", ""));
            }
        }
        public ActionResult Register(RegistrationModel info)
        {
            try
            {
                using (ContextBLL context = new ContextBLL())
                {
                    UserBLL user = context.UserFindByEmail(info.Email);
                    if (user != null)
                    {
                        info.Message = $"The EMail Address '{info.Email}' already exists in the database";
                        ModelState.Clear();
                        return(View(info));
                    }
                    if (!ModelState.IsValid)
                    {
                        return(View(info));
                    }
                    user = new UserBLL
                    {
                        Email = info.Email,
                        Salt  = System.Web.Helpers.Crypto.
                                GenerateSalt(Constants.SaltSize)
                    };
                    user.Hash = System.Web.Helpers.Crypto.
                                HashPassword(info.Hash + user.Salt);
                    user.RoleID = 3;

                    context.UserCreate(user.Email, user.Hash, user.Salt, Constants.NonVerifiedUser);
                    Session["AUTHUsername"] = user.Email;
                    Session["AUTHRoles"]    = user.RoleName;
                    Session["AUTHTYPE"]     = "HASHED";
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return(View("Error", ex));
            }
        }
Example #22
0
        public async Task <IActionResult> Register(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                // Copy data from RegistrationModel to IdentityUser
                var user = new ApplicationUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    PhoneNumber = model.PhoneNumber,
                    City        = model.City,
                    Gender      = model.Gender
                };

                // Store user data in AspNetUsers database table
                var result = await userManager.CreateAsync(user, model.Password);

                // If user is successfully created, sign-in the user using
                // SignInManager and redirect to index action of HomeController
                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent : false);

                    bookDBContext.LoginTable.Add(model);
                    bookDBContext.SaveChanges();
                    string Message = "Register Sucess Fully";
                    return(this.Ok(new { Message }));
                }

                // If there are any errors, add them to the ModelState object
                // which will be displayed by the validation summary tag helper
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            string message = "Put right pattern of email and password";

            return(this.BadRequest(new { message }));
        }
        public async Task <IActionResult> Register(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new PizzaUser
                {
                    UserName    = model.EmailAddress.ToLower(),
                    Email       = model.EmailAddress.ToLower(),
                    PhoneNumber = NormalizePhoneNumber(model.PhoneNumber),

                    EncryptionAlgorithm = model.EncryptionAlgorithm,
                    ReceivesEmails      = model.ReceivesEmails,
                    FirstName           = model.FirstName,
                    LastName            = model.LastName,
                    PhoneExtension      = model.PhoneExtension,
                    Country             = model.Country,
                    StreetAddress       = model.StreetAddress,
                    ApartmentNumber     = model.ApartmentNumber,
                    City    = model.City,
                    State   = model.State,
                    ZipCode = model.ZipCode
                };
                IdentityResult result = await _userManager.CreateAsync(user, model.PasswordHash);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    model.Registered = true;

                    return(View(model));
                }
                else
                {
                    AddErrors(result);
                }
            }

            return(View(model));
        }
Example #24
0
        public ActionResult Registration(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                LibraryUser libraryUser = null;
                using (LibraryUserContext db = new LibraryUserContext())
                {
                    libraryUser = db.LibraryUsers.FirstOrDefault(l => l.Login == model.Name);
                }
                if (libraryUser == null)
                {
                    using (LibraryUserContext db = new LibraryUserContext())
                    {
                        db.LibraryUsers.Add(new LibraryUser
                        {
                            Login      = model.Name,
                            Password   = model.Password,
                            Email      = model.Email,
                            FirstName  = model.FirstName,
                            MiddleName = model.MiddleName,
                            LastName   = model.LastName
                        });
                        db.SaveChanges();

                        libraryUser = db.LibraryUsers.Where(l => l.Login == model.Name && l.Password == model.Password).FirstOrDefault();
                    }

                    if (libraryUser != null)
                    {
                        FormsAuthentication.SetAuthCookie(model.Name, true);
                        return(RedirectToAction("MyPublications", "Manage"));
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Пользователь с таким логином уже существует");
            }
            return(View(model));
        }
        public void RegistrationTest()
        {
            var userData = new Mock <IUserRepositoryManager>();
            var user     = new UserBusinessManagerService(userData.Object);

            ////Object of RegistrationModel
            var registrationModelData = new RegistrationModel()
            {
                UserName  = "******",
                FirstName = "FirstName",
                LastName  = "LastName",
                EmailId   = "EmailId",
                Password  = "******",
                Image     = "Image"
            };

            ////Act
            var data = user.Registration(registrationModelData);

            ////Asert
            Assert.NotNull(data);
        }
Example #26
0
        public DatabaseCode Register(RegistrationModel registerModel)
        {
            registerModel.User.ID = Guid.NewGuid();
            (int CompanyID, DatabaseCode CompanyStatus)companyInserted = companyService.Insert(registerModel.Company);
            if (companyInserted.CompanyStatus == DatabaseCode.Error)
            {
                return(companyInserted.CompanyStatus);
            }
            registerModel.User.CompanyID = companyInserted.CompanyID;
            DatabaseCode userInserted = userRepository.Insert(userMapper.ToEntity(registerModel.User));

            if (userInserted == DatabaseCode.Inserted)
            {
                registerModel.Contact.UserID    = registerModel.User.ID;
                registerModel.Contact.CompanyID = companyInserted.CompanyID;
                contactService.CreateContact(registerModel.Contact);
                registerModel.MainAddress.UserID    = registerModel.User.ID;
                registerModel.MainAddress.CompanyID = companyInserted.CompanyID;
                return(addressService.CreateAddress(registerModel.MainAddress).dbCode);
            }
            return(userInserted);
        }
Example #27
0
 public IActionResult AddUser([FromForm]  RegistrationModel registrationModel)
 {
     try
     {
         var result = _regisService.AddUser(registrationModel);
         if (result == null)
         {
             return(NotFound(new ServiceResponse <RegistrationModel> {
                 StatusCode = (int)HttpStatusCode.NotFound, Message = "Internal server error", Data = null
             }));
         }
         return(Ok(new ServiceResponse <RegistrationModel> {
             StatusCode = (int)HttpStatusCode.OK, Message = "Added Successful", Data = result
         }));
     }
     catch (Exception)
     {
         return(BadRequest(new ServiceResponse <RegistrationModel> {
             StatusCode = (int)HttpStatusCode.BadRequest, Message = "Page not found ", Data = null
         }));
     }
 }
Example #28
0
 public IActionResult LoginUser([FromForm] RegistrationModel registrationModel)
 {
     try
     {
         var result = _regisService.checkLoginUser(registrationModel);
         if (result == null)
         {
             return(NotFound(new ServiceResponse <RegistrationModel> {
                 StatusCode = (int)HttpStatusCode.NotFound, Message = "user is not identified", Data = null
             }));
         }
         return(Ok(new ServiceResponse <string> {
             StatusCode = (int)HttpStatusCode.OK, Message = "login successfully", Data = result
         }));
     }
     catch (Exception)
     {
         return(BadRequest(new ServiceResponse <RegistrationModel> {
             StatusCode = (int)HttpStatusCode.BadRequest, Message = "Page not found ", Data = null
         }));
     }
 }
Example #29
0
 public ActionResult Settings(AccountSettingsViewModel model)
 {
     if (ModelState.IsValid)
     {
         var account = new RegistrationModel
         {
             Email    = model.Email,
             Password = model.FirstPassword,
             UserName = model.UserName
         };
         var result = userService.ChangeAccountSettings(User.Identity.GetUserId <int>(), model.OldPassword, account);
         if (!result.Succedeed)
         {
             ModelState.AddModelError(string.Empty, result.Message);
         }
         else
         {
             ViewBag.Message = result.Message;
         }
     }
     return(View(new AccountSettingsViewModel()));
 }
Example #30
0
        public async Task Registratation([FromBody] RegistrationModel registrationModel)
        {
            await _userService.Registration(registrationModel);

            UserModel userModel = await _userService.GetUserModelByEmaiil(registrationModel.Email);



            string confirmToken = await _userService.GetEmailConfirmationToken(userModel);

            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append($"{Request.Scheme}://{Request.Host}/api/account/confirmation/");
            stringBuilder.Append($"?email={HttpUtility.UrlEncode(registrationModel.Email)}");
            stringBuilder.Append($"&confirmToken={HttpUtility.UrlEncode(confirmToken)}");


            string callbackUrl = stringBuilder.ToString();

            await _mailService.SendEmailAsync(registrationModel.Email, "Confirmation",
                                              $"Подтвердите регистрацию, перейдя по ссылке: <a href='{callbackUrl}'>link</a>");
        }
        public async Task <IActionResult> Registration(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Pass1 != model.Pass2)
                {
                    ModelState.AddModelError("", "Введенные вами пароли не совпадают");
                    return(View(model));
                }

                User user = new User {
                    Name     = model.Name,
                    UserName = model.UserName,
                    Email    = model.Email,
                    Joined   = DateTime.Now
                };

                IdentityResult result = await _userManager.CreateAsync(user, model.Pass1);

                if (result.Succeeded)
                {
                    TempData["Message"] = "Регистрация завершена успешно";
                    string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    string mailMessage = $"Регистрация завершена. Для подтверждения регистрации перейдите по ссылке -> {Url.Action("ConfirmEmail", "Account", new {userId = user.Id, token = token}, protocol:HttpContext.Request.Scheme)}";
                    await MyExtensions.SendEmailAsync(user.Email, "Подтверждение регистрации", mailMessage);

                    return(RedirectToAction("index", "home"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View(model));
        }
        public string Registration(RegistrationModel model)
        {
            SetSessionVariable("UserId", "");
            SetSessionVariable("CoreId", "");

            if (model != null)
            {
                if (ModelState.IsValid)
                {
                    if (!RemoteProcedureCallClass
                        .GetUserChannel()
                        .IsRegisteredUser(model.Nickname, model.PasswordHash))
                    {
                        if (RemoteProcedureCallClass
                            .GetUserChannel()
                            .RegisterUserToTable(model.FirstName,
                                                 model.SecondName, model.PasswordHash,
                                                 model.Nickname, model.Email))
                        {
                            FormsAuthentication.SetAuthCookie(model.Nickname, true);
                            return(model.ToJson());
                        }
                        return("");
                    }
                    else
                    {
                        return("");
                    }
                }
                else
                {
                    return("");
                }
            }
            else
            {
                return("");
            }
        }
Example #33
0
        public async Task RegisterAsync_ReturnsFailed_WhenOfficeNotExists()
        {
            // Arrange
            _mockOfficeRepo.Setup(s => s.ReadAsync(It.IsAny <int>())).ReturnsAsync((OfficeLocation)null).Verifiable();
            var model = new RegistrationModel
            {
                Username         = "******",
                Email            = "TestEmail",
                Password         = "******",
                FirstName        = "Test",
                LastName         = "Test",
                OfficeLocationId = 1,
                PhoneNumber      = "18001111111",
                Title            = "Test"
            };

            // Act
            var result = await _accountService.RegisterAsync(model);

            // Assert
            Assert.That(result.Succeeded, Is.False);
        }
Example #34
0
        public async Task RegisterAsync_ReturnsFailed_WhenUserManagerFails()
        {
            // Arrange
            _mockUserManager.Setup(_ => _.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed(new IdentityError())).Verifiable();
            var model = new RegistrationModel
            {
                Username         = "******",
                Email            = "TestEmail",
                Password         = "******",
                FirstName        = "Test",
                LastName         = "Test",
                OfficeLocationId = 1,
                PhoneNumber      = "18001111111",
                Title            = "Test"
            };

            // Act
            var result = await _accountService.RegisterAsync(model);

            // Assert
            Assert.That(result.Succeeded, Is.False);
        }
Example #35
0
        public ActionResult Register(RegistrationModel model)
        {
            try
            {
                var password     = EncryptPassword(model.Password);
                var passwordHash = MD5Hasher.GetMd5Hash(model.Email);

                var role = _roleService.Get(1);

                var user = new User
                {
                    ContactNumber = model.ContactNumber,
                    Email         = model.Email,
                    Name          = model.FirstName,
                    Surname       = model.LastName,
                    CreatedAt     = DateTime.Now,
                    ModifiedAt    = DateTime.Now,
                    Password      = password,
                    PasswordHash  = passwordHash
                };
                role.CreatedAt  = DateTime.Now;
                role.ModifiedAt = DateTime.Now;

                user.AddRole(role);
                var id = _userService.Save(user);

                if (id > 0)
                {
                    return(RedirectToAction("Login", "User"));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(View());
        }
Example #36
0
        public ServiceResponse <UserModel> Register(RegistrationModel model)
        {
            var response = new ServiceResponse <UserModel>();
            var users    = _userRepository.Select();
            var user     = users.FirstOrDefault(x => x.Username.ToUpper() == model.Username.ToUpper());

            if (user != null)
            {
                return(response.AddError("Логин уже занят"));
            }

            user = new AppUser
            {
                Username = model.Username,
                Password = Crypto.HashPassword(model.Password),
                Role     = UserRole.Player
            };

            _userRepository.InsertOrUpdate(user);
            response.Object = Mapper.Map <UserModel>(user);
            return(response);
        }
        public ActionResult ResetPassword(RegistrationModel resetModel)
        {
            UserProcess userProcessor = new UserProcess();

            int result = userProcessor.ResetPassword(resetModel.EmployeeID);

            if (result == FASTConstant.RETURN_VAL_SUCCESS)
            {
                TempData[FASTConstant.TMPDATA_RESULT]       = FASTConstant.SUCCESSFUL;
                TempData[FASTConstant.TMPDATA_EXTRAMESSAGE] = "An email confirmation will be sent to you. This will contain a random generated initial password. You can change the password inside the user area";
            }
            else
            {
                TempData[FASTConstant.TMPDATA_RESULT]       = FASTConstant.FAILURE;
                TempData[FASTConstant.TMPDATA_EXTRAMESSAGE] = "Reset password failed. Please try again or contact the AppAdmin";
            }
            TempData[FASTConstant.TMPDATA_SOURCE]     = "Reset Password";
            TempData[FASTConstant.TMPDATA_CONTROLLER] = "Home";
            TempData[FASTConstant.TMPDATA_ACTION]     = "Index";

            return(View("~/Views/Shared/Result.cshtml"));
        }
Example #38
0
        public async Task <ActionResult> RegisterUser(RegistrationModel registrationModel)
        {
            var user = await userManager.FindByNameAsync(registrationModel.UserName);

            if (user != null)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new Response {
                    Status = "Error", Message = "Such username already exists"
                }));
            }

            if (!await roleManager.RoleExistsAsync(registrationModel.Role))
            {
                return(StatusCode(StatusCodes.Status400BadRequest, new Response {
                    Status = "Error", Message = "No such role"
                }));
            }

            ApplicationUser applicationUser = new ApplicationUser()
            {
                UserName = registrationModel.UserName,
                Email    = registrationModel.Email
            };

            var result = await userManager.CreateAsync(applicationUser, registrationModel.Password);

            if (!result.Succeeded)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, new Response {
                    Status = "Error", Message = "User creation failed! Please check user details and try again."
                }));
            }

            await AddToRoleAsync(applicationUser, registrationModel.Role);

            return(Ok(new Response {
                Status = "Success", Message = "User created"
            }));
        }
        public IActionResult Registration(RegistrationModel client)
        {
            if (ModelState.IsValid)
            {
                var existClient = _client.Read(new ClientBindingModel
                {
                    Login = client.Login
                }).FirstOrDefault();

                if (existClient != null)
                {
                    ModelState.AddModelError("", "Данный логин уже занят");
                    return(View(client));
                }

                existClient = _client.Read(new ClientBindingModel
                {
                    Email = client.Email
                }).FirstOrDefault();

                if (existClient != null)
                {
                    ModelState.AddModelError("", "Данный E-Mail уже занят");
                    return(View(client));
                }

                _client.CreateOrUpdate(new ClientBindingModel
                {
                    Login    = client.Login,
                    Password = client.Password,
                    Email    = client.Email,
                    Phone    = client.Phone
                });

                return(RedirectToAction("Login"));
            }

            return(View(client));
        }
Example #40
0
        public async Task<ActionResult> Register(RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                var task = checkLastNameAsync(model.LastName, model.GroupId);
                var student = task != null ? await task : null;
                if (student == null || student.HasUserAccount)
                {
                    ModelState.AddModelError("LastName", Resource.NoLastNameFound);
                    return View(model);
                }
                if (!await CheckCaptcha())
                {
                    ModelState.AddModelError("", Resource.ConfirmNoRobot);
                    return View(model);
                }
                var emailUser = await Manager.FindByEmailAsync(model.Email);
                User user = null;
                IdentityResult result;
                if(!student.AccountId.IsEmpty())
                    user = await Manager.FindByIdAsync(student.AccountId);

                if (emailUser != null && (user == null || user.Id != emailUser.Id))
                {
                    ModelState.AddModelError("Email", Resource.EmailIsUsed);
                    return View(model);
                }

                if (user != null)
                {
                    user.GroupId = model.GroupId;
                    user.Email = TransformEmail(model.Email);
                    user.StudentId = student.Id;
                    var hashedNewPassword = Manager.PasswordHasher.HashPassword(model.Password);
                    user.PasswordHash = hashedNewPassword;
                    result = await Manager.UpdateAsync(user);
                    /*var store = new UserStore<User>();
                    await store.SetPasswordHashAsync(user, hashedNewPassword);*/
                }
                else
                {
                    model.Email = TransformEmail(model.Email);
                    user = Map<RegistrationModel, User>(model);
                    user.LoginKey = Guid.NewGuid().ToString("N").Substring(0, 8);
                    user.StudentId = student.Id;
                    result = await Manager.CreateAsync(user, model.Password);
                }
                
                if (result.Succeeded)
                {
                    student.HasUserAccount = true;
                    Site.StudentManager.Update(student);
                    Mailer.Send(ConirmRegistrationMail, model.Email, CreateConfirmTags(user.Id.Or(model.Id)));
                    return View("_Success");
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return View(model);
        }
    public ActionResult Information(DeviceRegistration registration)
    {
      if (ModelState.IsValid)
      {
        using (AzureManagerContext context = new AzureManagerContext())
        {
          DeviceRegistration deviceRegistration = context.DeviceRegistrations.Find(registration.Id);

          if (HttpContext.Request.Files.Count > 0)
          {
            using (BinaryReader r = new BinaryReader(HttpContext.Request.Files[0].InputStream))
            {
              byte[] buffer = new byte[HttpContext.Request.ContentLength];
              r.Read(buffer, 0, HttpContext.Request.ContentLength);
              deviceRegistration.Certificate = buffer;
            }
          }

          deviceRegistration.SubscriptionId = registration.SubscriptionId;
          context.SaveChanges();

          RegistrationModel model = new RegistrationModel();
          String response = model.NotifyDeviceOfInformation(deviceRegistration);

          ViewBag.Response = response;
        }

        return RedirectToAction("InformationSent");
      }

      return View(registration);
    }
 public RegistrationViewModel()
 {
     _registrationModel = new RegistrationModel();
 }