コード例 #1
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null && await UserMgr.IsEmailConfirmedAsync(user))
                {
                    var token = await UserMgr.GeneratePasswordResetTokenAsync(user);

                    var passwordResetLink = Url.Action("ResetPassword", "Account",
                                                       new { email = model.Email, token = token }, Request.Scheme);

                    logger.Log(LogLevel.Warning, passwordResetLink);

                    return(View("ForgotPasswordConfirmation"));
                }

                Console.WriteLine("Eu não entrei no if");


                return(View("ForgotPasswordConfirmation"));
            }

            return(View(model));
        }
コード例 #2
0
ファイル: UserController.cs プロジェクト: MikeJLeon/todolist
        public async Task <IActionResult> Forgot(string email)
        {
            Console.WriteLine(email);
            var user = await UserMgr.FindByEmailAsync(email);

            var todoEmail = Environment.GetEnvironmentVariable("TODOLIST_EMAIL");
            var password  = Environment.GetEnvironmentVariable("TODOLIST_EMAIL_PASSWORD");
            var route     = Request.Host.Value;

            if (user != null)
            {
                var token = await UserMgr.GeneratePasswordResetTokenAsync(user);

                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Password Recovery - Mike's Todolist", todoEmail));
                message.To.Add(MailboxAddress.Parse(email));
                message.Subject = "Password Recovery - Mike's Todolist";
                message.Body    = new TextPart("plain")
                {
                    Text = "https://" + route + "/Recover/" + email + "/" + HttpUtility.UrlEncode(token)
                };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    client.Authenticate(todoEmail, password);
                    client.Send(message);
                    client.Disconnect(true);
                }
                return(Ok(true));
            }
            return(BadRequest("Wrong email"));
        }
コード例 #3
0
ファイル: UserController.cs プロジェクト: MikeJLeon/todolist
        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));
            }
        }
コード例 #4
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));
        }
コード例 #5
0
        public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            Console.WriteLine(model.Email);
            Console.WriteLine(model.Token);

            if (ModelState.IsValid)
            {
                var user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var result = await UserMgr.ResetPasswordAsync(user, model.Token, model.Password);

                    if (result.Succeeded)
                    {
                        return(View("ResetPasswordConfirmation"));
                    }

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

                return(View("ResetPasswordConfirmation"));
            }

            return(View(model));
        }
コード例 #6
0
        public async Task <IActionResult> GetToken([FromBody] AuthBindingModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var signInResult = await SignInMgr.CheckPasswordSignInAsync(user, model.Password.ToString(), false);

                    if (signInResult.Succeeded)
                    {
                        var roles = await UserMgr.GetRolesAsync(user);

                        return(generateToken(user, roles.FirstOrDefault()));
                    }
                    else
                    {
                        var err2 = new { status = "error", message = "Authentication Failed ! Check Email & Password" };
                        return(BadRequest(err2));
                    }
                }

                var err = new { status = "error", message = "Could not find a user for given Email!" };
                return(BadRequest(err));
            }

            return(BadRequest());
        }
コード例 #7
0
ファイル: AccountController.cs プロジェクト: nhoarau/NAS
        public async Task <bool> Login(JObject userJson)
        {
            var userInfo = JsonConvert.DeserializeObject <UserLoginModel>(userJson.ToString());

            if (!ModelState.IsValid)
            {
                return(false);
            }

            var user = await UserMgr.FindByEmailAsync(userInfo.Email);

            if (user != null &&
                await UserMgr.CheckPasswordAsync(user, userInfo.Password))
            {
                var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));

                await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme,
                                              new ClaimsPrincipal(identity));

                return(true);
            }
            else
            {
                ModelState.AddModelError("", "Invalid UserName or Password");
                return(false);
            }
        }
コード例 #8
0
        public async Task <IActionResult> DeleteUser(string id)
        {
            if (await UserMgr.FindByEmailAsync(id) != null)
            {
                await UserMgr.DeleteAsync(UserMgr.FindByEmailAsync(id).Result);

                return(Ok($"Successfully Deleted User with User ID of {id}"));
            }

            return(BadRequest($"failed to delete User, User with User ID of {id} not found"));
        }
コード例 #9
0
        public async Task <IActionResult> GenerateToken([FromBody] AuthBindingModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var signInResult = await SignInMgr.CheckPasswordSignInAsync(user, model.Password.ToString(), false);

                    if (signInResult.Succeeded)
                    {
                        var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JWTSettings.Secret));
                        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim("UserType", ""),
                        };

                        var token = new JwtSecurityToken(

                            JWTSettings.Issuer,
                            JWTSettings.Audience,
                            claims,
                            expires: DateTime.UtcNow.AddMinutes(JWTSettings.ExpieryTimeInMins),
                            signingCredentials: cred

                            );

                        var results = new
                        {
                            thisuser   = new { UserName = user.UserName, Email = user.Email },
                            token      = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration = token.ValidTo
                        };
                        return(Ok(results));
                    }
                    else
                    {
                        var err2 = new { status = "error", message = "Authentication Failed ! Check UserName & Password" };
                        return(BadRequest(err2));
                    }
                }

                var err = new { status = "error", message = "Could not find a user!" };
                return(BadRequest(err));
            }

            return(BadRequest());
        }
コード例 #10
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));
            }
        }
コード例 #11
0
        public async Task <IActionResult> IsEmailInUse(string email)
        {
            var user = await UserMgr.FindByEmailAsync(email);

            if (user == null)
            {
                return(Json(true));
            }
            else
            {
                return(Json($"Email {email} is already in use"));
            }
        }
コード例 #12
0
        public async Task <IActionResult> getinfoAsync()
        {
            string email = User.Claims.First(c => c.Type == "Email").Value;
            User   user  = await UserMgr.FindByEmailAsync(email);

            var returnuser = new
            {
                Username = user.UserName,
                Email    = user.Email,
            };

            return(Ok(returnuser));
        }
コード例 #13
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());
            }
        }
コード例 #14
0
        public async Task <IActionResult> Register(RegisterModel userModel)
        {
            if (ModelState.IsValid)
            {
                UserApiRepository.AddUser(userModel);
            }

            if (await UserMgr.FindByEmailAsync(userModel.Email) != null)
            {
                return(View("Login"));
            }

            return(View());
        }
コード例 #15
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));
            }
        }
コード例 #16
0
        public async Task <ActionResult> AccountInfo(User userUpdate)
        {
            //Get logged in user
            var userId      = UserMgr.GetUserId(HttpContext.User);
            var currentUser = UserMgr.FindByIdAsync(userId).Result;

            //Ensure unique email
            string updateEmail = userUpdate.Email;

            if (UserMgr.FindByEmailAsync(updateEmail).Result == null || UserMgr.FindByEmailAsync(updateEmail).Result == currentUser)
            {
                currentUser.Email = userUpdate.Email;
            }
            else
            {
                return(View());
            }

            //Password
            if (userUpdate.Password == null)
            {
                currentUser.Password = currentUser.Password;
            }
            else
            {
                currentUser.Password = userUpdate.Password;
                await UserMgr.RemovePasswordAsync(currentUser);

                await UserMgr.AddPasswordAsync(currentUser, userUpdate.Password);
            }

            //Name
            currentUser.FirstName = userUpdate.FirstName;
            currentUser.LastName  = userUpdate.LastName;

            IdentityResult x = await UserMgr.UpdateAsync(currentUser);

            if (x.Succeeded)
            {
                return(RedirectToAction("Dashboard", "Application"));
            }
            else
            {
                ViewBag.ErrorMessage = "Error";
                return(View(userUpdate));
            }
        }
コード例 #17
0
        public async Task <IActionResult> getinfoAsync()
        {
            string email = User.Claims.First(c => c.Type == "Email").Value;
            User   user  = await UserMgr.FindByEmailAsync(email);

            var roles = await UserMgr.GetRolesAsync(user);

            var returnuser = new UserResourceModel
            {
                UserName    = user.UserName,
                DisplayName = user.DisplayName,
                Role        = roles.FirstOrDefault().ToString(),
                Email       = user.Email,
            };

            return(Ok(returnuser));
        }
コード例 #18
0
ファイル: UserController.cs プロジェクト: MikeJLeon/todolist
        public async Task <IActionResult> Recover(string email, string token, string password)
        {
            var user = await UserMgr.FindByEmailAsync(email);

            token = HttpUtility.UrlDecode(token);
            token = token.Replace(" ", "+");
            var result = await UserMgr.ResetPasswordAsync(user, token, password);

            Console.WriteLine(result);
            Console.WriteLine(email);
            Console.WriteLine(token);
            Console.WriteLine(password);
            if (result.Succeeded)
            {
                return(Ok());
            }

            return(BadRequest());
        }
コード例 #19
0
        public async Task <IActionResult> Edit(User user)
        {
            userToUpdate = await UserMgr.FindByEmailAsync(user.Email);

            userToUpdate.Email        = user.Email;
            userToUpdate.PhoneNumber  = user.PhoneNumber;
            userToUpdate.StreetAdress = user.StreetAdress;
            userToUpdate.City         = user.City;
            userToUpdate.PostNumber   = user.PostNumber;
            userToUpdate.LastName     = user.LastName;
            userToUpdate.FirstName    = user.FirstName;
            userToUpdate.Country      = user.Country;
            userToUpdate.Currency     = user.Currency;
            userToUpdate.UserName     = user.Email;

            await UserMgr.UpdateAsync(userToUpdate);


            return(View(userToUpdate));
        }
コード例 #20
0
        public async Task <IActionResult> ForgotPassword(ForgotPassword model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    token = await UserMgr.GeneratePasswordResetTokenAsync(user);

                    passwordResetLink = Url.Action("ResetPassword", "UserWithAuthentication",
                                                   new { token, email = model.Email }, Request.Scheme);

                    SendResetPasswordLink(passwordResetLink, model.Email);

                    return(View("ForgotPasswordConfirmation"));
                }
                return(View("ForgotPasswordConfirmation"));
            }

            return(View(model));
        }
コード例 #21
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await SignInMgr.PasswordSignInAsync(model.Email, model.Password, false, false);

                var user = await UserMgr.FindByEmailAsync(model.Email);

                var roles = await UserMgr.GetRolesAsync(user);

                if (result.Succeeded)
                {
                    if (roles.Contains("Admin"))
                    {
                        return(RedirectToAction("Index", "Admin"));
                    }

                    if (roles.Contains("Institution admin"))
                    {
                        return(RedirectToAction("Index", "Moderator"));
                    }

                    if (roles.Contains("Employee"))
                    {
                        return(RedirectToAction("Index", "Employee"));
                    }

                    if (roles.Contains("Donor"))
                    {
                        return(RedirectToAction("Index", "Donor"));
                    }
                }

                ModelState.AddModelError(string.Empty, "Slaptažodis arba prisijungimo vardas netinkamas");
            }

            return(View("IncorectLoging"));
        }
コード例 #22
0
ファイル: UserController.cs プロジェクト: MikeJLeon/todolist
        public async Task <IActionResult> Login(string user_email, string password)
        {
            Console.WriteLine(user_email);
            var userToVerify = await UserMgr.FindByEmailAsync(user_email);

            var result = await SignInMgr.PasswordSignInAsync(userToVerify.UserName, password, true, false);

            Console.WriteLine(result.Succeeded);
            if (result.Succeeded)
            {
                var identity = await UserMgr.GetClaimsAsync(userToVerify);

                var userToSend = new UserModel();
                userToSend.FirstName = userToVerify.FirstName;
                userToSend.LastName  = userToVerify.LastName;
                userToSend.UserName  = userToVerify.NormalizedEmail.ToLower();
                userToSend.Email     = userToVerify.NormalizedEmail.ToLower();
                Console.WriteLine(userToSend + "<-----");
                return(Ok(userToSend));
            }

            return(Ok(user_email));
        }
コード例 #23
0
ファイル: UserController.cs プロジェクト: MikeJLeon/todolist
        public async Task <IActionResult> Update(string field, string value)
        {
            Console.WriteLine(field);
            Console.WriteLine(value);
            var username = User?.Identity.Name;
            var user     = await UserMgr.FindByNameAsync(username);

            if (field == "firstName")
            {
                user.FirstName = value;
            }
            else if (field == "lastName")
            {
                user.LastName = value;
            }
            else if (field == "newPassword")
            {
                await UserMgr.RemovePasswordAsync(user);

                await UserMgr.AddPasswordAsync(user, value);
            }
            else if (field == "newEmail")
            {
                Console.WriteLine(RegexUtilities.IsValidEmail(value));
                if (RegexUtilities.IsValidEmail(value))
                {
                    var checkEmail = await UserMgr.FindByEmailAsync(value);

                    if (checkEmail == null)
                    {
                        await UserMgr.SetEmailAsync(user, value);

                        var newUser = await UserMgr.FindByEmailAsync(value);

                        await SignInMgr.SignOutAsync();

                        await SignInMgr.SignInAsync(newUser, true);

                        user = newUser;
                    }
                    else
                    {
                        return(Ok("Email exists"));
                    }
                }
                else
                {
                    return(Ok("Email invalid"));
                }
            }

            IdentityResult result = await UserMgr.UpdateAsync(user);

            Console.WriteLine(result.Succeeded + "<----");
            if (result.Succeeded)
            {
                var userToSend = new UserModel();
                userToSend.FirstName = user.FirstName;
                userToSend.LastName  = user.LastName;
                userToSend.UserName  = user.NormalizedEmail;
                return(Ok(userToSend));
            }
            return(Ok("Accout update failed"));
        }
コード例 #24
0
ファイル: HomeController.cs プロジェクト: NOV0511/BP_tTask
        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
ファイル: HomeController.cs プロジェクト: NOV0511/BP_tTask
        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));
        }