Exemple #1
0
        public ActionResult Index(FormCollection form)
        {
            try
            {
                myauthuserViewModel = new AuthUserViewModel();

                if (ModelState.IsValid)
                {
                    var chckedValues = form.GetValues("chkStatus");

                    foreach (var id in chckedValues)
                    {
                        int id1 = Convert.ToInt32(id);
                        myauthuserViewModel.UpdateUserActive(id1);
                    }

                    myauthuserViewModel.getAuthUsersFrmDB();

                    ViewBag.Numberofauthusers = myauthuserViewModel.lstauthusers.Count;
                }
                return(View(myauthuserViewModel.lstauthusers));
            }
            catch (Exception ex)
            {
                errorlogviewmodel = new ErrorLogViewModel();
                errorlogviewmodel.LogError(ex);
                return(View("Error"));
            }
        }
Exemple #2
0
        public ActionResult AuthAjaxForm(AuthUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView("AuthForm"));
            }
            var res = _service.Auth(model.Value, model.Password);

            if (res == null)
            {
                ModelState.AddModelError("Password", "Не найдена комбинация логин/пароль");
                return(PartialView("AuthForm"));
            }
            ClaimsIdentity ci = new ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Name, model.Value),
                new Claim(ClaimTypes.NameIdentifier, res.Id.ToString()),
                new Claim(ClaimTypes.Email, res.Email),
                new Claim(ClaimTypes.DateOfBirth, res.BirthDate.ToString())
            }, ConfigurationManager.AppSettings["authtype"]);

            foreach (var role in res.Roles)
            {
                ci.AddClaim(new Claim(ClaimTypes.Role, role));
            }
            HttpContext.GetOwinContext().Authentication.SignIn(ci);
            return(Json(new { status = "ok" }, JsonRequestBehavior.AllowGet));
        }
Exemple #3
0
        public AuthUserViewModel GetAuthUser(string userId)
        {
            var user          = GetUser(userId);
            var userViewModel = new AuthUserViewModel(user);

            return(userViewModel);
        }
Exemple #4
0
        private async Task <AuthUserViewModel> GetUser(string userName)
        {
            var user = await _userManager.FindByNameAsync(userName);

            var claims = await _userManager.GetClaimsAsync(user);

            var vm = new AuthUserViewModel()
            {
                UserName = user.UserName,
                IsAdmin  = claims.Any(x => x.Value.Equals("admin"))
            };

            return(vm);
        }
Exemple #5
0
        public async Task <IActionResult> SignIn([FromBody] LogInViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByNameAsync(model.Username);

                if (user != null)
                {
                    if (await this.userManager.IsLockedOutAsync(user))
                    {
                        ModelState.AddModelError("userbanned", "Your account has been disabled by an administrator.");
                        return(Conflict(ModelState));
                    }
                    var result = await signInManager.CheckPasswordSignInAsync(user, model.Password, false);

                    if (result.Succeeded)
                    {
                        string       role   = userManager.GetRolesAsync(user).Result.FirstOrDefault();
                        List <Claim> claims = new List <Claim>
                        {
                            new Claim(ClaimTypes.Name, user.UserName),
                            new Claim(ClaimTypes.NameIdentifier, user.Id),
                            new Claim(ClaimTypes.Role, role)
                        };
                        ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "jwt");
                        var            output         = new AuthUserViewModel
                        {
                            User  = model.Username,
                            Role  = role,
                            Token = this.GetToken(claimsIdentity)
                        };
                        return(Ok(output));
                    }
                    else
                    {
                        ModelState.AddModelError("wrongpass", "The password you entered is incorrect");
                        return(Conflict(ModelState));
                    }
                }
                else
                {
                    return(NotFound("A user with this credentials does not exist."));
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
        public async Task <IActionResult> Auth()
        {
            string userID = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (String.IsNullOrEmpty(userID))
            {
                return(BadRequest("User not found"));
            }
            Users u = await userManager.FindByIdAsync(userID);

            AuthUserViewModel retVal = new AuthUserViewModel()
            {
                UserName = u.UserName, UserId = u.Id, Roles = await userManager.GetRolesAsync(u) as List <string>
            };

            return(Ok(retVal));
        }
Exemple #7
0
        //[Authorize(Policy = "RequireAdministrator")]
        public async Task <IActionResult> Add([FromBody] AuthUserViewModel model)
        {
            try
            {
                //Hash Pass
                string salt = BCrypt.Net.BCrypt.GenerateSalt();
                model.Password = BCrypt.Net.BCrypt.HashPassword(model.Password, salt);

                model.Id = new Guid();
                await _authUserService.CreateAsync(model);

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Exemple #8
0
        public object Post([FromBody] AuthUserViewModel usuario)
        {
            usuario = usuario ?? new AuthUserViewModel();

            var authUser = new Core.Entities.AuthUser()
            {
                Email = usuario.Email, Password = usuario.Senha
            };

            var response = appAuthenticate.ValidanteAndCreateToken(authUser);

            if (!response.Status)
            {
                return(BadRequest(response));
            }

            return(response);
        }
Exemple #9
0
        public async Task <ActionResult> Update([FromBody] AuthUserViewModel model)
        {
            try
            {
                var model_db = await _authUserService.FindByIdAsync(model.Id);

                if (model_db == null)
                {
                    return(BadRequest("Model is not exists"));
                }
                model_db = model;
                await _authUserService.UpdateAsync(model_db, model_db.Id);

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
 public IActionResult Login(AuthUserViewModel authUserViewModel)
 {
     if (ModelState.IsValid)
     {
         var admin = db.User.Where(x => x.Email == authUserViewModel.Email && x.Password == authUserViewModel.Password && x.UserTypeId == 1).FirstOrDefault();
         if (admin == null)
         {
             return(RedirectToAction("Index"));
         }
         else
         {
             HttpContext.Session.SetObjectAsJson("admin", admin);
             return(RedirectToAction("Index", "Home"));
         }
     }
     else
     {
         return(RedirectToAction("Index"));
     }
 }
Exemple #11
0
        public ActionResult Index()
        {
            try
            {
                myauthuserViewModel = new AuthUserViewModel();
                // List<AuthUserViewModel> lstauthuserViewModel = new List<AuthUserViewModel>();

                myauthuserViewModel.getAuthUsersFrmDB();

                ViewBag.Numberofauthusers = myauthuserViewModel.lstauthusers.Count;

                return(View(myauthuserViewModel.lstauthusers));
            }
            catch (Exception ex)
            {
                errorlogviewmodel = new ErrorLogViewModel();
                errorlogviewmodel.LogError(ex);
                return(View("Error"));
            }
        }
        public IActionResult Authenticate([FromBody] AuthUserViewModel model)
        {
            if (model == null || model.Login == null || model.Password == null)
            {
                return(BadRequest(new { message = "Логин или пароль не валидны" }));
            }

            var user = userService.Authenticate(model.Login, model.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Логин или пароль не валидны" }));
            }

            var tokenString = GetToken(user);

            return(Ok(new
            {
                token = tokenString,
                userLogin = user
            }));
        }
Exemple #13
0
        public async Task <AuthUserViewModel> Authenticate(string email, string senha)
        {
            var result = _service.Filter(email, senha);

            // return null if user not found
            if (result == null)
            {
                return(null);
            }

            var user = new AuthUserViewModel
            {
                Email = result.Email,
                Id    = result.Id
            };

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();

            var appSettingsSection = _configuration.GetSection("AppSettings");
            var appSettings        = appSettingsSection.Get <AppSettings>();

            var key             = Encoding.ASCII.GetBytes(appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            return(user);
        }
Exemple #14
0
        private async Task <AuthUserViewModel> GetUser(ApplicationUser user)
        {
            //var user = await _userManager.FindByNameAsync(userName);

            var roles = await _userManager.GetRolesAsync(user);

            var vm = new AuthUserViewModel()
            {
                UserName = user.UserName,
                Email    = user.Email,
                AvatarId = user.AvatarId,
                IsAdmin  = roles.Contains("Admin")
                           //Email,
                           //Avatar,
                           //birthday,
                           //socialpriviledge,
                           //isPresident,
                           //friendsList,
            };

            return(vm);
        }
Exemple #15
0
        private async Task <AuthUserViewModel> GetUser(string userName)
        {
            var user = await _userManager.FindByNameAsync(userName);

            var claims = await _userManager.GetClaimsAsync(user);

            var vm = new AuthUserViewModel()
            {
                UserName        = user.UserName,
                Nickname        = user.Nickname,
                IsAdmin         = claims.Any(x => x.Value.Equals("admin")),
                Tokens          = user.Tokens,
                GamesPlayed     = user.GamesPlayed,
                GamesWon        = user.GamesWon,
                NavBarColor     = user.NavBarColor,
                BackgroundColor = user.BackgroundColor,
                Id      = user.Id,
                Friends = user.Friends
                          //
            };

            return(vm);
        }
Exemple #16
0
        public IActionResult Authenticate([FromBody] AuthUserViewModel model)
        {
            if (model == null || model.Email == null || model.Password == null)
            {
                return(BadRequest(new { message = "Электронная почта или пароль не валидны" }));
            }

            var user = userService.Authenticate(model.Email, model.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Электронная почта или пароль не валидны" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(config.GetSection("Config:SecretKey").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString()),
                    new Claim(ClaimTypes.Role, user.RoleId.ToString()),
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new {
                token = tokenString,
                email = user.Email,
                fullName = user.FullName,
                phone = user.Phone
            }));
        }
Exemple #17
0
        public async Task <IActionResult> GetActiveUsers()
        {
            // UPDATE USER TRACKING INFORMATION
            userTracker.UpdateUserActivity(Request);

            List <AuthUserViewModel> authModel = new List <AuthUserViewModel>();
            var authUser = new AuthUserViewModel();

            var userList = _context.UserActivity;

            if (userList == null)
            {
                return(NoContent());
            }

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

            foreach (var item in userList)
            {
                DateTime dt1            = Convert.ToDateTime(item.LastActivity);
                DateTime dt2            = DateTime.UtcNow;
                double   totalminutes   = (dt2 - dt1).TotalMinutes;
                int      minutesRounded = (int)Math.Round(totalminutes);

                if (minutesRounded < 30)
                {
                    activeUsers.Add(item.Username);
                }
            }

            foreach (var username in activeUsers)
            {
                var user = await _userManager.FindByNameAsync(username);

                if (user != null)
                {
                    authUser = await GetUser(user);

                    var record = (from c in _context.Avatars
                                  where c.Id == authUser.AvatarId
                                  select c).FirstOrDefault();
                    authUser.AvatarUrl = record.ImageUrl;

                    var record2 = (from c in _context.PlayerStats
                                   where c.userName == authUser.UserName
                                   select c).FirstOrDefault();
                    if (record2 == null)
                    {
                        record2 = new PlayerStat();
                    }

                    authUser.gamesPlayed         = record2.gamesPlayed;
                    authUser.gamesWon            = record2.gamesWon;
                    authUser.questionsRight      = record2.questionsRight;
                    authUser.questionsRightDelay = record2.questionsRightDelay;
                    authUser.questionsWon        = record2.questionsWon;

                    authModel.Add(authUser);
                }
            }

            return(Ok(authModel));
        }
Exemple #18
0
        public async Task <IActionResult> SearchUserByPrimaryUserName([FromQuery] string userName)
        {
            // UPDATE USER TRACKING INFORMATION
            userTracker.UpdateUserActivity(Request);

            List <AuthUserViewModel> authModel = new List <AuthUserViewModel>();

            var friendsList = (from c in _context.Friends
                               where c.primaryUserName == userName
                               select c).Distinct().ToList();

            if (friendsList.Count > 0)
            {
                var authUser = new AuthUserViewModel();

                foreach (var item in friendsList)
                {
                    try
                    {
                        var friend = await _userManager.FindByNameAsync(item.friendUserName);

                        authUser = await GetUser(friend);

                        var record = (from c in _context.Avatars
                                      where c.Id == authUser.AvatarId
                                      select c).FirstOrDefault();

                        var record2 = (from c in _context.PlayerStats
                                       where c.userName == authUser.UserName
                                       select c).FirstOrDefault();
                        if (record2 == null)
                        {
                            record2 = new PlayerStat();
                        }
                        authUser.gamesPlayed         = record2.gamesPlayed;
                        authUser.gamesWon            = record2.gamesWon;
                        authUser.questionsRight      = record2.questionsRight;
                        authUser.questionsRightDelay = record2.questionsRightDelay;
                        authUser.questionsWon        = record2.questionsWon;

                        authUser.AvatarUrl = record.ImageUrl;
                    }
                    catch
                    {
                        authUser.AvatarUrl = "avatar_generic.png";
                    }
                    authUser.FriendId = item.Id;
                    authModel.Add(authUser);
                }

                if (authModel.Count() > 0)
                {
                    return(Ok(authModel));
                }

                //return NotFound("No Registered Users were located!");
                return(NoContent());
            }
            //return NotFound($"No Results Found for Primary User: {userName}");
            return(NoContent());
        }