Exemplo n.º 1
32
      public async Task<ActionResult> Index()
      {
         if (this.User.Identity.IsAuthenticated)
         {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

            var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

            IQueryable<Game> games = from membership in db.GameMemberships
                                     where membership.ApplicationUserID == appUser.Id
                                     join game in db.Games on membership.GameID equals game.ID
                                     select game;

            var adminRole = await db.Roles.FirstOrDefaultAsync(role => role.Name == "Admin");

            this.ViewBag.Games = await games.ToListAsync();

            this.ViewBag.Claims = await manager.GetClaimsAsync(appUser.Id);
            this.ViewBag.Roles = await manager.GetRolesAsync(appUser.Id);
         }

         return View();
      }
Exemplo n.º 2
0
      public async Task<ActionResult> Create([Bind(Include = "ID,Name,Visibility")] Game game)
      {
         if (ModelState.IsValid)
         {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

            var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

            db.Games.Add(game);

            await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
            await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
            await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));

            var membership = new GameMembership()
            {
               Game = game,
               ApplicationUser = appUser,
               Roles = "Owner",
            };
            db.GameMemberships.Add(membership);
            await db.SaveChangesAsync();

            return RedirectToAction("Index");
         }

         return View(game);
      }
 public ActionResult Index()
 {
     if (User.Identity.IsAuthenticated)
     {
         var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
         ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
         if (UserManager.IsInRole(user.Id, "Admin"))
         {
             return RedirectToAction("Index", "Admins");
         }
         else if (UserManager.IsInRole(user.Id, "Profesor"))
         {
             return RedirectToAction("Index", "Profesors");
         }
         else if (UserManager.IsInRole(user.Id, "Referada"))
         {
             return RedirectToAction("Index", "Referadas");
         }
         else if (UserManager.IsInRole(user.Id, "Dekan"))
         {
             return RedirectToAction("Index", "Dekans");
         }
         else if (UserManager.IsInRole(user.Id, "Procelnik"))
         {
             return RedirectToAction("Index", "Procelniks");
         }
     }
     return View();
 }
        public async Task<JsonData> ChangePassword(ChangePasswordModel changePass)
        {
            try
            {
                var db = new DataContext();
                var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
                userMan.UserValidator = new UserValidator<MyUser>(userMan)
                {
                    AllowOnlyAlphanumericUserNames =
                        false
                };

                var user = await userMan.FindByIdAsync(User.Identity.GetUserId());
                if (user == null) throw new Exception("please check your old password");

                var newPassword = changePass.NewPassword;
                var result = await userMan.RemovePasswordAsync(user.Id);
                if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
                var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
                if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
                return DataHelpers.ReturnJsonData(null, true, "Password changed successful");
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
        protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var query = request.RequestUri.ParseQueryString();

            if (query.AllKeys.Any(x => x == "token"))
            {
                var jwt = ((JwtSecurityToken)new JwtSecurityTokenHandler().ReadToken(query.GetValues("token")[0]));

                var userId = jwt.Claims.FirstOrDefault(x => x.Type.Equals("nameid")).Value;

                if (userId != null)
                    using (var context = DatabaseContext.Create())
                    using (var userManager = new UserManager(new UserStore<User>(context)))
                    {
                        User currentUser = null;

                        if ((currentUser = await userManager.FindByIdAsync(userId)) != null)
                        {
                            var identity = await currentUser.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

                            var principal = new GenericPrincipal(identity, (await userManager.GetRolesAsync(currentUser.Id)).ToArray());

                            Thread.CurrentPrincipal = principal;
                            HttpContext.Current.User = principal;
                        }
                    }
            }

            return await base.SendAsync(request, cancellationToken);
        }
        public async Task<MyUser> GetUser(string userId)
        {
            var db = new DataContext();
            var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
            
            var currentUser = await userMan.FindByIdAsync(userId);

            return currentUser;
        }
        //
        // GET: /Users/
        public async Task<ActionResult> Index()
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(db);

            var userManager = new UserManager<ApplicationUser>(userStore);
            var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
            return View(user);
        }
        public ActionResult Profile()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));

            var currentUser = manager.FindByIdAsync(User.Identity.GetUserId<string>()).Result;

            ViewBag.HomeTown = currentUser.HomeTown;
            ViewBag.FirstName = currentUser.UserInfo.FirstName;

            return View();
        }
Exemplo n.º 9
0
        public static string PhoneNumber(this ClaimsPrincipal user, UserManager<ApplicationUser> userManager)
        {
            if (user.Identity.IsAuthenticated)
            {
                var appUser = userManager.FindByIdAsync(user.Identity.GetUserId()).Result;

                return appUser.PhoneNumber;
            }

            return "";
        }
Exemplo n.º 10
0
        public static string Email(this ClaimsPrincipal user, UserManager<ApplicationUser> userManager)
        {
            if (user.Identity.IsAuthenticated)
            {
                var appUser = userManager.FindByIdAsync(user.Identity.GetUserId()).Result;

                return appUser.Email;
            }

            return string.Empty;
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Edit(int id)
        {
            var article = await _articleRepository.FirstOrDefaultAsync(id);

            if (article == null)
            {
                _logger.LogError("Doesn't exist article. Controller:Article. Action:Edit");
                return(NotFound());
            }
            var user = await _userManager?.FindByIdAsync(article.ProfileID);

            if (User?.Identity.Name.ToString() == user?.UserName || User.IsInRole("admin"))
            {
                return(View(article));
            }
            return(NotFound());
        }
Exemplo n.º 12
0
      public async Task<GameResult> Create([FromBody]GameResult result)
      {
         if (result == null)
         {
            throw new ArgumentNullException("game");
         }

         GameVisibility visibility;
         if (!Enum.TryParse(result.Visibility, out visibility))
         {
            throw new ArgumentException("game.Visibility is not valid");
         }

         var game = new Game()
         {
            Name = result.Name,
            Visibility = visibility,
         };

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         db.Games.Add(game);

         await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
         await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
         await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));

         var membership = new GameMembership()
         {
            Game = game,
            ApplicationUser = appUser,
            Roles = "Owner",
         };
         db.GameMemberships.Add(membership);
         await db.SaveChangesAsync();


         result.GameId = game.ID;

         return result;
      }
Exemplo n.º 13
0
        // GET: Profile
        public async Task<ActionResult> Index(ManageController.ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageController.ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageController.ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageController.ManageMessageId.SetTwoFactorSuccess ? "Your two factor provider has been set."
                : message == ManageController.ManageMessageId.Error ? "An error has occurred."
                : message == ManageController.ManageMessageId.AddPhoneSuccess ? "The phone number was added."
                : message == ManageController.ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());

            var model = new IndexViewModel
            {
                HasPassword = HasPassword(),
                PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()),
                TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()),
                Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()),


                FirstName = currentUser.UserProfile.FirstName,
                LastName = currentUser.UserProfile.LastName,
                Email = currentUser.UserProfile.Email,
                Address1 = currentUser.UserProfile.Address1,
                City = currentUser.UserProfile.City,
                ProvState = currentUser.UserProfile.ProvState,
                PostZipCode = currentUser.UserProfile.PostZipCode,
                Country = currentUser.UserProfile.Country,
                Telephone = currentUser.UserProfile.Telephone,
                AvatarImgUrl = currentUser.UserProfile.AvatarImgUrl,

            };

            ViewBag.UserId = User.Identity.GetUserId();

            return View(model);
        }
Exemplo n.º 14
0
        public async Task<ActionResult> Me()
        {
            using (var ctx = new SportDataContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var user = await userManager.FindByIdAsync(User.Identity.GetUserId());

                await ctx.Entry(user).Collection(u => u.Licenses).LoadAsync();

                var license = user.Licenses.FirstOrDefault(l => l.Season == 2014);
                return Json(new
                {
                    found = user != null,
                    lastName = user != null ? user.LastName : "",
                    firstName = user != null ? user.FirstName : "",
                    license = license!=null? license.Number : "",
                    userId = user!=null ? user.Id : ""
                },
                JsonRequestBehavior.AllowGet);
            }
        }
Exemplo n.º 15
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CityPolicyRequirment requirement)
        {
            var authFilterContext = context.Resource as AuthorizationFilterContext;

            if (authFilterContext == null)
            {
                return(Task.CompletedTask);
            }


            string loggedInAdminId =
                context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;

            string adminIdBeingEdited = authFilterContext.HttpContext.Request.Query["userId"];


            var loggedInAdmin =
                context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
            var appUser = userManager?.FindByIdAsync(loggedInAdmin).Result;

            var user = context.User;

            var city = appUser.City;

            if (city == "London")
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 16
0
        //Receive Ajax call
        //public ActionResult GetMerchantDetails(string id)
        //{
        //    //Get current user
        //    //var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        //    var profileId = UserManager.FindById(id).UserProfile.Id;

        //    //var currentUser = UserManager.FindById(User.Identity.GetUserId());

        //    var merchant = _merchantServie.FindSupplierBy(profileId);
            

        //    return PartialView("_MerchantDetails", merchant);
        //}


        //public ActionResult GetMerchantEdit(string id)
        //{
        //    var profileId = UserManager.FindById(id).UserProfile.Id;

        //    //var currentUser = UserManager.FindById(User.Identity.GetUserId());

        //    var merchant = _merchantServie.FindSupplierBy(profileId);


        //    return PartialView("_MerchantEdit", merchant);
        //}


        //Ajax call to get full name
        public async Task<ActionResult> GetFullName()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());

            var model = new IndexViewModel
            {
                //HasPassword = HasPassword(),
                //PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()),
                //TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()),
                //Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()),
                //BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()),


                FirstName = currentUser.UserProfile.FirstName,
                LastName = currentUser.UserProfile.LastName,
                //Email = currentUser.UserProfile.Email,
                //Address1 = currentUser.UserProfile.Address1,
                //City = currentUser.UserProfile.City,
                //ProvState = currentUser.UserProfile.ProvState,
                //PostZipCode = currentUser.UserProfile.PostZipCode,
                //Country = currentUser.UserProfile.Country,
                //Telephone = currentUser.UserProfile.Telephone,
                //AvatarImgUrl = currentUser.UserProfile.AvatarImgUrl,

            };


            return PartialView("_Name", model);

        }
Exemplo n.º 17
0
//        public async Task<ActionResult> Edit([Bind(Include = "Email,Id")] EditUserViewModel editUser, params string[] selectedRole)
        public async Task <ActionResult> Edit(EditUserViewModel editUser, params string[] selectedRole)
        {
            if (!Security.IsValid("/Admin/Users"))
            {
                return(Redirect("~/"));
            }

            //MembershipUser u = Membership.GetUser(editUser.UserName, false);
            IList <string> userRoles;

            userRoles = await UserManager.GetRolesAsync(editUser.Id);

            editUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
            {
                Selected = userRoles.Contains(x.Name),
                Text     = x.Name,
                Value    = x.Name
            });

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(editUser.Id);

                string test = user.PasswordHash;
                if (user == null)
                {
                    return(HttpNotFound());
                }

                user.UserName  = editUser.UserName;
                user.Email     = editUser.Email;
                user.FirstName = editUser.FirstName;
                user.LastName  = editUser.LastName;
                user.MemberID  = editUser.MemberID ?? 0;

                userRoles = await UserManager.GetRolesAsync(user.Id);

                selectedRole = selectedRole ?? new string[] { };

                var result = await UserManager.AddToRolesAsync(user.Id, selectedRole.Except(userRoles).ToArray <string>());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(editUser));
                }
                result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToArray <string>());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(editUser));
                }

                if (!String.IsNullOrEmpty(editUser.Password))
                {
                    string passwordToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                    result = await UserManager.ResetPasswordAsync(user.Id, passwordToken, editUser.Password);

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        return(View(editUser));
                    }
                }

                if (await UserManager.IsLockedOutAsync(user.Id))
                {
                    MembershipUser u = Membership.GetUser(editUser.UserName, false);

                    u.UnlockUser();
                    await UserManager.ResetAccessFailedCountAsync(user.Id);
                }
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", "Something failed.");

            return(View(editUser));
        }
        public async Task <Dictionary <string, string> > GetCurrentUserLinkedLogins()
        {
            var identityUser = await UserManager.FindByIdAsync(UmbracoContext.Security.GetUserId());

            return(identityUser.Logins.ToDictionary(x => x.LoginProvider, x => x.ProviderKey));
        }
Exemplo n.º 19
0
        public async Task <ActionResult> EditUser(string id, AdminUserViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                var user = await UserManager.FindByIdAsync(id);

                var            emailChanged = user.Email != model.ApplicationUser.Email;
                IdentityResult result       = null;
                if (emailChanged)
                {
                    user.Email    = model.ApplicationUser.Email;
                    user.UserName = model.ApplicationUser.Email;
                    result        = await UserManager.UpdateAsync(user);
                }
                if (!emailChanged || result.Succeeded)
                {
                    var identityUserRole = user.Roles.FirstOrDefault();
                    if (identityUserRole != null)
                    {
                        var role = await RoleManager.FindByIdAsync(identityUserRole.RoleId);

                        if (role.Name != model.IdentityRole.Name)
                        {
                            var upgrade = await UserManager.AddToRoleAsync(user.Id, model.IdentityRole.Name);

                            if (upgrade.Succeeded)
                            {
                                var demote = await UserManager.RemoveFromRolesAsync(user.Id, role.Name);

                                if (demote.Succeeded)
                                {
                                }
                                else
                                {
                                    return(RedirectToAction("Index", new { Message = AdminMessageId.AsyncError }));
                                }
                            }
                            else
                            {
                                return(RedirectToAction("Index", new { Message = AdminMessageId.AsyncError }));
                            }
                        }
                        else if (!emailChanged)
                        {
                            return(RedirectToAction("Index", new { Message = AdminMessageId.NoAction }));
                        }
                    }
                    return(RedirectToAction("Index", new { Message = AdminMessageId.EditSuccess }));
                }
                return(RedirectToAction("Index", new { Message = AdminMessageId.AsyncError }));
            }
            catch
            {
                return(RedirectToAction("Index", new { Message = AdminMessageId.Error }));
            }
        }
Exemplo n.º 20
0
        public async Task <ActionResult> UserGridViewPartialUpdate(NorthOps.Ops.Models.User item)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = await UserManager.FindByIdAsync(item.Id);

                    user.FirstName    = item.FirstName;
                    user.LastName     = item.LastName;
                    user.MiddleName   = item.MiddleName;
                    user.Gender       = item.Gender;
                    user.BirthDate    = item.BirthDate;
                    user.AddressLine1 = item.AddressLine1;
                    user.AddressLine2 = item.AddressLine2;
                    user.TownCity     = item.TownCity;
                    user.Cellular     = item.Cellular;
                    user.Religion     = item.Religion;
                    user.Citizenship  = item.Citizenship;
                    user.Languages    = item.Languages;
                    user.CivilStatus  = item.CivilStatus;
                    user.Skills       = item.Skills;
                    await UserManager.UpdateAsync(user);

                    #region UpdateRole
                    var roles = await UserManager.GetRolesAsync(user.Id);

                    await UserManager.RemoveFromRolesAsync(user.Id, roles.ToArray());

                    await UserManager.AddToRoleAsync(user.Id, item.userRole);

                    #endregion

                    if (item.Password != null)
                    {
                        var token = await UserManager.GeneratePasswordResetTokenAsync(item.Id);

                        var res = await UserManager.ResetPasswordAsync(item.Id, token, item.Password);

#if DEBUG
                        if (!res.Succeeded)
                        {
                            Debug.WriteLine(string.Join(",", res.Errors));
                        }
#endif
                    }
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            else
            {
                StringBuilder stringBuilder = new StringBuilder();
                foreach (var m in ModelState)
                {
                    if (m.Value.Errors.Count() > 0)
                    {
                        ModelState.AddModelError(m.Key, string.Join(Environment.NewLine, m.Value.Errors.Select(x => x.ErrorMessage)));
                        stringBuilder.AppendLine(m.Value.Errors[0].ErrorMessage);
                    }
                }
                ViewData["EditError"] = "Please, correct all errors." + Environment.NewLine + stringBuilder.ToString();
                ViewData["Model"]     = item;
            }

            return(PartialView("_UserGridViewPartial", unitOfWork.UserRepository.Get(includeProperties: "UserRoles")));
        }
Exemplo n.º 21
0
      public async Task Delete(int? gameID)
      {
         if (gameID == null)
         {
            throw new ArgumentNullException("gameID");
         }

         var id = gameID.Value;

         var game = await db.Games.FindAsync(id);

         if (game == null)
         {
            throw new ArgumentException("Could not find game with id " + id);
         }
         var userID = this.User.Identity.GetUserId();

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         if (!DoesUserOwnGame(appUser, id))
         {
            throw new ArgumentException("Could not delete game");
         }

         var memberships = await db.GameMemberships.Where(m => m.GameID == id).Include(m => m.ApplicationUser).ToListAsync();

         var claims = await Task.WhenAll(memberships.Select(m => m.ApplicationUser).Select(user =>
            manager.GetClaimsAsync(user.Id).ContinueWith(t => new { Claims = t.Result, User = user })));

         var strId = id.ToString();
         var removeTasks = from tuple in claims
                           from claim in tuple.Claims
                           where (claim.Type == "GameOwnership" || claim.Type == "GameOwnership" || claim.Type == "GameMaster") && claim.Value == strId
                           select manager.RemoveClaimAsync(tuple.User.Id, claim);
         await Task.WhenAll(removeTasks);


         db.GameMemberships.RemoveRange(memberships);
         db.Games.Remove(game);

         await db.SaveChangesAsync();
      }
Exemplo n.º 22
0
		public async Task EnsureDatabaseAsync()
		{
			await MigrateDatabaseAsync(ServiceProvider);
			_userManager = ServiceProvider.GetService<UserManager<ApplicationUser>>();
			var roleManager = ServiceProvider.GetService<RoleManager<IdentityRole>>();
			await EnsureUsersAsync(false);
			Context = ServiceProvider.GetRequiredService<ApplicationDbContext>();
			//var userStore = new UserStore<ApplicationUser>(context);
			////var roleManager = new RoleManager<IdentityRole>();
			//var userManager = new UserManager<ApplicationUser>(
			//	, );
			EnsureDatabaseExists();
			Context.Database.EnsureCreated();
			// Add Mvc.Client to the known applications.
			_productsCrud = new CrudBase<Product, int>(
				Context, Context.Products, p => p.ProductId);
			_ordersCrud = new CrudBase<Order, int>(
				Context, Context.Orders, p => p.Id);
			var customersCrud = new CrudBase<Customer, int>(
				Context, Context.Customers, p => p.CustomerId);

			//Action<string, double, int?, DateTime?, string> prod = (name, price, customerId, dateCreated, cratedByUserId) =>
			//{
			//	productId = Prod(productsCrud, productId, name, price, customerId, dateCreated, cratedByUserId);
			//};
			Action<string, string, string> cust = (guid, firstName, lastName) =>
			{
				customersCrud.EnsureEntity(
					guid, customer =>
					{
						customer.FirstName = firstName;
						customer.LastName = lastName;
					});
			};

			cust("6c13ec25-b9cf-4c99-87e7-13a45a034342", "Harry", "Whitburn");
			cust("0e941f32-8ae1-4eae-875a-f748bae3ce2a", "Nick", "Lawden");
			cust("134bd420-f64a-40db-bbe4-0b9a9ff3eb01", "Emil", "Roijer");
			Context.SaveChanges();
			Prod("00d5c0b0-738d-41ff-86d4-dca84da1d4d5", "Apple number1", 10, null, null);
			Prod("cd4c554d-3ca2-49aa-9286-08abacba3fa0", "Apple number1", 10, 1, null, "1");
			Prod("d100c753-3335-439c-88db-b8d9b6c09cc8", "Orange number1", 20, null, null);
			Prod("da93b8a4-4378-4ce0-918e-653f1bd4acaf", "Peanut butter number1", 25, 2, null);
			Prod("fe208521-4a77-4b09-94c2-2f08a4dd8872", "xApple number2", 10, 1, null);
			Prod("844fbc16-3d77-4421-9498-aa65300bc789", "xOrange number2", 20, 2, null);
			Prod("78509968-0073-4c57-8774-ec0d58ea7ff3", "xPeanut butter number2", 25, 2, null);
			Prod("18b8c4e7-48a2-40c7-bea8-1d1879bf852e", "xApple number2", 10, 1, null);
			Prod("e5ab744c-441c-447b-ae92-055b1bce5541", "xOrange number2", 20, 2, null);
			Prod("3a5476b1-7dd8-40b0-a6ce-b6bd3127da6f", "xPeanut butter number2", 25, 2, null);
			Prod("633a125c-1fe2-4f06-859d-a8d8fd52eb11", "xApple number2", 10, 1, null);
			Prod("27eea6ff-c4aa-44a0-84fe-32b0e13beec4", "xOrange number2", 20, 2, null);
			Prod("dcdc6836-3b44-41c5-8ade-792e39ce2112", "xPeanut butter number2", 25, 2, null);
			Prod("fdc3139d-8585-4b34-b815-13598bf55791", "xApple number2", 10, 1, null);
			Prod("46b058b2-dd55-4741-9ee0-99c63c4bd94a", "xOrange number2", 20, 2, null);
			Prod("11c0e3e5-c5d7-4ff5-ba6c-a54b77f91d1b", "xPeanut butter number2", 25, 2, null);
			Prod("796b6b1d-2d6d-413c-bcab-2659c0fdf02f", "Apple number3", 10, 1, null);
			Prod("5f928f2f-bc1b-4e73-a0d8-20c36f817342", "Orange number3", 20, 2, null);
			Prod("f4fa623d-f412-4b68-8a26-17cfa16cb0a0", "Peanut butter number3", 25, 2, null);
			Prod("8f81d6ab-4c8f-4800-aea0-3cb1ca116fc6", "Apple number4", 10, 1, null);
			Prod("f2b8032f-c8ac-406f-8038-939201771901", "Orange number4", 20, 2, null);
			Prod("dc872dbf-956c-43aa-aba4-e75395af7d83", "Peanut butter number4", 25, 2, null);
			Prod("4ca16ce0-1466-4ba6-a69b-5465ed0a4b1d", "Apple number5", 10, 1, null);
			Prod("66cc487b-2eb1-470b-98c8-03ee913d860e", "Orange number5", 20, 2, null);
			Prod("e77e6589-1dba-4c8b-97b1-1564056ddf10", "Peanut butter number5", 25, 2, null);
			Prod("183946f3-41a9-4140-a1cb-b328e3a778d1", "Apple number6", 10, 1, null);
			Prod("2995edec-ec1b-42ed-aa97-1e68a9ef765c", "Orange number6", 20, 2, null);
			Prod("a78204ae-169a-4d30-936b-034cda5abd0f", "Peanut butter number6", 25, 2, null);
			Context.SaveChanges();
			Order("31d57282-4824-4441-9bd0-49588b952728", "First order", 1);
			Order("fc41cc01-6dc3-4ca5-88a4-c4a463cd6316", "Second order", 1);
			Order("f1379562-c779-43bc-a507-71a8506ca8c9", "Third order", 1);
			Context.SaveChanges();
			await EnsureUsersAsync(true);
			await roleManager.CreateAsync(new IdentityRole("Admin"));
			await roleManager.CreateAsync(new IdentityRole("User"));
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "Admin");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "User");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("2"), "User");
		}
 public Task <Worker> FindByIdAsync(string id)
 {
     return(_aspUserManager.FindByIdAsync(id));
 }
        public async Task <IActionResult> Edit(string id, EmployeeManagement employeeManagement)
        {
            if (id != employeeManagement.Employee.Id)
            {
                return(NotFound());
            }

            if (employeeManagement.Employee.SupervisorId == id || employeeManagement.Employee.ApproverId == id)
            {
                ViewBag.ErrorMessage = "Supervisor and Approver can't be themselves";
                return(await Edit(id));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var something = _userManager.GetUserId(this.User);
                    if (id == _userManager.GetUserId(this.User) && employeeManagement.Employee.Title == Employee.ADMIN)
                    {
                        ViewBag.ErrorMessage = "You cannot assign yourself to admin";
                        return(await Edit(id));
                    }

                    var oldEmployee = await _context.Employees.FindAsync(id);

                    if (oldEmployee != null)
                    {
                        var oldApprover = await _context.Employees.FindAsync(oldEmployee.ApproverId);

                        if (oldApprover != null)
                        {
                            await _userManager.RemoveFromRoleAsync(oldApprover, ApplicationRole.TA);
                        }
                        var oldSupervisor = await _context.Employees.FindAsync(oldEmployee.SupervisorId);

                        if (oldSupervisor != null)
                        {
                            await _userManager.RemoveFromRoleAsync(oldSupervisor, ApplicationRole.LM);
                        }
                        if (oldEmployee.Title == Employee.HR_MANAGER)
                        {
                            await _userManager.RemoveFromRoleAsync(oldEmployee, ApplicationRole.HR);
                        }
                        if (oldEmployee.Title == Employee.ADMIN)
                        {
                            await _userManager.RemoveFromRoleAsync(oldEmployee, ApplicationRole.AD);
                        }
                    }

                    var employeeToBeEdited = await _userManager.FindByIdAsync(id);

                    employeeToBeEdited.FirstName    = employeeManagement.Employee.FirstName;
                    employeeToBeEdited.LastName     = employeeManagement.Employee.LastName;
                    employeeToBeEdited.Title        = employeeManagement.Employee.Title;
                    employeeToBeEdited.FlexTime     = employeeManagement.Employee.FlexTime;
                    employeeToBeEdited.VacationTime = employeeManagement.Employee.VacationTime;
                    employeeToBeEdited.Status       = employeeManagement.Employee.Status;
                    employeeToBeEdited.ApproverId   = employeeManagement.Employee.ApproverId;
                    employeeToBeEdited.SupervisorId = employeeManagement.Employee.SupervisorId;
                    employeeToBeEdited.UserName     = employeeManagement.Employee.Email;
                    employeeToBeEdited.Email        = employeeManagement.Employee.Email;
                    employeeToBeEdited.PhoneNumber  = employeeManagement.Employee.PhoneNumber;
                    if (!string.IsNullOrEmpty(employeeManagement.passPhrase))
                    {
                        var datetime     = DateTime.Now;
                        var newSignature = new Signature
                        {
                            HashedSignature = Utility.HashEncrypt(employeeManagement.passPhrase + datetime),
                            CreatedTime     = datetime,
                            Status          = Signature.VALID,
                            EmployeeId      = id
                        };

                        var oldSig = _context.Signatures
                                     .Where(s => s.EmployeeId == id)
                                     .FirstOrDefault();

                        if (oldSig == null)
                        {
                            _context.Signatures.Add(newSignature);
                        }
                        else
                        {
                            oldSig.CreatedTime     = newSignature.CreatedTime;
                            oldSig.HashedSignature = newSignature.HashedSignature;
                            _context.Signatures.Update(oldSig);
                        }

                        await _context.SaveChangesAsync();
                    }
                    await _userManager.UpdateAsync(employeeToBeEdited);

                    var employeePayToBeDisabled = _context.EmployeePays.Find(employeeManagement.EmployeePay.EmployeePayId);
                    employeePayToBeDisabled.Status = EmployeePay.INVALID;
                    _context.Update(employeePayToBeDisabled);
                    await _context.SaveChangesAsync();

                    var newEmployeePay = new EmployeePay
                    {
                        AssignedDate = DateTime.Now,
                        Status       = EmployeePay.VALID,
                        EmployeeId   = employeeToBeEdited.Id,
                        PayGradeId   = employeeManagement.EmployeePay.PayGradeId
                    };
                    _context.Add(newEmployeePay);
                    await _context.SaveChangesAsync();

                    var approver = _context.Employees.Find(employeeManagement.Employee.ApproverId);
                    await _userManager.AddToRoleAsync(approver, ApplicationRole.TA);

                    var supervisor = _context.Employees.Find(employeeManagement.Employee.SupervisorId);
                    await _userManager.AddToRoleAsync(supervisor, ApplicationRole.LM);

                    if (employeeManagement.Employee.Title == Employee.HR_MANAGER)
                    {
                        await _userManager.AddToRoleAsync(employeeToBeEdited, ApplicationRole.HR);
                    }
                    if (employeeManagement.Employee.Title == Employee.ADMIN)
                    {
                        await _userManager.AddToRoleAsync(employeeToBeEdited, ApplicationRole.AD);
                    }
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmployeeExists(employeeManagement.Employee.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }

            return(View(employeeManagement));
        }
Exemplo n.º 25
0
        public async Task <IList <string> > GetUserRolesById(string userId)
        {
            var user = await _userManager.FindByIdAsync(userId);

            return(await _userManager.GetRolesAsync(user));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> EditUser([FromRoute] string id, [FromBody] UsuarioModel model)
        {
            try
            {
                //variavel para indicar que o email não foi alterado
                bool email = false;
                //variavel para indicar que a senha não foi alterada
                bool pass = false;
                //variavel para efetuar validação de email
                IdentityResult validEmail = new IdentityResult();
                //variavel para efetuar validação de senha
                IdentityResult validPass = new IdentityResult();

                Usuario usuario = await userManager.FindByIdAsync(id);

                if (usuario != null)
                {
                    //verifica se o email não foi alterado
                    if ((!usuario.Email.Equals(model.Email)) && (!string.IsNullOrEmpty(model.Email)))
                    {
                        //validar email do usuario
                        usuario.Email    = model.Email;
                        usuario.UserName = model.Email;
                        validEmail       = await userValidator.ValidateAsync(userManager, usuario);

                        if (!validEmail.Succeeded)
                        {
                            ModelState.AddModelError("Email", "E-mail já cadastrado");
                        }
                    }
                    else
                    {
                        email = true;
                    }

                    //validar senha(se foi passada)
                    if (!string.IsNullOrEmpty(model.Senha))
                    {
                        validPass = await passwordValidator.ValidateAsync(userManager, usuario, model.Senha);

                        if (validPass.Succeeded)
                        {
                            usuario.PasswordHash = passwordHasher.HashPassword(usuario, model.Senha);
                        }
                        else
                        {
                            ModelState.AddModelError("Senha", "Senha invalida");
                        }
                    }
                    else
                    {
                        pass = true;
                    }

                    if ((validEmail.Succeeded || email) && (validPass.Succeeded || pass))
                    {
                        usuario.Nome = model.Nome;

                        IdentityResult result = await userManager.UpdateAsync(usuario);

                        if (result.Succeeded)
                        {
                            return(Ok(usuario));
                        }
                    }

                    return(BadRequest(ModelState.Values.SelectMany(v => v.Errors)));
                }
                else
                {
                    ModelState.AddModelError("Usuario", "Usuário não encontrado");
                    return(NotFound(ModelState.Values.SelectMany(v => v.Errors)));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Exemplo n.º 27
0
 public async Task <User> GetUserById(string id) => await UserManager.FindByIdAsync(id);
        public async Task <ActionResult> Edit([Bind(Include = "Id")] ApplicationUser applicationUser, params string[] rolesSelectedOnView)
        {
            if (ModelState.IsValid)
            {
                // If the user is currently stored having the Admin role,
                var rolesCurrentlyPersistedForUser = await UserManager.GetRolesAsync(applicationUser.Id);

                bool isThisUserAnAdmin = rolesCurrentlyPersistedForUser.Contains("Admin");

                // and the user did not have the Admin role checked,
                rolesSelectedOnView = rolesSelectedOnView ?? new string[] { };
                bool isThisUserAdminDeselected = !rolesSelectedOnView.Contains("Admin");

                // and the current stored count of users with the Admin role == 1,
                var role = await RoleManager.FindByNameAsync("Admin");

                bool isOnlyOneUserAnAdmin = role.Users.Count == 1;

                // (populate the roles list in case we have to return to the Edit view)
                applicationUser = await UserManager.FindByIdAsync(applicationUser.Id);

                applicationUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
                {
                    Selected = rolesCurrentlyPersistedForUser.Contains(x.Name),
                    Text     = x.Name,
                    Value    = x.Name
                });

                // then prevent the removal of the Admin role.
                if (isThisUserAnAdmin && isThisUserAdminDeselected && isOnlyOneUserAnAdmin)
                {
                    ModelState.AddModelError("", "At least one user must retain the Admin role; you are attempting to delete the Admin role from the last user who has been assigned to it.");
                    return(View(applicationUser));
                }

                var result = await UserManager.AddToRolesAsync(
                    applicationUser.Id,
                    rolesSelectedOnView.Except(rolesCurrentlyPersistedForUser).ToArray());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(applicationUser));
                }

                result = await UserManager.RemoveFromRolesAsync(
                    applicationUser.Id,
                    rolesCurrentlyPersistedForUser.Except(rolesSelectedOnView).ToArray());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return(View(applicationUser));
                }

                return(RedirectToAction("Index"));
            }

            ModelState.AddModelError("", "Something failed.");
            return(View(applicationUser));
        }
Exemplo n.º 29
0
            public async Task CanFindById()
            {
                var user = await _userManager.FindByIdAsync(2.ToString());

                Assert.NotNull(user);
            }
Exemplo n.º 30
0
        public async Task<ActionResult> RegisterFinish(OrderViewModel modelObj, string slug)
        {
            if (modelObj == null) modelObj = new OrderViewModel();

            TryUpdateModel(modelObj);

            using (var ctx = new SportDataContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId());

                var team = SearchService.FindTeam(modelObj.Entrant, ctx);
                if (team == null)                
                    team = modelObj.CreateTeam();

                var driver1 = await SearchService.FindUser(modelObj.Driver1License, ctx) ?? await SearchService.FindUserById(modelObj.Driver1Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver1FirstName, modelObj.Driver1LastName, ctx);
                var driver2 = await SearchService.FindUser(modelObj.Driver2License, ctx) ?? await SearchService.FindUserById(modelObj.Driver2Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver2FirstName, modelObj.Driver2LastName, ctx);

                //Защита от
                if (driver1==null || string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + "")) {
                    driver1 = modelObj.CreateDriver1();
                    var existingUser = await userManager.FindByNameAsync(driver1.UserName);
                    if (existingUser != null)
                        driver1.UserName = Guid.NewGuid().ToString();
                }
                if (driver2 == null || string.IsNullOrWhiteSpace(driver2.LastName + driver2.FirstName + ""))
                {
                    driver2 = modelObj.CreateDriver2();
                    var existingUser = await userManager.FindByNameAsync(driver2.UserName);
                    if (existingUser != null)
                        driver2.UserName = Guid.NewGuid().ToString();
                }

                var car = modelObj.CreateCar();

                var ev = await EventService.GetEvent(slug, ctx);

                Dictionary<SubEvent, Order> orders = new Dictionary<SubEvent,Order>();
                ViewBag.Error = null;
                if (driver1.Id == driver2.Id)
                {
                    ViewBag.Error = "В вашей заявке совпадают первый и второй водитель. Пожалуйста, проверьте правильность заполнения заявки. Если у вас в настоящее время нет полной информации о составе экипажа - оставьте недостающие поля пустыми.";                    
                }
                if (string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + driver2.LastName + driver2.FirstName))
                {
                    ViewBag.Error = "Укажите пожалуйста в заявке не менее 1 водителя.";                    
                }
                if (modelObj.Groups == null || modelObj.Groups.Count() == 0)
                {
                    ViewBag.Error = "В вашей заявке на " + ev.Title + " не указано ни одной зачетной группы. Пожалуйста, укажите минимум 1 зачет из списка.";                    
                }
                if(!string.IsNullOrWhiteSpace(ViewBag.Error))
                    return View("RegistrationError", ev);

                foreach (var group in modelObj.Groups)
                {
                    var tokens = group.Split('_');
                    var subEv = ev.SubEvents.First(e=>e.Id == int.Parse(tokens[0]));

                    if(!orders.ContainsKey(subEv)) {
                        orders.Add(subEv, new Order() {
                            Driver = driver1,
                            CoDriver = driver2,
                            Team = team,
                            Car = car,
                            Redimmed = false,
                            Confirmed = false,
                            CreatedAt= DateTime.Now,
                            StartNumber="",
                            Group = new List<Group>(),
                            CreatedBy = currentUser
                        });
                    }

                    orders[subEv].Group.Add(subEv.Groups.First(g => g.Id == int.Parse(tokens[1])));
                }

                foreach (var item in orders.Keys)
                {

                    item.Tag.Orders = item.Tag.Orders ?? new List<Order>();
                    item.Tag.Orders.Add(orders[item]);
                }
                try
                {
                    await ctx.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    throw;
                }

                return View("RegistrationComplete", ev);
            }
        }
        //
        // GET: /Users/Details/5
        public async Task<ActionResult> Details(string id)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(db);
            var roleStore = new RoleStore<ApplicationRole>(db);

            var userManager = new UserManager<ApplicationUser>(userStore);
            var roleManager = new RoleManager<ApplicationRole>(roleStore);
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await userManager.FindByIdAsync(id);

            ViewBag.RoleNames = await userManager.GetRolesAsync(user.Id);

            return View(user);
        }
Exemplo n.º 32
0
        public async Task <IActionResult> AddUser(int id)
        {
            User userInviting = await _userManager.GetUserAsync(User);

            if (userInviting == null)
            {
                return(Problem());
            }

            var profileInviting = _context.Profile
                                  .Include(u => u.User)
                                  .FirstOrDefault(u => u.UserId == userInviting.Id);

            var profileInvited = _context.Profile
                                 .Include(u => u.User)
                                 .FirstOrDefault(u => u.ProfileId == id);

            User userInvited = await _userManager.FindByIdAsync(profileInvited.UserId.ToString());

            if (profileInvited == null)
            {
                ModelState.AddModelError("user", $"No results found matching \"{profileInvited.ProfileName}\"");
                return(View());
            }


            // friend relationship (or invite) already exists
            if (await _context.UserRelationships.AnyAsync(r => r.RelatedUser.Id == userInvited.Id && r.RelatingUser.Id == userInviting.Id))
            {
                return(RedirectToAction(nameof(Index)));
            }

            var relationship = new UserRelationship
            {
                RelatingProfileId = profileInviting.ProfileId,
                RelatedProfileId  = profileInvited.ProfileId,
                RelatedUser       = userInvited,
                RelatingUser      = userInviting,
                Type = Relationship.Pending
            };

            //friend has already sent relationship invite -add them as a friend without invite
            var existingRelationship = await _context.UserRelationships.FirstOrDefaultAsync(r => r.RelatedProfileId == profileInviting.ProfileId && r.RelatingProfileId == profileInvited.ProfileId);

            if (existingRelationship != null)
            {
                existingRelationship.Type = Relationship.Friend;
                _context.UserRelationships.Update(existingRelationship);
                relationship.Type        = Relationship.Friend;
                TempData["FriendInvite"] = $"{profileInvited.ProfileName} has been added to your friends.";
            }
            else
            {
                TempData["FriendInvite"] = $"A friend invite was sent to {userInvited.Profile.ProfileName}.";
                _context.UserRelationships.Add(relationship);
            }

            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
        /// <summary>
        /// Initializes the user.
        /// </summary>
        public void InitializeUser(SessionAuthUser authUser)
        {
            AuthUser = authUser;
              if ((AuthUser == null) || (AuthUser.SystemUserID == 0))
              {
            var store = new UserStore<ApplicationUser>(new AuthenticationDbContext());
            var userManager = new UserManager<ApplicationUser>(store);
            ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
            if (user == null)
              return;

            string nickname = user.UserName;
            if (nickname.Contains(" "))
              nickname = user.UserName.Substring(0, user.UserName.IndexOf(" "));

            if (nickname.Length > 30)
              nickname = nickname.Substring(0, 30);

            using (AuthManager authManager = PublicConfigurationSettings.GetAuthManager.Invoke())
            {
              authManager.RegisterUser(User.Identity.GetUserId(), nickname,
            user.UserName, user.PhoneNumber, user.Email);
              AuthUser = authManager.GetAuthUser(User.Identity.GetUserId());
            }
              }

              ViewBag.AuthUser = AuthUser;
              bool hasClient = PublicLogicManager.Client.CurrentUserHasClient();
              ViewBag.HasClient = hasClient;
              ViewBag.UserNickname = AuthUser.Nickname;
              if (hasClient)
              {
            ClientData client = PublicLogicManager.Client.LoadClientModel(false);
            ViewBag.ClientName = client.CompanyName;
            ViewBag.Client = client;

            ViewBag.Build = BuildNumber;
              }

              PerformClientLogic();
        }
        public async Task <IActionResult> Edit(string id, [Bind("Id,Nom,Prenom,Email,PhoneNumber,AssociationID")] ApplicationUser applicationUser)
        {
            ApplicationUser applicationUser1 = await _userManager.FindByIdAsync(id);

            if (id != applicationUser.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    applicationUser1.Email = applicationUser.Email;

                    applicationUser1.Nom         = applicationUser.Nom;
                    applicationUser1.Prenom      = applicationUser.Prenom;
                    applicationUser1.PhoneNumber = applicationUser.PhoneNumber;

                    applicationUser1.AssociationID = applicationUser.AssociationID;
                    //applicationUser1.UserName = applicationUser.Nom;


                    var Result = await _userManager.UpdateAsync(applicationUser1);

                    // await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    //if (!ApplicationUserExists(applicationUser.Id))
                    //{
                    foreach (var entry in ex.Entries)
                    {
                        if (entry.Entity is ApplicationUser)
                        {
                            var proposedValues = entry.CurrentValues;
                            var databaseValues = entry.GetDatabaseValues();

                            foreach (var property in proposedValues.Properties)
                            {
                                var proposedValue = proposedValues[property];
                                var databaseValue = databaseValues[property];

                                // TODO: decide which value should be written to database
                                // proposedValues[property] = <value to be saved>;
                            }

                            // Refresh original values to bypass next concurrency check
                            entry.OriginalValues.SetValues(databaseValues);
                        }
                        else
                        {
                            throw new NotSupportedException(
                                      "Don't know how to handle concurrency conflicts for "
                                      + entry.Metadata.Name);
                        }
                    }
                    //return NotFound();


                    //}
                    //else
                    //{
                    //    throw;
                    //}
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["AssociationID"] = new SelectList(_context.Associations, "AssociationID", "Nom", applicationUser.AssociationID);
            return(View(applicationUser));
        }
Exemplo n.º 35
0
        public async Task DeleteAsync(string id)
        {
            var user = await _userManager.FindByIdAsync(id);

            await _userManager.DeleteAsync(user);
        }
Exemplo n.º 36
0
 public async static Task <ApplicationUser> GetCurrentUser(this UserManager <ApplicationUser> _userManager, HttpContext httpContext)
 {
     return(await _userManager.FindByIdAsync(httpContext.User.GetUserId()));
 }
Exemplo n.º 37
0
 private async Task <ApplicationUser> GetCurrentUserAsync() => await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
Exemplo n.º 38
0
 public async Task <IActionResult> ReturnPosterUsername(string usernameId) => Json((await _userManager.FindByIdAsync(usernameId)).UserName);
Exemplo n.º 39
0
        public async Task <AuthenticationResult> RefreshTokenAsync(string token, string refreshToken)
        {
            var validatedToken = GetPrincipalFromToken(token);

            if (validatedToken == null)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "Invalid Token" }
                });
            }

            var expiryDateUnix =
                long.Parse(validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Exp).Value);

            var expiryDateTimeUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                                    .AddSeconds(expiryDateUnix);

            if (expiryDateTimeUtc > DateTime.UtcNow)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "This token hasn't expired yet" }
                });
            }

            var jti = validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Jti).Value;

            var storedRefreshToken = await _context.RefreshTokens.SingleOrDefaultAsync(x => x.Token == refreshToken);

            if (storedRefreshToken == null)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "This refresh token does not exist" }
                });
            }

            if (DateTime.UtcNow > storedRefreshToken.ExpiryDate)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "This refresh token has expired" }
                });
            }

            if (storedRefreshToken.Invalidated)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "This refresh token has been invalidated" }
                });
            }

            if (storedRefreshToken.Used)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "This refresh token has been used" }
                });
            }

            if (storedRefreshToken.JwtId != jti)
            {
                return(new AuthenticationResult {
                    Errors = new[] { "This refresh token does not match this JWT" }
                });
            }

            storedRefreshToken.Used = true;
            _context.RefreshTokens.Update(storedRefreshToken);
            await _context.SaveChangesAsync();

            var user = await _userManager.FindByIdAsync(validatedToken.Claims.Single(x => x.Type == "id").Value);

            return(await GenerateAuthenticationResultForUserAsync(user));
        }
Exemplo n.º 40
0
 public async Task <ApplicationUser> GetUserByIdAsync(string userId)
 {
     return(await _userManager.FindByIdAsync(userId));
 }
Exemplo n.º 41
0
        public async Task SignUserById(string id, bool isPersistent)
        {
            var user = await _userManager.FindByIdAsync(id);

            await _signInManager.SignInAsync(user, isPersistent);
        }
Exemplo n.º 42
0
        public async Task <JsonResult> Get(int pageIndex,
                                           int pageSize,
                                           string pageOrder,
                                           int group,
                                           string userName,
                                           string title,
                                           string fromDate,
                                           string toDate,
                                           sbyte articleStatus
                                           )
        {
            DateTime?sDate = null,
                    eDate  = null;

            ArticleStatus?status = null;

            if (!String.IsNullOrWhiteSpace(fromDate))
            {
                sDate = Utilities.ToEnglishDate(fromDate).Date;
            }

            if (!String.IsNullOrWhiteSpace(toDate))
            {
                eDate = Utilities.ToEnglishDate(toDate).Date;
            }

            if (articleStatus != -1)
            {
                status = (ArticleStatus)articleStatus;
            }

            if (pageOrder.Trim() == "ID")
            {
                pageOrder = "LastUpdate desc";
            }

            var list = Articles.Get(pageIndex,
                                    pageSize,
                                    pageOrder,
                                    _articleType,
                                    group,
                                    userName,
                                    title,
                                    sDate,
                                    eDate,
                                    status
                                    );

            foreach (var item in list)
            {
                try
                {
                    item.UserTitle = (await UserManager.FindByIdAsync(item.UserID)).UserName;
                }
                catch (Exception)
                {
                    item.UserTitle = StaticValues.HomeTitle;
                }
            }

            int total     = Articles.Count(_articleType, group, userName, title, sDate, eDate, status);
            int totalPage = (int)Math.Ceiling((decimal)total / pageSize);

            if (pageSize > total)
            {
                pageSize = total;
            }

            if (list.Count < pageSize)
            {
                pageSize = list.Count;
            }

            JsonResult result = new JsonResult()
            {
                Data = new
                {
                    TotalPages = totalPage,
                    PageIndex  = pageIndex,
                    PageSize   = pageSize,
                    Rows       = list
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            return(result);
        }
Exemplo n.º 43
0
 private async Task <ApplicationUser> GetCurrentUserAsync()
 {
     return(await UserManager.FindByIdAsync(Context.User.GetUserId()));
 }
Exemplo n.º 44
0
      public async Task Update(GameResult result)
      {
         if (result == null)
         {
            throw new ArgumentNullException("game");
         }

         GameVisibility visibility;
         if (!Enum.TryParse(result.Visibility, out visibility))
         {
            throw new ArgumentException("game.Visibility is not valid");
         }

         var game = await db.Games.FindAsync(result.GameId);

         if (game == null)
         {
            throw new ArgumentException("Could not find game with id " + result.GameId);
         }

         var userID = this.User.Identity.GetUserId();

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         var gameId = game.ID.ToString();

         var ownership = appUser.Claims.FirstOrDefault(c => c.ClaimType == "GameOwnership" && c.ClaimValue == gameId);

         if (ownership == null)
         {
            throw new ArgumentException("Could not update game");
         }

         game.Name = result.Name;
         game.Visibility = visibility;

         await db.SaveChangesAsync();
      }
Exemplo n.º 45
0
        public async Task<ActionResult> AccreditationFinish(Accreditation model, string slug)
        {
            using(var ctx = new SportDataContext()) {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId());

                model.User = currentUser;
                var ev = await EventService.GetEvent(slug, ctx); 

                var tag = ev.SubEvents.Select(s => s.Tag).First();                
                model.Tag = tag;

                tag.Accreditations.Add(model);
                await ctx.SaveChangesAsync();

                ViewBag.Slug = slug;
                ViewBag.EventName = ev.Title;

                EmailService.SendAdministrativeMail("Поступила заявка на аккредитацию на " + ev.Title,
                    @"Поступила заявка на аккредитацию на " + ev.Title + " от " + model.User.LastName + " " + model.User.FirstName + ". Пожалуйста перейдите по ссылке http://www.afspb.org.ru/controlpanel/accreditations/validate/" + model.Id + " для обработки заявки."); 

                return View();
            }
        }
        public IActionResult add([FromBody] AdvertViewModel model)
        {
            var advert = model;

            if (advert != null)
            {
                string imageName = Guid.NewGuid().ToString() + ".jpg";
                string base64    = model.Image;
                if (base64.Contains(","))
                {
                    base64 = base64.Split(',')[1];
                }

                var    bmp         = base64.FromBase64StringToImage();
                string fileDestDir = _env.ContentRootPath;
                fileDestDir = Path.Combine(fileDestDir, _configuration.GetValue <string>("ImagesPath"));

                string fileSave = Path.Combine(fileDestDir, imageName);
                if (bmp != null)
                {
                    int size  = 1000;
                    var image = ImageHelper.CompressImage(bmp, size, size);
                    image.Save(fileSave, ImageFormat.Jpeg);
                }
                dbcontext.Adverts.Add(new Advert {
                    Title = model.Title, Description = model.Description, ImagePath = imageName, User = _userManager.FindByIdAsync(model.UserId).Result
                });
                dbcontext.SaveChanges();
                return(Ok(advert));
            }

            else
            {
                return(new BadRequestObjectResult("Server error"));
            }
        }
 private ApplicationUser currentUser()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
     return user;
 }
Exemplo n.º 48
0
        public async Task <IActionResult> OnGet()
        {
            AppUser = await _userManager.FindByIdAsync(User.GetUserId());

            return(Page());
        }
Exemplo n.º 49
0
        public async Task<ActionResult> DeleteConfirmed(string id) {

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

            var userStore = new UserStore<ApplicationUser>(db);
            var userManager = new UserManager<ApplicationUser>(userStore);

            if (ModelState.IsValid) {
                if (id == null) {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                var user = await userManager.FindByIdAsync(id);
                
                // ev. 3parts inloggningar
                var logins = user.Logins;
                foreach (var login in logins.ToList()) {
                    await userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                }

                var rolesForUser = await userManager.GetRolesAsync(id);

                if (rolesForUser.Count() > 0) {
                    foreach (var item in rolesForUser.ToList()) {
                        // item should be the name of the role
                        var result = await userManager.RemoveFromRoleAsync(user.Id, item);
                    }
                }

                if (user.Documents.Count() > 0) {
                    foreach (var doc in user.Documents.ToList()) {
                        db.Documents.Remove(doc);
                    }
                }

                await userManager.DeleteAsync(user);

                return RedirectToAction("Index");
            }
            else {
                return View();
            }
        }
Exemplo n.º 50
0
 public async Task<UserEntity> GetUserAsync(Guid userId)
 {
     return await _userManager.FindByIdAsync(userId.ToString());
 }
        public async Task <UserDataResponseObj> FetchLoggedInUserDetailsAsync(string userId)
        {
            try
            {
                var currentUser = await _userManager?.FindByIdAsync(userId);

                if (currentUser == null)
                {
                    return new UserDataResponseObj {
                               Status = new APIResponseStatus {
                                   IsSuccessful = true
                               }
                    }
                }
                ;
                cor_staff            currentUserStaffDetails         = null;
                cor_companystructure currentUserCompanyStructDetails = null;
                UserDataResponseObj  profile    = null;
                List <string>        activities = new List <string>();

                var additionalActivityIds = _dataContext.cor_userroleadditionalactivity.Where(x => x.UserId == currentUser.Id).Select(x => x.ActivityId);

                var userRoleActivityIds = (from a in _dataContext.UserRoles
                                           join b in _dataContext.cor_userrole on a.RoleId equals b.Id
                                           join c in _dataContext.cor_userroleactivity on b.Id equals c.RoleId
                                           where a.UserId == currentUser.Id
                                           select c.ActivityId).ToList();



                if (userRoleActivityIds.Count() > 0)
                {
                    activities = _dataContext.cor_activity
                                 .Where(x => additionalActivityIds
                                        .Contains(x.ActivityId) || userRoleActivityIds
                                        .Contains(x.ActivityId)).Select(x => x.ActivityName.ToLower()).ToList();
                }
                var userRoles = await _userManager.GetRolesAsync(currentUser);

                if (userRoles.Contains(StaticRoles.GODP))
                {
                    activities = await _dataContext.cor_activity.Where(x => x.Deleted == false).Select(s => s.ActivityName).ToListAsync();
                }

                if (currentUser.StaffId > 0)
                {
                    currentUserStaffDetails = await _dataContext.cor_staff.FirstOrDefaultAsync(z => z.StaffId == currentUser.StaffId);

                    currentUserCompanyStructDetails = await _dataContext.cor_companystructure.SingleOrDefaultAsync(m => m.CompanyStructureId == currentUserStaffDetails.StaffOfficeId);

                    if (currentUserCompanyStructDetails != null)
                    {
                        return(profile = new UserDataResponseObj
                        {
                            BranchId = currentUserCompanyStructDetails.CompanyStructureId,
                            StaffId = currentUserStaffDetails.StaffId,
                            BranchName = currentUserCompanyStructDetails.Name,
                            CompanyId = currentUserCompanyStructDetails.CompanyStructureId,
                            CompanyName = currentUserCompanyStructDetails.Name,
                            CountryId = currentUserStaffDetails.CountryId,
                            CustomerName = currentUserStaffDetails.FirstName + " " + currentUserStaffDetails.LastName,
                            StaffName = currentUserStaffDetails.FirstName + " " + currentUserStaffDetails.LastName,
                            LastLoginDate = DateTime.Now,
                            UserId = currentUser.Id,
                            UserName = currentUser.UserName,
                            Roles = await _userManager.GetRolesAsync(currentUser),
                            Activities = activities.Count() < 1 ? null : activities,
                            Email = currentUser.Email,
                            DepartmentId = currentUserStaffDetails.StaffOfficeId ?? 0,
                            Status = new APIResponseStatus
                            {
                                IsSuccessful = true
                            }
                        });
                    }
                }
                profile = new UserDataResponseObj
                {
                    LastLoginDate = DateTime.Now,
                    UserId        = currentUser.Id,
                    UserName      = currentUser.UserName,
                    StaffId       = currentUser.StaffId,
                    Activities    = activities.Count() < 1 ? null : activities,
                    Roles         = await _userManager.GetRolesAsync(currentUser),
                    Email         = currentUser.Email,
                    Status        = new APIResponseStatus
                    {
                        IsSuccessful = true
                    }
                };


                if (profile == null)
                {
                    return(new UserDataResponseObj
                    {
                        Status = new APIResponseStatus
                        {
                            IsSuccessful = false,
                            Message = new APIResponseMessage
                            {
                                FriendlyMessage = "Unable to fetch user details"
                            }
                        }
                    });
                }
                return(profile);
            }
            catch (Exception ex)
            {
                #region Log error
                var errorCode = ErrorID.Generate(4);
                _logger.Error($"ErrorID : FetchLoggedInUserDetailsAsync{errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}");
                return(new UserDataResponseObj
                {
                    Status = new APIResponseStatus
                    {
                        IsSuccessful = false,
                        Message = new APIResponseMessage
                        {
                            FriendlyMessage = "Error occured!! Please tyr again later",
                            MessageId = errorCode,
                            TechnicalMessage = $"ErrorID : FetchLoggedInUserDetailsAsync{errorCode} Ex : {ex?.Message ?? ex?.InnerException?.Message} ErrorStack : {ex?.StackTrace}"
                        }
                    }
                });

                #endregion
            }
        }
Exemplo n.º 52
0
 private async Task <User> GetCurrentUserAsync()
 {
     return(await _userManager.FindByIdAsync(HttpContext.User.GetUserId()));
 }
Exemplo n.º 53
0
    private async Task CreateUsersAsync()
    {
        // local variables
        DateTime createdDate         = new DateTime(2016, 03, 01, 12, 30, 00);
        DateTime lastModifiedDate    = DateTime.Now;
        string   role_Administrators = "Administrators";
        string   role_Registered     = "Registered";

        //Create Roles (if they doesn't exist yet)
        if (!await RoleManager.RoleExistsAsync(role_Administrators))
        {
            await RoleManager.CreateAsync(new IdentityRole(role_Administrators));
        }
        if (!await RoleManager.RoleExistsAsync(role_Registered))
        {
            await RoleManager.CreateAsync(new IdentityRole(role_Registered));
        }
        // Create the "Admin" ApplicationUser account (if it doesn't exist already)
        var user_Admin = new ApplicationUser()
        {
            UserName         = "******",
            Email            = "*****@*****.**",
            CreatedDate      = createdDate,
            LastModifiedDate = lastModifiedDate
        };

        // Insert "Admin" into the Database and also assign the "Administrator" role to him.
        if (await UserManager.FindByIdAsync(user_Admin.Id) == null)
        {
            await UserManager.CreateAsync(user_Admin, "Pass4Admin");

            await UserManager.AddToRoleAsync(user_Admin, role_Administrators);

            // Remove Lockout and E-Mail confirmation.
            user_Admin.EmailConfirmed = true;
            user_Admin.LockoutEnabled = false;
        }
#if DEBUG
        // Create some sample registered user accounts (if they don't exist already)
        var user_Ryan = new ApplicationUser()
        {
            UserName         = "******",
            Email            = "*****@*****.**",
            CreatedDate      = createdDate,
            LastModifiedDate = lastModifiedDate,
            EmailConfirmed   = true,
            LockoutEnabled   = false
        };
        var user_Solice = new ApplicationUser()
        {
            UserName         = "******",
            Email            = "*****@*****.**",
            CreatedDate      = createdDate,
            LastModifiedDate = lastModifiedDate,
            EmailConfirmed   = true,
            LockoutEnabled   = false
        };
        var user_Vodan = new ApplicationUser()
        {
            UserName         = "******",
            Email            = "*****@*****.**",
            CreatedDate      = createdDate,
            LastModifiedDate = lastModifiedDate,
            EmailConfirmed   = true,
            LockoutEnabled   = false
        };
        // Insert sample registered users into the Database and also assign the "Registered" role to him.
        if (await UserManager.FindByIdAsync(user_Ryan.Id) == null)
        {
            await UserManager.CreateAsync(user_Ryan, "Pass4Ryan");

            await UserManager.AddToRoleAsync(user_Ryan, role_Registered);

            // Remove Lockout and E-Mail confirmation.
            user_Ryan.EmailConfirmed = true;
            user_Ryan.LockoutEnabled = false;
        }
        if (await UserManager.FindByIdAsync(user_Solice.Id) == null)
        {
            await UserManager.CreateAsync(user_Solice, "Pass4Solice");

            await UserManager.AddToRoleAsync(user_Solice, role_Registered);

            // Remove Lockout and E-Mail confirmation.
            user_Solice.EmailConfirmed = true;
            user_Solice.LockoutEnabled = false;
        }
        if (await UserManager.FindByIdAsync(user_Vodan.Id) == null)
        {
            await UserManager.CreateAsync(user_Vodan, "Pass4Vodan");

            await UserManager.AddToRoleAsync(user_Vodan, role_Registered);

            // Remove Lockout and E-Mail confirmation.
            user_Vodan.EmailConfirmed = true;
            user_Vodan.LockoutEnabled = false;
        }
#endif
        await DbContext.SaveChangesAsync();
    }
Exemplo n.º 54
0
 public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
 {
     if (!ModelState.IsValid)
     {
         return View(model);
     }
     ApplicationDbContext db = new ApplicationDbContext();
     var userStore = new UserStore<ApplicationUser>(db);
     var userManager = new UserManager<ApplicationUser>(userStore);
     var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
     if (user != null)
     {
         user.PhoneNumber = model.Number;
     }
     var result = await userManager.UpdateAsync(user);
     var ctx = userStore.Context;
     var result1 = await ctx.SaveChangesAsync();
     // However, it always succeeds inspite of not updating the database
     if (!result.Succeeded)
     {
         AddErrors(result);
     }
     return RedirectToAction("Index", "Manage");
 }