Inheritance: MonoBehaviour
        // GET: Home
        public async Task<ActionResult> Index()
        {
            var context = new ApplicationDbContext(); // DefaultConnection
            var store = new UserStore<CustomUser>(context);
            var manager = new UserManager<CustomUser>(store);

            var email = "[email protected]";
            var password = "Passw0rd";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
            {
                user = new CustomUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = "Super",
                    LastName = "Admin"
                };

                await manager.CreateAsync(user, password);
            }
            else
            {
                user.FirstName = "Super";
                user.LastName = "Admin";

                await manager.UpdateAsync(user);
            }


            return Content("Hello, Index");
        }
        public string AddBlock(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var blockedUser = manager.FindById(userId);

                if (type.Equals("Block"))
                {
                    currentUser.blockedList.Add(blockedUser);

                    //unfollow each person if there was any following
                    UnFollow(currentUser, blockedUser);
                    UnFollow(blockedUser, currentUser);
                }
                else  //unblock user just remove him from the list
                {
                    var block = currentUser.blockedList.Find(user => user.Id == blockedUser.Id);

                    if (block != null)
                    {
                        currentUser.blockedList.Remove(block);
                    }
                }

              //  manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

               // store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
        public string AddFollow(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var followedUser = manager.FindById(userId);

                if (type.Equals("Follow"))
                {
                    currentUser.followList.Add(followedUser);
                }
                else
                {
                    UnFollow(currentUser, followedUser);
                }

                //manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

                //store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
        public UserManagerService(UserManager<AppIdentityUser> userMenager, IAuthenticationManager authenticationManager, RoleManager<IdentityRole> roleManager)
        {
            this._userMenager = userMenager;
            this._authenticationManager = authenticationManager;
            this._roleManager = roleManager;

            //Pasword validation rules

            _userMenager.UserValidator = new UserValidator<AppIdentityUser>(userMenager) { RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = false };
            _userMenager.PasswordValidator = new PasswordValidator() { RequiredLength = 6, RequireLowercase = true, RequireUppercase = true, RequireDigit = true };
            _signInMenager = new SignInManager<AppIdentityUser, string>(_userMenager, _authenticationManager);

            //_userMenager.UserLockoutEnabledByDefault = true;
            //_userMenager.DefaultAccountLockoutTimeSpan = TimeSpan.FromDays(int.MaxValue);
            //_userMenager.SetLockoutEnabled(user.Id, enabled) // Enables or disables lockout for a user 
            //Register e-mail service for identity

            _userMenager.EmailService = new EmailService();

            //Token provider for password reset
            var dataProtectionProvider = Startup.dataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
                userMenager.UserTokenProvider = new DataProtectorTokenProvider<AppIdentityUser>(dataProtector);
            }
        }
Example #5
0
 public IEnumerable<UserLoginInfo> GetLogins()
 {
     UserManager manager = new UserManager();
     var accounts = manager.GetLogins(User.Identity.GetUserId());
     CanRemoveExternalLogins = accounts.Count() > 1 || HasPassword(manager);
     return accounts;
 }
 public DevelopmentDefaultData(IOptions<DevelopmentSettings> options, IDataContext dataContext, UserManager<User> userManager, RoleManager<Role> roleManager)
 {
     this.settings = options.Value;
     this.dataContext = dataContext;
     this.userManager = userManager;
     this.roleManager = roleManager;
 }
        public ActionResult Menu()
        {
            ApplicationDbContext userscontext = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(userscontext);
            var userManager = new UserManager<ApplicationUser>(userStore);

            var roleStore = new RoleStore<IdentityRole>(userscontext);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            if (User.Identity.IsAuthenticated)
            {

                if (userManager.IsInRole(this.User.Identity.GetUserId(), "Admin"))
                {
                    return PartialView("_AdminMenuView");
                }
                else if (userManager.IsInRole(this.User.Identity.GetUserId(), "Principal"))
                {
                    return PartialView("_PrincipalenuView");
                }
                else
                {
                    return PartialView("_Student");
                }
            }

            return PartialView("_Empty");
        }
 public AccountController(IConfigurationRoot appSettings, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILoggerFactory loggerFactory)
 {
     _appSettings = appSettings;
     _userManager = userManager;
     _signInManager = signInManager;
     _logger = loggerFactory.CreateLogger<AccountController>();
 }
 public EmployeeAdminRepository()
 {
     AspContext = new IdentityDbContext();
     _db = new GtrackDbContext();
     UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
     RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>());
 }
Example #10
0
 public AccountController(
     UserManager<User> userManager,
     SignInManager<User> signInManager)
 {
     _signInManager = signInManager;
     _userManager = userManager;
 }
 private void CreateAndLoginUser()
 {
     if (!IsValid)
     {
         return;
     }
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = userName.Text };
     IdentityResult result = manager.Create(user);
     if (result.Succeeded)
     {
         var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
         if (loginInfo == null)
         {
             Response.Redirect("~/Account/Login");
             return;
         }
         result = manager.AddLogin(user.Id, loginInfo.Login);
         if (result.Succeeded)
         {
             IdentityHelper.SignIn(manager, user, isPersistent: false);
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
             return;
         }
     }
     AddErrors(result);
 }
Example #12
0
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Определите разделы для отображения
                UserManager manager = new UserManager();
                if (HasPassword(manager))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Отобразить сообщение об успехе
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Извлечь строку запроса из действия
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Пароль изменен."
                        : message == "SetPwdSuccess" ? "Пароль задан."
                        : message == "RemoveLoginSuccess" ? "Учетная запись удалена."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine las secciones que se van a presentar
                UserManager manager = new UserManager();
                if (HasPassword(manager))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Presentar mensaje de operación correcta
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Seccionar la cadena de consulta desde la acción
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Se cambió la contraseña."
                        : message == "SetPwdSuccess" ? "Se estableció la contraseña."
                        : message == "RemoveLoginSuccess" ? "La cuenta se quitó."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }
Example #14
0
        public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName,
           string password, bool lockOutEnabled)
        {
            var user = userManager.FindByName(email);

            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = firstName,
                    LastName = lastName,
                    EmailConfirmed = true
                };
                try
                {
                    userManager.Create(user, password);
                }
                catch (Exception ex)
                {
                    Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex);
                }
                userManager.SetLockoutEnabled(user.Id, lockOutEnabled);
            }
            return user;
        }
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                    lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception q)
            {
                Response.Redirect("/error.aspx");
            }
        }
 public ManageController(
 UserManager<ApplicationUser> userManager,
 SignInManager<ApplicationUser> signInManager,)
 {
     _userManager = userManager;
     _signInManager = signInManager;
 }
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
     UserManager<ApplicationUser> manager,
     string authenticationType)
 {
     var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
     return userIdentity;
 }
Example #18
0
 [TestInitialize()]//初始化
 public void MyTestInitialize()
 {
     ue = MockUPAUser.CreateUPAuser();
     cell = MockUPAcell.CreatUPACell();
     ue.ServiceCell = cell;
     target = new UserManager(3, 3, 3);//MaxLossTTi,MinCIR,FastLossRemain
 }
 public AccountController(
     UserManager userManager,
     IMultiTenancyConfig multiTenancyConfig,
     IUserEmailer userEmailer,
     RoleManager roleManager,
     TenantManager tenantManager,
     IUnitOfWorkManager unitOfWorkManager,
     ITenancyNameFinder tenancyNameFinder,
     ICacheManager cacheManager,
     IAppNotifier appNotifier,
     IWebUrlService webUrlService,
     AbpLoginResultTypeHelper abpLoginResultTypeHelper,
     IUserLinkManager userLinkManager,
     INotificationSubscriptionManager notificationSubscriptionManager)
 {
     _userManager = userManager;
     _multiTenancyConfig = multiTenancyConfig;
     _userEmailer = userEmailer;
     _roleManager = roleManager;
     _tenantManager = tenantManager;
     _unitOfWorkManager = unitOfWorkManager;
     _tenancyNameFinder = tenancyNameFinder;
     _cacheManager = cacheManager;
     _webUrlService = webUrlService;
     _appNotifier = appNotifier;
     _abpLoginResultTypeHelper = abpLoginResultTypeHelper;
     _userLinkManager = userLinkManager;
     _notificationSubscriptionManager = notificationSubscriptionManager;
 }
Example #20
0
        public ActionResult Create(Skill skill)
        {
            if (ModelState.IsValid)
            {
                List<Category> cats = db.Categories.ToList();           // get the category list from the db only once.
                //skill.Categories = new List<Category>();   // initialize the Skill's Category List, since it starts null.
                //foreach (string k in skill.CategoriesList.Keys)
                //{
                //    // if the user selected this key name
                //    if (skill.CategoriesList[k]) {
                //        Category cat = cats.First(c => c.Name == k);
                //        // add the category matching the key name
                //        skill.Categories.Add(cat);
                //        cat.Skills.Add(skill);
                //        db.Entry(cat).State = EntityState.Modified;
                //    }
                //}

                UserManager manager = new UserManager(db);
                skill.User = manager.findByUserName(User.Identity.Name);
                db.Skills.Add(skill);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(skill);
        }
        public AuthorizationRepository()
        {
            _dataContext = new DataContext();
            var userStore = new UserStore<PropertyManagerUser>(_dataContext);
            _userManager = new UserManager<PropertyManagerUser>(userStore);

        }
Example #22
0
        //
        // GET: /Manage/Index
        public async Task<ActionResult> Index(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var userId = User.Identity.GetUserId();
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());

            // lambda to extract photolist using currentUser as filter
            var photoList = Db.Photos.Where(x => x.UserId == userId).ToList();
            var model = new IndexViewModel
            {
                PhotoList = photoList,
                HasPassword = HasPassword(),
                PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
                TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
                Logins = await UserManager.GetLoginsAsync(userId),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
            };

            ViewBag.User = currentUser;
            return View(model);
        }
Example #23
0
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
 {
     // Обратите внимание, что authenticationType должен совпадать с типом, определенным в CookieAuthenticationOptions.AuthenticationType
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
     // Здесь добавьте утверждения пользователя
     return userIdentity;
 }
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // レンダリングするセクションを判別します
                UserManager manager = new UserManager();
                if (HasPassword(manager))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // 成功メッセージをレンダリングします
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // アクションからクエリ文字列を削除します
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "パスワードが変更されました。"
                        : message == "SetPwdSuccess" ? "パスワードが設定されました。"
                        : message == "RemoveLoginSuccess" ? "アカウントは削除されました。"
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }
Example #25
0
        public HttpResponseMessage AddUser(UserSignUpViewModel userParam)
        {
            UserManager userManager = new UserManager();
            HistoryManager historyManager = new HistoryManager();
            try
            {
                var user = new User();
                user.UserName = userParam.UserName;
                user.Password = userParam.Password;
                user.Email = userParam.Email;
                user.FirstName = userParam.FirstName;
                user.MiddleName = userParam.MiddleName;
                user.LastName = userParam.LastName;

                userManager.Create(user);
                var dbUser = userManager.FindUserEmail(user.Email);
                historyManager.AddHistory(new History(dbUser)
                {
                    Activity = Activities.Joined,
                    Description = Helper.GenerateActivityDescription(dbUser, Activities.Joined)
                });
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            // create new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            // search for and create a new user object
            var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text);

            // if a match is found for the user
            if(user != null)
            {
                // authenticate and login our new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                // Sign the user
                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // Redirect to Main Menu
                Response.Redirect("~/Contoso/MainMenu.aspx");
            }
            else
            {
                // throw an error to the AlertFlash div
                StatusLabel.Text = "Invalid Username or Password";
                AlertFlash.Visible = true;
            }
        }
Example #27
0
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine the sections to render
                UserManager manager = new UserManager();
                if (HasPassword(manager))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Your password has been changed."
                        : message == "SetPwdSuccess" ? "Your password has been set."
                        : message == "RemoveLoginSuccess" ? "The account was removed."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }
Example #28
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };
                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("/user/index.aspx");

                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception d)
            {
                Response.Redirect("/error.aspx");
            }
        }
Example #29
0
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
 {
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
     // Add custom user claims here
     return userIdentity;
 }
Example #30
0
 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<UserAccount> manager)
 {
     // authenticationType が CookieAuthenticationOptions.AuthenticationType で定義されているものと一致している必要があります
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
     // ここにカスタム ユーザー クレームを追加します
     return userIdentity;
 }