Ejemplo n.º 1
0
        public HttpMessage <UserWithRole> Login(LoginUser login)
        {
            return(TryCatchResponse(() =>
            {
                if (login == null || string.IsNullOrEmpty(login.Email) || string.IsNullOrEmpty(login.Pass))
                {
                    throw new Exception("Неверные параметры для входа.");
                }

                List <User> users = GetUsers(login.Email);

                if (users == null || users.Count == 0)
                {
                    throw new Exception("Пользователь не найден.");
                }

                User user = GetUserByPass(Password.ComputeHash(login.Pass), users);

                if (user == null || user.D != 0)
                {
                    throw new Exception("Пользователь не найден.");
                }

                UserWithRole result = new UserWithRole()
                {
                    Id = user.Id, Email = user.Email
                };
                result.Roles = GetUserRoles(user.Id);

                return CreateResponseOk(result);
            }));
        }
        public async Task <HttpMessage <IdentityResult> > Login(LoginUser login)
        => await TryCatchResponseAsync(async() =>
        {
            HttpMessage <UserWithRole> postResult = await Json.PostAsync <HttpMessage <UserWithRole>, LoginUser>(AppSettings.AccountService.Server, AppSettings.AccountService.ApiAccount + "/login", login,
                                                                                                                 onError: (e) =>
            {
                postResult = CreateResponseError <UserWithRole>(e);
            });


            UserWithRole user = postResult?.Data;

            if (user == null)
            {
                throw new Exception("Невозможно произвести авторизацию!");
            }

            Principal principal = new Principal(user);
            AuthUserManager.LogIn(principal);
            int siteUserId = SetUserUid(login.Uid, user.Id);

            bool Cms = user.Roles != null && user.Roles.Count > 0 && user.Roles.FirstOrDefault(f => f.Role == 1) != null;

            return(CreateResponseOk(new IdentityResult {
                SiteUserId = siteUserId, Auth = true, Cms = Cms, Token = principal.GetKey(), User = user
            }));
        });
        public async Task <JsonResult> GetUserRoles(String id)
        {
            var res = new List <UserWithRole>();

            var user = await userManager.FindByIdAsync(id);

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



            foreach (var role in roleManager.Roles)
            {
                var model = new UserWithRole()
                {
                    Role = role, UserId = user.Id
                };

                if (await userManager.IsInRoleAsync(user, role.Name))
                {
                    model.roleIsAssign = true;
                }
                else
                {
                    model.roleIsAssign = false;
                }

                res.Add(model);
            }
            return(Json(res));
        }
Ejemplo n.º 4
0
        public void UserWithRole_InstanceWithRole_Ok(Role role)
        {
            const string firstName = "John";
            const string lastName  = "Smith";
            const string email     = "*****@*****.**";

            var source = new UserWithRole
            {
                User = new DbUser
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Email     = email,
                    UserName  = email,
                },
                Role = role
            };

            var destination = AutomapperSingleton.Mapper.Map <ApplicationUser>(source);

            Assert.NotNull(destination);

            Assert.Equal(role, destination.Role);
            Assert.Equal(firstName, destination.FirstName);
            Assert.Equal(lastName, destination.LastName);
            Assert.Equal(email, destination.Email);
            Assert.Equal(email, destination.UserName);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> RegisterUser([FromBody] UserWithRole userRole)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var newUser = new IdentityUser
            {
                UserName = userRole.uEmail,
                Email    = userRole.uEmail,

                PhoneNumber = userRole.uPhoneNumber
            };

            IdentityResult userCreationResult = null;

            try
            {
                userCreationResult = await _userManager.CreateAsync(newUser, userRole.Password);

                if (userCreationResult.Succeeded)
                {
                    //  await _userManager.AddToRoleAsync(newUser, "User");
                    await _signInManager.SignInAsync(newUser, isPersistent : false);
                }
                else
                {
                    //userCreationResult.Errors
                    string msg = "";
                    if (userCreationResult.Errors.Count() > 0)
                    {
                        msg = userCreationResult.Errors.FirstOrDefault().Code + ":" + userCreationResult.Errors.FirstOrDefault().Description;
                    }
                    var model1 = new
                    {
                        StatusCode = 400,
                        result     = "error",
                        message    = "User creation failed! " + msg
                    };
                    return(BadRequest(model1));
                }
            }
            catch (SqlException)
            {
                //return Json(new Response(HttpStatusCode.InternalServerError){Message = "Error communicating with the database, see logs for more details"});
                // return Json("{ 'HttpStatusCode':'InternalServerError','Message':'Error communicating with the database, see logs for more details' }");
            }
            //_context.UserRole.Add(userRole);
            //await _context.SaveChangesAsync();
            var model = new
            {
                StatusCode = 201,
                result     = "success",
                message    = "User has been saved successfully.",
                profile    = userRole
            };

            return(CreatedAtAction("GetUserWithRole", new { id = userRole.uId }, model));
        }
        public UserWithRole GetCurrentUser(int id)
        {
            UserWithRole result = new UserWithRole();

            dataProvider.ExecuteCmd(
                "Users_GetCurrentUser",
                inputParamMapper: parameters =>
            {
                parameters.AddWithValue("@Id", id);
            },
                singleRecordMapper: (reader, resultsSetNumber) =>
            {
                result.Id           = (int)reader["Id"];
                result.FirstName    = (string)reader["FirstName"];
                result.LastName     = (string)reader["LastName"];
                result.Email        = (string)reader["Email"];
                result.UserTypeId   = reader.GetSafeInt32Nullable("UserTypeId");
                result.UserTypeName = (string)reader["UserTypeName"];
                result.Role         = reader.GetSafeInt32Nullable("Role");
                result.AvatarUrl    = reader["AvatarUrl"] as string ?? default(string);
                result.DateCreated  = (DateTime)reader["DateCreated"];
                result.DateModified = (DateTime)reader["DateModified"];
                result.DisplayName  = reader.GetSafeString("DisplayName");
            });
            return(result);
        }
Ejemplo n.º 7
0
        // GET: User
        public async Task <ActionResult> Index()
        {
            var userList = new List <UserWithRole>();
            var users    = context.Users.ToList();

            var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            foreach (var u in users)
            {
                var user = new UserWithRole();
                user.UserName    = u.UserName;
                user.Email       = u.Email;
                user.PhoneNumber = u.PhoneNumber;
                user.Id          = u.Id;

                if (u.Roles.Count == 0)
                {
                    user.Role = "";
                }
                else
                {
                    var role = await RoleManager.FindByIdAsync(u.Roles.First().RoleId);

                    user.Role = role.Name;
                }
                userList.Add(user);
            }
            return(View(userList));
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> Index(string searchTerm, int pageNumber = 1)
        {
            var indexUserModel = new IndexUserModel();

            indexUserModel.Users = new List <UserWithRole>();
            var result = _userManager.Users.AsQueryable();

            if (!String.IsNullOrEmpty(searchTerm))
            {
                result = result.Where(x => x.Email.Contains(searchTerm));
            }
            var applicationUsers = result.ToPagedList(pageNumber, 3);


            foreach (var user in applicationUsers.ToList())
            {
                var temp = await _userManager.GetRolesAsync(user);

                var userwithModel = new UserWithRole();
                userwithModel.User = user;

                userwithModel.RoleName = temp.FirstOrDefault();
                indexUserModel.Users.Add(userwithModel);
            }
            indexUserModel.SearchTerm = searchTerm;
            indexUserModel.tempUser   = applicationUsers;



            return(View(indexUserModel));
        }
        public async Task <IActionResult> PutUserWithRole([FromRoute] string id, [FromBody] UserWithRole userWithRole)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != userWithRole.uId)
            {
                return(BadRequest());
            }
            string msg    = "";
            bool   status = false;

            try
            {
                var user = await _userManager.FindByIdAsync(id);

                user.PhoneNumber = userWithRole.uPhoneNumber;
                var res = await _userManager.UpdateAsync(user);

                if (!res.Succeeded)
                {
                    status = false;
                    msg    = res.Errors.FirstOrDefault().Code + ":" + res.Errors.FirstOrDefault().Description;
                }
                else
                {
                    status = true;
                }


                // await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                msg += ex.Message;
            }
            if (status)
            {
                var model = new
                {
                    result  = "success",
                    message = "User has been updated successfully.",
                    profile = userWithRole
                };
                return(Ok(model));
            }
            else
            {
                var model1 = new
                {
                    StatusCode = 400,
                    result     = "error",
                    message    = "User updation failed! " + msg
                };
                return(BadRequest(model1));
            }
        }
Ejemplo n.º 10
0
        public void UserWithRole_UserIsNull_Ok()
        {
            var source = new UserWithRole();

            Assert.Null(source.User);

            Assert.Throws <ArgumentNullException>(() => AutomapperSingleton.Mapper.Map <ApplicationUser>(source));
        }
Ejemplo n.º 11
0
        public async Task <ApplicationUser> FirstUserWithRoleOrNullAsync(Role role)
        {
            UserWithRole userOrNull = await(from user in GetAllUsersWithRoles()
                                            where user.Role == role
                                            select user)
                                      .FirstOrDefaultAsync();

            return(Mapper.Map <ApplicationUser>(userOrNull));
        }
        public async Task <ApplicationUser> UserByEmailOrNullAsync(string email)
        {
            email.ThrowIfNullOrEmpty(nameof(email));

            UserWithRole user = await _context
                                .Users
                                .SearchBy(email : email)
                                .AttachRoles(_context)
                                .FirstOrDefaultAsync();

            return(_mapper.Map <ApplicationUser>(user));
        }
Ejemplo n.º 13
0
        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            UserWithRole user = await _userRepository.UserWithRoleOrFailAsync(FetchUserId(context.Subject));

            var principal = await _claimsFactory.CreateAsync(user.User);

            var claims = principal
                         .Claims
                         .Where(claim => context.RequestedClaimTypes.Contains(claim.Type))
                         .ToList();

            context.IssuedClaims = AddClaims(claims, user);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a new user
        /// </summary>
        /// <param name="newUser">A UserWithRole object containing the new user details</param>
        /// <returns>Returns true if the user has been created successfully</returns>
        public async Task <bool> CreateUserAsync(UserWithRole newUser)
        {
            IdentityResult result = await _userManager.CreateAsync(newUser.User, newUser.User.PasswordHash);

            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(newUser.User, newUser.Role);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 15
0
        public async Task <UserWithRole> GetUserWithRole(ApplicationUser user)
        {
            var role = await _userManager.GetRolesAsync(user);

            var userWithRole = new UserWithRole
            {
                Id       = user.Id,
                Email    = user.Email,
                UserName = user.UserName,
                Role     = role.Count > 0 ? role[0] : null
            };

            return(userWithRole);
        }
        public async Task <ActionResult> PostCreate([FromBody] UserWithRole newUser)
        {
            if (newUser == null)
            {
                return(BadRequest());
            }

            bool result = await _userMethods.CreateUserAsync(newUser);

            if (result)
            {
                return(StatusCode(201));
            }

            return(StatusCode(500));
        }
        public async Task <ActionResult <UserWithRole> > Put(string id, [FromBody] UserWithRole modifiedUser)
        {
            if (modifiedUser == null)
            {
                return(BadRequest());
            }

            UserWithRole edited = await _userMethods.EditUserAsync(id, modifiedUser);

            if (edited != null)
            {
                return(Ok(edited));
            }

            return(NotFound());
        }
        public async Task <ActionResult <UserWithRole> > Get(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(BadRequest());
            }

            UserWithRole user = await _userMethods.GetUserByIdAsync(id);

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

            return(NotFound());
        }
Ejemplo n.º 19
0
        public ActionResult ModifyRole(string id)
        {
            var u    = context.Users.Where(us => us.Id == id).FirstOrDefault();
            var user = new UserWithRole();

            user.UserName    = u.UserName;
            user.Email       = u.Email;
            user.PhoneNumber = u.PhoneNumber;
            user.Id          = u.Id;

            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem {
                Value = rr.Name.ToString(), Text = rr.Name
            }).ToList();

            ViewBag.Roles = list;
            return(View(user));
        }
Ejemplo n.º 20
0
        public HttpMessage <UserWithRole> LoginCheck(UserUid uu)
        {
            return(TryCatchResponse(() =>
            {
                UserWithRole result = new UserWithRole()
                {
                    Id = uu.User
                };
                User user = GetUser(uu.User);

                if (user != null && user.D == 0)
                {
                    result.Email = user.Email;
                    result.Roles = GetUserRoles(user.Id);
                }
                return CreateResponseOk(result);
            }));
        }
Ejemplo n.º 21
0
        public override async Task UpdateAsync(long id, ApplicationUser data)
        {
            data.ThrowIfNull(nameof(data));
            data.ThrowIfInvalid();

            UserWithRole user = await GetByIdWithRoleOrFailInternalAsync(id);

            user.User.FirstName   = data.FirstName;
            user.User.LastName    = data.LastName;
            user.User.PhoneNumber = data.PhoneNumber;

            if (user.Role != data.Role)
            {
                await ChangeRoleWithoutSaveAsync(id, data.Role);
            }

            await Context.SaveChangesAsync();
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> DeleteUser(UserWithRole userWithRole)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                var result = await _masterRepository.DeleteUser(userWithRole);

                return(new OkResult());
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Master/DeleteUser", ex);
                return(BadRequest(ex.Message));
            }
        }
Ejemplo n.º 23
0
        public IEnumerable <UserWithRole> GetUserWithRole()
        {
            var users = _userManager.Users.ToList();
            List <UserWithRole> url = new List <UserWithRole>();

            foreach (var u in users)
            {
                UserWithRole ur = new UserWithRole();
                ur.uId    = u.Id;
                ur.uEmail = u.Email;

                // if (_userManager.IsInRoleAsync(u, "User").Result)
                ur.Role = "User";
                //else if (_userManager.IsInRoleAsync(u, "Admin").Result)
                //  ur.Role = "Admin";
                url.Add(ur);
            }
            return(url);
        }
Ejemplo n.º 24
0
        public UserWithRole GetCurrentUser(string id)
        {
            var          convertStr = Convert.ToInt32(id);
            UserWithRole result     = new UserWithRole();

            dataProvider.ExecuteCmd(
                "Users_GetCurrentUser",
                inputParamMapper: parameters =>
            {
                parameters.AddWithValue("@Id", convertStr);
            },
                singleRecordMapper: (reader, resultSetNumber) =>
            {
                result.Id         = (int)reader["Id"];
                result.UserName   = (string)reader["UserName"];
                result.Email      = (string)reader["Email"];
                result.UserTypeId = (int)reader["UserTypeId"];
            });
            return(result);
        }
        public async Task <HttpMessage <List <AskQuestion> > > AskQuestions(AskQuestion q)
        => await TryCatchResponseAsync(async() =>
        {
            return(await Task.Run(() =>
            {
                Principal principal = Core.Http.HttpContext.Current.User as Principal;
                string email = principal == null || principal.User == null ? string.Empty : principal.User.Email;
                int userId = principal == null || principal.User == null ? 0 : principal.User.Id;

                bool isAdmin = false;
                if (userId > 0)
                {
                    UserWithRole user = principal.User as UserWithRole;
                    isAdmin = user != null && user.Roles != null && user.Roles.Count > 0 && user.Roles.FirstOrDefault(f => f.Role == 1) != null;
                }

                List <AskQuestion> result = GetAskQuestions(email, isAdmin ? -1 : userId);
                return CreateResponseOk(result);
            }));
        });
Ejemplo n.º 26
0
        /// <summary>
        /// Edits an existing user
        /// </summary>
        /// <param name="id">The id of the user to modify</param>
        /// <param name="modifiedUser">A UserWithRole object containing the modified user details</param>
        /// <returns>Returns the modified user object if successfull</returns>
        public async Task <UserWithRole> EditUserAsync(string id, UserWithRole modifiedUser)
        {
            IdentityUser user = await _userManager.FindByIdAsync(id);

            if (user != null)
            {
                //Update the email
                if (user.Email != modifiedUser.User.Email)
                {
                    user.Email = modifiedUser.User.Email;
                    await _userManager.UpdateAsync(user);
                }

                //The password has been changed
                if (user.PasswordHash != modifiedUser.User.PasswordHash)
                {
                    string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

                    await _userManager.ResetPasswordAsync(user, resetToken, modifiedUser.User.PasswordHash);
                }

                //Role has been changed
                if (!await _userManager.IsInRoleAsync(user, modifiedUser.Role))
                {
                    //Remove old role
                    await _userManager.RemoveFromRoleAsync(user, (await _userManager.GetRolesAsync(user)).FirstOrDefault());

                    //Apply new one
                    await _userManager.AddToRoleAsync(user, modifiedUser.Role);
                }

                return(new UserWithRole()
                {
                    User = user, Role = modifiedUser.Role
                });
            }

            return(null);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Returns a user given its id. Returns null if not found.
        /// </summary>
        /// <param name="id">The id of the user</param>
        public async Task <UserWithRole> GetUserByIdAsync(string id)
        {
            try
            {
                IdentityUser user = await _userManager.FindByIdAsync(id);

                if (user != null)
                {
                    IList <string> roles = await _userManager.GetRolesAsync(user);

                    UserWithRole result = new UserWithRole()
                    {
                        User = user, Role = roles.FirstOrDefault()
                    };

                    return(result);
                }
            }
            catch { }

            return(null);
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> UpdateUser(UserWithRole userWithRole)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                else
                {
                    var result = await _masterRepository.UpdateUser(userWithRole);

                    return(Ok(result));
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Master/UpdateUser", ex);
                return(BadRequest(ex.Message));
            }
            //return Ok();
        }
        public async Task <HttpMessage <UidResult> > Uid(string uid)
        => await TryCatchResponseAsync(async() =>
        {
            return(await Task.Run(() =>
            {
                Principal principal = Core.Http.HttpContext.Current.User as Principal;
                UserWithRole user = null;
                if (principal == null || principal.User == null)
                {
                    UserUid uu = GetUserUid(uid);
                    HttpMessage <UserWithRole> postResult = Json.Post <HttpMessage <UserWithRole>, UserUid>(AppSettings.AccountService.Server, AppSettings.AccountService.ApiAccount + "/loginCheck", uu);
                    user = postResult?.Data;
                }
                else
                {
                    user = (principal.User as UserWithRole);
                }

                if (principal == null && user != null && user.Id != 0)
                {
                    principal = new Principal(user);
                    AuthUserManager.LogIn(principal);
                }

                int userId = user.Id;
                int siteUserId = SetUserUid(uid, userId);

                bool Cms = user.Roles != null && user.Roles.Count > 0 && user.Roles.FirstOrDefault(f => f.Role == 1) != null;
                bool auth = user != null && user.Id != 0;
                string version = this.GetType().Assembly.GetCustomAttribute <AssemblyFileVersionAttribute>().Version;
                return CreateResponseOk(new UidResult()
                {
                    Version = version, Identity = new IdentityResult {
                        SiteUserId = siteUserId, Auth = auth, Cms = Cms, Token = principal == null ? "" : principal.GetKey(), User = user
                    }
                });
            }));
        });
Ejemplo n.º 30
0
        public string AddRoleUser(int RoleID, List <ViewUser> VU)
        {
            try
            {
                //清空旧数据(未来可改进!取非集节省空间)
                Condition where = Condition.Empty;
                where          &= CK.K["RoleID"].Eq(RoleID);
                dbContext.Delete <UserWithRole>(where);

                foreach (ViewUser VP in VU)
                {
                    UserWithRole UR = new UserWithRole();
                    UR.RoleID = RoleID;
                    UR.UserID = VP.UserId;
                    dbContext.Insert <UserWithRole>(UR);
                }

                return("Yes");
            }
            catch (Exception err)
            {
                return(err.Message);
            }
        }