Exemple #1
0
        protected override void Seed(MyDbContext context)
        {
            var userManager = new MyUserManager(new UserStore <User>(context));

            var roles = new List <IdentityRole>
            {
                new IdentityRole("Admin"),
                new IdentityRole("User"),
                new IdentityRole("Manager")
            };

            foreach (var role in roles)
            {
                context.Roles.Add(role);
            }

            context.SaveChanges();

            // Create users.
            var users = new[]
            {
                new User
                {
                    Email    = "*****@*****.**",
                    UserName = "******"
                },
                new User
                {
                    Email       = "*****@*****.**",
                    UserName    = "******",
                    PhoneNumber = "(095) 333-33-33",
                    FirstName   = "Valera",
                    LastName    = "Revolver",
                    Purchased   = 3,
                    Flowers     = new List <Flower> {
                    },
                }
            };

            foreach (var user in users)
            {
                userManager.Create(user);
                userManager.AddPassword(user.Id, "Password_1");
            }
            context.SaveChanges();

            // Set roles to main users.
            userManager.AddToRole(users[0].Id, "Admin");
            userManager.AddToRole(users[1].Id, "Manager");
            context.SaveChanges();

            // Set roles to other users.
            for (int i = 2; i < users.Length; i++)
            {
                userManager.AddToRole(users[i].Id, "User");
            }
            context.SaveChanges();

            base.Seed(context);
        }
 public void NewMethod()
 {
     var userManager = new MyUserManager();
     var task = userManager.FindAsync("jadmin", "");
     var user = task.Wait(20000);
     Assert.IsNotNull(task.Result);
 }
        /// <summary>
        /// stop following the target
        /// </summary>
        /// <param name="targetUserId">target(followee) user id</param>
        /// <param name="followerUserId">the follower user id</param>
        public void UnFollow(Guid targetUserId, Guid followerUserId)
        {
            var targetPid   = MyUserManager.FindByIdAsync(targetUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];
            var followerPid = MyUserManager.FindByIdAsync(followerUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];

            FollowService.UnFollow(targetPid, followerPid);
        }
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                MyUserManager myUserManager = new MyUserManager();

                BusinessLayerResult <MyUser> result = myUserManager.RegisterUser(model);

                if (result.Errors.Count > 0)
                {
                    result.Errors.ForEach(x => ModelState.AddModelError("", x.Message));
                    return(View(model));
                }


                OkViewModel notifyObj = new OkViewModel();
                notifyObj.Title = "Registiration is Successfully Done!";
                notifyObj.Items.Add("Please go to your e-mail address and activate your account by clicking the activation link.");


                return(View("Ok", notifyObj));
            }

            // TODO List
            // username control-
            // email control-
            // insert user
            // activation e-mail

            return(View(model));
        }
        public OldHouseUser GetTestFackUser(string nickName, string userName, string password)
        {
            var user = MyUserManager.FindByNameAsync(userName).Result;

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

            user = new OldHouseUser {
                NickName     = nickName,
                UserName     = userName,
                PasswordHash = password
            };
            //todo put all oldhouse user roles in consts
            //todo use a fake user iu data base later
            user.Roles.Add("User");
            //it has no profile yet
            //todo may return a fake profile in data base
            var profile = CreateAFakeProfile();

            user.Profiles.Add(OldHouseUserProfile.PROFILENBAME, profile.Id);
            MyUserManager.CreateAsync(user).Wait();
            ProfileService.SaveOne(profile);
            return(user);
        }
        public ActionResult UserActivate(Guid id)
        {
            //user activation

            MyUserManager userManager           = new MyUserManager();
            BusinessLayerResult <MyUser> result = userManager.ActivateUser(id);

            if (result.Errors.Count > 0)
            {
                ErrorViewModel errorNotifyObj = new ErrorViewModel()
                {
                    Title = "Wrong Attempt",
                    Items = result.Errors,
                };

                return(View("Error", errorNotifyObj));
            }

            OkViewModel okNotifyObj = new OkViewModel();

            okNotifyObj.Title          = "Account is Activated";
            okNotifyObj.RedirectingUrl = "/Home/Login";
            okNotifyObj.Items.Add("Welcome to TrendOl family. We wish you have great enjoy during the shopping!");

            return(View("Ok", okNotifyObj));
        }
        public ActionResult Login(LoginViewModel avm, string returnUrl = "")
        {
            var am = new MyUserManager();

            if (!ModelState.IsValid || !Membership.ValidateUser(avm.Username, avm.Password))
            {
                ViewBag.Error = "Account credentials are invalid";
                return(View("Login"));
            }

            var user     = am.Find(avm.Username, avm.Password);
            var js       = new JavaScriptSerializer();
            var data     = js.Serialize(user);
            var ticket   = new FormsAuthenticationTicket(1, avm.Username, DateTime.Now, DateTime.Now.AddMinutes(30), avm.RememberMe, data);
            var encToken = FormsAuthentication.Encrypt(ticket);
            var cockie   = new HttpCookie(FormsAuthentication.FormsCookieName, encToken);

            Response.Cookies.Add(cockie);


            //FormsAuthentication.SetAuthCookie(avm.Username, avm.RememberMe);
            if (Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("Index", "Profile"));
            }
        }
Exemple #8
0
 public MyGroupManager()
 {
     _db          = HttpContext.Current.GetOwinContext().Get <MyDbContext>();
     _userManager = HttpContext.Current.GetOwinContext().GetUserManager <MyUserManager>();
     _roleManager = HttpContext.Current.GetOwinContext().Get <MyRoleManager>();
     _groupStore  = new GroupStore(_db);
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (MyUserManager userManager = new MyUserManager())
            {
                IdentityUser user = new IdentityUser();
                if (FindUser(context.UserName, context.Password) != null)
                {
                    user = userManager.FindByName(context.UserName);
                }
                //IdentityUser user2 = await userManager.FindAsync(context.UserName, context.Password);
               
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);
                AuthenticationProperties properties = CreateProperties(user);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        /// <summary>
        /// Am i following this user
        /// </summary>
        /// <param name="targetUserId">the followee user id</param>
        /// <param name="followerUserId">the follower userid</param>
        /// <returns></returns>
        public bool AmIFollowing(Guid targetUserId, Guid followerUserId)
        {
            var targetPid   = MyUserManager.FindByIdAsync(targetUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];
            var followerPid = MyUserManager.FindByIdAsync(followerUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];

            return(FollowService.AmIFollowing(targetPid, followerPid));
        }
Exemple #11
0
        public async Task <TokenAuthorizeModel> RegisterExternalAsync(MyUserManager userManager, RegisterExternalViewModel viewModel)
        {
            var identity           = viewModel.ToEntity();
            var authenticationType = Enum.Parse <ExternalAuthenticationType>(viewModel.Provider, true);

            _externalAuthenticationFactory.Create(authenticationType).GetUserDetails(identity, viewModel.ProviderIdToken);

            identity.UserName = identity.Email;

            //If user exist in the system
            var user = await userManager.FindByNameAsync(identity.UserName);

            if (user != null)
            {
                return(await user.AuthorizeAsync(userManager, _extensionSettings.appSettings));
            }

            //if user is not exist in the system
            IdentityResult result = await userManager.CreateAsync(identity);

            if (result.Succeeded)
            {
                await updateOtherInfoForIdentity(userManager, identity);

                return(await identity.AuthorizeAsync(userManager, _extensionSettings.appSettings));
            }

            throw new FoodCourtException(ErrorMessage.USER_CREATE_FAIL);
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login

            //var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
            var result = new MyUserManager().ExternalSignIn(loginInfo, HttpContext);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
        /// <summary>
        /// just the create user method in the jtext103Identity, but with profile added
        //
        /// </summary>
        /// <param name="user">the oldhouse user</param>
        /// <param name="profileNames">you can indecate a list of new profile name</param>
        /// <returns></returns>
        public async Task <IdentityResult> CreateUserWithProfile(OldHouseUser user, HashSet <string> profileNames)
        {
            //default user role
            user.Roles.Add("User");
            var avatarName = "defaultAvatar_boy_";

            if (user.sex == "female")
            {
                avatarName = "defaultAvatar_girl_";
            }
            var rnd = new Random();

            avatarName += rnd.Next(1, 6).ToString() + ".jpg";
            user.Avatar = avatarName;

            var result = await MyUserManager.CreateAsync(user);

            //only when the user is added then can we add profiels
            if (result.IsSuccessful)
            {
                //done add userId in profile
                user.Profiles = CreateNewProfile(profileNames, user.Id);
                await MyUserManager.UpdateAsync(user);
            }
            return(result);
        }
        /// <summary>
        /// let the followerId follow the target id
        /// </summary>
        /// <param name="targetUserId">target(followee) user id</param>
        /// <param name="followerUserId">the follower user id</param>
        public void Follow(Guid targetUserId, Guid followerUserId)
        {
            //todo limit the following count here
            var targetPid   = MyUserManager.FindByIdAsync(targetUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];
            var followerPid = MyUserManager.FindByIdAsync(followerUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];

            FollowService.Follow(targetPid, followerPid);
        }
        public void NewMethod()
        {
            var userManager = new MyUserManager();
            var task        = userManager.FindAsync("jadmin", "");
            var user        = task.Wait(20000);

            Assert.IsNotNull(task.Result);
        }
Exemple #16
0
        private async Task updateOtherInfoForIdentity(MyUserManager userManager, MyIdentity identity)
        {
            await userManager.UpdateNormalizedEmailAsync(identity);

            await userManager.UpdateNormalizedUserNameAsync(identity);

            await userManager.AddToRoleAsync(identity, RoleType.MEMBER.ToString());
        }
        //[ChildActionOnly]
        //public ActionResult RemoveAccountList()
        //{
        //    var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
        //    ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
        //    return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
        //}

        protected override void Dispose(bool disposing)
        {
            if (disposing && UserManager != null)
            {
                UserManager.Dispose();
                UserManager = null;
            }
            base.Dispose(disposing);
        }
        public WizardStepFourController()
        {
            db           = new TExpEntities();
            _userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <MyUserManager>();
            _userName    = User.Identity.Name;
#if DEBUG
            Debug.WriteLine("~~~~~~~~ user name ->" + User.Identity.Name);
#endif
        }
 public AccountController(MyUserManager userManager,
     ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
 {
     UserManager = userManager;
     //UserManager.PasswordHasher = new CustomPassword();
     
     //password validator
     AccessTokenFormat = accessTokenFormat;
 }
Exemple #20
0
        /// <summary>
        /// Add user to role
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="roleName"></param>
        public void removeUserFromRole(string userName, string roleName)
        {
            var user = new ApplicationUser()
            {
                UserName = userName
            };

            var selectedUser = MyUserManager.FindByName(user.UserName);

            MyUserManager.RemoveFromRole(selectedUser.Id, roleName);
        }
Exemple #21
0
 public AccountController(
     MyUserManager userManager,
     IEmailSender emailSender,
     ISmsSender smsSender,
     ILoggerFactory loggerFactory)
 {
     _userManager = userManager;
     _emailSender = emailSender;
     _smsSender   = smsSender;
     _logger      = loggerFactory.CreateLogger <AccountController>();
 }
Exemple #22
0
 public IndexModel(
     MyUserManager myUserManager,
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     IEmailSender emailSender,
     IHostingEnvironment env)
 {
     _myUserManager = myUserManager;
     _userManager   = userManager;
     _signInManager = signInManager;
     _emailSender   = emailSender;
     _env           = env;
 }
Exemple #23
0
 public RegisterModel(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     MyUserManager myUserManager,
     ILogger <RegisterModel> logger,
     IEmailSender emailSender)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _myUserManager = myUserManager;
     _logger        = logger;
     _emailSender   = emailSender;
 }
Exemple #24
0
            public static MyUserManager Create(IdentityFactoryOptions <MyUserManager> options, IOwinContext context)
            {
                var manager = new MyUserManager(new UserStore <Account>(new MyDbContext()));

                manager.UserValidator = new UserValidator <Account>(manager)
                {
                    AllowOnlyAlphanumericUserNames = false,
                    RequireUniqueEmail             = true
                };

                // Configure validation logic for passwords
                manager.PasswordValidator = new PasswordValidator
                {
                    RequiredLength          = 6,
                    RequireNonLetterOrDigit = true,
                    RequireDigit            = true,
                    RequireLowercase        = true,
                    RequireUppercase        = true,
                };

                // Configure user lockout defaults
                manager.UserLockoutEnabledByDefault          = true;
                manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
                manager.MaxFailedAccessAttemptsBeforeLockout = 5;

                // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
                // You can write your own provider and plug it in here.
                manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <Account>
                {
                    MessageFormat = "Your security code is {0}"
                });
                manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <Account>
                {
                    Subject    = "Security Code",
                    BodyFormat = "Your security code is {0}"
                });

                //manager.EmailService = new EmailService();
                //manager.SmsService = new SmsService();

                var dataProtectionProvider = options.DataProtectionProvider;

                if (dataProtectionProvider != null)
                {
                    manager.UserTokenProvider =
                        new DataProtectorTokenProvider <Account>(dataProtectionProvider.Create("ASP.NET Identity"));
                }

                return(manager);
            }
Exemple #25
0
        /// <summary>
        /// Add user to role
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="roleName"></param>
        public void addUserToRole(string userName, string roleName)
        {
            var user = new ApplicationUser()
            {
                UserName = userName
            };

            var selectedUser = MyUserManager.FindByName(user.UserName);

            //HttpContext.Current.Session["Error"] = user.UserName;
            //HttpContext.Current.Response.Redirect("/UserPages/ErrorPage.aspx");

            MyUserManager.AddToRole(selectedUser.Id, roleName);
        }
Exemple #26
0
        public async Task <TokenAuthorizeModel> RegisterAsync(MyUserManager userManager, RegisterViewModel viewModel)
        {
            //save
            var identity = viewModel.ToEntity();

            identity.PasswordHash = userManager.PasswordHasher.HashPassword(identity, viewModel.Password);
            IdentityResult result = await userManager.CreateAsync(identity);

            if (result.Succeeded)
            {
                await updateOtherInfoForIdentity(userManager, identity);

                return(await identity.AuthorizeAsync(userManager, _extensionSettings.appSettings));
            }
            throw new FoodCourtException(ErrorMessage.USER_CREATE_FAIL);
        }
Exemple #27
0
        private bool HasPassword()
        {
            //var user = UserManager.FindById(User.Identity.GetUserId());
            //if (user != null)
            //{
            //    return user.PasswordHash != null;
            //}
            //return false;
            var user = new MyUserManager().FindById(User.Identity.GetUserId());

            if (user != null)
            {
                return(!String.IsNullOrEmpty(user.password));
            }
            return(false);
        }
        /// <summary>
        /// toggle the follow of a user
        /// </summary>
        /// <param name="targetUserId"></param>
        /// <param name="followerUserId"></param>
        /// <returns></returns>
        public bool ToggoleFollow(Guid targetUserId, Guid followerUserId)
        {
            var targetPid   = MyUserManager.FindByIdAsync(targetUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];
            var user        = MyUserManager.FindByIdAsync(targetUserId).Result;
            var followerPid = MyUserManager.FindByIdAsync(followerUserId).Result.Profiles[OldHouseUserProfile.PROFILENBAME];

            if (FollowService.AmIFollowing(targetPid, followerPid))
            {
                FollowService.UnFollow(targetPid, followerPid);
                return(false);
            }
            else
            {
                FollowService.Follow(targetPid, followerPid);
                return(true);
            }
        }
Exemple #29
0
        //public AccountController(IUserStore<t_User,int> userStore)
        public AccountController(MyUserManager userManager, MySignInManager signInManager)
        {
#if DEBUG
            if (userManager != null)
            {
                Debug.WriteLine("userManager is not null!");
            }
            else
            {
                Debug.WriteLine("userManager is null!");
            }
#endif

            UserManager = userManager;
            //_userManager=new MyUserManager(userStore);
            SignInManager = signInManager;
        }
Exemple #30
0
        protected override void Seed(ExtJS_Store.DAL.ApplicationContext context)
        {
            var userManager = new MyUserManager(new UserStore <User>(context));
            var roleManager = new MyRoleManager(new RoleStore <MyRole>(context));

            // создаем две роли
            var role1 = new MyRole {
                Name = "admin"
            };
            var role2 = new MyRole {
                Name = "user"
            };

            // добавляем роли в бд
            roleManager.Create(role1);
            roleManager.Create(role2);

            // создаем пользователей
            var user = new User {
                Email = "*****@*****.**", UserName = "******"
            };
            string password = "******";
            var    result   = userManager.Create(user, password);

            // если создание пользователя прошло успешно
            if (result.Succeeded)
            {
                // добавляем для пользователя роли
                userManager.AddToRole(user.Id, role1.Name);
                userManager.AddToRole(user.Id, role2.Name);
            }

            //  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. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
        public AccountController(IConfiguration configuration, MySignInManager signInManager, MyUserManager userManager,
                                 IUserStore <MyUser> userStore)
            : base(configuration)
        {
            Configuration = configuration;
            SignInManager = signInManager;
            UserManager   = userManager;
            UserStore     = userStore;

            if (UserManager.SupportsUserEmail)
            {
                EmailStore = (IUserEmailStore <MyUser>)UserStore;
            }
            else
            {
                throw new Exception("Soporte de Emails sin habilitar");
            }
        }
        public ActionResult ShowProfile()
        {
            MyUser        currentUser        = Session["login"] as MyUser;
            MyUserManager myUserManager      = new MyUserManager();
            BusinessLayerResult <MyUser> res = myUserManager.GetUserById(currentUser.Id);

            if (res.Errors.Count > 0)
            {
                ErrorViewModel errorNotifyObj = new ErrorViewModel()
                {
                    Title = "Error Occurred",
                    Items = res.Errors
                };
                return(View("Error", errorNotifyObj));
            }

            return(View(res.Result));
        }
Exemple #33
0
        public AccountController()
        {
            //_db=new CardPayEntities();
            //UserStore userStore=new UserStore(_db);
            _userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <MyUserManager>();
            //_signInManager = HttpContext.GetOwinContext().Get<MySignInManager>();
            _signInManager = System.Web.HttpContext.Current.GetOwinContext().Get <MySignInManager>();
#if DEBUG
            if (_userManager != null)
            {
                Debug.WriteLine("_userManager is not null!");
            }
            else
            {
                Debug.WriteLine("_userManager is null!");
            }
#endif
        }
Exemple #34
0
        private Task<IEnumerable<Claim>> validationCallback(string userName, string password)
        {
            using (DbContext dbContext = MyCtx.Create())
            using (MyUserStore userStore = new MyUserStore(dbContext))
            using (MyUserManager userManager = new MyUserManager(userStore))
            {
                var user = userManager.FindByName(userName);
                if (user == null)
                {
                    return null;
                }

                if (!userManager.CheckPassword(user, password))
                {
                    return null;
                }
                ClaimsIdentity claimsIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                return Task.FromResult(claimsIdentity.Claims);
            }
        }
 public void Initialize()
 {
     conString = "MacheteConnection";
     idb = new DatabaseFactory(conString);
     userManager = new MyUserManager(idb);
 }
 public AccountController(MyUserManager userManager)
 {
     UserManager = userManager;
 }