Beispiel #1
0
        public async Task <IActionResult> Login(User model, string totalPrice)
        {
            result = await SignInMgr.PasswordSignInAsync(model.Email, model.Password, false, false);

            if (result.Succeeded && totalPrice != null)
            {
                currentUser = await UserMgr.FindByEmailAsync(model.Email);

                await ChangeToKeyCustomer(currentUser);

                IsKeyCustomer   = UserMgr.IsInRoleAsync(currentUser, "KeyCustomer");
                DiscountedPrice = Convert.ToDouble(totalPrice);

                if (IsKeyCustomer.Result == true)
                {
                    DiscountedPrice *= 0.9;

                    return(RedirectToAction("SelectPaymentAndDeliveryOption", "OrderConfirmation", new { totalPrice = DiscountedPrice.ToString(), keyCustomer = IsKeyCustomer.Result }));
                }

                return(RedirectToAction("SelectPaymentAndDeliveryOption", "OrderConfirmation", new { totalPrice, keyCustomer = IsKeyCustomer.Result }));
            }
            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Products"));
            }


            ModelState.AddModelError(string.Empty, "Invalid Login Attempt");


            return(View(model));
        }
        public async Task <IActionResult> Register([FromForm] RegisterVM registerVM)
        {
            var user = new UserModel()
            {
                Subscribed = true,
                UserName   = registerVM.UserName,
                Email      = registerVM.Email
            };

            var res = await UserMgr.CreateAsync(user, registerVM.Password);

            if (res.Succeeded)
            {
                await _email.Welcome(registerVM.Email);

                var curUser = await UserMgr.FindByNameAsync(user.UserName);

                var roleResult = UserMgr.AddToRoleAsync(curUser, "Visitor");
                roleResult.Wait();

                var signIn = await SignInMgr.PasswordSignInAsync(user.UserName, registerVM.Password, true, lockoutOnFailure : true);

                if (signIn.Succeeded)
                {
                    return(Redirect("/"));
                }
            }

            return(Redirect("/error"));
        }
        public async Task <Microsoft.AspNetCore.Identity.SignInResult> login([FromBody] JsonElement body)
        {
            Dictionary <string, string> json = JsonConvert.DeserializeObject <Dictionary <string, string> >(body.ToString());

            Microsoft.AspNetCore.Identity.SignInResult result = await SignInMgr.PasswordSignInAsync(json["email"], json["password"], true, false);

            return(result);
        }
        public async Task <IActionResult> SignIn([FromForm] string username, [FromForm] string password)
        {
            var res = await SignInMgr.PasswordSignInAsync(username, password, true, lockoutOnFailure : true);

            if (res.Succeeded)
            {
                return(Redirect("/"));
            }

            return(Redirect("/signin/attempt"));
        }
        public async Task <IActionResult> Login(Staff obj)
        {
            var result = await SignInMgr.PasswordSignInAsync(obj.UserName, obj.PasswordHash, false, false);

            if (result.Succeeded)
            {
                //HttpContext.Session.SetString("Role", RoleMgr.FindByIdAsync(User.FindFirstValue("RoleId")).ToString());
                return(RedirectToAction("Index", "home"));
            }
            ViewData["Message"] = "Tài khoản hoặc mật khẩu không chính xát vui lòng đăng nhập lại";
            return(View());
        }
Beispiel #6
0
        public async Task <IActionResult> Login()
        {
            var result = await SignInMgr.PasswordSignInAsync("TestUser", "test123", false, false);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ViewBag.Result = "result is: " + result.ToString();
            }



            return(View());
        }
        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));
            }
        }
Beispiel #8
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));
        }
Beispiel #9
0
        public async Task <IActionResult> SignIn(SignInForm signIn)
        {
            if (ModelState.IsValid)
            {
                if (HttpContext.Items["domain"] as string != "default")
                {
                    User user = await UserMgr.FindByEmailAsync(signIn.Email);

                    if (user != null)
                    {
                        var TenantPolicyResult = await _authorization.AuthorizeAsync(User, "TenantPolicy");

                        if (TenantPolicyResult.Succeeded)
                        {
                            var result = await SignInMgr.PasswordSignInAsync(user, signIn.Password, true, false);

                            if (result.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
                                }
                                    );

                                _notificationTable.NotifyCloseDeadlineTasks(user.Id);
                                if (user.Id == 1)
                                {
                                    _notificationTable.NotifyClosePaymentExpirationDate(_tt.GetTenantId(HttpContext.Items["domain"] as string));
                                }
                                return(RedirectToAction("Index", "HomePage"));
                            }
                            else
                            {
                                ModelState.AddModelError("CustomErr", $"Unable to login user {signIn.Email}.");
                            }
                        }
                        else
                        {
                            if (await UserMgr.IsInRoleAsync(user, nameof(Roles.DomainAdmin)))
                            {
                                var result = await SignInMgr.PasswordSignInAsync(user, signIn.Password, true, false);

                                if (result.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", "Profile"));
                                }
                                else
                                {
                                    ModelState.AddModelError("CustomErr", $"Unable to login user {signIn.Email}.");
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("CustomErr", $"Service is not paid! Please contact your domain admin.");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("CustomErr", $"User {signIn.Email} does not exist in application.");
                    }
                }
                else
                {
                    GlobalUser user = await SharedUserMgr.FindByEmailAsync(signIn.Email);

                    if (user != null)
                    {
                        var result = await SharedSignInMgr.PasswordSignInAsync(user, signIn.Password, true, false);

                        if (result.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", "Admin"));
                        }
                        else
                        {
                            ModelState.AddModelError("CustomErr", $"Unable to login user {signIn.Email}.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("CustomErr", $"User {signIn.Email} does not exist in application.");
                    }
                }
            }
            var model = new IndexViewModel
            {
                Domain         = HttpContext.Items["domain"] as string,
                SignUpSelected = false,
                SignIn         = signIn,
                SignUp         = new SignUpForm()
            };

            return(View("Index", model));
        }