public async Task <IActionResult> Put(Guid id, [FromBody] UserBindingModel model)
        {
            if (id.Equals(Guid.Empty) || !id.Equals(model.Id))
            {
                return(BadRequest("Id is empty or not equals to the id in the model"));
            }

            try
            {
                var user = _mapper.Map <UserBindingModel, UserDto>(model);
                await _userService.UpdateAsync(user);

                return(Ok());
            }
            catch (ServiceException aex)
            {
                return(this.StatusCode((int)aex.ErrorCode, aex.Message));
            }
            catch (Exception ex)
            {
                await _logger.Error(ex.Message);

                return(StatusCode(500, "Something went wrong"));
            }
        }
Exemplo n.º 2
0
        public async System.Threading.Tasks.Task Post_ShouldCreateUserAsync()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <User, UserBindingModel>();
            });

            var user = new UserBindingModel
            {
                Email      = "*****@*****.**",
                Username   = "******",
                ClientURL  = "/User/Activate?token=B7BDBF93BA5AE5E2A7DBB926EE8ACD2A",
                IsVerified = false,
                Token      = "B7BDBF93BA5AE5E2A7DBB926EE8ACD2A"
            };
            var options = new DbContextOptionsBuilder <UpstackDbContext>()
                          .UseInMemoryDatabase(databaseName: "Post_ShouldCreateUserAsync")
                          .Options;

            using (var context = new UpstackDbContext(options))
            {
                IUnitOfWork _unitofWork = new UnitOfWork(context);
                _userController = new UserController(_unitofWork, ioptions);
                var result = await _userController.Post(user);

                _unitofWork.Save();


                var createdResult = result as OkResult;

                Assert.Equal(200, createdResult.StatusCode);
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> DeleteEncryptedFilesAsync(long fileCryptId)
        {
            dynamic          ajaxReturn          = new JObject();
            UserBindingModel loggedInUserDetails = new UserBindingModel();

            loggedInUserDetails = this.User.GetLoggedInUserDetails();
            FileCrypt fileCrypt = new FileCrypt();

            fileCrypt.ModifiedBy = loggedInUserDetails.UserId;
            fileCrypt            = await this._fileCryptService.GetEncryptedFileDetailsAsync(fileCryptId);

            bool isFileDeletionSuccess = await this._fileCryptService.DeleteEncryptedFileAsync(fileCrypt);

            if (isFileDeletionSuccess)
            {
                ajaxReturn.Status         = "Success";
                ajaxReturn.GetGoodJobVerb = "Good Work";
                ajaxReturn.Message        = fileCrypt.FileName + " - file delete sucessfully" +
                                            "";
            }
            else
            {
                ajaxReturn.Status  = "Error";
                ajaxReturn.Message = "Error occured while deleting file - " + fileCrypt.FileName +
                                     "";
            }

            return(this.Json(ajaxReturn));
        }
Exemplo n.º 4
0
        public UserViewModel GetElement(UserBindingModel model)
        {
            if (model == null)
            {
                return(null);
            }
            using (var context = new JournalDb())
            {
                var user = context.Users
                           .Include(rec => rec.Role)
                           .Include(rec => rec.Group)
                           .FirstOrDefault(rec => rec.Login == model.Login ||
                                           rec.Id == model.Id);

                return(user != null ?
                       new UserViewModel
                {
                    Id = user.Id,
                    RoleId = user.RoleId,
                    NameRole = user.Role.NameRole,
                    GroupId = user.GroupId.HasValue ? user.GroupId : null,
                    NameGroup = user.GroupId.HasValue ? user.Group.NameGroup : string.Empty,
                    UserName = user.UserName,
                    Login = user.Login,
                    Password = user.Password
                } :
                       null);
            }
        }
Exemplo n.º 5
0
        [ProducesResponseType(500)] //If there was an internal server error
        public async Task <IActionResult> GetUserDetailsAndRolesAsync(string userName)
        {
            var response = new SingleResponse <dynamic>();

            if (userName == null || userName == string.Empty)
            {
                response.DidValidationError = true;
                response.ErrorMessage       = "User Name is incorrect";
                response.DidValidationError = true;
                return(response.ToHttpResponse());
            }

            List <UserRoleBindingModel> userRolesBindingModel = new List <UserRoleBindingModel>();
            UserBindingModel            userBindingModel      = new UserBindingModel();
            User            user  = new User();
            List <UserRole> roles = new List <UserRole>();

            user = await this._authenticationService.GetUserDetailsByUserNameAsync(userName);

            if (user == null)
            {
                response.DidValidationError = true;
                response.ErrorMessage       = "User Name - " + userName + "not found";
                return(response.ToHttpResponse());
            }

            List <UserRole> userRoles = await this._userManagementService.GetUserRolesAsync(user);

            userBindingModel      = this._mapper.Map <UserBindingModel>(user);
            userRolesBindingModel = this._mapper.Map <List <UserRoleBindingModel> >(userRoles);

            response.Model = (userDetails : userBindingModel, userRoles : userRolesBindingModel);

            return(response.ToHttpResponse());
        }
Exemplo n.º 6
0
        public IHttpActionResult UpdateUser(int id, UserBindingModel user)
        {
            using (var ctx = new testEntities())
            {
                var existingUser = ctx.users.Where(s => s.ID == id)
                                   .FirstOrDefault <user>();

                if (existingUser != null)
                {
                    existingUser.NAME        = user.Name;
                    existingUser.FIRST_NAME  = user.FirstName;
                    existingUser.LAST_NAME   = user.LastName;
                    existingUser.EMAIL       = user.Email;
                    existingUser.PASSWORD    = user.Password;
                    existingUser.GENDER      = user.Gender;
                    existingUser.BIRTHDAY    = user.Birthday;
                    existingUser.PHONE       = user.Phone;
                    existingUser.ADDRESS     = user.Address;
                    existingUser.ROLE        = user.Role;
                    existingUser.IS_ENABLE   = user.Status;
                    existingUser.MODIFY_DATE = DateTime.Now;

                    ctx.SaveChanges();
                }
                else
                {
                    return(NotFound());
                }
            }

            return(Ok());
        }
Exemplo n.º 7
0
        public async Task <IActionResult> AddUserAsync(UserBindingModel userBindingModel)
        {
            if (!ModelState.IsValid)
            {
                return(await Task.Run(() => this.PartialView("_AddUser", userBindingModel)));
            }

            dynamic ajaxReturn = new JObject();

            User user = this._mapper.Map <User>(userBindingModel);

            var userCreationSuccess = await this._authenticationService.RegisterUserAsync(user);

            if (userCreationSuccess > 0)
            {
                ajaxReturn.Status         = "Success";
                ajaxReturn.UserId         = userCreationSuccess;
                ajaxReturn.UserName       = userBindingModel.UserName;
                ajaxReturn.GetGoodJobVerb = "Congratulations";
                ajaxReturn.Message        = userBindingModel.UserName + " - user sucessfully created." +
                                            " ";
            }
            else
            {
                ajaxReturn.Status   = "Error";
                ajaxReturn.UserId   = userCreationSuccess;
                ajaxReturn.UserName = userBindingModel.UserName;
                ajaxReturn.Message  = "Error occured while creating user - " + userBindingModel.UserName +
                                      "";
            }

            return(this.Json(ajaxReturn));
        }
Exemplo n.º 8
0
        [HttpPost("")]          // api/token
        public async Task <IActionResult> GenerateToken(UserBindingModel model)
        {
            var user = await this.userManager.FindByNameAsync(model.Username);

            bool isPasswordValid = await userManager.CheckPasswordAsync(user, model.Password);

            if (!isPasswordValid)
            {
                return(Unauthorized());
            }

            var roles = await this.userManager.GetRolesAsync(user);

            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes("supersecretsupersecretsupersecretsupersecret")); //TODO: keep this key NOT HERE!
            var token = new JwtSecurityToken(
                claims: new[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Role, string.Join(", ", roles))
            },
                issuer: "localhost",
                audience: "localhost",
                expires: DateTime.Now + TimeSpan.FromHours(24),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
            string tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            return(Ok(new { Token = tokenString }));
        }
Exemplo n.º 9
0
        // public IEnumerable<Individual> Individuals => _ProjectContext.Individual;
        public async Task <IdentityResult> AddAsync(UserBindingModel user)
        {
            //string error = "";
            //try
            //{

            //}
            //catch(Exception e)
            //{
            //    error=e.Message;
            //}
            //return IdentityResult.Failed();

            var User = new Individual
            {
                UserName     = user.UserName,
                Email        = user.Email,
                Name         = user.FullName,
                Address      = user.Address,
                OrgAddress   = user.OrgAddress,
                Organization = user.Organization,
                Identity     = user.Identity,
                IndivType    = user.IndivType,
                ManagerId    = user.ManagerId,
                Birthday     = user.Birthday,
                DateOfIssue  = user.DateOfIssue,
                PhoneNumber  = user.PhoneNumber,
                PlaceOfIssue = user.PlaceOfIssue,
                RolePersonal = user.RolePersonal
            };
            var result = await _userManager.CreateAsync(User, user.Password);


            return(result);
        }
Exemplo n.º 10
0
        public bool Update(UserBindingModel model)
        {
            try
            {
                using (var libraryDb = new LibraryManagementEntities())
                {
                    // Check first get item
                    var user = libraryDb.Users.FirstOrDefault(s => s.Id == model.Id);
                    if (user == null)
                    {
                        throw new ArgumentNullException("No exist");
                    }
                    user.Name        = model.Name;
                    user.Account     = model.Account;
                    user.Password    = model.Password;
                    user.Gender      = model.Gender;
                    user.DayOfBirth  = model.DayOfBirth;
                    user.Address     = model.Address;
                    user.PhoneNumber = model.PhoneNumber;
                    //user.PositionId = model.PositionId;
                    //user.UnitId = model.UnitId;
                    //user.RoleId = model.RoleId;
                    user.Email = model.Email;

                    libraryDb.SaveChanges();
                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <ActionResult> Login([FromBody] UserBindingModel userBindingModel)
        {
            var userFromDb = await this.context.Users.FirstOrDefaultAsync(user => user.Username == userBindingModel.Username &&
                                                                          user.Password == userBindingModel.Password);

            if (userFromDb == null)
            {
                return(this.BadRequest("Username or Password is invalid."));
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(this.jwtSettings.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userFromDb.Username)
                }),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(this.Ok(token));
        }
Exemplo n.º 12
0
        [ProducesResponseType(500)] //If there was an internal server error
        public async Task <IActionResult> RegisterUserAsync([FromBody] UserBindingModel userBindingModel)
        {
            var errors   = new Dictionary <string, string>();
            var response = new SingleCreatedResponse <dynamic>();

            User user = await this._authenticationService.GetUserDetailsByUserNameAsync(userBindingModel.UserName);

            if (user != null)
            {
                errors.Add("UserName", "User Name " + userBindingModel.UserName + " already exists");
                response.ErrorMessage       = "Validation error occured";
                response.DidValidationError = true;
                response.Model = errors;
                return(response.ToHttpResponse());
            }

            user = this._mapper.Map <User>(userBindingModel);

            var userCreationSuccess = await this._authenticationService.RegisterUserAsync(user);

            if (userCreationSuccess > 0)
            {
                UserAuthenticationBindingModel userAuthentication = new UserAuthenticationBindingModel();

                userAuthentication.UserName = userBindingModel.UserName;

                response.Message = "User " + userAuthentication.UserName
                                   + " created successfully. Redirecting to Home screen.";
                this.CreateJWTToken(response, userAuthentication);
            }

            return(response.ToHttpResponse());
        }
Exemplo n.º 13
0
        public async Task <IActionResult> UpdateUserProfile()
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var client = new HttpClient();

            client.SetBearerToken(accessToken);

            var userEmail = GetClaimValue("email");

            var userData = new UserBindingModel
            {
                Email               = userEmail,
                IsActive            = true,
                IsPasswordTemporary = false
            };

            var json        = JsonConvert.SerializeObject(userData, Formatting.Indented);
            var buffer      = System.Text.Encoding.UTF8.GetBytes(json);
            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = client.PostAsync("http://localhost:5000/api/Account/Update", byteContent).Result;
            var result   = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                ViewBag.Json = result;
                return(View("json"));
            }
            return(RedirectToAction("Error", "Home"));
        }
Exemplo n.º 14
0
        public HttpResponseMessage Login([FromBody] LoginBindingModel loginModel)
        {
            try
            {
                using (TLC_DBEntities entities = new TLC_DBEntities())
                {
                    tbUser tbUserModel = entities.tbUsers.Where(user => user.vcUserName == loginModel.UserName && user.vcPassword == loginModel.Password).FirstOrDefault();

                    if (tbUserModel != null)
                    {
                        string baseToken    = loginModel.UserName + ':' + loginModel.Password;
                        string encodedToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(baseToken));

                        UserBindingModel userModel = new UserBindingModel
                        {
                            Token     = encodedToken,
                            UserKey   = tbUserModel.kUser.ToString(),
                            UserName  = tbUserModel.vcUserName.ToString(),
                            ClientKey = tbUserModel.kLookClient.ToString()
                        };

                        return(Request.CreateResponse(HttpStatusCode.OK, userModel));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid username or password"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
Exemplo n.º 15
0
 private User CreateModel(User user, UserBindingModel model)
 {
     user.Email    = model.Email;
     user.Login    = model.Login;
     user.Password = model.Password;
     return(user);
 }
Exemplo n.º 16
0
        public async Task <IActionResult> DeleteUserAsync(UserBindingModel userBindingModel)
        {
            dynamic ajaxReturn = new JObject();

            User user = this._mapper.Map <User>(userBindingModel);

            var userCreationSuccess = await this._userManagementService.DeleteUserAsync(user);

            if (userCreationSuccess)
            {
                ajaxReturn.Status         = "Success";
                ajaxReturn.UserName       = userBindingModel.UserName;
                ajaxReturn.GetGoodJobVerb = "Good Work";
                ajaxReturn.Message        = userBindingModel.UserName + " - user deleted sucessfully" +
                                            " ";
            }
            else
            {
                ajaxReturn.Status   = "Error";
                ajaxReturn.UserId   = userCreationSuccess;
                ajaxReturn.UserName = userBindingModel.UserName;
                ajaxReturn.Message  = "Error occured while deleting user - " + userBindingModel.UserName +
                                      "";
            }

            return(this.Json(ajaxReturn));
        }
Exemplo n.º 17
0
        public bool Create(UserBindingModel model)
        {
            try
            {
                using (var libraryDb = new LibraryManagementEntities())
                {
                    // check duplicated
                    var currentUser = libraryDb.Users.FirstOrDefault(s => s.Name == model.Name);
                    if (currentUser != null)
                    {
                        throw new ArgumentNullException();
                    }

                    // Check account for user
                    currentUser = libraryDb.Users.FirstOrDefault(s => s.Account == model.Account);
                    if (currentUser != null)
                    {
                        throw new ArgumentNullException();
                    }

                    // Insert db
                    var userInfo = _entityMapper.Map <UserBindingModel, User>(model);
                    libraryDb.Users.Add(userInfo);
                    libraryDb.SaveChanges();

                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 18
0
        public IActionResult Signup(UserBindingModel model)
        {
            UserService service = new UserService(Data.Data.Context);

            service.RegisterUser(model);
            return(View("Home", "Index"));
        }
Exemplo n.º 19
0
        async public Task <ActionResult> EditUser([Bind] UserBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorList = ModelState.Values.SelectMany(m => m.Errors)
                                .Select(e => e.ErrorMessage)
                                .ToList();

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(errorList));
            }
            if (UserManager.IsInRole(model.Id, "Admin"))
            {
                return(new HttpStatusCodeResult(401, "Cannot edit admins"));
            }

            (HttpStatusCodeResult result, ApplicationUser user) = await UserHandler.EditUser(model);

            if (result.StatusCode == 200)
            {
                return(PartialView("_UserRow", user));
            }
            else
            {
                return(result);
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> LoadEditUserPartialView(string userName)
        {
            dynamic ajaxReturn = new JObject();
            List <UserRoleBindingModel> userRolesBindingModel = new List <UserRoleBindingModel>();
            UserBindingModel            userBindingModel      = new UserBindingModel();
            User            user  = new User();
            List <UserRole> roles = new List <UserRole>();

            roles = await this._authenticationService.GetRolesAsync();

            user = await this._authenticationService.GetUserDetailsByUserNameAsync(userName);

            List <UserRole> userRoles = await this._userManagementService.GetUserRolesAsync(user);

            var rolesNotMapped = (from r in roles
                                  join ur in userRoles on r.RoleName equals ur.RoleName
                                  into result
                                  where result.Count() == 0
                                  select r).ToList();

            if (rolesNotMapped != null && rolesNotMapped.Count > 0)
            {
                userRoles.AddRange(rolesNotMapped);
            }

            userBindingModel      = this._mapper.Map <UserBindingModel>(user);
            userRolesBindingModel = this._mapper.Map <List <UserRoleBindingModel> >(userRoles);
            return(await Task.Run(() => this.PartialView("_EditUser", (userBindingModel, userRolesBindingModel))));
        }
Exemplo n.º 21
0
 public void CreateOrUpdate(UserBindingModel model)
 {
     using (var context = new DatabaseContext())
     {
         User user = context.Users.FirstOrDefault(rec =>
                                                  rec.Login == model.Login && rec.ID != model.ID);
         if (user != null)
         {
             throw new Exception("Поставщик уже зарегристрирован");
         }
         if (model.ID.HasValue)
         {
             user = context.Users.FirstOrDefault(rec => rec.ID == model.ID);
             if (user == null)
             {
                 throw new Exception("Пользователь не найден");
             }
         }
         else
         {
             user = new User();
             context.Users.Add(user);
         }
         user.FullName     = model.FullName;
         user.RoleID       = model.RoleID;
         user.Login        = model.Login;
         user.Password     = model.Password;
         user.CreationDate = model.CreationDate;
         context.SaveChanges();
     }
 }
Exemplo n.º 22
0
 public void Insert(UserBindingModel model)
 {
     using (var context = new NewsBlogDatabase())
     {
         context.Users.Add(CreateModel(model, new Users()));
         context.SaveChanges();
     }
 }
Exemplo n.º 23
0
 public void Insert(UserBindingModel model)
 {
     using (var context = new UrskiyPeriodDatabase())
     {
         context.Users.Add(CreateModel(new User(), model));
         context.SaveChanges();
     }
 }
 public IActionResult SaveUser(UserBindingModel model)
 {
     if (false == ModelState.IsValid)
     {
         return(View(model));
     }
     return(RedirectToAction("Success"));
 }
Exemplo n.º 25
0
        public async Task <IActionResult> EditUser(UserBindingModel model)
        {
            IIndividualResponsitory individual = new IndividualResponsitory(_userManager, _context);
            var user = individual.GetIndividualsByName(model.UserName);
            await individual.EditAsync(user.Id, model);

            return(View("Edit"));
        }
Exemplo n.º 26
0
        public IActionResult Signup(HttpResponse response, UserBindingModel model)
        {
            UserService.Register(this.db, model);

            Redirect(response, "/home/index");

            return(null);
        }
Exemplo n.º 27
0
 public void Insert(UserBindingModel model)
 {
     using (var context = new JournalDb())
     {
         context.Users.Add(CreateModel(model, new User()));
         context.SaveChanges();
     }
 }
Exemplo n.º 28
0
        public IActionResult EditUser(UserBindingModel userModel, [FromRoute] int userId)
        {
            var user             = _mapper.Map <User>(userModel);
            var updatedUser      = _userService.EditUser(user, userId);
            var updatedUserModel = _mapper.Map <UserDetailsApiModel>(updatedUser);

            return(Ok(updatedUserModel));
        }
Exemplo n.º 29
0
        public async Task <IActionResult> Delete(UserBindingModel model)
        {
            var user = await this.userManager.FindByNameAsync(model.Username);

            await this.userManager.DeleteAsync(user);

            return(RedirectToAction("Index"));
        }
 public IActionResult Index(UserBindingModel model)
 {
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     return(RedirectToAction(nameof(Success)));
 }
Exemplo n.º 31
0
        public ActionResult EditProfile()
        {
            if (this.User.Identity.IsAuthenticated)
            {
                UserBindingModel ubm = new UserBindingModel();

                return View(ubm);
            }
            else
            {
                return RedirectToAction("Login", "Account");
            }
        }
Exemplo n.º 32
0
        public ActionResult EditProfile(UserBindingModel model)
        {
            string userId = this.User.Identity.GetUserId();
            var user = this.Data.Users.All()
                .FirstOrDefault(u => u.Id == userId);

            user.Email = model.Username;
            user.UserName = model.Username;

            this.Data.SaveChanges();

            return RedirectToAction("Index", "Home");
        }