Exemple #1
0
        public static MvcHtmlString GetRoleName(this HtmlHelper html, string id)
        {
            AppRoleManager mgr
                = HttpContext.Current.GetOwinContext().GetUserManager <AppRoleManager>();

            return(new MvcHtmlString(mgr.FindByIdAsync(id).Result.Name));
        }
Exemple #2
0
 public AccountController()
 {
     _userManager      = new AppUserManager();
     _userRoleManager  = new UserRoleManager();
     _roleManager      = new AppRoleManager();
     _lastVisitManager = new LastVisitManager();
 }
        public async Task <IHttpActionResult> RemoveFromRole(string userId, string roleId)
        {
            var appUser = await AppUserManager.FindByIdAsync(userId);

            if (appUser == null)
            {
                ModelState.AddModelError("", "User does not exist");
                return(BadRequest(ModelState));
            }

            var role = await AppRoleManager.FindByIdAsync(roleId);

            if (role == null)
            {
                ModelState.AddModelError("", "Role does not exist");
                return(BadRequest(ModelState));
            }

            var result = await AppUserManager.RemoveFromRoleAsync(userId, role.Name);

            if (!result.Succeeded)
            {
                GetIdentityErrorResult(result);
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Exemple #4
0
        public void PerformInitialSetup(AppIdentityDbContext context)
        {
            var userMgr = new AppUserManager(new UserStore <AppUser>(context));
            var roleMgr = new AppRoleManager(new RoleStore <AppRole>(context));

            const string roleName = "Administrators";
            const string userName = "******";
            const string password = "******";
            const string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new AppRole(roleName));
            }

            var user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new AppUser {
                    UserName = userName, Email = email
                },
                               password);
                user = userMgr.FindByName(userName);
            }

            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
            }
        }
        public async Task <HttpResponseMessage> GetAllUserConfigDelegation(HttpRequestMessage request, int page, int pageSize, string groupID, string[] lstFullName)
        {
            Func <HttpResponseMessage> func = () =>
            {
                if (string.IsNullOrEmpty(groupID))
                {
                    return(request.CreateErrorResponse(HttpStatusCode.BadRequest, nameof(groupID) + MessageSystem.NoValues));
                }
                var groupleaderID  = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                var convertGroupID = Int32.Parse(groupID);
                var user           = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID)) && x.GroupId == convertGroupID).ToList();
                var model          = _configDelegationService.GetListUserConfigDelegationFilter(groupID, lstFullName).Where(x => !x.UserId.Equals(user[0].Id));
                var data           = model.Skip((page - 1) * pageSize).Take(pageSize);
                var paginationSet  = new PaginationSet <ConfigDelegationModel>()
                {
                    Items     = data,
                    PageIndex = page,
                    TotalRows = model.Count(),
                    PageSize  = pageSize
                };
                return(request.CreateResponse(HttpStatusCode.OK, paginationSet));
            };

            return(await CreateHttpResponse(request, func));
        }
Exemple #6
0
        protected override void Seed(Infrastructure.Database.AppIdentityDbContext context)
        {
            AppUserManager userManager = new AppUserManager(new UserStore <AppUser>(context));
            AppRoleManager roleManager = new AppRoleManager(new RoleStore <AppRole>(context));
            string         roleName    = "Administrators";
            string         name        = "Admin";
            string         password    = "******";
            string         email       = "*****@*****.**";

            if (!roleManager.RoleExists(roleName))
            {
                roleManager.Create(new AppRole(roleName));
            }
            AppUser user = userManager.FindByName(name);

            if (user == null)
            {
                userManager.Create(new AppUser
                {
                    Email    = email,
                    UserName = name
                }, password);
                user = userManager.FindByName(user.UserName);
            }
            if (!userManager.IsInRole(user.Id, roleName))
            {
                userManager.AddToRole(user.Id, user.UserName);
            }
            foreach (AppUser dbUser in userManager.Users)
            {
                dbUser.City    = Cities.PARIS;
                dbUser.Country = Countries.FRANCE;
            }
            context.SaveChanges();
        }
        public void PerformInitialSetup(AppIdentityDbContext context)
        {
            var userManager = new AppUserManager(new UserStore <User>(context));
            var roleManager = new AppRoleManager(new RoleStore <Role>(context));
            var role1       = new Role {
                Name = "admin"
            };
            var role2 = new Role {
                Name = "user"
            };

            roleManager.Create(role1);
            roleManager.Create(role2);
            var admin = new User {
                Email = "*****@*****.**", UserName = "******"
            };
            string password = "******";
            var    result   = userManager.Create(admin, password);

            if (result.Succeeded)
            {
                userManager.AddToRole(admin.Id, role1.Name);
                userManager.AddToRole(admin.Id, role2.Name);
            }
        }
Exemple #8
0
        protected override void Seed(LittleBlog.DAL.Persistence.Context context)
        {
            var userManager = new AppUserManager(new UserStore <AppUser>(context));

            var roleManager = new AppRoleManager(new RoleStore <AppRole>(context));

            roleManager.Create(new AppRole {
                Name = "User"
            });
            roleManager.Create(new AppRole {
                Name = "Admin"
            });

            var adminName     = "*****@*****.**";
            var adminPassword = "******";

            var user = new AppUser()
            {
                UserName = adminName,
                Email    = adminName
            };

            userManager.Create(user, adminPassword);
            userManager.AddToRole(user.Id, "Admin");
        }
Exemple #9
0
        private static void RegisterTypes(ContainerBuilder builder, IAppBuilder app)
        {
            // Identity specific
            builder.RegisterType <TicketDataFo‌​rmat>()
            .As <ISecureDataFormat <AuthenticationTicket> >();
            builder.RegisterType <TicketSerializer>()
            .As <IDataSerializer <AuthenticationTicket> >();
            builder.Register(c => app.GetDataProtectionProvider().Create("ASP.NET Identity"))
            .As <IDataProtector>();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication);

            builder.RegisterType <AppDbContext>()
            .AsSelf();
            builder.Register <IDbContext>(c => c.Resolve <AppDbContext>());
            builder.RegisterType <UserStore <Client> >()
            .As <IUserStore <Client> >();
            builder.RegisterType <UserStore <Santa> >()
            .As <IUserStore <Santa> >();
            builder.Register(c => AppUserManager <User> .Create(c.Resolve <IDataProtector>(), c.Resolve <AppDbContext>()));
            builder.Register(c => AppUserManager <Client> .Create(c.Resolve <IDataProtector>(), c.Resolve <AppDbContext>()));
            builder.Register(c => AppUserManager <Santa> .Create(c.Resolve <IDataProtector>(), c.Resolve <AppDbContext>()));
            builder.Register(c => AppRoleManager.Create(c.Resolve <AppDbContext>()));

            builder.RegisterType <OrdersService>()
            .AsSelf();
            builder.RegisterType <SantaOrdersService>()
            .AsSelf();
            builder.RegisterType <SantasService>()
            .AsSelf();
            builder.RegisterType <StaticService>()
            .AsSelf();
        }
Exemple #10
0
        public async Task <IHttpActionResult> GetApplicationUser(string id)
        {
            var user = await AppUserManager.FindByIdAsync(id);

            var coachRole = AppRoleManager.FindByName("Coach");

            if (user == null)
            {
                return(NotFound());
            }
            var response = new GetUserResponse
            {
                Item = new UserHttpResponse
                {
                    Id        = user.Id,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    IsCoach   = user.Roles.Any(j => j.RoleId == coachRole.Id),
                    Email     = user.UserName,
                    RoleIds   = user.Roles.Select(i => i.RoleId).ToList(),
                    Timezone  = user.Timezone,
                    CVLink    = user.CVLink,
                    Webex     = user.Webex,
                },
            };

            response.UsageCount = AppDb.CoachingPrograms
                                  .Count(i =>
                                         i.Coach.Id == id ||
                                         i.Coachee.Id == id);
            return(Ok(response));
        }
Exemple #11
0
        private async Task SeedAsync(AppContext context)
        {
            var user = new ShopUser()
            {
                UserName  = AdminUser.UserName,
                Email     = AdminUser.Email,
                FirstName = AdminUser.FirstName,
                LastName  = AdminUser.LastName,
            };
            var role = new AppRole(RoleNames.Admin);

            ///
            UserStore <ShopUser> uStore = new UserStore <ShopUser>(context);
            var userManager             = new AppUserManager(uStore);
            RoleStore <AppRole> rStore  = new RoleStore <AppRole>(context);
            var roleManager             = new AppRoleManager(rStore);
            var adminRole = await roleManager.FindByNameAsync(RoleNames.Admin);

            if (adminRole == null)
            {
                adminRole = new AppRole(RoleNames.Admin);
                await roleManager.CreateAsync(adminRole);
            }

            // await roleManager.CreateAsync(new AppRole(RoleNames.Admin));
            var result = await userManager.CreateAsync(user, AdminUser.Password);

            user = await userManager.FindByNameAsync(AdminUser.UserName);

            await userManager.AddToRoleAsync(user.Id, RoleNames.Admin);
        }
Exemple #12
0
        public string CreateCashier(Account us)
        {
            var user = db.Users.FirstOrDefault(u => u.Id == us.Id);

            if (user != null)
            {
                AppUserManager userMgr = new AppUserManager(new UserStore <AppUser>(db));
                AppRoleManager roleMgr = new AppRoleManager(new RoleStore <UserRoles>(db));

                var usr = userMgr.Users.FirstOrDefault(u => u.Id == us.Id);

                if (usr != null)
                {
                    userMgr.RemoveFromRole(usr.Id, "user");
                    IdentityResult role = userMgr.AddToRole(user.Id, "cashier");

                    return(null);
                }
                else
                {
                    return("Пользователь с такой ролью не найден");
                }
            }
            else
            {
                return("Пользователь не найден");
            }
        }
Exemple #13
0
        protected override void Seed(AppIdentityDbContext context)
        {
            var userManager = new AppUserManager(new UserStore <AppUser>(context));
            var roleManager = new AppRoleManager(new RoleStore <AppRole>(context));

            if (!roleManager.RoleExists(SuperAdminRoleName))
            {
                roleManager.Create(new AppRole(SuperAdminRoleName));
            }

            var user = userManager.FindByName(SuperAdminUserName);

            if (user == null)
            {
                userManager.Create(new AppUser {
                    UserName = SuperAdminUserName, Email = SuperAdminEmail
                }, SuperAdminPassword);
                user = userManager.FindByName(SuperAdminUserName);
            }

            if (!userManager.IsInRole(user.Id, SuperAdminRoleName))
            {
                userManager.AddToRole(user.Id, SuperAdminRoleName);
            }

            context.SaveChanges();
        }
        protected override void Seed(AppContext context)
        {
            var roleStore   = new RoleStore <Role>(context);
            var roleManager = new AppRoleManager(roleStore);

            roleManager.Create(new Role()
            {
                Name = "admin"
            });
            roleManager.Create(new Role()
            {
                Name = "user"
            });

            var  userStore   = new UserStore <User>(context);
            var  userManager = new AppUserManager(userStore);
            User admin       = new User()
            {
                UserName = "******", LastEnter = DateTime.Now, UserBasket = new UserBasket()
            };

            //TODO
            userManager.Create(admin, "1Admin!");
            userManager.AddToRole(admin.Id, "admin");
        }
Exemple #15
0
        private void SetDefaultAccountAndRole(Practice.Domain.Concrete.AppIdentityDbContext context)
        {
            AppUserManager userMgr = new AppUserManager(new UserStore <AppUser>(context));
            AppRoleManager roleMgr = new AppRoleManager(new RoleStore <AppRole>(context));

            string roleName  = "Administrators";
            string userName  = "";
            string password  = "";
            string email     = "@example.com";
            int    CityID    = 1;
            int    CountryID = 1;

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new AppRole(roleName));
            }

            AppUser user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new AppUser {
                    UserName = userName, Email = email, CityID = CityID, CountryID = CountryID
                },
                               password);
                user = userMgr.FindByName(userName);
            }

            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
            }

            context.SaveChanges();
        }
Exemple #16
0
        protected override void Seed(AppIdentityDbContext context)
        {
            //seed admin
            AppUserManager userMgr = new AppUserManager(new UserStore <User>(context));
            AppRoleManager roleMgr = new AppRoleManager(new RoleStore <Role>(context));

            string roleName = "Admin";

            string userName = "******";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new Role(roleName));
            }

            User user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new User {
                    UserName = userName, Email = email
                }, password);
                user = userMgr.FindByName(userName);
            }

            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
            }

            base.Seed(context);
        }
Exemple #17
0
        public void PerformInitialSetup(Store context)
        {
            AppUserManager userMgr = new AppUserManager(new UserStore <AppUser>(context));
            AppRoleManager roleMgr = new AppRoleManager(new RoleStore <AppRole>(context));

            string roleName = "Administrators";
            string userName = "******";
            string password = "******";
            string email    = "*****@*****.**";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new AppRole(roleName));
            }

            AppUser user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new AppUser {
                    UserName = userName, Email = email
                },
                               password);
                user = userMgr.FindByName(userName);
            }

            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
            }
        }
 public HttpResponseMessage Create(HttpRequestMessage request, ApplicationRoleViewModel applicationRoleViewModel)
 {
     if (ModelState.IsValid)
     {
         var newAppRole = new AppRole();
         var identity = (ClaimsIdentity)User.Identity;
         IEnumerable<Claim> claims = identity.Claims;
         newAppRole.UpdateApplicationRole(applicationRoleViewModel);
         try
         {
             AppRoleManager.Create(newAppRole);
             Log log = new Log()
             {
                 AppUserId = claims.FirstOrDefault().Value,
                 Content = Notification.CREATE_ROLE,
                 Created = DateTime.Now
             };
             _logService.Create(log);
             _logService.Save();
             return request.CreateResponse(HttpStatusCode.OK, applicationRoleViewModel);
         }
         catch (NameDuplicatedException dex)
         {
             return request.CreateErrorResponse(HttpStatusCode.BadRequest, dex.Message);
         }
     }
     else
     {
         return request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
     }
 }
Exemple #19
0
        public async Task <HttpResponseMessage> GetAllPaging(HttpRequestMessage request, int page, int pageSize, string roleName, string userID)
        {
            Func <HttpResponseMessage> func = () =>
            {
                if (roleName.Equals(CommonConstants.GroupLead))
                {
                    var lstGr     = _groupService.GetAllGroup();
                    var listGroup = Mapper.Map <List <Group>, List <GroupViewModel> >(lstGr);
                    List <GroupViewModel> listGroupTmp = new List <GroupViewModel>();
                    var users = AppUserManager.Users.Where(x => x.Id.Equals(userID)).ToList();
                    foreach (var item in listGroup)
                    {
                        var user = users.Where(x => x.GroupId == item.ID).FirstOrDefault();
                        if (user != null)
                        {
                            item.GroupLeadID      = user != null ? user.Id : CommonConstants.StringEmpty;
                            item.GroupLead        = user != null ? user.FullName : CommonConstants.DefaultGroupLeader;
                            item.GroupLeadAccount = user != null ? user.UserName : CommonConstants.DefaultGroupLeader;
                            listGroupTmp.Add(item);
                        }
                    }
                    int totalRow = listGroupTmp.Count;
                    PaginationSet <GroupViewModel> pagedSet = new PaginationSet <GroupViewModel>()
                    {
                        PageIndex = page,
                        PageSize  = pageSize,
                        TotalRows = totalRow,
                        Items     = listGroupTmp,
                    };
                    return(request.CreateResponse(HttpStatusCode.OK, pagedSet));
                }
                else
                {
                    var lstGr     = _groupService.GetAllGroup();
                    var listGroup = Mapper.Map <List <Group>, List <GroupViewModel> >(lstGr);
                    int totalRow  = listGroup.Count;

                    listGroup = listGroup.Where(x => !x.Name.Equals("SuperAdmin")).Skip((page - 1) * pageSize).Take(pageSize).ToList();
                    var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
                    var users         = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID))).ToList();
                    foreach (var item in listGroup)
                    {
                        var user = users.Where(x => x.GroupId == item.ID).FirstOrDefault();
                        item.GroupLeadID      = user != null ? user.Id : CommonConstants.StringEmpty;
                        item.GroupLead        = user != null ? user.FullName : CommonConstants.DefaultGroupLeader;
                        item.GroupLeadAccount = user != null ? user.UserName : CommonConstants.DefaultGroupLeader;
                    }
                    PaginationSet <GroupViewModel> pagedSet = new PaginationSet <GroupViewModel>()
                    {
                        PageIndex = page,
                        PageSize  = pageSize,
                        TotalRows = totalRow,
                        Items     = listGroup,
                    };
                    return(request.CreateResponse(HttpStatusCode.OK, pagedSet));
                }
            };

            return(await CreateHttpResponse(request, func));
        }
Exemple #20
0
 private void RoleCreate(AppRoleManager roleManager, string roleName)
 {
     if (!roleManager.RoleExists(roleName))
     {
         roleManager.Create(new AppRole(roleName));
     }
 }
Exemple #21
0
 public UserManagerController(AppUserManager userManager, AppRoleManager roleManager, ApplicationDbContext dbContext, AppSignInManager signInManager)
 {
     _userManager   = userManager;
     _roleManager   = roleManager;
     _dbContext     = dbContext;
     _signInManager = signInManager;
 }
Exemple #22
0
 public IdentityUnitOfWork(string connectionString)
 {
     db             = new ApplicationContext(connectionString);
     UserManager    = new AppUserManager(new UserStore <AppUser>(db));
     RoleManager    = new AppRoleManager(new RoleStore <AppRole>(db));
     ProfileManager = new ProfileManager(db);
 }
        public HttpResponseMessage Delete(HttpRequestMessage request, string id)
        {
            var appRole = AppRoleManager.FindById(id);

            AppRoleManager.Delete(appRole);
            return(request.CreateResponse(HttpStatusCode.OK, id));
        }
Exemple #24
0
        protected override void Seed(AppIdentityDbContext context)
        {
            AppUserManager userMgr  = new AppUserManager(new UserStore <AppUser>(context));
            AppRoleManager roleMgr  = new AppRoleManager(new RoleStore <AppRole>(context));
            string         roleName = "Administrators";
            string         userName = "******";
            string         password = "******";
            string         email    = " [email protected] ";

            if (!roleMgr.RoleExists(roleName))
            {
                roleMgr.Create(new AppRole(roleName));
            }
            AppUser user = userMgr.FindByName(userName);

            if (user == null)
            {
                userMgr.Create(new AppUser {
                    UserName = userName, Email = email
                }, password);
                user = userMgr.FindByName(userName);
            }
            if (!userMgr.IsInRole(user.Id, roleName))
            {
                userMgr.AddToRole(user.Id, roleName);
            }

            context.SaveChanges();
        }
        public IHttpActionResult Delete(string id)
        {
            var appRole = AppRoleManager.FindById(id);

            AppRoleManager.Delete(appRole);
            return(Ok(id));
        }
Exemple #26
0
        public async Task <IHttpActionResult> AddUserToRole(UserRoleBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string userId   = model.UserId;
            string roleName = model.RoleName;

            ApplicationUser user = UserManager.FindById(userId);

            if (user == null)
            {
                return(BadRequest("The user id does not exist: \"" + userId + "\""));
            }

            IdentityRole role = new IdentityRole(roleName);

            if (!AppRoleManager.RoleExists(roleName))
            {
                IdentityResult result = await AppRoleManager.CreateAsync(role);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }

            UserManager.AddToRole(user.Id, roleName);

            return(Ok());
        }
Exemple #27
0
        public async Task <IHttpActionResult> FacebookRegister(RegisterExternalBindingModel3 model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Token))
                {
                    return(BadRequest("Invalid OAuth access token"));
                }

                var tokenExpirationTimeSpan = TimeSpan.FromDays(360);
                // Get the fb access token and make a graph call to the /me endpoint
                var fbUser = await VerifyFacebookAccessToken(model.Token);

                if (fbUser?.Email == null)
                {
                    return(BadRequest("Invalid OAuth access token"));
                }

                // Check if the user is already registered
                var user = await UserManager.FindByEmailAsync(fbUser.Email);

                // If not, register it
                if (user == null)
                {
                    var userPassword   = "******" + fbUser.ID.ToString();
                    var randomPassword = System.Web.Security.Membership.GeneratePassword(10, 0) + "1Ds@";
                    user = new User()
                    {
                        UserName = fbUser.Email, MobileNumber = model.PhoneNumber, Email = fbUser.Email, Name = string.IsNullOrWhiteSpace(fbUser.Name) ? model.Name : fbUser.Name, PhoneNumber = model.PhoneNumber, Photo = model.Photo, CountryCode = model.CountryCode
                    };
                    user.Id = Guid.NewGuid().ToString();
                    IdentityResult result = await UserManager.CreateAsync(user, userPassword + randomPassword);

                    if (!result.Succeeded)
                    {
                        return(GetErrorResult(result));
                    }


                    IdentityResult roleResult;
                    bool           adminRoleExists = await AppRoleManager.RoleExistsAsync("User");

                    if (!adminRoleExists)
                    {
                        roleResult = await AppRoleManager.CreateAsync(new RoleForUser()
                        {
                            Id   = Guid.NewGuid().ToString(),
                            Name = "User"
                        });
                    }

                    var userResult = await UserManager.AddToRoleAsync(user.Id, "User");
                }
                return(Ok(GenerateLocalAccessTokenResponse(user.UserName, user.Id)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemple #28
0
        public async Task <IHttpActionResult> Create(CreateRoleModel model)
        {
            var currentRole = await AppRoleManager.FindByNameAsync(model.Name);

            if (currentRole != null)
            {
                ModelState.AddModelError("Name", "A role with this name already exists");
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var role = new IdentityRole {
                Name = model.Name
            };

            var result = await this.AppRoleManager.CreateAsync(role);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            Uri locationHeader = new Uri(Url.Link("GetRoleById", new { id = role.Id }));

            return(Created(locationHeader, TheModelFactory.CreateViewModel(role)));
        }
        public static void EnsureSeedData(this AppIdentityDbContext context)
        {
            AppUserManager userMgr  = new AppUserManager(new UserStore <AppUser, AppRole, AppIdentityDbContext, string>(context), null, new PasswordHasher <AppUser>(), null, null, null, null, null, null);
            AppRoleManager roleMgr  = new AppRoleManager(new RoleStore <AppRole, AppIdentityDbContext, string>(context), null, null, null, null, null);
            string         roleName = "Administrators";
            string         userName = "******";
            string         password = "******";
            string         email    = "*****@*****.**";

            if (!roleMgr.RoleExistsAsync(roleName).Result)
            {
                roleMgr.CreateAsync(new AppRole(roleName)).Wait();
            }

            AppUser user = userMgr.FindByNameAsync(userName).Result;

            if (user == null)
            {
                user = new AppUser {
                    UserName = userName, Email = email
                };
                userMgr.CreateAsync(user, password).Wait();
                user = userMgr.FindByNameAsync(userName).Result;
            }

            if (!userMgr.IsInRoleAsync(user, roleName).Result)
            {
                userMgr.AddToRoleAsync(user, roleName).Wait();
            }

            context.SaveChanges();
        }
Exemple #30
0
 public async Task <HttpResponseMessage> Delete(HttpRequestMessage request, int id)
 {
     if (_groupService.IsGroupEmpty(id, _groupService.GetGroupLeadIdByGroup(id)))
     {
         var result = _groupService.Delete(id);
         if (result != null)
         {
             var groupleaderID = AppRoleManager.FindByNameAsync(CommonConstants.GroupLead).Result.Id;
             var user          = AppUserManager.Users.Where(x => x.Roles.Any(r => r.RoleId.Equals(groupleaderID) && x.GroupId == id)).FirstOrDefault();
             if (user != null)
             {
                 user.GroupId = null;
                 var resultUpdate = await AppUserManager.UpdateAsync(user);
             }
             _groupService.SaveChange();
             return(request.CreateResponse(HttpStatusCode.OK, id));
         }
         else
         {
             return(request.CreateResponse(HttpStatusCode.BadRequest, id));
         }
     }
     else
     {
         Func <HttpResponseMessage> func = () =>
         {
             return(request.CreateResponse(HttpStatusCode.BadRequest, MessageSystem.ERROR_ExistMemberInGroup));
         };
         return(await CreateHttpResponse(request, func));
     }
 }
Exemple #31
0
 public AccountController(IUnitOfWork unitOfWork, AppUserManager appUserManager, AppRoleManager appRoleManager)
 {
     _unitOfWork = unitOfWork;
     _appUserManager = appUserManager;
     _appRoleManager = appRoleManager;
 }
 public RolesController(AppUserManager userManager,
     AppRoleManager roleManager)
 {
     UserManager = userManager;
     RoleManager = roleManager;
 }