Example #1
0
        public async Task <string> SignUp(string email, string username, string password)
        {
            SignUpUser SUU = new SignUpUser();

            SUU.Email    = email.ToLower();
            SUU.UserName = username;
            SUU.Password = password;

            var signUpResponse = await DS.PostAsync(SUU, "user/SignUp");

            if (signUpResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseJSON = await signUpResponse.Content.ReadAsStringAsync();

                UserReturnToken URT = Newtonsoft.Json.JsonConvert.DeserializeObject <UserReturnToken>(responseJSON);
                if (string.IsNullOrEmpty(URT.Message))
                {
                    myAuthService.SaveUserSessionData(URT);
                    return("");
                }

                else
                {
                    return(URT.Message);
                }
            }

            return(signUpResponse.Content.ToString());
        }
Example #2
0
        public async Task Add_ReturnsUserAdded()
        {
            // Arrange
            _usersContext = _db.SeedUsersContext();
            int          currentUsersCount = _db.Users.Count;
            List <Users> currentUsers      = _db.Users;
            SignUpUser   expected          = new SignUpUser
            {
                UserName     = "******",
                UserEmail    = "*****@*****.**",
                FirstName    = "Carl",
                LastName     = "Johnson",
                UserPassword = "******",
                UserRole     = "user"
            };

            // Act
            Users actual = await _usersContext.Add(expected);

            int updatedUsersCount = _db.Users.Count;

            _db.Users = new List <Users>(currentUsers);

            // Assert
            Assert.Equal(expected.UserName, actual.UserName);
            Assert.Equal(currentUsersCount + 1, updatedUsersCount);
        }
        public async Task <User> Put(SignUpUser userModel)
        {
            var userEntity = Mapper.Map <User>(userModel);

            userEntity.SaltAndHash = _encryptionService.CreatePasswordSaltHash(userModel.Password);
            return(await Put(userEntity));
        }
Example #4
0
        public static void SignUp(SignUpUser user)
        {
            SignUpPageObjects signUpPageObjects = new SignUpPageObjects();

            signUpPageObjects.User.SendKeys(user.Username);
            signUpPageObjects.Password.SendKeys(user.Password);
            signUpPageObjects.ConfirmPassword.SendKeys(user.ConfirmPassword);
            signUpPageObjects.Email.SendKeys(user.Email);
            signUpPageObjects.CreateUserButton.Click();
        }
Example #5
0
        public async Task <IdentityResult> CreateUser(SignUpUser usermodel)
        {
            var user = new IdentityUser()
            {
                Email = usermodel.Email, UserName = usermodel.Email
            };

            var result = await _userManager.CreateAsync(user, usermodel.Password);

            return(result);
        }
Example #6
0
 public bool Post(SignUpUser command)
 {
     try
     {
         IUserCommandsService userCommandsService = servicesFactory.CreateUserCommandsService();
         userCommandsService.SignUpNewUser(command);
         return(true);
     }
     catch (UserAlreadyInUseException)
     {
         return(false);
     }
 }
Example #7
0
        public ActionResult SignUp(SignUp su)
        {
            SignUpUser spu = new SignUpUser();

            if (spu.SignUpBO(su))
            {
                pladbEntities    pladb = new pladbEntities();
                lawyer           lwr   = pladb.lawyers.Where(lr => lr.EMAIL == su.Email).FirstOrDefault();
                LawyerController lrc   = new LawyerController();
                lrc.SendMail(lwr);
                pladb.Dispose();
                return(RedirectToAction("ConfirmationMessage", "lawyer"));
            }

            return(View(su));
        }
Example #8
0
        public async Task <JwtToken> SignUpUserAsync(SignUpUser signUpUser)
        {
            var user = _mapper.Map <IdentityUser>(signUpUser);

            if (await _userManager.FindByNameAsync(user.UserName) != null)
            {
                throw new Exception("Such a user already exist");
            }
            if ((await _userManager.CreateAsync(user, signUpUser.Password)).Succeeded)
            {
                await _signInManager.SignInAsync(user, false);

                return(await GetTokenForSignedInUser(user));
            }
            throw new Exception("Can't create user, username, email or password are invalid");
        }
Example #9
0
        public async Task <IActionResult> Signup(SignUpUser usermodel)
        {
            if (ModelState.IsValid)
            {
                var result = await _usermanager.CreateUser(usermodel);

                if (!result.Succeeded)
                {
                    foreach (var errorMessage in result.Errors)
                    {
                        ModelState.AddModelError(" ", errorMessage.Description);
                    }
                }
                ModelState.Clear();
            }
            return(View());
        }
        public async Task <IActionResult> SignUp(SignUpUser user)
        {
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(user.ID) && !string.IsNullOrEmpty(user.Name) && !string.IsNullOrEmpty(user.Password) && !string.IsNullOrEmpty(user.CheckPassword))
                {
                    if (user.Password != user.CheckPassword)
                    {
                        ViewBag.ErrorInfo = "Created and confirmed passwords are not the same";
                        return(View(user));
                    }
                    else if (!await _signUpService.CheckId(user.ID))
                    {
                        if (await _signUpService.SignUpAsync(user))
                        {
                            await HttpContext.SignOutAsync();

                            var claimIdentity = new ClaimsIdentity("Cookie");
                            claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.ID));
                            claimIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
                            claimIdentity.AddClaim(new Claim("Avatar", "Default.png"));
                            claimIdentity.AddClaim(new Claim(ClaimTypes.Role, "Commom"));

                            var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
                            await HttpContext.SignInAsync(claimsPrincipal);

                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ViewBag.ErrorInfo = "注册过程存在异常,请进行调试";
                        }
                    }
                    else
                    {
                        ViewBag.ErrorInfo = "UserId is exist";
                    }
                }
                else
                {
                    ViewBag.ErrorInfo = "Information is incomplete";
                }
            }
            return(View(user));
        }
Example #11
0
        public async Task <IActionResult> SignUp([FromBody] SignUpUser user)
        {
            try
            {
                var u = new YouQuizUser()
                {
                    Email     = user.Email,
                    UserType  = Enum.GetName(typeof(UserType), user.UserType),//Enum.Parse<UserType>(user.UserType.ToString()).ToString(),
                    Gender    = user.Gender,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    UserName  = $"{user.FirstName.ToLower()[0]}{user.LastName}"
                };
                var dbUser = await _userManager.CreateAsync(u);

                if (dbUser.Succeeded)
                {
                    var r = await _userManager.AddPasswordAsync(u, user.Password);

                    if (r.Succeeded)
                    {
                        return(Ok(new { status = true, message = "User creation succeeded!" }));
                    }
                    else
                    {
                        var userToDelete = new YouQuizUser()
                        {
                            Email = u.Email
                        };
                        await _userManager.DeleteAsync(userToDelete);

                        throw new Exception("User password hashing failed!");
                    }
                }
                else
                {
                    throw new Exception("User creation failed! " + dbUser.Errors.FirstOrDefault().Description);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString() ?? e.Message);
                return(BadRequest(new { status = false, message = e.Message ?? e.ToString() }));
            }
        }
Example #12
0
        public void TestUserStory1()
        {
            try
            {
                const String INPUT_FILE = "SignUpTest.xml";
                SignUpUser   user       = XML.DeserializeObject <SignUpUser>(FileUtils.CreateInputPath(INPUT_FILE));

                PropertiesCollection.OpenURL(Constants.START_URL);
                Panel.Log_Click();
                SeleniumGetMethods.GetWebElementInnerHTML("Inregistrati-va").Click();
                Authentication.SignUp(user);
            }
            catch (Exception ex)
            {
                Logger.LogException("", ex);
                Assert.Fail(ex.Message);
            }
        }
Example #13
0
        public async Task <IdentityResult> CreateUser(SignUpUser userModel)
        {
            var user = new ApplicationUser()
            {
                Name     = userModel.Name,
                Email    = userModel.Email,
                UserName = userModel.Email
            };

            var result = await _userManager.CreateAsync(user, userModel.Password);

            if (result.Succeeded)
            {
                await GenerateEmailConfirmationTokenAsync(user);
            }

            return(result);
        }
Example #14
0
        public void Handle_SignUpUser_Test()
        {
            #region === ARRANGE ===

            string expectedNewUserName = "******";

            int businessChancesNumber = 0;
            int businessConsultNumber = 0;

            Mock <IMediatorsFactory> mockedBusinessEventsFactory = new Mock <IMediatorsFactory>();
            Mock <IInfrastructureOperationsFactory> mockedInfrastructureOperationsFactory = new Mock <IInfrastructureOperationsFactory>();
            BusinessDataMediator businessDataMediator = new BusinessDataMediator();

            businessDataMediator.AppendBusinessChangeNeedHandler((sender, args) => {
                businessChancesNumber++;
            });

            businessDataMediator.AppendBusinessConsultNeedHandler((sender, args) => {
                args.result = new List <User>();
                businessConsultNumber++;
            });

            mockedBusinessEventsFactory.Setup(x => x.CreateBusinessDataMediator(It.IsAny <EventHandler <BusinessConsultEventArgs> >(), It.IsAny <EventHandler <BusinessChangeEventArgs> >())).Returns(businessDataMediator);

            SignUpUser comand = new SignUpUser {
                Id = new Guid(), UserName = expectedNewUserName, Password = "******"
            };
            UsersComandHandler comandHandler = new UsersComandHandler(mockedBusinessEventsFactory.Object, mockedInfrastructureOperationsFactory.Object);

            #endregion

            #region === ACT ===

            comandHandler.Handle(comand);

            #endregion

            #region === ASSERT ===

            Assert.AreEqual <int>(1, businessConsultNumber);
            Assert.AreEqual <int>(2, businessChancesNumber);

            #endregion
        }
Example #15
0
        public async Task <IActionResult> Signup(SignUpUser userModel)
        {
            if (ModelState.IsValid)
            {
                var result = await _accountRepository.CreateUser(userModel);

                if (!result.Succeeded)
                {
                    foreach (var errorMessage in result.Errors)
                    {
                        ModelState.AddModelError("", errorMessage.Description);
                    }

                    return(View(userModel));
                }

                ModelState.Clear();
                return(RedirectToAction("ConfirmEmail", new { email = userModel.Email }));
            }
            return(View(userModel));
        }
        public HttpResponseMessage SignUp(dynamic user)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            SignUpUser signUpUser = new SignUpUser();

            try
            {
                signUpUser = JsonConvert.DeserializeAnonymousType(JsonObjectConverter.ObjectToJson(user), signUpUser);
            }
            catch (Exception e)
            {
                response.Content = new StringContent("post数据格式错误\nReceives:\n" + JsonObjectConverter.ObjectToJson(user));
                return(response);
            }
            // 判断用户的id是否存在
            // 数据库中插入用户信息
            string result = UserHelper.SignUp(signUpUser);

            if (result.StartsWith("Already"))
            {
                response.Content    = new StringContent(result);
                response.StatusCode = HttpStatusCode.BadRequest;
                return(response);
            }
            else if (result.StartsWith("Insert"))
            {
                response.Content    = new StringContent("数据错误:" + result);
                response.StatusCode = HttpStatusCode.BadRequest;
                return(response);
            }
            // 注册成功 分发cookie
            SignIn(user);

            PatientInfo info = UserHelper.GetPatientInfoByCredNum(signUpUser.credit_num);

            response.Content    = new StringContent(info.patient_id);
            response.StatusCode = HttpStatusCode.OK;
            return(response);
        }
Example #17
0
        public async Task <bool> SignUpAsync(SignUpUser signUpUser)
        {
            bool success = false;

            using (OracleConnection con = new OracleConnection(ConString.conString))
            {
                using (OracleCommand cmd = con.CreateCommand())
                {
                    try
                    {
                        con.Open();
                        cmd.BindByName  = true;
                        cmd.CommandText = "insert into users values(" +
                                          "'" + signUpUser.ID + "'" + "," +
                                          "'" + signUpUser.Name + "'" + "," +
                                          "'" + signUpUser.Password + "'" + "," +
                                          "'Commom'" + "," +
                                          "'Default.png'" + ")";


                        await cmd.ExecuteNonQueryAsync();

                        cmd.CommandText = "insert into common_user values(" +
                                          "'" + signUpUser.ID + "'" + "," +
                                          "'" + "No Introduction" + "'" + "," +
                                          +0 + "," +
                                          +2000 + ")";

                        await cmd.ExecuteNonQueryAsync();

                        success = true;
                    }
                    catch (Exception ex)
                    {
                        string e = ex.Message;
                    }
                }
            }
            return(success);
        }
Example #18
0
        public async Task <ActionResult <Users> > PostUsers([FromBody] SignUpUser user)
        {
            if (!_authorizationService.ValidateJWTToken(Request))
            {
                return(Unauthorized(new { errors = new { Token = new string[] { "Invalid token" } }, status = 401 }));
            }

            var existingUser = await _context.Users.AnyAsync(u => u.UserName == user.UserName || u.UserEmail == user.UserEmail);

            if (!existingUser)
            {
                string salt = _authenticationService.GenerateSalt();
                string hash = _authenticationService.HashPassword(user.UserPassword, salt);

                Users userToBeAdded = new Users
                {
                    UserName         = user.UserName,
                    UserEmail        = user.UserEmail,
                    FirstName        = user.FirstName,
                    LastName         = user.LastName ?? "",
                    UserRole         = user.UserRole,
                    UserPasswordHash = hash,
                    UserPasswordSalt = salt
                };

                _context.Users.Add(userToBeAdded);

                await _context.SaveChangesAsync();

                var addedUser = await _context.Users.FirstOrDefaultAsync(u => u.UserName == userToBeAdded.UserName || u.UserEmail == userToBeAdded.UserEmail);

                return(CreatedAtAction("GetUsers", new { id = addedUser.Id }, userToBeAdded.WithoutPassword()));
            }

            // return Conflict(new { errors =  "User already exists" });
            return(Conflict(new { errors = new { Users = new string[] { "User already exists" } }, status = 409 }));
        }
Example #19
0
        public async Task <IActionResult> OnPostSignUpAsync()
        {
            LoginUser.UserName = Request.Form["registerUsername"];
            LoginUser.Email    = Request.Form["registerEmail"];
            LoginUser.Password = Request.Form["registerPassword1"];
            SignUpUser SUU = new SignUpUser();

            SUU.Email    = LoginUser.Email;
            SUU.UserName = LoginUser.UserName;
            SUU.Password = LoginUser.Password;
            UserReturnToken URT            = new UserReturnToken();
            var             signUpResponse = await DS.PostAsync(SUU, "user/SignUp");

            if (signUpResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseJSON = await signUpResponse.Content.ReadAsStringAsync();

                URT = Newtonsoft.Json.JsonConvert.DeserializeObject <UserReturnToken>(responseJSON);
                if (string.IsNullOrEmpty(URT.Message))
                {
                    myAuthService.SaveUserSessionData(URT);
                }
            }

            if (string.IsNullOrEmpty(URT.Message))
            {
                //user is registerd and signed in, all is good.
                LogInSuccessful = true;
            }
            else
            {
                RegisterMessage = URT.Message;
            }

            return(Page());
        }
        public async Task <IActionResult> Create([FromBody] SignUpUser userModel)
        {
            var addedUser = await _userRepository.Put(userModel);

            return(Json(Mapper.Map <ViewUser>(addedUser)));
        }
Example #21
0
        //Handle Button Click
        private async Task Submit_ClickedAsync(object sender, EventArgs e)
        {
            //Check for Null Values
            if (FirstNameEntry.Text == null || SurnameEntry.Text == null || EmailEntry.Text == null || PasswordEntry.Text == null || ConfirmPasswordEntry.Text == null)
            {
                await DisplayAlert("Warning", "You must fill out all the details above", "Ok");
            }
            //Check for Special Characters
            else if (FIeldValidationCheck.HasSpecialChars(FirstNameEntry.Text).ToString() == "False" || FIeldValidationCheck.HasSpecialChars(SurnameEntry.Text).ToString() == "False" || FIeldValidationCheck.HasSpecialChars(PasswordEntry.Text).ToString() == "False" || FIeldValidationCheck.HasSpecialChars(ConfirmPasswordEntry.Text).ToString() == "False")
            {
                await DisplayAlert("Warning", "Sign up details must not include special characters, please fill out the details entered again without special characters", "Ok");
            }
            else
            {
                try
                {
                    //Set loading symbol
                    LoadingLayout.IsVisible = true;
                    LoadingSymbol.IsRunning = true;

                    //Test Passwords to see if they are similar
                    if (ConfirmPasswordEntry.Text == PasswordEntry.Text)
                    {
                        //Set newUser Object
                        SignUpUser newUser = new SignUpUser();
                        newUser.strFirstName = FirstNameEntry.Text;
                        newUser.strSurname   = SurnameEntry.Text;
                        newUser.strEmail     = EmailEntry.Text;
                        newUser.dtDOB        = DateOfBirthEntry.Date;
                        newUser.strPassword  = PasswordEntry.Text;

                        try
                        {
                            //Declare Connection Strings
                            HttpClient client = new HttpClient();
                            string     url    = "https://melbourneicewebapi.azurewebsites.net/api/UserRequests/Add_User";
                            var        uri    = new Uri(url);
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                            var json     = JsonConvert.SerializeObject(newUser);
                            var content  = new StringContent(json, Encoding.UTF8, "application/json");
                            var response = await client.PostAsync(uri, content);

                            //POST newUser and test if it works, if it does, set appropriate variables and push user to news page.
                            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
                            {
                                LoadingSymbol.IsRunning = false;
                                LoadingLayout.IsVisible = false;
                                string alert = "Welcome " + newUser.strFirstName;
                                await DisplayAlert(alert, "You details have been registered and you are now logged in", "Continue");

                                Application.Current.Properties["User"] = "******";
                                await Application.Current.SavePropertiesAsync();

                                await Navigation.PushModalAsync(new NavigationPage(new HomePage()));
                            }
                            //If Response has no content, Email has already been entered
                            else if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
                            {
                                //Set Alert
                                LoadingSymbol.IsRunning = false;
                                LoadingLayout.IsVisible = false;
                                await DisplayAlert("Warning", "The Email entered is already associated with an account, if you cannot remember your password for this email, try accessing the 'Forgotten your password' button on the login screen to recover your account", "Ok");
                            }
                            else
                            {
                                //Display Connection Error
                                LoadingSymbol.IsRunning = false;
                                LoadingLayout.IsVisible = false;
                                await DisplayAlert("Warning", "There was an error establishing a connection with the server, please try again later", "Ok");
                            }
                        }
                        //Handle Exception
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            await DisplayAlert("Warning", "Please connect to the internet and try again", "ok");
                        }
                    }
                    //Display Passwords don't match
                    else
                    {
                        await DisplayAlert("Warning", "Your passwords do not match", "Ok");
                    }
                }
                //Handle no connection error
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    await DisplayAlert("Warning", "Please connect to the internet and try again", "Ok");
                }
            }
        }
Example #22
0
        /// <summary>
        /// Ctor.
        /// </summary>
        public SignUpViewModel(ISignUp signUp, IContainer container) : base(container)
        {
            this.signUp = signUp;

            User = new SignUpUser();
        }
Example #23
0
        public async Task <IActionResult> Post([FromBody] SignUpUser command)
        {
            await _commandDispatcher.DispatchAsync(command);

            return(Ok(command.Token));
        }
        public void SignUpNewUser(SignUpUser command)
        {
            ICommandHandler <SignUpUser> commandHandler = commandHandlerFactory.CreateCommandHandler <SignUpUser>();

            commandHandler.Handle(command);
        }
Example #25
0
 public async Task <IActionResult> Register(SignUpUser signUpUser) => Ok(await _authService.SignUpUserAsync(signUpUser));
Example #26
0
        public async Task <IActionResult> SignUp([FromBody] SignUpUser newUser)
        {
            if (string.IsNullOrWhiteSpace(Request.Headers["Origin"]))
            {
                return(Unauthorized(new { errors = new { Origin = new string[] { "Invalid request origin" } }, status = 401 }));
            }

            var user = await _context.Users.FirstOrDefaultAsync(u => u.UserName.Trim().ToLower() == newUser.UserName.Trim().ToLower() || u.UserEmail.Trim().ToLower() == newUser.UserEmail.Trim().ToLower());

            if (user == null)
            {
                // New user, add to DB and authenticate
                // Also, validate/sanitise properties here

                string salt = _authenticationService.GenerateSalt();
                string hash = _authenticationService.HashPassword(newUser.UserPassword, salt);

                // By default, every new user will be registered as "user" in their user role
                // Their status should only be changed by admins
                Users userToBeAdded = new Users
                {
                    UserName         = newUser.UserName,
                    UserEmail        = newUser.UserEmail,
                    FirstName        = newUser.FirstName,
                    LastName         = newUser.LastName ?? "",
                    UserPasswordHash = hash,
                    UserPasswordSalt = salt
                };

                _context.Users.Add(userToBeAdded);

                await _context.SaveChangesAsync();

                // Get newly created user from database to create a new account record
                // Stored procedures would be preferred in this case in order to avoid making so many calls to the database
                var savedUser = await _context.Users.FirstOrDefaultAsync(u => u.UserName == newUser.UserName);

                // TODO: Handle the opposite case
                if (savedUser != null)
                {
                    _context.Accounts.Add(new Accounts {
                        UserId = savedUser.Id
                    });
                    await _context.SaveChangesAsync();
                }

                var authenticatedUser = await _authenticationService.Authenticate(newUser.UserName, newUser.UserPassword);

                // var baseUser = await _context.Users.FirstOrDefaultAsync(u => u.Id == authenticatedUser.Id);

                authenticatedUser.BaseUser = savedUser.WithoutPassword();

                // Send cookie with fresh token
                Response.Headers.Append("X-Authorization-Token", authenticatedUser.Token);
                _authorizationService.SetAuthCookie(Request, Response, authenticatedUser.Token);

                authenticatedUser.Token = null;

                // Send back newly created user without token
                return(CreatedAtAction(nameof(GetUser), new { authenticatedUser.Id }, authenticatedUser));
            }

            // Existing user, return 409 (Conflict)
            // Alternatively, refresh this user's token
            return(Conflict(new { errors = new { Users = new string[] { "User already registered" } }, status = 409 }));
        }
        public IActionResult SignUp()
        {
            SignUpUser user = new SignUpUser();

            return(View(user));
        }
        public ActionResult SignUp(SignUpUser su, HttpPostedFileBase Image)
        {
            bool isValidEmail = repoLogin.GetAll().Any(m => m.Email == su.Email);

            if (isValidEmail)
            {
                ModelState.AddModelError("", "Email account already exists");
                return(View(su));
            }

            if (ModelState.IsValid)
            {
                string filenameUser;

                if (Image != null)
                {
                    string filename = Path.GetFileNameWithoutExtension(Image.FileName);
                    string extnss   = Path.GetExtension(Image.FileName);
                    filename     = filename + DateTime.Now.ToString("yymmddfff") + extnss;
                    filenameUser = filename;
                    filename     = Path.Combine(Server.MapPath("~/Images/ProfilePicture/"), filename);
                    Image.SaveAs(filename);
                }
                else
                {
                    filenameUser = "******";
                }
                User u = new User();
                u.Name         = su.Name;
                u.Email        = su.Email;
                u.Address      = su.Address;
                u.DOB          = su.DOB.ToString();
                u.PhoneNumber  = su.PhoneNumber.ToString();
                u.Role_Id      = 1;
                u.Image        = filenameUser;
                u.AddedDate    = DateTime.Now;
                u.ModifiedDate = DateTime.Now;
                repoUser.Insert(u);
                repoUser.EContext.SaveChanges();

                Login l = new Login();
                l.Email   = su.Email;
                l.Pass    = su.Password;
                l.Role_Id = 1;
                l.Status  = "APPROVED";
                u         = repoUser.GetByEmail(su.Email);
                if (u != null)
                {
                    l.User_Id = u.Id;
                }

                repoLogin.Insert(l);
                repoLogin.SaveChanges();

                //Add Customer
                Customer c = new Customer();
                c.User_Id = u.Id;
                c.Area    = su.Area;
                repoLogin.EContext.Customers.Add(c);
                repoLogin.SaveChanges();

                Session["UserEmail"] = su.Email;
                //return Content(su.Password);

                return(RedirectToAction("Index", "Home"));
            }
            ModelState.AddModelError("", "Something went wrong! Please try again");
            return(View(su));
        }
Example #29
0
 /// <summary>
 /// Ctor for design.
 /// </summary>
 public SignUpViewModel()
 {
     User = new SignUpUser();
 }
Example #30
0
        /// <summary>
        /// Adds a new user
        /// </summary>
        /// <param name="user">User to be added</param>
        /// <returns>User added</returns>
        public async Task <Users> Add(SignUpUser user)
        {
            Users userAdded = null;

            if (_context != null)
            {
                var existingUser = await _context
                                   .Users
                                   .AnyAsync(
                    u => u.UserName == user.UserName ||
                    u.UserEmail == user.UserEmail
                    );

                if (!existingUser)
                {
                    string salt = _authenticationService.GenerateSalt();
                    string hash = _authenticationService.HashPassword(user.UserPassword, salt);

                    userAdded = new Users
                    {
                        UserName         = user.UserName,
                        UserEmail        = user.UserEmail,
                        FirstName        = user.FirstName,
                        LastName         = user.LastName ?? "",
                        UserRole         = user.UserRole,
                        UserPasswordHash = hash,
                        UserPasswordSalt = salt
                    };

                    _context.Users.Add(userAdded);

                    await _context.SaveChangesAsync();

                    userAdded = await _context.Users.FirstOrDefaultAsync(
                        u => u.UserName == userAdded.UserName ||
                        u.UserEmail == userAdded.UserEmail
                        );
                }
            }
            else
            {
                var existingUser = Users.Any(
                    u => u.UserName == user.UserName ||
                    u.UserEmail == user.UserEmail
                    );

                if (!existingUser)
                {
                    var authenticationService = new AuthenticationService(
                        new AppSettings {
                        Pepper = "Pepper1", Secret = "Secret1"
                    },
                        this
                        );

                    string salt = authenticationService.GenerateSalt();
                    string hash = authenticationService.HashPassword(user.UserPassword, salt);

                    userAdded = new Users
                    {
                        UserName         = user.UserName,
                        UserEmail        = user.UserEmail,
                        FirstName        = user.FirstName,
                        LastName         = user.LastName ?? "",
                        UserRole         = user.UserRole,
                        UserPasswordHash = hash,
                        UserPasswordSalt = salt
                    };

                    Users.Add(userAdded);
                }
            }

            return(userAdded);
        }