public async Task <User> Add(User user)
        {
            user.UserId = Guid.NewGuid();

            #region HashPassword

            byte[] salt;
            new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);

            var    pbkdf2 = new Rfc2898DeriveBytes(user.Password, salt, 10000);
            byte[] hash   = pbkdf2.GetBytes(20);

            byte[] hashBytes = new byte[36];
            Array.Copy(salt, 0, hashBytes, 0, 16);
            Array.Copy(hash, 0, hashBytes, 16, 20);

            string savedPasswordHash = Convert.ToBase64String(hashBytes);

            user.Password = savedPasswordHash;

            #endregion

            var addedUser = _context.Add(user);
            await _context.SaveChangesAsync();

            user.UserId = addedUser.Entity.UserId;

            return(user);
        }
Beispiel #2
0
        public async Task <UserData> Add(UserData userData)
        {
            var addedData = _context.Add(userData);
            await _context.SaveChangesAsync();

            userData.UserId = addedData.Entity.UserId;

            return(userData);
        }
Beispiel #3
0
        public async Task <IActionResult> Create([Bind("Id,UserName")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(user));
        }
Beispiel #4
0
        public async Task <Post> Add(Post post)
        {
            var date = DateTime.UtcNow.Date;

            post.DateCreated = date;
            var addedPost = _context.Add(post);
            await _context.SaveChangesAsync();

            post.PostId = addedPost.Entity.PostId;
            return(post);
        }
Beispiel #5
0
        public async Task <IActionResult> Create([Bind("PostID,ReleaseDate")] Post post)
        {
            if (ModelState.IsValid)
            {
                _context.Add(post);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(post));
        }
        public async Task <IActionResult> Like(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Post     post     = null;
            PostLike postlike = null;

            try
            {
                var user = await _userManager.GetUserAsync(User);

                post = await _context.Posts
                       .AsNoTracking()
                       .FirstOrDefaultAsync(m => m.ID == id);

                postlike = new PostLike
                {
                    UserID = await _userManager.GetUserIdAsync(user),
                    PostID = post.ID
                };

                if (ModelState.IsValid)
                {
                    if (_context.PostLikes.Contains(postlike))
                    {
                        _context.Remove(postlike);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction(nameof(Index)));
                    }
                    _context.Add(postlike);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(RedirectToAction(nameof(Index)));
        }
Beispiel #7
0
        public async Task <string> Registrate(string name, string password)
        {
            var user = await context.Users.FirstOrDefaultAsync(user => user.Name == name);

            if (!(user is null))
            {
                return(null);
            }

            context.Users.Add(new Models.User {
                Name = name, Password = password
            });
            await context.SaveChangesAsync();

            //https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(jwtSecret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, name)
                }),
                Expires            = DateTime.UtcNow.AddMinutes(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(securityToken));
        }
Beispiel #8
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == model.Email);

                if (user == null)
                {
                    // добавляем пользователя в бд
                    user = new User {
                        UserName = model.Email, Password = model.Password
                    };
                    Role userRole = await _context.Roles.FirstOrDefaultAsync(r => r.Name == "user");

                    if (userRole != null)
                    {
                        user.Role = userRole;
                    }

                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();

                    await Authenticate(user); // аутентификация

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Некорректные логин и(или) пароль");
                }
            }
            return(View(model));
        }
        public async Task <IActionResult> OnPostAsync(string login, string password)
        {
            _context.Users.Add(new User
            {
                Login    = login,
                Password = password
            });
            await _context.SaveChangesAsync();

            return(Redirect(""));
        }
Beispiel #10
0
        //will need to send CREATE the IFormFile
        public async Task <IActionResult> Create([Bind("Id,Description,ImageURL,UserId")] Post post /*, IFormFile upload*/)
        {
            if (ModelState.IsValid)
            {
                post.PostedOn = System.DateTime.Now;
                _context.Add(post);
                await _context.SaveChangesAsync();

                //attempt at saving a file to /images directory
                //var path = Path.Combine("~/images/", System.IO.Path.GetFileName(post.ImageURL)); // this is where we need to figure out path
                ////post.imageurl = pre += post.imageurl
                //upload.CopyToAsync(path); //This is how to save, need to figure out Path
                ////product.ImageName = img;

                System.Console.WriteLine("trying to create");

                return(RedirectToAction(nameof(Index)));
            }
            return(View(post));
        }
Beispiel #11
0
        public async Task <bool> CreateUser(string userName)
        {
            var user = new User(userName);

            try
            {
                await _userRepository.AddAsync(user);

                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                return(false);
            }
        }