コード例 #1
0
        public async Task <User> CreateUser(string username, string password, string firstName, string lastName)
        {
            // validation
            if (string.IsNullOrWhiteSpace(password))
            {
                return(null);
            }

            if (_dbContext.Users.Any(x => x.Username == username))
            {
                return(null);
            }

            byte[] passwordHash, passwordSalt;
            PasswordMethods.CreatePasswordHash(password, out passwordHash, out passwordSalt);

            var user = new User
            {
                FirstName    = firstName,
                LastName     = lastName,
                Username     = username,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Role         = Role.Admin,
                Token        = string.Empty
            };

            await _dbContext.Users.AddAsync(user);


            return(user);
        }
コード例 #2
0
        public async Task <User> AuthenticateAsync(string username, string password)
        {
            var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Username == username);

            if (user == null)
            {
                return(null);
            }

            if (!PasswordMethods.VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes("obligatory secret");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new []
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString()),
                    new Claim(ClaimTypes.Role, user.Role)
                }),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            return(user.WithoutPassword());
        }
コード例 #3
0
        public async Task <ActionResult <UserDTO> > Post([FromBody] UserRegisterModel userRegisterModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Not all of the needed information is supplied."));
            }

            userRegisterModel.Password = PasswordMethods.GeneratePassword(true, true, true, true, 16);

            var savedUser = await UnitOfWork.UsersRepository.CreateUser(userRegisterModel.Username, userRegisterModel.Password,
                                                                        userRegisterModel.FirstName, userRegisterModel.LastName);

            if (savedUser == null)
            {
                return(BadRequest("Error saving user to DB"));
            }

            var sendEmailResult = EmailMethods.SendEmail(userRegisterModel.Username, userRegisterModel.FirstName,
                                                         userRegisterModel.LastName, userRegisterModel.Password);

            if (!sendEmailResult)
            {
                BadRequest("Email is not sent!");
            }

            await UnitOfWork.SaveChangesAsync();

            var userMapResult = Mapper.Map <User, UserDTO>(savedUser);

            return(Created(string.Empty, userMapResult));
        }
コード例 #4
0
 public ActionResult ChangePassword(string oldpass,string newpass1,string newpass2)
 {
     if (Request.IsAuthenticated)
     {
         if(newpass1==newpass2)
         {
             PasswordMethods pass = new PasswordMethods();
             UserData userData = UserData.GetUserData();
             User user = new User();
             user.username = User.Identity.Name;
             user.password = pass.Hash(oldpass);
             if (userData.LoginUser(user))
             {
                 userData.ChangePassword(User.Identity.Name, pass.Hash(newpass1));
                 TempData["Message"] = "Şifreniz başarıyla değiştirildi";
                 return RedirectToAction("Index");
             }
             else
             {
                 TempData["Message"] = "Eski şifrenizi yanlış girdiniz";
                 return RedirectToAction("Index");
             }
         }
         else
         {
             TempData["Message"] = "Şifreler birbiriyle uyuşmuyor";
             return RedirectToAction("Index");
         }
     }
     else
     {
         TempData["Message"] = "Giriş yapmamışsınız";
         return RedirectToAction("Index");
     }
 }
コード例 #5
0
 public ActionResult AddUser(string username, string password, string role)
 {
     RolesData rolesData = RolesData.GetRolesData();
     if (Request.IsAuthenticated)
     {
         if(User.IsInRole("admin"))
         {
             UserData userData = UserData.GetUserData();
             if (!userData.CheckIfExists(username))
             {
                 User user = new Entities.User();
                 user.username = username;
                 PasswordMethods pass = new PasswordMethods();
                 user.password = pass.Hash(password);
                 userData.AddUser(user);
                 rolesData.AddUser(username, role);
                 TempData["Message"] = "Kullanıcı başarıyla eklendi";
                 return RedirectToAction("Index","Home");
             }
             else
             {
                 TempData["Message"] = "Kullanıcı zaten var";
                 return RedirectToAction("Index","Home");
             }
         }
         else
         {
            TempData["Message"] = "Yeterli yetkiniz yok";
             return RedirectToAction("Index", "Home");
         }
     }
     else
     {
         return RedirectToAction("Index", "Home");
     }
 }
コード例 #6
0
        public ActionResult EditUser(string oldname, string newname = "",string password = "", string role = "")
        {
            RolesData rolesData = RolesData.GetRolesData();
            if (Request.IsAuthenticated)
            {
                if (User.IsInRole("admin"))
                {
                    UserData userData = UserData.GetUserData();
                    PasswordMethods pass = new PasswordMethods();
                    if (password != "")
                    {
                        password = pass.Hash(password);
                        userData.ChangePassword(newname, password);
                    }
                    if (newname != "")
                    {
                        rolesData.ChangeUserName(oldname, newname);
                        userData.ChangeName(oldname, newname);
                    }
                    if (role != "")
                    {
                        if (newname != "")
                        {
                            rolesData.SetRole(newname, role);
                        }
                        else
                        {
                            rolesData.SetRole(oldname, role);
                        }
                    }

                    return View("Index");
                }
                else
                {
                    TempData["Message"] = "Yeterli yetkiniz yok";
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
コード例 #7
0
        public ActionResult Login(string username, string remember, string password)
        {
            User user = new User();
            user.username = username;
            PasswordMethods pass = new PasswordMethods();
            user.password = pass.Hash(password);

            UserData userData = UserData.GetUserData();
            if (Request.IsAuthenticated)
            {
                TempData["Message"] = "Zaten giriş yapmışsınız";
                return RedirectToAction("Index");
            }
            else
            {
                if (userData.LoginUser(user))
                {
                    if (remember == "on")
                    {
                        HttpCookie hc = new HttpCookie("username");
                        hc.Value = username;
                        Response.Cookies.Add(hc);
                    }
                    else if (remember == null)
                    {
                        if (Request.Cookies["username"] != null)
                        {
                            HttpCookie hc = new HttpCookie("username");
                            hc.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(hc);
                        }
                    }

                    RolesData rolesData = RolesData.GetRolesData();
                    string role = rolesData.GetRole(user.username);

                    System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(
                        1,
                        user.username,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        role,
                        System.Web.Security.FormsAuthentication.FormsCookiePath);

                    string EncryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);

                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedTicket);
                    cookie.HttpOnly = true;
                    Response.Cookies.Add(cookie);

                    //System.Web.Security.FormsAuthentication.SetAuthCookie(user.username, false);
                    TempData["Message"] = "Giriş başarılı";
                    return RedirectToAction("Index");
                }
                else
                {
                    TempData["Message"] = "Yanlış kullanıcı adı veya şifre";
                    return RedirectToAction("Index");
                }
            }
        }