C# (CSharp) ApplicationUser примеры использования

C# (CSharp) ApplicationUser - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для ApplicationUser, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
0
 protected void CreateUser_Click(object sender, EventArgs e)
 {
     var manager = new UserManager();
     var user = new ApplicationUser() { UserName = UserName.Text };
     IdentityResult result = manager.Create(user, Password.Text);
     if (result.Succeeded)
     {
         ApplicationUser newUser = manager.Find(UserName.Text, Password.Text);
         var sa = new StoredAccount();
         sa.CreateNewAccount(newUser.Id,Email.Text);
         var returnUrl = Request.QueryString["ReturnUrl"];
         IdentityHelper.SignIn(manager, user, isPersistent: false);
         if (returnUrl == null)
         {
             IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response);
         }
         else
         {
             IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
         }
     }
     else
     {
         ErrorMessage.Text = result.Errors.FirstOrDefault();
     }
 }
 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);
 }
Пример #3
0
        // ************************
        // Beer Postings Methods
        // ************************
        public BeerPosting CreatePosting(ApplicationUser owner, BeerPosting _newbeerposting)
        {
            context.BeerPostings.Add(_newbeerposting);
            context.SaveChanges();

            return _newbeerposting;
        }
        public ActionResult Create([DataSourceRequest]DataSourceRequest request, UserAdministrationModel model)
        {
            if (model != null && this.ModelState.IsValid)
            {
                var newUser = new ApplicationUser
                {
                    UserName = model.UserName,
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    CreatedOn = DateTime.Now
                };

                var password = string.IsNullOrEmpty(model.NewPassword) ? "123456" : model.NewPassword;

                this.userManager.Create(newUser, password);

                if (model.IsAdmin)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Admin);
                }

                if (model.IsArtist)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Artist);
                }

                if (model.IsDesigner)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Designer);
                }

                if (model.IsRegular)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Regular);
                }

                if (model.IsSeller)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Seller);
                }

                if (model.IsStudent)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Student);
                }

                if (model.IsTrainer)
                {
                    this.userManager.AddToRole(newUser.Id, ApplicationRoles.Trainer);
                }

                model.Id = newUser.Id;
                model.NewPassword = string.Empty;

                return this.GridOperationObject(model, request);
            }

            return null;
        }
Пример #5
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;
        }
Пример #6
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);

                    var service = new Service();
                    User register = new User();
                    register.Active = true;
                    register.BirthYear = model.BirthYear;
                    register.DisplayName = model.DisplayName;
                    register.Email = model.Email;
                    register.Gender = model.Gender;
                    register.UserName = model.UserName;
                    service.CreateUser(ref register);

                    DisplayWelcomeMessage(register);
                    return RedirectToAction("Index", "User");
                }
                else
                {
                    ModelState.AddModelError("UserName", "That username is already taken");
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form.
            return View(model);
        }
Пример #7
0
 // Allow Initialization with an instance of ApplicationUser:
 public EditUserViewModel(ApplicationUser user)
 {
     this.UserName = user.UserName;
     this.FirstName = user.FirstName;
     this.LastName = user.LastName;
     this.Email = user.Email;
 }
Пример #8
0
        private static void AddAllUserCohortMeetings(ApplicationDbContext context, ApplicationUser user, int utcOffset, ref List<MeetingViewModel> meetingDtos)
        {
            var enrollmentsWithThisUser = context.Courses.SelectMany(u => u.Enrollments.Where(e => e.ApplicationUserId == user.Id));

            foreach (var enrollment in enrollmentsWithThisUser)
            {
                //Get all meetings with this enrollment where its cohort has a meeting that is in the future
                Enrollment enrollment1 = enrollment;
                var cohortMeetings = context.Meetings.Where(m => m.CourseId == enrollment1.CourseId);
                foreach (var meeting in cohortMeetings)
                {
                    var meetingToAdd = new MeetingViewModel
                    {
                        Id = meeting.Id,
                        Title = meeting.Title,
                        Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc).AddMinutes(utcOffset),
                        End = DateTime.SpecifyKind(meeting.End, DateTimeKind.Utc).AddMinutes(utcOffset),
                        Description = meeting.Description,
                        IsAllDay = meeting.IsAllDay,
                        RecurrenceRule = meeting.RecurrenceRule,
                        RecurrenceException = meeting.RecurrenceException,
                        RecurrenceId = meeting.RecurrenceId,
                        CourseId = meeting.CourseId,
                        GtmUrl = meeting.GtmUrl
                    };
                    meetingDtos.Add(meetingToAdd);
                }
            }
        }
Пример #9
0
        public ActionResult Index()
        {
            using (profiler.Step("Home/Index Action"))
            {
                var model = new HomeModel();

                var UserId = User.Identity.GetUserId();
                user = db.Users.Where(u => u.Id == UserId).SingleOrDefault();
                if(user == null ) return RedirectToAction("Login", "Account", new { ReturnUrl = "/" });

                var UnsolvedQuestions = user.GetUnsolvedQuestions();

                if (user.QuizInfo != null && user.QuizInfo.HasCompletedQuiz)
                {
                    model.FirstQuestionId = 0;
                }
                else
                {
                    model.FirstQuestionId = UnsolvedQuestions.OrderBy(q => q.QuestionId).FirstOrDefault().QuestionId;
                }
                //model.FirstQuestionId = new eQuizContext().Questions.OrderBy(q => q.QuestionId).FirstOrDefault().QuestionId;

                var QuizStartTime = DateTime.Parse(db.Settings.SingleOrDefault(s => s.Name == "Quiz Start Time").Value);
                //ViewBag.QuizStartTime = db.Settings.SingleOrDefault(s => s.Name == "Quiz Start Time").Value;

                string EasternStandardTimeId = "Eastern Standard Time";
                TimeZoneInfo ESTTimeZone = TimeZoneInfo.FindSystemTimeZoneById(EasternStandardTimeId);
                DateTime ESTDateTime = TimeZoneInfo.ConvertTimeFromUtc(QuizStartTime.ToUniversalTime(), ESTTimeZone);
                var TimeDiff = QuizStartTime.Subtract(ESTDateTime);
                model.QuizStartTime = QuizStartTime.ToString("yyyy-MM-ddTHH:mm:ss-04:00");
                return View(model);
            }
        }
Пример #10
0
        public async Task<ActionResult> Edit (string id, ApplicationUser applicationUser)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id);
                if(applicationUser.LockoutEnabled == true)
                {
                    user.LockoutEnd = DateTime.UtcNow.AddYears(100);
                }
                else
                {
                    user.LockoutEnd = DateTime.UtcNow;
                }

                user.LockoutEnabled = applicationUser.LockoutEnabled;

                await _userManager.UpdateAsync(user);
                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                ModelState.AddModelError(string.Empty, "Unable to save changes.");
            }

            return View(applicationUser);
        }
Пример #11
0
        //public static IEnumerable<MeetingViewModel> UserMeetingsTodayAll(ApplicationDbContext context, ApplicationUser user, Double utcOffset)
        //{
        //    var meetingDtos = new List<MeetingViewModel>();
        //    UserCohortMeetingsToday(context, user, utcOffset, ref meetingDtos);
        //    MeetingsServices.UserPrivateMeetingsToday(context, user, utcOffset, ref  meetingDtos);

        //    return meetingDtos;
        //}

        private static void UserCohortMeetingsToday(ApplicationDbContext context, ApplicationUser user, Double utcOffset, ref List<MeetingViewModel> meetingDtos)
        {
            var enrollmentsWithThisUser = context.Courses.SelectMany(u => u.Enrollments.Where(e => e.ApplicationUserId == user.Id));
            var localNow = DateTime.UtcNow.AddMinutes(utcOffset);
            var localTodayDate = localNow.ToShortDateString();

            //foreach (var enrollment in enrollmentsWithThisUser)
            //{
            //    //Get all meetings with this enrollment where its cohort has a meeting that is in the future
            //    var enrollment1 = enrollment;
            //    //var cohortMeetings = context.Meetings.ToList().Where(m => m.CourseId == enrollment1.CourseId && m.Start.AddMinutes(utcOffset).ToShortDateString()==rightNow);
            //    var cohortMeetings = context.Meetings.Where(m => m.CourseId == enrollment1.CourseId).OrderBy(m => m.Start);
            //    foreach (var meeting in cohortMeetings)
            //    {
            //        if (meeting.Start.AddMinutes(utcOffset).ToShortDateString() == localTodayDate)
            //        {
            //            var meetingToAdd = new MeetingViewModel
            //            {
            //                Id = meeting.Id,
            //                Title = meeting.Title,
            //                Start = DateTime.SpecifyKind(meeting.Start, DateTimeKind.Utc).AddMinutes(utcOffset),
            //                End = meeting.End.AddMinutes(utcOffset),
            //                Description = meeting.Description,
            //                IsAllDay = meeting.IsAllDay,
            //                RecurrenceRule = meeting.RecurrenceRule,
            //                RecurrenceException = meeting.RecurrenceException,
            //                RecurrenceId = meeting.RecurrenceId,
            //                CourseId = meeting.CourseId,
            //                GtmUrl = meeting.GtmUrl
            //            };
            //            meetingDtos.Add(meetingToAdd);
            //        }
            //    }
            //}
        }
Пример #12
0
        public ActionResult Create([Bind(Include = "Id,Name,Address,Phone,Email,VendorId,AspId")] VendorUser vendorUser)
        {
            //if (ModelState.IsValid)
            //{
            //    db.VendorUsers.Add(vendorUser);
            //    db.SaveChanges();
            //    return RedirectToAction("Index");
            //}
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = vendorUser.Email, Email = vendorUser.Email };
                var result = UserManager.Create(user, "Test@123");
                var VendorUserId = db.AspNetUsers.Where(x => x.Email == vendorUser.Email).FirstOrDefault().Id;
                string userAspId = VendorUserId;
                vendorUser.AspId = userAspId;
                string loginId = User.Identity.GetUserId();

                int vendorId = db.Vendors.Where(x => x.AspId == loginId).FirstOrDefault().VendorId;
                vendorUser.VendorId = vendorId;

                db.VendorUsers.Add(vendorUser);
                db.SaveChanges();
                TempData["VendorId"] = vendorId;
                return RedirectToAction("Index");
            }
            ViewBag.VendorId = new SelectList(db.Vendors, "VendorId", "Name", vendorUser.VendorId);
            return View(vendorUser);
        }
Пример #13
0
        public ActionResult Index()
        {
            //cria um usuário de sistema.            
            if (UserManager.FindByEmail("sps.smartparkingsystem@gmail.com") == null)
            {
                ApplicationUser systemUser = new ApplicationUser
                {
                    UserName = "SPS",
                    Email = "sps.smartparkingsystem@gmail.com",
                    FirstName = "Smart Parking",
                    LastName = "System",
                    PhoneNumber = "(00) 00000-0000",
                    UserType = UserType.Client
                };
                
                var res = UserManager.Create(systemUser, "System12__");

                if (res == null)
                {

                }
            }

            return View();
        }
Пример #14
0
        public ActionResult CreateAccount(NewUserModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUserManager um = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext()));
                var pass = StringHelper.RandomString(8, 10);
                var user = new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserName = model.UserName,
                    Email = model.Email,
                    Created = DateTime.Now,
                    LastLogin = null
                };
                var result = um.Create(user, pass);
                if(result.Succeeded)
                {
                    MailHelper.WelcomeSendPassword(user.UserName, user.Email, pass);
                    return RedirectToAction("Index", "People");
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            return View(model);
        }
        public void It_Sets_The_Basic_User_Information_For_The_Requested_User()
        {
            expectedApplicationUser = new ApplicationUser
            {
                Id = "some application user id",
                UserName = "some user name",
                Email = "some email address",
                UserGamingGroups = new List<UserGamingGroup>
                {
                    new UserGamingGroup
                    {
                        GamingGroup = new GamingGroup()
                    }
                },
                Players = new List<Player>(),
                BoardGameGeekUser = new BoardGameGeekUserDefinition
                {
                    Name = "bgg name",
                    Id = 1
                }
            };
            var userQueryable = new List<ApplicationUser>
            {
                expectedApplicationUser,
                new ApplicationUser()
            }.AsQueryable();
            autoMocker.Get<IDataContext>().Expect(mock => mock.GetQueryable<ApplicationUser>()).Return(userQueryable);

            var actualResult = autoMocker.ClassUnderTest.RetrieveUserInformation(expectedApplicationUser);

            Assert.That(actualResult.UserId, Is.EqualTo(expectedApplicationUser.Id));
            Assert.That(actualResult.UserName, Is.EqualTo(expectedApplicationUser.UserName));
            Assert.That(actualResult.Email, Is.EqualTo(expectedApplicationUser.Email));
            Assert.That(actualResult.BoardGameGeekUser.Name, Is.EqualTo(expectedApplicationUser.BoardGameGeekUser.Name));
        }
        public override UmcTrack GetTrackInfo(string url, ApplicationUser currentUser)
        {
            ISoundCloudConnector soundCloudConnector = new SoundCloudConnector();

            string token = currentUser.ApplicationUserData.SoundcloudToken;
            //string token = "ssadad";

            UmcTrack resultTrack = new SoundcloudTrack();

            //var tokenLogin = soundCloudConnector.RefreshToken(clientId, clientSecret, token);

            //var newToken = tokenLogin.AccessToken;

            //var soundCloudClient = soundCloudConnector.Connect(new SCAccessToken {AccessToken = token});
            var soundCloudClient = soundCloudConnector.UnauthorizedConnect(clientId, clientSecret);  
              
                var track = soundCloudClient.Resolve.GetTrack(url);
                resultTrack.Url = url;
                resultTrack.Title = track.Title;
                resultTrack.Artist = track.User.UserName;
                resultTrack.Year = track.CreatedAt.Year.ToString();
                resultTrack.InternalId = track.Id;
                
            return resultTrack;
        }
Пример #17
0
 public EntityBase SetCreated(ApplicationUser user)
 {
     CreatedOn = DateTime.Now;
     //CreatedBy = user;
     UpdatedOn = DateTime.Now;
     return this;
 }
        public override void SetUp()
        {
            base.SetUp();

            expectedGamingGroup = new GamingGroup() { Id = currentUser.CurrentGamingGroupId };
            autoMocker.Get<IDataContext>().Expect(mock => mock.Save(Arg<GamingGroup>.Is.Anything, Arg<ApplicationUser>.Is.Anything))
                .Return(expectedGamingGroup);
            expectedPlayer = new Player();
            autoMocker.Get<IPlayerSaver>().Expect(mock => mock.CreatePlayer(
                Arg<CreatePlayerRequest>.Is.Anything, 
                Arg<ApplicationUser>.Is.Anything,
                Arg<bool>.Is.Anything)).Return(expectedPlayer);
            
            expectedUserGamingGroup = new UserGamingGroup
            {
                ApplicationUserId = currentUser.Id,
                GamingGroupId = expectedGamingGroup.Id
            };
            autoMocker.Get<IDataContext>().Expect(mock => mock.Save<UserGamingGroup>(Arg<UserGamingGroup>.Is.Anything, Arg<ApplicationUser>.Is.Anything))
                           .Return(expectedUserGamingGroup);

            appUserRetrievedFromFindMethod = new ApplicationUser()
            {
                Id = currentUser.Id
            };
            autoMocker.Get<IDataContext>().Expect(mock => mock.FindById<ApplicationUser>(Arg<ApplicationUser>.Is.Anything))
                .Return(appUserRetrievedFromFindMethod);
            autoMocker.Get<IDataContext>().Expect(mock => mock.Save(Arg<ApplicationUser>.Is.Anything, Arg<ApplicationUser>.Is.Anything))
                 .Return(new ApplicationUser());
        }
Пример #19
0
        public async Task<ActionResult> Register(RegisterVm Model) 
        {
            Tuple<RegisterVm, LoginVm> badModel;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = Model.EmailReg,  Email = Model.EmailReg };
                IdentityUserClaim _claim = new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim();
                _claim.ClaimType = "FullName";
                _claim.ClaimValue = Model.FullName;
                _claim.UserId = user.Id;
                user.Claims.Add(_claim);
                ViewBag.FullName = Model.FullName;
                ViewBag.Email = user.Email;
                
                Random random = new Random(DateTime.Now.Day);
                StringBuilder strBuilder = new StringBuilder("!164");
                for (int i = 0; i < 3; i++)
                {
                    strBuilder.Append((char)random.Next(65, 90));
                    strBuilder.Append((char)random.Next(97, 122));
                }
                string temporaryPassword = strBuilder.ToString();

                var result = await UserManager.CreateAsync(user, temporaryPassword);


               if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ConfirmEmailAndChangePassword", "Init", new { userId = System.Web.HttpUtility.UrlEncode(user.Id), code = System.Web.HttpUtility.UrlEncode(code) }, protocol: Request.Url.Scheme);
                    try
                    {
                        ViewBag.Logo = Url.Content("~/Content/images/init/Logo.png", true);
                        ViewBag.ConfirmReference = callbackUrl;
                        string textmail = ViewToString("emailConfirmation", null);
                        await UserManager.SendEmailAsync(user.Id, "Confirm your account", textmail);//"Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    }
                    catch (SmtpException e1)
                    {
                        await UserManager.DeleteAsync(user);
                        ViewBag.UnsuccessfulError = e1.Message;
                        ModelState.AddModelError("", "Не удалось создать пользователя. " + e1.Message);
                        badModel =
                            new Tuple<RegisterVm, LoginVm>(Model, new LoginVm());
                        return View("Welcome", badModel);
                    }
                    
                    return View("RegisterConfirmationSent");
                }
                else
                {
                    ModelState.AddModelError("", "Не удалось создать пользователя. " + result.Errors.First());
                }
            }
            
            // If we got this far, something failed, redisplay form
            badModel = new Tuple<RegisterVm, LoginVm>(Model, new LoginVm());
            return View("Index", badModel);
        }
Пример #20
0
        internal void AddUserAndRole()
        {
            // access the application context and create result variables.
            Models.ApplicationDbContext context = new ApplicationDbContext();
            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            // create roleStore object that can only contain IdentityRole objects by using the ApplicationDbContext object.
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // create admin role if it doesn't already exist
            if (!roleMgr.RoleExists("admin"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "admin" });
            }

            // create a UserManager object based on the UserStore object and the ApplicationDbContext object.
            // defines admin email account
            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "zverse123@gmail.com",
                Email = "zverse123@gmail.com"
            };
            IdUserResult = userMgr.Create(appUser, "Pa$$word1");

            // If the new admin user was successfully created, add the new user to the "admin" role.
            if (!userMgr.IsInRole(userMgr.FindByEmail("zverse123@gmail.com").Id, "admin"))
            {
                IdUserResult = userMgr.AddToRole(userMgr.FindByEmail("zverse123@gmail.com").Id, "admin");
            }
        }
Пример #21
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName};
                try
                {
                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        await SignInAsync(user, false);
                        return RedirectToAction("Index", "Home");
                    }
                    AddErrors(result);
                }
                catch (Exception)
                {
                    //When no database, sometimes database creation fails.
                    AddErrors(new IdentityResult("Database creation failed, please restart the application!"));
                    return View(model);
                }
               
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Пример #22
0
        internal void AddUserAndRole()
        {
            Models.ApplicationDbContext context = new Models.ApplicationDbContext();

            IdentityResult IdRoleResult;
            IdentityResult IdUserResult;

            var roleStore = new RoleStore<IdentityRole>(context);

            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            if (!roleMgr.RoleExists("administrator"))
            {
                IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" });
            }

            var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var appUser = new ApplicationUser
            {
                UserName = "administrator",
            };
            IdUserResult = userMgr.Create(appUser, "1qaz2wsxE");
            var user = userMgr.FindByName("administrator");
            if (!userMgr.IsInRole(user.Id, "administrator"))
            {
                //userMgr.RemoveFromRoles(user.Id, "read", "edit");
                IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator");
            }
        }
Пример #23
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = await UserManager.FindByNameAsync(model.UserName);

            if(user == null)
            {
                user = new ApplicationUser { UserName = model.UserName, TotalCredits = AppSettingsConfig.StartCredits };
                var result = await UserManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    AddErrors(result);
                    return View(model);
                }
            }

            await SignInManager.SignInAsync(user, false, false);
            
            return RedirectToLocal(returnUrl);       
        }
Пример #24
0
        public async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
        {
            // Clear any partial cookies from external or two factor partial sign ins
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie,
                DefaultAuthenticationTypes.TwoFactorCookie);

            var userIdentity = await user.GenerateUserIdentityAsync(UserManager);

            if (rememberBrowser)
            {
                var rememberBrowserIdentity =
                    AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id);

                AuthenticationManager.SignIn(
                    new AuthenticationProperties { IsPersistent = isPersistent },
                    userIdentity,
                    rememberBrowserIdentity);
            }
            else
            {
                AuthenticationManager.SignIn(
                    new AuthenticationProperties { IsPersistent = isPersistent },
                    userIdentity);
            }
        }
Пример #25
0
        public async Task<bool> Create([Bind(Include = "UserName,Email,EmailConfirmed,PasswordHash,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled")] AspNetUser aspNetUser)
        {

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser();
                user.AccessFailedCount = 0;
                user.Email = aspNetUser.Email.Trim();
                user.EmailConfirmed = aspNetUser.EmailConfirmed;
                user.LockoutEnabled = aspNetUser.LockoutEnabled;
                user.LockoutEndDateUtc = aspNetUser.LockoutEndDateUtc;
                user.PhoneNumber = aspNetUser.PhoneNumber == null ? aspNetUser.PhoneNumber : aspNetUser.PhoneNumber.Trim();
                user.PhoneNumberConfirmed = aspNetUser.PhoneNumberConfirmed;
                user.TwoFactorEnabled = aspNetUser.TwoFactorEnabled;
                user.UserName = aspNetUser.UserName.Trim();

                try
                {
                    // Use the password hash as actual password
                    var res = await UserManager.CreateAsync(user, aspNetUser.PasswordHash);
                    if (!res.Succeeded)
                    {
                        return false;
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            return true;

        }
 public ActionResult Create([Bind(Include = "ID,FirstName,LastName,Username")] Patient patient)
 {
     DBContext temp = new DBContext();
     if (ModelState.IsValid)
     {
            if (db.Patients.Where(p=>p.Username == patient.Username).Count()==0)
             {
                 ApplicationUser newUser = new ApplicationUser
                 {
                     Email = patient.Username,
                     UserName = patient.Username
                 };
                 ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                 UserManager.Create(newUser, "Password1!");
                 var currentUser = UserManager.FindByName(patient.Username);
                 UserManager.AddToRole(currentUser.Id, "Patient");
                 db.Patients.Add(patient);
                 db.SaveChanges();
                 return RedirectToAction("PatientDoctor");
             }
             else
             {
                 return View("PatientExists");
             }
     }
     return View(patient);
 }
 /// <summary>
 /// Regenerates the identity callback function for cookie configuration (above).
 /// </summary>
 /// <param name="applicationUserManager">The application user manager.</param>
 /// <param name="applicationUser">The application user.</param>
 private static async Task<ClaimsIdentity> RegenerateIdentityCallback(ApplicationUserManager applicationUserManager, ApplicationUser applicationUser)
 {
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
     var userIdentity = await applicationUserManager.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);
     // Add custom user claims here
     return userIdentity;
 }
        public virtual ActionResult Details(int? id, ApplicationUser currentUser)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            GameDefinitionDetailsViewModel gamingGroupGameDefinitionViewModel;

            try
            {
                var gameDefinitionSummary = _gameDefinitionRetriever.GetGameDefinitionDetails(id.Value, NUMBER_OF_RECENT_GAMES_TO_SHOW);
                gamingGroupGameDefinitionViewModel = _gameDefinitionTransformation.Build(gameDefinitionSummary, currentUser);
            }
            catch (KeyNotFoundException)
            {
                return new HttpNotFoundResult();
            }
            catch (UnauthorizedAccessException)
            {
                return new HttpUnauthorizedResult();
            }

            return View(MVC.GameDefinition.Views.Details, gamingGroupGameDefinitionViewModel);
        }
Пример #29
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
            var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text };
            IdentityResult result = manager.Create(user, Password.Text);
            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                //string code = manager.GenerateEmailConfirmationToken(user.Id);
                //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                signInManager.SignIn( user, isPersistent: false, rememberBrowser: false);

                using (WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions())
                {
                    String cartId = usersShoppingCart.GetCartId();
                    usersShoppingCart.MigrateCart(cartId, user.Id);
                }

                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                user.UserInfo = new ApplicationUserInfo { ApplicationUser = user };
                Image defaultAvatar = new Image { Name = "defaultAvatar" };
                user.UserInfo.Avatar = defaultAvatar;
                db.SaveChanges();
                var result = await UserManager.CreateAsync(user, model.Password);
                
                if (result.Succeeded)
                {
                    db.SaveChanges();
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }