Пример #1
0
        public async Task <IActionResult> Register(string user_name, string email, string first_name, string last_name, string password)
        {
            try
            {
                UserModel user = await UserMgr.FindByEmailAsync(email);

                if (user == null)
                {
                    user           = new UserModel();
                    user.UserName  = email;
                    user.Email     = email;
                    user.FirstName = first_name;
                    user.LastName  = last_name;
                    IdentityResult result = await UserMgr.CreateAsync(user, password);

                    Console.WriteLine(user.UserName + user.Email + user.FirstName + user.LastName);
                    Console.WriteLine(result);
                    return(Ok(result));
                }
                return(Ok("Account exists..."));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
Пример #2
0
        public async Task <IActionResult> UserRegistration(User user)
        {
            if (ModelState.IsValid)
            {
                var newUser = new User
                {
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    Email     = user.Email,
                    UserName  = user.UserName,
                    Password  = user.Password
                };
                var result = await UserMgr.CreateAsync(newUser, user.Password);

                if (result.Succeeded)
                {
                    await SignInMgr.SignInAsync(newUser, isPersistent : false);

                    return(RedirectToAction("Dashboard", "Application"));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(user));
        }
Пример #3
0
        public async Task <IActionResult> Register(MergeModel user)
        {
            try
            {
                ViewBag.Message = "User already registered.";
                AppUser appuser = await UserMgr.FindByNameAsync(user.AppUsers.UserName);

                if (appuser == null)
                {
                    appuser           = new AppUser();
                    appuser.UserName  = user.AppUserName;
                    appuser.Email     = user.AppUserEmail;
                    appuser.FirstName = user.AppUsers.FirstName;
                    appuser.LastName  = user.AppUsers.LastName;

                    IdentityResult result = await UserMgr.CreateAsync(appuser, user.AppUserPassword);

                    ViewBag.Message = "User was successfully created!";

                    return(RedirectToAction("Login"));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return(View());
        }
Пример #4
0
        public async Task <IActionResult> RegisterIntern(CreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    Name       = model.Name,
                    Surname    = model.Surname,
                    University = model.University,
                    Major      = model.Major,
                    Department = model.Department,
                    UserName   = model.Email,
                    Email      = model.Email
                };

                var result = await UserMgr.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    UserMgr.AddToRoleAsync(user, "Intern").Wait();
                    return(RedirectToAction("index", "Home"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return(View(model));
        }
Пример #5
0
        //public async Task<IActionResult> Register(string firstName, string lastName, string username, string password, string email)
        public async Task <IActionResult> Register(RegisterInfo registerInfo)
        {
            IdentityResult result;

            try
            {
                AppUser user = await UserMgr.FindByNameAsync(registerInfo.UserName);

                if (user == null)
                {
                    user = new AppUser
                    {
                        UserName  = registerInfo.UserName,
                        Email     = registerInfo.Email,
                        FirstName = registerInfo.FirstName,
                        LastName  = registerInfo.LastName
                    };

                    result = await UserMgr.CreateAsync(user, registerInfo.Password);
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return(RedirectToAction("Login", "Account"));
        }
Пример #6
0
        public async Task <IActionResult> AddUser(UserViewModel userModel)
        {
            var user = new User()
            {
                FirstName   = userModel.FirstName,
                LastName    = userModel.LastName,
                PhoneNumber = userModel.ContactNumber,
                UserName    = userModel.Email,
                Email       = userModel.Email,
                Department  = userModel.Department
            };
            var result = await UserMgr.CreateAsync(user, userModel.Password);

            if (result.Succeeded)
            {
                await SignInMgr.SignOutAsync();

                if ((await SignInMgr.PasswordSignInAsync(user.UserName, userModel.Password, false, false))
                    .Succeeded)
                {
                    return(Ok("Successfully Added"));
                }
            }

            return(BadRequest("Failed to Add User"));
        }
Пример #7
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            try
            {
                ViewBag.Message = "Toks vartotojo vardas jau registruotas";
                User usr = await UserMgr.FindByNameAsync(model.Email);

                if (usr == null)
                {
                    usr = new User
                    {
                        UserName = model.Email,
                        Email    = model.Email
                    };

                    IdentityResult result = await UserMgr.CreateAsync(usr, model.Password);

                    if (result.Succeeded)
                    {
                        ViewBag.Message = "Vartotojas sukurtas";
                    }
                    else
                    {
                        ViewBag.Message = result.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }
            return(View());
        }
Пример #8
0
        public async Task <IActionResult> Register(RegisterModel userModel)
        {
            if (ModelState.IsValid)
            {
                var user = new User()
                {
                    FirstName   = userModel.FirstName,
                    LastName    = userModel.LastName,
                    PhoneNumber = userModel.ContactNumber,
                    UserName    = userModel.Email,
                    Email       = userModel.Email,
                };
                var result = await UserMgr.CreateAsync(user, userModel.Password);

                if (result.Succeeded)
                {
                    await SignInMgr.SignOutAsync();

                    if ((await SignInMgr.PasswordSignInAsync(user.UserName, userModel.Password, false, false))
                        .Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    return(View());
                }
            }

            return(View());
        }
Пример #9
0
        public async Task <IActionResult> Register()
        {
            try
            {
                ViewBag.Message = "User already register";
                AppUser user = await UserMgr.FindByNameAsync("TestUser");

                if (user == null)
                {
                    user           = new AppUser();
                    user.UserName  = "******";
                    user.Email     = "*****@*****.**";
                    user.FirstName = "Nguyen";
                    user.LastName  = "Son";

                    IdentityResult result = await UserMgr.CreateAsync(user, "Admin123!");

                    ViewBag.Message = "User was created";
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }
            return(View());
        }
Пример #10
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser
                {
                    UserName = model.Email,
                    Email    = model.Email
                };

                var result = await UserMgr.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInMgr.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction("Index", "Home"));
                }

                foreach (var errors in result.Errors)
                {
                    ModelState.AddModelError("", errors.Description);
                }
            }
            return(View(model));
        }
Пример #11
0
        public async Task <string> getMethod()
        {
            var Message = "";

            try
            {
                Message = "User already registered";

                AppUser user = await UserMgr.FindByNameAsync("nhoarau");

                if (user == null)
                {
                    user           = new AppUser();
                    user.UserName  = "******";
                    user.Email     = "*****@*****.**";
                    user.FirstName = "Nathan";
                    user.LastName  = "HOARAU";

                    IdentityResult result = await UserMgr.CreateAsync(user, "PhilDougTest33*");

                    Message = "User was created";
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }

            return(Message);
        }
        public async Task <IActionResult> Register(RegisterViewModel userForm)
        {
            try
            {
                ViewBag.Message = "User already registered";

                AppUser user = await UserMgr.FindByNameAsync(userForm.UserName);

                if (user == null)
                {
                    user           = new AppUser();
                    user.UserName  = userForm.UserName;
                    user.Email     = userForm.Email;
                    user.FirstName = userForm.FirstName;
                    user.LastName  = userForm.LastName;

                    IdentityResult result = await UserMgr.CreateAsync(user, userForm.Password);

                    if (result.Succeeded)
                    {
                        ViewBag.Message = "User was created";
                    }
                    else
                    {
                        ViewBag.Message = result.Errors;
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return(View());
        }
Пример #13
0
        public async Task <IActionResult> Register(RegisterViewModel usermodel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    AppUser user = await UserMgr.FindByNameAsync(usermodel.Username);

                    if (user == null)
                    {
                        user = new AppUser
                        {
                            UserName = usermodel.Username,
                            Email    = usermodel.Email,
                            FullName = usermodel.FullName,
                            Address  = usermodel.Address,
                            Type     = "Customer"
                        };

                        IdentityResult result = await UserMgr.CreateAsync(user, usermodel.Password);

                        //await UserMgr.AddToRoleAsync(user, user.Type);
                        if (result.Succeeded)
                        {
                            await LogChangeAsync(user, "REGISTER");

                            return(Created("", usermodel));
                        }
                        else
                        {
                            var err = new { status = "error", message = "User registration failed!" };
                            return(BadRequest(err));
                        }
                    }
                    else
                    {
                        //User Already exsist
                        var err = new { status = "error", message = "User already exsist!" };
                        return(BadRequest(err));
                    }
                }
                catch (Exception ex)
                {
                    var err = new { status = "error", message = ex.Message };
                    return(BadRequest(err));
                }
            }
            else
            {
                var err = new { status = "error", message = "Invalid details" };
                return(BadRequest(err));
            }
        }
Пример #14
0
        public async Task <IActionResult> Register(RegisterBindingModel model)
        {
            try
            {
                User user = await UserMgr.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    user = new User
                    {
                        UserName    = model.UserName,
                        DisplayName = model.DisplayName,
                        Email       = model.Email,
                    };

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

                    await UserMgr.AddToRoleAsync(user, EntityConstants.Role_SuperAdmin);

                    if (result.Succeeded)
                    {
                        var response = new ResponseModel {
                            Status = "Success", Code = "200", Message = "Account Created", Data = model
                        };
                        return(Created("", response));
                    }
                    else
                    {
                        var response = new ResponseModel {
                            Status = "Error", Code = "400", Message = "User registration " + result.ToString(), Data = null
                        };
                        return(Ok(response));
                    }
                }
                else
                {
                    //User Already exsist

                    var response = new ResponseModel {
                        Status = "Error", Code = "400", Message = "Email/UserName already exsist!", Data = null
                    };
                    return(Ok(response));
                }
            }
            catch (Exception ex)
            {
                var response = new ResponseModel {
                    Status = "Error", Code = "400", Message = ex.Message, Data = null
                };
                return(Ok(response));
            }
        }
Пример #15
0
        public async Task <IActionResult> AdminRegister(RegisterBindingModel model)
        {
            string usertype = User.Claims.First(c => c.Type == "Role").Value;

            if (usertype.Equals(EntityConstants.Role_SuperAdmin) || usertype.Equals(EntityConstants.Role_Admin))
            {
                try
                {
                    User user = await UserMgr.FindByEmailAsync(model.Email);

                    if (user == null)
                    {
                        user = new User
                        {
                            UserName    = model.UserName,
                            DisplayName = model.DisplayName,
                            Email       = model.Email,
                        };

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

                        await UserMgr.AddToRoleAsync(user, model.Role);

                        if (result.Succeeded)
                        {
                            return(Created("", model));
                        }
                        else
                        {
                            var err = new { status = "error", message = "User registration " + result.ToString() };
                            return(BadRequest(err));
                        }
                    }
                    else
                    {
                        //User Already exsist
                        var err = new { status = "error", message = "User already exsist!" };
                        return(BadRequest(err));
                    }
                }
                catch (Exception ex)
                {
                    var err = new { status = "error", message = ex.Message };
                    return(BadRequest(err));
                }
            }
            else
            {
                return(Forbid());
            }
        }
Пример #16
0
        public async Task <IActionResult> Register(RegisterBindingModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    User user = await UserMgr.FindByEmailAsync(model.Email);

                    if (user == null)
                    {
                        user = new User
                        {
                            UserName = model.Username,
                            Email    = model.Email,
                        };

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

                        //await UserMgr.AddToRoleAsync(user, user.Type);
                        if (result.Succeeded)
                        {
                            return(Created("", model));
                        }
                        else
                        {
                            var err = new { status = "error", message = "User registration failed! " };
                            return(BadRequest(err));
                        }
                    }
                    else
                    {
                        //User Already exsist
                        var err = new { status = "error", message = "User already exsist!" };
                        return(BadRequest(err));
                    }
                }
                catch (Exception ex)
                {
                    var err = new { status = "error", message = ex.Message };
                    return(BadRequest(err));
                }
            }
            else
            {
                var err = new { status = "error", message = "Invalid details" };
                return(BadRequest(err));
            }
        }
Пример #17
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = new AppUser
                    {
                        UserName  = model.UserName,
                        Email     = model.Email,
                        FirstName = model.FirstName,
                        LastName  = model.LastName
                    };

                    var result = await UserMgr.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        var token = await UserMgr.GenerateEmailConfirmationTokenAsync(user);

                        var confirmationLink = Url.Action("ConfirmEmail", "Account",
                                                          new { userId = user.Id, token = token }, Request.Scheme);

                        logger.Log(LogLevel.Warning, confirmationLink);

                        ViewBag.MessageTitle = "Registro feito com sucesso!";
                        ViewBag.MessageBody  = "Antes que você possa fazer login, por favor, confirme " +
                                               "seu email clicando no link de confirmação que mandamos para seu email";
                        return(View("ConfirmEmail"));
                    }

                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }

                    return(View());
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);

                    return(View(model));
                }
            }

            return(View(model));
        }
Пример #18
0
        public async Task <IActionResult> Register(UserViewModel model)
        {
            // Tar emot modellen som 'model' och kan då börja arbeta med den

            // Skapar en ny användare via ApplicationUser
            ApplicationUser user = new ApplicationUser
            {
                FirstName   = model.FirstName,
                LastName    = model.LastName,
                UserName    = model.Email,
                Gender      = model.Gender,
                PhoneNumber = model.PhoneNumber,
                City        = model.City,
                Email       = model.Email
            };

            // Skapar användaren. skickar in password här så den blir hashad i databasen.
            IdentityResult result = await UserMgr.CreateAsync(user, model.Password);

            // Skickar användaren till User/Index
            return(View(nameof(Index)));

            //// Kod som kan användas för att skapa en testanvändare.
            //
            //// Letar upp om det finns en användare med namner Username
            //// Om inte FindByNameAsync hittar användaren Username så skapar den en testanvändare.
            //
            //ApplicationUser user = await UserMgr.FindByNameAsync("Username");
            //
            //if(user == null)
            //{
            //    user = new ApplicationUser();
            //    user.FirstName = "FirstName";
            //    user.LastName = "LastName";
            //    user.UserName = "******";
            //    user.Gender = "SheMale";
            //    user.PhoneNumber = "0701234567";
            //    user.City = "Sundsvall";
            //    user.Email = "*****@*****.**";

            //    // Skapar en testanvändaren och sätter password till Qwerty1234!
            //    IdentityResult result = await UserMgr.CreateAsync(user, "Qwerty1234!");
            //}
        }
Пример #19
0
        public async Task <ActionResult <IdentityResult> > post([FromBody] JsonElement body)
        {
            Dictionary <string, string> json = JsonConvert.DeserializeObject <Dictionary <string, string> >(body.ToString());
            string password = json["password"];

            ApplicationUser appUser = new ApplicationUser(json["email"], json["firstName"], json["lastName"], json["email"]);
            IdentityResult  result;

            ApplicationUser user = await UserMgr.FindByNameAsync(appUser.Email);

            if (user == null)
            {
                //appUser.NormalizedUserName = appUser.Email;
                result = await UserMgr.CreateAsync(appUser, password);


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

                user = await UserMgr.FindByNameAsync(appUser.Email);

                //update
                user.UserName = json["userName"];
                context.UpdateUser(appUser);

                //emaim, password, mantiente login, bloqueo por x fallos
                await SignInMgr.PasswordSignInAsync(appUser.Email, password, true, false);

                return(result);
            }
            else
            {
                IdentityError error = new IdentityError();
                error.Code        = "10";
                error.Description = "Usuario existente";
                return(IdentityResult.Failed(error));
            }
        }
Пример #20
0
        public async Task <IActionResult> Register(User model, string totalPrice)
        {
            var user = new User {
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                UserName     = model.Email,
                Email        = model.Email,
                City         = model.City,
                StreetAdress = model.StreetAdress,
                PostNumber   = model.PostNumber,
                CreatedAt    = DateTime.Now,
                PhoneNumber  = model.PhoneNumber,
                Currency     = model.Currency,
                Country      = model.Country
            };

            var result = await UserMgr.CreateAsync(user, model.Password);


            if (result.Succeeded && totalPrice != null)
            {
                await SignInMgr.SignInAsync(user, isPersistent : false);

                return(RedirectToAction("SelectPaymentAndDeliveryOption", "OrderConfirmation", new { totalPrice }));
            }
            if (result.Succeeded)
            {
                await SignInMgr.SignInAsync(user, isPersistent : false);

                return(RedirectToAction("Index", "Products"));
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error.Description);
            }

            return(View(model));
        }
        public async Task <IActionResult> Register(AppUser user, string pwd)
        {
            if (ModelState.IsValid)
            {
                AppUser appUser = new AppUser
                {
                    UserName  = user.UserName,
                    Email     = user.Email,
                    FristName = user.FristName,
                    LastName  = user.LastName,
                    companyID = user.companyID
                };

                if (pwd != null)
                {
                    IdentityResult result = await UserMgr.CreateAsync(appUser, pwd);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        foreach (IdentityError error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                    }
                }
                else
                {
                    ViewBag.message = "Password Cannot be NULL!!!!!!";
                }
                return(View());
            }
            return(View());
        }
Пример #22
0
        public async Task<IActionResult> Register(User newUser)
        {
            try
            {
                ViewBag.Message = "User already registered";
                AppUser user = await UserMgr.FindByNameAsync(newUser.userName);
                if (user == null)
                {                    
                    user = new AppUser();
                    user.UserName = newUser.userName;
                    user.Email = newUser.eMail;
                    user.FirstName = newUser.firstName;
                    user.LastName = newUser.lastName;

                    IdentityResult result;

                    result = await UserMgr.CreateAsync(user, newUser.password);
                    
                    if(result.Succeeded)
                    {
                        ViewBag.Message = "User created!";
                    }
                    else
                    {
                        ViewBag.Message = result.Errors;
                    }


                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return View();
        }
Пример #23
0
        public async Task <IActionResult> GoogleLoginCallback(string remoteError = null)
        {
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Invalid Login Attempt: {remoteError}");
                return(RedirectToAction("Login"));
            }

            var info = await SignInMgr.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information.");
                return(RedirectToAction("Login"));
            }

            var googleEmail = info.Principal.FindFirstValue(ClaimTypes.Email);

            if (String.IsNullOrEmpty(googleEmail))
            {
                ModelState.AddModelError(string.Empty, "Could not find an email associated with your google account. Make sure your Google account has a registered email address.");
                return(RedirectToAction("Login"));
            }

            var matchingUser = Context.Users.Where(u => u.Email == googleEmail).FirstOrDefault();

            if (matchingUser != null && !Context.UserLogins.Where(u => u.UserId == matchingUser.Id).Any())
            {
                ModelState.AddModelError(string.Empty, "An account with that email address already exists.");
                return(RedirectToAction("Login"));
            }

            var result = await SignInMgr.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Products"));
            }

            var user = new User
            {
                Email         = googleEmail,
                UserName      = googleEmail,
                FirstName     = info.Principal.FindFirstValue(ClaimTypes.GivenName),
                LastName      = info.Principal.FindFirstValue(ClaimTypes.Surname),
                StreetAdress  = info.Principal.FindFirstValue(ClaimTypes.StreetAddress),
                PostNumber    = info.Principal.FindFirstValue(ClaimTypes.PostalCode),
                City          = info.Principal.FindFirstValue(ClaimTypes.Locality),
                Country       = info.Principal.FindFirstValue(ClaimTypes.Country),
                Currency      = "SEK",
                PhoneNumber   = info.Principal.FindFirstValue(ClaimTypes.MobilePhone),
                Password      = null,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            await UserMgr.CreateAsync(user);

            await UserMgr.AddLoginAsync(user, info);

            await SignInMgr.SignInAsync(user, false);

            return(RedirectToAction("Index", "Products"));
        }
Пример #24
0
        public async Task <IActionResult> SignUp(SignUpForm signUp)
        {
            if (HttpContext.Items["domain"] as string == "default")
            {
                if (!string.IsNullOrEmpty(signUp.TenantDomain) && !string.IsNullOrEmpty(signUp.TenantName) && ModelState.IsValid)
                {
                    if (Regex.Matches(signUp.TenantDomain, @"[a-zA-Z]").Count == signUp.TenantDomain.Length)
                    {
                        var blacklist = new string[] { "default", "admin", "NewTenantUser", "sa", "helper", "dbo", "guest", "sys", "ttask" };
                        if (!_tt.TenantAlreadyExists(signUp.TenantDomain) && !blacklist.Contains(signUp.TenantDomain))
                        {
                            _newTenant.NewTenant(signUp.TenantName, signUp.TenantDomain);
                            Directory.CreateDirectory(@"wwwroot/img/profile/" + signUp.TenantDomain);

                            HttpContext.Items["domain"] = signUp.TenantDomain;

                            int tenantId = _tt.GetTenantId(signUp.TenantDomain);


                            var user = new User()
                            {
                                Id          = 1,
                                UserName    = signUp.Email,
                                Email       = signUp.Email,
                                FirstName   = signUp.FirstName,
                                Surname     = signUp.Surname,
                                PhoneNumber = signUp.PhoneNumber,
                                IdTenant    = tenantId
                            };


                            HttpContext.Items["domain"] = signUp.TenantDomain;
                            IdentityResult result = await UserMgr.CreateAsync(user, signUp.Password);

                            if (result.Succeeded)
                            {
                                await UserMgr.AddToRolesAsync(user, new List <string> {
                                    nameof(Roles.NormalUser), nameof(Roles.DomainAdmin), nameof(Roles.Manager)
                                });

                                var settings = new UserSettings()
                                {
                                    Coloring      = "0",
                                    CustomizeView = "0",
                                    Notifications = "0",
                                    IdUser        = user.Id
                                };
                                _ut.InsertSettings(settings);


                                return(Redirect($"https://{HttpContext.Request.Host}/{signUp.TenantDomain}"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("CustomErr", $"Domain {signUp.TenantDomain} already exists.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("CustomErr", $"Domain has to contain letters only.");
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(signUp.TenantName))
                    {
                        ModelState.AddModelError("signUp.TenantName", "Company name is required field!");
                    }
                    if (string.IsNullOrEmpty(signUp.TenantDomain))
                    {
                        ModelState.AddModelError("signUp.TenantDomain", "Domain is required field!");
                    }
                }
            }
            else
            {
                var idService = _serviceOrderTable.GetInUseServiceIdByTenantId(_tt.GetTenantId(HttpContext.Items["domain"] as string));
                var noUsers   = _ut.GetNOUsers();

                if ((idService == (int)Services.Basic && noUsers < 5) || (idService == (int)Services.Pro && noUsers < 10) || idService == (int)Services.Business)
                {
                    if (ModelState.IsValid)
                    {
                        signUp.TenantDomain = HttpContext.Items["domain"] as string;

                        int tenantId = _tt.GetTenantId(signUp.TenantDomain);
                        int userId   = _ut.GetMaxId();


                        User user = await UserMgr.FindByEmailAsync(signUp.Email);

                        if (user == null)
                        {
                            user = new User()
                            {
                                Id          = userId,
                                UserName    = signUp.Email,
                                Email       = signUp.Email,
                                FirstName   = signUp.FirstName,
                                Surname     = signUp.Surname,
                                PhoneNumber = signUp.PhoneNumber,
                                IdTenant    = tenantId
                            };


                            IdentityResult result = await UserMgr.CreateAsync(user, signUp.Password);

                            if (result.Succeeded)
                            {
                                await UserMgr.AddToRoleAsync(user, nameof(Roles.NormalUser));

                                if (userId == 1)
                                {
                                    await UserMgr.AddToRoleAsync(user, nameof(Roles.DomainAdmin));

                                    await UserMgr.AddToRoleAsync(user, nameof(Roles.Manager));
                                }

                                var settings = new UserSettings()
                                {
                                    Coloring      = "0",
                                    CustomizeView = "0",
                                    Notifications = "0",
                                    IdUser        = user.Id
                                };
                                _ut.InsertSettings(settings);

                                var TenantPolicyResult = await _authorization.AuthorizeAsync(User, "TenantPolicy");

                                if (TenantPolicyResult.Succeeded)
                                {
                                    var msg = "User " + user.FirstName + " " + user.Surname + " has signed up in your application.";
                                    _notificationTable.NotifyUser(1, msg);
                                    var signInResult = await SignInMgr.PasswordSignInAsync(user, signUp.Password, false, false);

                                    if (signInResult.Succeeded)
                                    {
                                        HttpContext.Response.Cookies.Append(
                                            "Identity.Domain",
                                            HttpContext.Items["domain"] as string,
                                            new CookieOptions {
                                            Expires  = DateTime.Now.AddDays(30),
                                            HttpOnly = true,
                                            Secure   = true,
                                            SameSite = SameSiteMode.Lax
                                        }
                                            );
                                        return(RedirectToAction("Index", "HomePage"));
                                    }
                                }
                                else
                                {
                                    ModelState.AddModelError("CustomErr", $"User was created, but service of your domain is not paid. Sign in is impossible. Please contact your domain admin.");
                                }
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("CustomErr", $"User {user.Email} already exists.");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("CustomErr", $"Number of users has been exceeded! If you want to register, contact domain admin to subscribe to higher service.");
                }
            }

            var model = new IndexViewModel
            {
                Domain         = HttpContext.Items["domain"] as string,
                SignUpSelected = true,
                SignIn         = new SignInForm(),
                SignUp         = signUp
            };

            return(View("Index", model));
        }
Пример #25
0
        public async Task <IActionResult> AddMockUsers()
        {
            var password = "******";
            var userList = new List <User>()
            {
                new User()
                {
                    FirstName = "	Ashly		", LastName = "	Trendle		", Email = "[email protected]			", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Sales"
                },
                new User()
                {
                    FirstName = "	Bettye		", LastName = "	Paulack		", Email = "[email protected]			", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Cloud"
                },
                new User()
                {
                    FirstName = "	Calhoun		", LastName = "	Bolmann		", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu", UserName = "******", Department = "Operations"
                },
                new User()
                {
                    FirstName = "	Currie		", LastName = "	Braunfeld	", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team C", ProfilePicture = "https://source.unsplash.com/user/erondu", UserName = "******", Department = "Human Resources"
                },
                new User()
                {
                    FirstName = "	Cordula		", LastName = "	Fordyce		", Email = "[email protected]			", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu", UserName = "******", Department = "Finances"
                },
                new User()
                {
                    FirstName = "	Claudelle	", LastName = "	Lockery		", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Legal"
                },
                new User()
                {
                    FirstName = "	Dickie		", LastName = "	Cake		", Email = "[email protected]				", PhoneNumber = "555-123-4567", ResourceGroup = "Team C", ProfilePicture = "https://source.unsplash.com/user/erondu", UserName = "******", Department = "Technology and Research"
                },
                new User()
                {
                    FirstName = "	Derrick		", LastName = "	Frizzell	", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Operations"
                },
                new User()
                {
                    FirstName = "	Feodora		", LastName = "	Tripon		", Email = "[email protected]	", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu", UserName = "******", Department = "Development"
                },
                new User()
                {
                    FirstName = "	Hiram		", LastName = "	Lohmeyer	", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team C", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Development"
                },
                new User()
                {
                    FirstName = "	Harv		", LastName = "	Sacks		", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Operations"
                },
                new User()
                {
                    FirstName = "	Joann		", LastName = "	Fogel		", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu", UserName = "******", Department = "Operations"
                },
                new User()
                {
                    FirstName = "	Keriann		", LastName = "	Hofton		", Email = "[email protected]			", PhoneNumber = "555-123-4567", ResourceGroup = "Team C", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Technology and Research"
                },
                new User()
                {
                    FirstName = "	Minerva		", LastName = "	Cracknall	", Email = "[email protected]	", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Technology and Research"
                },
                new User()
                {
                    FirstName = "	Artemis		", LastName = "	Thresh		", Email = "[email protected]			", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu ", UserName = "******", Department = "Development"
                },
                new User()
                {
                    FirstName = "	Nora		", LastName = "	Edgecombe	", Email = "[email protected]		", PhoneNumber = "555-123-4567", ResourceGroup = "Team C", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Cloud"
                },
                new User()
                {
                    FirstName = "	Rennie		", LastName = "	Mathes		", Email = "[email protected]	", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Cloud"
                },
                new User()
                {
                    FirstName = "	Slade		", LastName = "	Throughton	", Email = "[email protected]	", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Technology and Research"
                },
                new User()
                {
                    FirstName = "	Tandie		", LastName = "	Casterot	", Email = "[email protected]	", PhoneNumber = "555-123-4567", ResourceGroup = "Team B", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Operations"
                },
                new User()
                {
                    FirstName = "	Toma		", LastName = "	Feary		", Email = "[email protected]		  	", PhoneNumber = "555-123-4567", ResourceGroup = "Team A", ProfilePicture = "https://source.unsplash.com/user/erondu	", UserName = "******", Department = "Cloud"
                }
            };

            foreach (var user in userList)
            {
                user.FirstName.Trim();
                user.LastName.Trim();
                user.Email.Trim();
                user.PhoneNumber.Trim();
                user.ResourceGroup.Trim();
                user.ProfilePicture.Trim();
                user.Department.Trim();

                var result = await UserMgr.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    await SignInMgr.SignOutAsync();

                    if ((await SignInMgr.PasswordSignInAsync(user.UserName, password, false, false))
                        .Succeeded)
                    {
                        Console.WriteLine("yes");
                    }
                }
            }

            return(Ok());
        }