Esempio n. 1
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);
        }
Esempio n. 2
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;
            }
        }
Esempio n. 3
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());
        }
Esempio n. 4
0
        public async Task <ActionResult> CreateRole(RoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppRole identityRole = new AppRole
                {
                    Name = model.RoleName
                };
                IdentityResult result = await RoleManager.CreateAsync(identityRole);

                if (result.Succeeded)
                {
                    TempData["Message"] = new Message()
                    {
                        Text = "Success! <strong>You have successfully added new role.</strong>", ClassName = "alertMessage successful"
                    };
                    return(RedirectToAction("List", "Roles"));
                }
                else
                {
                    return(View());
                }
            }
            return(View());
        }
        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();
        }
        private async Task <Tuple <ApplicationUser, string> > RegisterPelanggan(string email, string password)
        {
            try
            {
                ApplicationUser user = new Models.ApplicationUser {
                    UserName = email, Email = email, LockoutEnabled = false, EmailConfirmed = false
                };
                var created = await UserManager.CreateAsync(user, password);

                if (created.Succeeded)
                {
                    string roleName = "Pelanggan";
                    if (!await AppRoleManager.RoleExistsAsync(roleName))
                    {
                        var r           = new MySql.AspNet.Identity.IdentityRole("125", roleName);
                        var roleCreated = await AppRoleManager.CreateAsync(r);

                        if (!roleCreated.Succeeded)
                        {
                            throw new SystemException("Role Tidak Berhasil Disimpan");
                        }
                    }

                    var role = await AppRoleManager.FindByNameAsync(roleName);

                    if (role != null)
                    {
                        var added = await UserManager.AddToRoleAsync(user.Id, roleName);

                        if (!added.Succeeded)
                        {
                            throw new SystemException(string.Format("User Tidak Berhasil Di tambahkan Ke Role {0}", roleName));
                        }
                    }
                    else
                    {
                        throw new SystemException(string.Format("Role {0} Tidak Ditemukan", roleName));
                    }
                }
                else
                {
                    throw new SystemException("User TIdak Berhasil Dibuat");
                }
                string c = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                string strcode     = HttpUtility.UrlEncode(c);
                var    callbackUrl = Url.Link("DefaultApi", new { controller = "User/ConfirmPassword", userId = user.Id, code = strcode });
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return(Tuple.Create(user, strcode));
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }
Esempio n. 7
0
        private async Task CreateRole(string str)
        {
            var  role    = new ApplicationRole();
            bool rExists = await AppRoleManager.RoleExistsAsync(str);

            if (!rExists)
            {
                role.Name = str;
                await AppRoleManager.CreateAsync(role);
            }
        }
Esempio n. 8
0
        public async Task <IdentityResult> CreateRole(CreateRoleDto model)
        {
            var role = new Role
            {
                Name = model.RoleName,
            };

            var result = await _roleManger.CreateAsync(role);

            return(result);
        }
        private async Task <ApplicationUser> RegisterPetugas(string email)
        {
            try
            {
                var user = new Models.ApplicationUser {
                    UserName = email, Email = email, LockoutEnabled = true, EmailConfirmed = true
                };
                var created = await UserManager.CreateAsync(user, "Petugas#123");

                if (created.Succeeded)
                {
                    string roleName = "Petugas";
                    if (!await AppRoleManager.RoleExistsAsync(roleName))
                    {
                        var r           = new MySql.AspNet.Identity.IdentityRole("123", roleName);
                        var roleCreated = await AppRoleManager.CreateAsync(r);

                        if (!roleCreated.Succeeded)
                        {
                            throw new SystemException("Role Tidak Berhasil Disimpan");
                        }
                    }

                    var role = await AppRoleManager.FindByNameAsync(roleName);

                    if (role != null)
                    {
                        var added = await UserManager.AddToRoleAsync(user.Id, roleName);

                        if (!added.Succeeded)
                        {
                            throw new SystemException(string.Format("User Tidak Berhasil Di tambahkan Ke Role {0}", roleName));
                        }
                    }
                    else
                    {
                        throw new SystemException(string.Format("Role {0} Tidak Ditemukan", roleName));
                    }
                }
                else
                {
                    throw new SystemException("User TIdak Berhasil Dibuat");
                }

                return(user);
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }
Esempio n. 10
0
        public async Task <IHttpActionResult> TwitterRegister(RegisterExternalBindingModel2 model)
        {
            if (string.IsNullOrEmpty(model.AccessToken) || string.IsNullOrEmpty(model.AccessTokenSecret))
            {
                return(BadRequest("Invalid OAuth access token"));
            }
            Auth.SetUserCredentials(ConfigurationManager.AppSettings["Twitter.ConsumerKey"], ConfigurationManager.AppSettings["Twitter.ConsumerSecretKey"], model.AccessToken, model.AccessTokenSecret);
            var twUser = Tweetinvi.User.GetAuthenticatedUser();

            var tokenExpirationTimeSpan = TimeSpan.FromDays(360);

            // Get the fb access token and make a graph call to the /me endpoint
            if (twUser?.Email == null)
            {
                return(BadRequest("invalid token"));
            }
            // Check if the user is already registered
            var user = await UserManager.FindByEmailAsync(twUser.Email);

            // If not, register it
            if (user == null)
            {
                var randomPassword = System.Web.Security.Membership.GeneratePassword(10, 0) + "1Ds@";

                user = new User()
                {
                    UserName = twUser.Email, Email = twUser.Email, Name = twUser.Name.IsNullOrWhiteSpace() ? model.Name : twUser.Name, PhoneNumber = model.PhoneNumber, Photo = twUser.ProfileImageUrl, CountryCode = model.CountryCode
                };

                IdentityResult result = await UserManager.CreateAsync(user, randomPassword);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                IdentityResult roleResult;
                bool           adminRoleExists = await AppRoleManager.RoleExistsAsync("User");

                if (!adminRoleExists)
                {
                    roleResult = await AppRoleManager.CreateAsync(new RoleForUser()
                    {
                        Name = "User"
                    });
                }

                var userResult = await UserManager.AddToRoleAsync(user.Id, "User");
            }
            return(Ok(GenerateLocalAccessTokenResponse(user.UserName, user.Id)));
        }
        public async Task <ActionResult> Create([Required] string name)
        {
            if (ModelState.IsValid)
            {
                IdentityResult result = await RoleManager.CreateAsync(new AppRole(name));

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AddErrorsFromResult(result);
                }
            }
            return(View(name));
        }
        public async Task <IActionResult> Create(Role model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var result = await _roleManager.CreateAsync(model);

            if (result.Succeeded)
            {
                return(RedirectToRoute("GetRoles"));
            }

            AddErrors(result);

            return(View(model));
        }
Esempio n. 13
0
        public async Task <IHttpActionResult> Create(CreateRoleBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            var result = await AppRoleManager.CreateAsync(role);

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

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

            return(Created(locationHeader, ""));// TheModelFactory.Create(role));
        }
Esempio n. 14
0
        private void CheckAdminUserYN()
        {
            var  adminRole   = roleManager.FindByNameAsync("Administrators");
            long adminRoleId = -1;

            if (adminRole.Result == null)
            {
                var appRole = new AppRole {
                    Name = "Administrators"
                };
                var result = roleManager.CreateAsync(appRole).Result;
                if (result.Succeeded)
                {
                    adminRoleId = appRole.Id;
                }
            }

            var adminUser = userManager.FindByNameAsync("*****@*****.**");

            if (adminUser.Result == null)
            {
                var appUser = new AppUser {
                    UserName = "******",
                    Email    = "*****@*****.**",
                };
                var result = userManager.CreateAsync(appUser, "dbaldud123@").Result;

                if (result.Succeeded)
                {
                    appUser.Roles.Add(new AppUserRole {
                        UserId = appUser.Id,
                        RoleId = adminRoleId
                    });
                }
                userManager.Update(appUser);
            }
        }
        protected override void Seed(PrivateTutorOnline.Models.TutorOnlineDBContext context)
        {
            const string AdminUsername = "******";
            const string AdminPassword = "******";
            const string roleName      = "Admin";
            //const string AdminEmail = "*****@*****.**";
            const string AdminEmail = "*****@*****.**";


            if (AppRoleManager.FindByNameAsync("Admin") != null)
            {
                AppRoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Admin"));
            }
            if (AppRoleManager.FindByNameAsync("Customer") != null)
            {
                AppRoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Customer"));
            }
            if (AppRoleManager.FindByNameAsync("Tutor") != null)
            {
                AppRoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Tutor"));
            }


            //Initializer Admin account
            var admin = UserManager.FindByName(AdminUsername);

            if (admin == null)
            {
                admin = new ApplicationUser {
                    UserName = AdminUsername, Email = AdminEmail
                };
                IdentityResult AdminCreationResult = UserManager.Create(admin, AdminPassword);
                AdminCreationResult = UserManager.SetLockoutEnabled(admin.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = UserManager.GetRoles(admin.Id);

            if (!rolesForUser.Contains(roleName))
            {
                Task <IdentityResult> AdminRoleAddition = UserManager.AddToRoleAsync(admin.Id, roleName);
            }


            //Initializer Customer account
            //ApplicationUser customerUser = new ApplicationUser() { UserName = "******", Email = "*****@*****.**" };
            //var CustomerCreationResult = UserManager.CreateAsync(customerUser, AdminPassword);
            //if (CustomerCreationResult.IsCompleted)
            //    CustomerCreationResult = UserManager.SetLockoutEnabledAsync(customerUser.Id, false);
            //if (CustomerCreationResult.IsCompleted)
            //    UserManager.AddToRoleAsync(customerUser.Id, "Customer");

            //Initializer Tutor account
            //var tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //var result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            ////Initializer Tutor List account
            // tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            //tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            //tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");

            //tutor = new ApplicationUser { UserName = "******", Email = "*****@*****.**" };
            //result = UserManager.CreateAsync(tutor, AdminPassword);
            //if (result.IsCompleted)
            //    result = UserManager.SetLockoutEnabledAsync(tutor.Id, false);
            //if (result.IsCompleted)
            //    UserManager.AddToRoleAsync(tutor.Id, "Tutor");



            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
            if ((context.Subjects.Count() == 0))
            {
                context.Subjects.AddOrUpdate(
                    new Models.Subject()
                {
                    Name = "Toán"
                },
                    new Models.Subject()
                {
                    Name = "Tiếng Anh"
                },
                    new Models.Subject()
                {
                    Name = "Lý"
                },
                    new Models.Subject()
                {
                    Name = "Hóa"
                },
                    new Models.Subject()
                {
                    Name = "Sinh"
                },
                    new Models.Subject()
                {
                    Name = "Sử"
                },
                    new Models.Subject()
                {
                    Name = "Địa Lý"
                },
                    new Models.Subject()
                {
                    Name = "Vẽ"
                },
                    new Models.Subject()
                {
                    Name = "Vi Tính"
                },
                    new Models.Subject()
                {
                    Name = "Đàn-Nhạc"
                }
                    );
            }
            if (context.Grades.Count() == 0)
            {
                context.Grades.AddOrUpdate(
                    new Models.Grade()
                {
                    Name = "1"
                },
                    new Models.Grade()
                {
                    Name = "2"
                },
                    new Models.Grade()
                {
                    Name = "3"
                },
                    new Models.Grade()
                {
                    Name = "4"
                },
                    new Models.Grade()
                {
                    Name = "5"
                },
                    new Models.Grade()
                {
                    Name = "6"
                },
                    new Models.Grade()
                {
                    Name = "7"
                },
                    new Models.Grade()
                {
                    Name = "8"
                },
                    new Models.Grade()
                {
                    Name = "9"
                },
                    new Models.Grade()
                {
                    Name = "10"
                },
                    new Models.Grade()
                {
                    Name = "11"
                },
                    new Models.Grade()
                {
                    Name = "12"
                },
                    new Models.Grade()
                {
                    Name = "Luyện thi đại học"
                }
                    );
            }

            if (context.Customers.SingleOrDefault(c => c.Email == "*****@*****.**") == null)
            {
                //context.Customers.Add(
                //   new Models.Customer()
                //   {
                //       FullName = "Đinh Văn Thành",
                //       PhoneNumber = "01213546546",
                //       Email = "*****@*****.**",
                //       City = "TPHCM",
                //       District = "Quận 5",
                //       Ward = "Phường 13",
                //       Street = "An Dương Vương",
                //       UserId = customerUser.Id,
                //       IsEnable = true,
                //       IsActivate = false
                //   }
                //);
            }

            if (context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null &&
                context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null &&
                context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null &&
                context.Tutors.SingleOrDefault(s => s.Email == "*****@*****.**") == null
                )
            {
                //context.Tutors.AddOrUpdate(
                //new Models.Tutor()
                //{
                //    FullName = "Hoàng Tuấn Anh",
                //    Gender = Enums.Gender.Male,
                //    DateOfBirth = new DateTime(1994, 11, 2),
                //    Email = "*****@*****.**",
                //    PhoneNumber = "01526487656",
                //    IdentityNumber = "0225644478",
                //    City = "TPHCM",
                //    District = "Bình Tân",
                //    Ward = "Phú Thạnh",
                //    Street = "Nguyễn Sơn",
                //    HomeTown = "Tỉnh Hà Nam",
                //    University = "ĐH Sư Phạm TPHCM",
                //    MajorSubject = "Sư Phạm Toán Học",
                //    GraduationYear = "2016",
                //    Advantage = "Đã từng đi dạy",
                //    Degree = Enums.AcademicDegree.Teacher,
                //    Image = new byte[] { },
                //    IsEnable = true,
                //    IsActivate = true
                //},
                //new Models.Tutor()
                //{
                //    FullName = "Nguyễn Ngọc Ánh",
                //    Gender = Enums.Gender.Female,
                //    DateOfBirth = new DateTime(1993, 2, 2),
                //    Email = "*****@*****.**",
                //    PhoneNumber = "01526487656",
                //    IdentityNumber = "0225644478",
                //    City = "TPHCM",
                //    District = "Quận 5",
                //    Ward = "13",
                //    Street = "An Dương Vương",
                //    HomeTown = "TP Hải Phòng",
                //    University = "ĐH Ngoại Thương TPHCM",
                //    MajorSubject = "Quản trị kinh doanh",
                //    GraduationYear = "2015",
                //    Advantage = "Đã từng đi dạy",
                //    Degree = Enums.AcademicDegree.Master,
                //    Image = new byte[] { },
                //    IsEnable = true,
                //    IsActivate = true
                //},
                //new Models.Tutor()
                //{
                //    FullName = "Vương Tuấn Kiệt",
                //    Gender = Enums.Gender.Male,
                //    DateOfBirth = new DateTime(1995, 11, 11),
                //    Email = "*****@*****.**",
                //    PhoneNumber = "01526487656",
                //    IdentityNumber = "0225644478",
                //    City = "TPHCM",
                //    District = "Quận 1",
                //    Ward = "Hai Bà Trưng",
                //    Street = "Nguyễn Kiệm",
                //    HomeTown = "Tỉnh Đồng Tháp",
                //    University = "Cao Đẳng Kinh Tế Đối Ngoại",
                //    MajorSubject = "Kế toán",
                //    GraduationYear = "2017",
                //    Advantage = "Đã từng đi dạy",
                //    Degree = Enums.AcademicDegree.Student,
                //    Image = new byte[] { },
                //    IsEnable = true,
                //    IsActivate = true
                //},
                // new Models.Tutor()
                // {
                //     FullName = "Đỗ Thị Phương Nhung",
                //     Gender = Enums.Gender.Female,
                //     DateOfBirth = new DateTime(1996, 5, 13),
                //     Email = "*****@*****.**",
                //     PhoneNumber = "01526487656",
                //     IdentityNumber = "0225644478",
                //     City = "Đà Nẵng",
                //     District = "Cát Bà",
                //     Ward = "Phú Xuân",
                //     Street = "Nguyễn Sơn",
                //     HomeTown = "Thủ đô Hà Nội",
                //     University = "Đại Học Sài Gòn",
                //     MajorSubject = "Sư Phạm Tiếng Anh",
                //     GraduationYear = "2017",
                //     Advantage = "Đã từng đi dạy",
                //     Degree = Enums.AcademicDegree.Bachelor,
                //     Image = new byte[] { },
                //     IsEnable = true,
                //     IsActivate = true
                // },
                // new Models.Tutor()
                // {
                //     FullName = "Huỳnh Tấn Dũng",
                //     Gender = Enums.Gender.Male,
                //     DateOfBirth = new DateTime(1994, 5, 11),
                //     Email = "*****@*****.**",
                //     PhoneNumber = "01526487656",
                //     IdentityNumber = "0225644478",
                //     City = "Đà Nẵng",
                //     District = "Cát Bà",
                //     Ward = "Phú Xuân",
                //     Street = "Nguyễn Sơn",
                //     HomeTown = "Thủ đô Hà Nội",
                //     University = "Đại Học Sài Gòn",
                //     MajorSubject = "Sư Phạm Tiếng Anh",
                //     GraduationYear = "2017",
                //     Advantage = "Đã từng đi dạy",
                //     Degree = Enums.AcademicDegree.Bachelor,
                //     Image = new byte[] { },
                //     IsEnable = true,
                //     IsActivate = true,
                //     UserId = tutor.Id
                // }  );
            }
        }
Esempio n. 16
0
        // POST: api/Pegawai
        public async Task <HttpResponseMessage> Post([FromBody] pegawai value)
        {
            RegisterViewModel model = new RegisterViewModel();

            model.Email    = value.Email;
            model.Password = "******";

            try
            {
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    string role = "Pegawai";
                    if (result.Succeeded)
                    {
                        var isExis = await AppRoleManager.RoleExistsAsync(role);

                        if (!isExis)
                        {
                            var r = await AppRoleManager.CreateAsync(new IdentityRole(role) { Name = role });

                            if (r.Succeeded)
                            {
                                var roleResult = await UserManager.AddToRoleAsync(user.Id, role);

                                if (!roleResult.Succeeded)
                                {
                                    throw new System.Exception(string.Format("Gagal Menambahkan User Role"));
                                }
                            }
                            else
                            {
                                throw new System.Exception(string.Format("Role {0} Gagal Dibuat, Hubungi Administrator", role));
                            }
                        }

                        using (var db = new OcphDbContext())
                        {
                            value.UserId = user.Id;
                            value.Id     = db.Pegawai.InsertAndGetLastID(value);
                            string c = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                            string code        = HttpUtility.UrlEncode(c);
                            var    callbackUrl = Url.Link("DefaultApi", new { controller = "Account/ConfirmEmail", userId = user.Id, code = code });
                            await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                            return(Request.CreateResponse(HttpStatusCode.OK, value));
                        }
                    }
                    else
                    {
                        throw new SystemException("Data Tidak berhasil ditambah");
                    }
                }
                else
                {
                    throw new SystemException("Data Tidak Valid");
                }
            }
            catch (Exception ex)
            {
                if (value.Id > 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.Created, "Email Confirm Account Not Sended"));
                }

                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message, ex));
            }
        }
Esempio n. 17
0
 public async Task <IdentityResult> CreateAsync(ApplicationRole role)
 {
     return(await _roleManager.CreateAsync(role));
 }
        // PUT: api/SetPengawas/5
        public async Task <HttpResponseMessage> Put(int id, [FromBody] pegawai value)
        {
            var role = "Pengawas";

            using (var db = new OcphDbContext())
            {
                var trans = db.BeginTransaction();
                try
                {
                    if (value.Pengawas == false)
                    {
                        var isExis = await AppRoleManager.RoleExistsAsync(role);

                        if (!isExis)
                        {
                            var r = await AppRoleManager.CreateAsync(new IdentityRole(role) { Name = role });

                            if (!r.Succeeded)
                            {
                                throw new System.Exception(string.Format("Role {0} Gagal Dibuat, Hubungi Administrator", role));
                            }
                        }

                        if (db.Pegawai.Update(O => new { O.Pengawas }, new pegawai {
                            Pengawas = true
                        }, O => O.Id == value.Id))
                        {
                            var roleResult = await UserManager.AddToRoleAsync(value.UserId, role);

                            if (!roleResult.Succeeded)
                            {
                                throw new System.Exception(string.Format("Gagal Menambahkan User Role"));
                            }
                            else
                            {
                                trans.Commit();
                                value.Pengawas = true;
                                return(Request.CreateResponse(HttpStatusCode.OK, value));
                            }
                        }
                        else
                        {
                            throw new System.Exception(string.Format("Gagal Menambahkan User Role"));
                        }
                    }
                    else
                    {
                        if (db.Pegawai.Update(O => new { O.Pengawas }, new pegawai {
                            Pengawas = false
                        }, O => O.Id == value.Id))
                        {
                            var roleResult = await UserManager.RemoveFromRoleAsync(value.UserId, role);

                            if (!roleResult.Succeeded)
                            {
                                throw new System.Exception(string.Format("Gagal Menghapus User Role"));
                            }
                            else
                            {
                                trans.Commit();
                                value.Pengawas = false;
                                return(Request.CreateResponse(HttpStatusCode.OK, value));
                            }
                        }
                        else
                        {
                            throw new System.Exception(string.Format("Gagal Menghapus User Role"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
                }
            }
        }