Esempio n. 1
0
 public FormOutputModel Execute(InputModel input)
 {
     return new FormOutputModel()
     {
         Login = "******",
         Password = "******"
     };
 }
        public void SetUp()
        {
            _page = MockRepository.GenerateMock<IFubuPage>();
            _urls = new StubUrlRegistry();

            _page.Expect(p => p.Urls).Return(_urls);
            _model = new InputModel();
            //_urls.Stub(u => u.UrlFor(Arg<InputModel>.Is.NotNull)).Return("some url");
        }
Esempio n. 3
0
 public string Execute(InputModel model)
 {
     FacebookClient client = new FacebookClient()
         {
             ClientIdentifier = "378177968863661",
             ClientSecret = "1cb526369e0f68fdaee92732bf99e037",
         };
     client.RequestUserAuthorization(returnTo: null);
     return null;
 }
Esempio n. 4
0
        public void For_With_InputModel_Returns_Correct_Url()
        {
            var inputModel = new InputModel {Test = "uweb"};
            const string url = "/uweb";

            A.CallTo(() => routeCollection.FindFor<InputModel>()).Returns(route);
            A.CallTo(() => route.BuildUrl(inputModel)).Returns(url);

            var result = urlBuilder.For(inputModel);

            result.ShouldEqual(url);
        }
        public override void Invoke(Shell shell, string[] args)
        {
            var model = new InputModel();
            Console.Write("Name: ");
            model.Name = Console.ReadLine();

            Console.Write("Surname: ");
            model.Surname = Console.ReadLine();

            Console.WriteLine();
            Console.WriteLine("Hello {0} {1}!", model.Name, model.Surname);
        }
        public void SetUp()
        {
            _page = MockRepository.GenerateMock<IFubuPage<InputModel>>();
            _renderer = MockRepository.GenerateStub<IPartialRenderer>();
            _serviceLocator = MockRepository.GenerateStub<IServiceLocator>();
            
            _viewTypeRegistry = MockRepository.GenerateStub<IPartialViewTypeRegistry>();
            _serviceLocator.Stub(s => s.GetInstance<IPartialViewTypeRegistry>()).Return(_viewTypeRegistry);

            
            _model = new InputModel{Partials=new List<PartialModel>{new PartialModel()}};
            _page.Expect(p => p.Get<IElementGenerator<InputModel>>()).Return(MockRepository.GenerateMock<IElementGenerator<InputModel>>());;
            _page.Expect(p => p.Model).Return(_model);
            _page.Expect(p => p.Get<IPartialRenderer>()).Return(_renderer);
            _page.Expect(p => p.ServiceLocator).Return(_serviceLocator);
        }
Esempio n. 7
0
 public string Execute(InputModel model)
 {
     using (var openId = new OpenIdRelyingParty())
     {
         var response = openId.GetResponse();
         if (response != null)
         {
             switch (response.Status)
             {
                 case AuthenticationStatus.Authenticated:
                     var claimsResponse = response.GetExtension<ClaimsResponse>();
                     return String.Format("Authenticated as {0} ({1}) with email {2}", response.FriendlyIdentifierForDisplay, response.ClaimedIdentifier, claimsResponse.Email);
                 case AuthenticationStatus.Canceled:
                     return "User canceled authentication.";
                 case AuthenticationStatus.Failed:
                     return "Authentication failed.";
             }
         }
     }
     return "Invalid!";
 }
        public void SetUp()
        {
            _page = MockRepository.GenerateMock<IFubuPage<InputModel>>();
            _renderer = MockRepository.GenerateStub<IPartialRenderer>();
            var serviceLocator = MockRepository.GenerateStub<IServiceLocator>();
            var namingConvention = MockRepository.GenerateStub<IElementNamingConvention>();
            _tags = new TagGenerator<InputModel>(new TagProfileLibrary(), namingConvention,
                                                 serviceLocator);

            _viewTypeRegistry = MockRepository.GenerateStub<IPartialViewTypeRegistry>();
            serviceLocator.Stub(s => s.GetInstance<IPartialViewTypeRegistry>()).Return(_viewTypeRegistry);

            var inMemoryFubuRequest = new InMemoryFubuRequest();
            inMemoryFubuRequest.Set(new InputModel());

            _page.Stub(s => s.Get<IFubuRequest>()).Return(inMemoryFubuRequest);

            _model = new InputModel{Partials=new List<PartialModel>{new PartialModel()}};
            _page.Expect(p => p.Get<ITagGenerator<InputModel>>()).Return(_tags);
            _page.Expect(p => p.Model).Return(_model);
            _page.Expect(p => p.Get<IPartialRenderer>()).Return(_renderer);
            _page.Expect(p => p.ServiceLocator).Return(serviceLocator);
        }
        public void WeightCalculateTest()
        {
            var calculator = new WeightCalculator();

            var input = new InputModel
            {
                AverageCustomersPerDay = 30,
                WorkStart   = 9,
                WorkEnd     = 18,
                BusiestHour = 16
            };
            var weights = calculator.Calculate(input);

            //hours: 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - 17 - 18
            //index: 0 - 1  - 2  - 3  - 4  - 5  - 6  - 7  - 8  - 9
            Assert.Equal(10, weights.Count);

            var busiestHourWeight = weights[7];

            Assert.Equal(busiestHourWeight, weights.Max());
            Assert.Equal(7.67, busiestHourWeight, 2);
            Assert.Equal(1, weights[0]);
            Assert.Equal(1, weights[9]);
        }
Esempio n. 10
0
        public void SpreadCalculateFullTest()
        {
            var calculator = new SpreadCalculator();

            var input = new InputModel
            {
                AverageCustomersPerDay = 30,
                WorkStart   = 9,
                WorkEnd     = 18,
                BusiestHour = 16
            };
            var weights = new WeightCalculator().Calculate(input);

            var customersForMonth = Enumerable.Repeat(0, 1000)
                                    .Select(x => calculator.Calculate(input, weights));

            //customers per hour. indicating number of customers from the interval start time till the next interval
            //9 - .5 - 10 - .5 - 11 - .5 - 12 - .5 - 13 - .5 - 14 - .5 - 15 - .5 - 16 - .5 - 17 - .5
            Assert.All(customersForMonth, (spread) => Assert.Equal(18, spread.Count));

            var totalCustomersPerDay = customersForMonth.Select(spread => spread.Sum());

            Assert.True(Math.Abs(50 - totalCustomersPerDay.Average()) < 1);
        }
Esempio n. 11
0
        public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var userName = await _userManager.GetUserNameAsync(user);
            var email = await _userManager.GetEmailAsync(user);
            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                Email = email,
                PhoneNumber = phoneNumber
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);

            return Page();
        }
Esempio n. 12
0
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var userName = await _userManager.GetUserNameAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            var             claimsIdentity  = (ClaimsIdentity)User.Identity;
            var             claim           = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
            ApplicationUser applicationUser = await _db.ApplicationUser.Where(c => c.Id == claim.Value).FirstOrDefaultAsync();

            Username = userName;

            Input = new InputModel
            {
                Email         = email,
                PhoneNumber   = phoneNumber,
                City          = applicationUser.City,
                Name          = applicationUser.Name,
                PostalCode    = applicationUser.PostalCode,
                State         = applicationUser.State,
                StreetAddress = applicationUser.StreetAddress
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);

            return(Page());
        }
Esempio n. 13
0
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            var email = await _userManager.GetEmailAsync(user);

            var username = await _userManager.GetUserNameAsync(user);

            Input = new InputModel
            {
                Email               = email,
                UserName            = username,
                ShouldReceiveEmails = user.ShouldReceiveEmails
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);

            return(Page());
        }
        private async Task SetPageModel(DataAccess.Models.Configuration configuration)
        {
            Organizations = new SelectList(await dbContext.Organizations.Select(x => x).ToListAsync(), nameof(DataAccess.Models.Organization.Id), nameof(DataAccess.Models.Organization.DisplayName));

            Configuration = new ConfigurationVM()
            {
                Id    = configuration.Id,
                Key   = configuration.ConfigurationDict.Key,
                Value = configuration.Value,
                Notes = configuration.Notes,
                ConfigurationDictId = configuration.ConfigurationDictId,
                OrganizationId      = configuration.OrganizationId
            };

            Input = new InputModel()
            {
                Id    = configuration.Id,
                Key   = configuration.ConfigurationDict.Key,
                Value = configuration.Value,
                Notes = configuration.Notes,
                ConfigurationDictId = configuration.ConfigurationDictId,
                OrganizationId      = configuration.OrganizationId
            };
        }
Esempio n. 15
0
        public async Task <IActionResult> OnGet()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }
            Input = new InputModel
            {
                wishListItems = _context.WishListItem
                                .Include(a => a.Game)
                                .Include(g => g.Game.EsrbRatingCodeNavigation)
                                .Include(g => g.Game.GameCategory)
                                .Include(g => g.Game.GamePerspectiveCodeNavigation)
                                .Include(g => g.Game.GameFormatCodeNavigation)
                                .Include(g => g.Game.GameSubCategory)
                                .Where(a => a.UserId == user.Id)
                                .OrderByDescending(g => g.DateCreated).ToList()
            };
            Input.allFormatsSelected = true;

            return(Page());
        }
Esempio n. 16
0
        public async Task <IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Não pude carregar dados do usuário ID '{_userManager.GetUserId(User)}'."));
            }
            var userName = await _userManager.GetUserNameAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;
            Input    = new InputModel
            {
                Email       = email,
                PhoneNumber = phoneNumber
            };
            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);

            return(Page());
        }
        public async Task OnGetAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;

            if (Input == null)
            {
                Input = new InputModel();
            }

            if (Request?.Query?.ContainsKey("PinCode") == true)
            {
                Input.PinCode = int.Parse(Request.Query["PinCode"]);
            }

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            await _eventTrackingService.Create(new Shared.Functional.EventTrackingItem
            {
                Id          = Guid.NewGuid(),
                CreatedDate = DateTime.UtcNow,
                Category    = "Register",
                Key         = "Start"
            });
        }
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // ROLES
            var user = await _signInManager.UserManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);

            string role = "Admin";
            //await _signInManager.UserManager.AddToRoleAsync(user, role);
            await _signInManager.UserManager.RemoveFromRoleAsync(user, role);

            _logger.LogInformation($"Is {user.Email} at role \"{role}\"? R: {await _userManager.IsInRoleAsync(user, role)}");

            // CLAIMS
            await _signInManager.UserManager.AddClaimAsync(user, new Claim(ClaimTypes.Country, "Canada"));

            //await _signInManager.UserManager.RemoveClaimAsync(user, new Claim(ClaimTypes.Country, "Canada"));

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);



                //// ROLES
                //var user = await _signInManager.UserManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
                //string role = "Admin";
                //await _signInManager.UserManager.AddToRoleAsync(user, role);
                ////await _signInManager.UserManager.RemoveFromRoleAsync(user, role);
                //_logger.LogInformation($"Is {user.Email} at role \"{role}\"? R: {await _userManager.IsInRoleAsync(user, role)}");

                //// CLAIMS
                //await _signInManager.UserManager.AddClaimAsync(user, new Claim(ClaimTypes.Country, "Canada"));


                return(LocalRedirect(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout"));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl     = returnUrl;
                LoginProvider = info.LoginProvider;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };

                    //var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
                    //await _userManager.AddToRoleAsync(user, "Admin");
                }
                return(Page());
            }
        }
Esempio n. 19
0
 public LoginModel(IUserClaimsService userClaimsService)
 {
     _userClaimsService = userClaimsService;
     Input = new InputModel();
 }
Esempio n. 20
0
        public void should_build_partial_and_set_model()
        {
            var model = new InputModel();
            _page.Partial(model);

            _request.AssertWasCalled(r=>r.Set(model));
            _partialFactory.AssertWasCalled(f => f.BuildPartial(typeof(InputModel)));
            _page.AssertWasCalled(p => p.Get<IPartialFactory>());
            _behavior.AssertWasCalled(b => b.InvokePartial());
        }
Esempio n. 21
0
        public IActionResult OnGet()
        {
            Input = new InputModel();

            return(Page());
        }
Esempio n. 22
0
 public void Post(InputModel request, string param)
 {
 }
Esempio n. 23
0
        public async Task <IActionResult> OnPostAsync()
        {
            var valor    = false;
            var strategy = _objeto._context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async() =>
            {
                using (var transaction = _objeto._context.Database.BeginTransaction())
                {
                    try
                    {
                        var idUser   = _objeto._userManager.GetUserId(User);
                        var dataUser = _objeto._context.TUsuarios.Where(u => u.IdUser.Equals(idUser)).ToList().ElementAt(0);
                        var user     = await _objeto._userManager.FindByIdAsync(idUser);
                        var role     = await _objeto._userManager.GetRolesAsync(user);

                        //_objeto._context.Add(_model);
                        //await _objeto._context.SaveChangesAsync();
                        var compra = new TCompras
                        {
                            Descripcion = _model.Descripcion,
                            Cantidad    = _model.Cantidad,
                            Precio      = _model.Precio,
                            Importe     = _model.Importe,
                            IdProveedor = _model.IdProveedor,
                            Proveedor   = _model.Proveedor,
                            Email       = _model.Email,
                            IdSusuario  = idUser,
                            Usuario     = dataUser.Nombre + " " + dataUser.Apellido,
                            Role        = role[0],
                            Dia         = Convert.ToInt16(dia),
                            Mes         = mes,
                            Year        = year,
                            Fecha       = _model.Fecha,
                            Credito     = _model.Credito
                        };
                        int data = Convert.ToInt16("fg");
                        //_objeto._context.Add(compra);
                        //await _objeto._context.SaveChangesAsync();

                        // si todos los comandos o procesos se ejecutaron con exito,
                        transaction.Commit();
                    }catch (Exception ex)
                    {
                        Input = new InputModel
                        {
                            TComprasTemp = _model,
                            AvatarImage  = Input.AvatarImage,
                            ErrorMessage = ex.Message
                        };
                        transaction.Rollback();
                        valor = false;
                    }
                }
            });

            if (valor)
            {
                return(RedirectToPage("Compras"));
            }
            else
            {
                return(Page());
            }
        }
Esempio n. 24
0
 public void OnGet()
 {
     Input = new InputModel {
         UserId = UserId
     };
 }
Esempio n. 25
0
 public void DoSomething(InputModel model)
 {
 }
 public void Go(InputModel model)
 {
 }
Esempio n. 27
0
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;

            //You get the user’s first and last name below:
            var Name = userClaims?.FindFirst("name")?.Value;

            // The 'preferred_username' claim can be used for showing the username
            var Username = userClaims?.FindFirst("preferred_username")?.Value;

            // The subject/ NameIdentifier claim can be used to uniquely identify the user across the web
            var Subject = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;

            // TenantId is the unique Tenant Id - which represents an organization in Azure AD
            var TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;

            var upn = userClaims?.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value;

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // TODO here
            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
                return(LocalRedirect(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout"));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl           = returnUrl;
                ProviderDisplayName = info.ProviderDisplayName;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return(Page());
            }
        }
Esempio n. 28
0
 public void delete_something(InputModel model)
 {
 }
Esempio n. 29
0
 public FubuContinuation Execute(InputModel model)
 {
     return null;
 }
Esempio n. 30
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName      = Input.UserName,
                    Email         = Input.Email,
                    CompanyId     = Input.CompanyId,
                    StreetAddress = Input.StreetAddress,
                    City          = Input.City,
                    State         = Input.State,
                    PostalCode    = Input.PostalCode,
                    Name          = Input.Name,
                    PhoneNumber   = Input.PhoneNumber,
                    Role          = Input.Role
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("Ο χρήστης δημιούργησε έναν νέο λογαριασμό με κωδικό πρόσβασης.");


                    if (user.Role == null)
                    {
                        await _userManager.AddToRoleAsync(user, SD.Role_User_Indi);
                    }
                    else
                    {
                        if (user.CompanyId > 0)
                        {
                            await _userManager.AddToRoleAsync(user, SD.Role_User_Comp);
                        }
                        await _userManager.AddToRoleAsync(user, user.Role);
                    }

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);


                    var PathToFile = _hostEnvironment.WebRootPath + Path.DirectorySeparatorChar.ToString()
                                     + "Templates" + Path.DirectorySeparatorChar.ToString() + "EmailTemplates"
                                     + Path.DirectorySeparatorChar.ToString() + "Confirm_Account_Registration.html";

                    var    subject  = "Επιβεβαίωση εγγραφής λογαριασμού";
                    string HtmlBody = "";
                    using (StreamReader streamReader = System.IO.File.OpenText(PathToFile))
                    {
                        HtmlBody = streamReader.ReadToEnd();
                    }

                    //{0} : Subject
                    //{1} : DateTime
                    //{2} : Name
                    //{3} : Email
                    //{4} : Message
                    //{5} : callbackURL
                    //{6) : UserName

                    string Message = $"Επιβεβαιώστε το λογαριασμό σας <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>κάνοντας κλικ εδώ</a>.";

                    string messageBody = string.Format(HtmlBody,
                                                       subject,
                                                       String.Format("{0:dddd, d MMMM yyyy}", DateTime.Now),
                                                       user.Name,
                                                       user.Email,
                                                       Message,
                                                       callbackUrl,
                                                       user.UserName
                                                       );


                    await _emailSender.SendEmailAsync(Input.Email, "Επιβεβαιώστε το email σας", messageBody);

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        if (user.Role == null)
                        {
                            await _signInManager.SignInAsync(user, isPersistent : false);

                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            //admin is registering a new user
                            return(RedirectToAction("Index", "User", new { Area = "Admin" }));
                        }
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            Input = new InputModel()
            {
                CompanyList = _unitOfWork.Company.GetAll().Select(i => new SelectListItem
                {
                    Text  = i.Name,
                    Value = i.Id.ToString()
                }),
                RoleList = _roleManager.Roles.Where(u => u.Name != SD.Role_User_Indi).Select(x => x.Name).Select(i => new SelectListItem
                {
                    Text  = i,
                    Value = i
                })
            };

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 31
0
 public void DoSomething(InputModel model)
 {
 }
Esempio n. 32
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var email = await _userManager.GetEmailAsync(user);

            if (Input.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email);

                if (!setEmailResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
                }
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
                }
            }


            Input = new InputModel
            {
                Name      = Input.Name,
                Address   = Input.Address,
                BirthDate = Input.BirthDate,
            };

            user.Name      = Input.Name;
            user.Address   = Input.Address;
            user.BirthDate = Input.BirthDate;

            await _userManager.UpdateAsync(user);

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Your profile has been updated";
            return(RedirectToPage());
        }
Esempio n. 33
0
        public async Task <IActionResult> OnGetAsync()
        {
            if (!User.Identity.IsAuthenticated)
            {
                await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                return(RedirectToPage("/Account/Login"));
            }
            else
            {
                if (!User.IsInRole(StaticDetails.ApplicantRole) && User.IsInRole(StaticDetails.JudgeRole))
                {
                    await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                    return(RedirectToPage("/Judge/Dashboard"));
                }
                if (!User.IsInRole(StaticDetails.ApplicantRole) && User.IsInRole(StaticDetails.MentorRole))
                {
                    await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                    return(RedirectToPage("/Mentor/Dashboard"));
                }
                else
                {
                    var claimsIdentity = (ClaimsIdentity)this.User.Identity;
                    var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
                    await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                    if (claim.Value == null)
                    {
                        await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                        return(RedirectToPage("/Account/Login"));
                    }

                    Applicant = await _context.ApplicationUsers.FirstOrDefaultAsync(a => a.Id == claim.Value);

                    Address = await _context.Address.FirstOrDefaultAsync(d => d.ApplicantId == claim.Value);

                    if (Address == null)
                    {
                        await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                        Input = new InputModel {
                            FirstName = Applicant.FirstName, LastName = Applicant.LastName, Email = Applicant.Email,
                            State     = "Utah", Country = "United States"
                        };
                    }
                    else
                    {
                        await _util.SendEmailAsync(StaticDetails.Log, "MF User Profile", "profile");

                        ContactInfo = await _context.ContactInfo.FirstOrDefaultAsync(c => c.ApplicantId == claim.Value);

                        Demographics = await _context.Demographics.FirstOrDefaultAsync(d => d.ApplicationUserId == claim.Value);

                        Input = new InputModel {
                            FirstName         = Applicant.FirstName,
                            LastName          = Applicant.LastName,
                            Email             = Applicant.Email,
                            ContactInfoDetail = ContactInfo.ContactInfoDetail,
                            Street            = Address.Street,
                            Street_line2      = Address.StreetLine2,
                            City                     = Address.City,
                            State                    = Address.State,
                            Zip                      = Address.Zip,
                            Country                  = Address.Country,
                            Gender                   = Demographics.Gender,
                            RaceEthnicity            = Demographics.RaceEthnicity,
                            DOB                      = Demographics.DOB,
                            Income                   = Demographics.Income,
                            HighestEduCompleted      = Demographics.HighestEduCompleted,
                            ResidenceEnvironment     = Demographics.ResidenceEnvironment,
                            CurrentStudent           = Demographics.CurrentStudent,
                            VeteranStatus            = Demographics.VeteranStatus,
                            WSUEntrepreneurshipMinor = Demographics.WSUEntrepreneurshipMinor,
                            WSUEmployee              = Demographics.WSUEmployee,
                            WSUNumber                = Demographics.WSUNumber
                        };
                    }

                    return(Page());
                }
            }
        }
Esempio n. 34
0
    private async Task BuildModelAsync(string returnUrl)
    {
        Input = new InputModel
        {
            ReturnUrl = returnUrl
        };

        var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

        if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
        {
            var local = context.IdP == Duende.IdentityServer.IdentityServerConstants.LocalIdentityProvider;

            // this is meant to short circuit the UI and only trigger the one external IdP
            View = new ViewModel
            {
                EnableLocalLogin = local,
            };

            Input.Username = context?.LoginHint;

            if (!local)
            {
                View.ExternalProviders = new[] { new ViewModel.ExternalProvider {
                                                     AuthenticationScheme = context.IdP
                                                 } };
            }
        }

        var schemes = await _schemeProvider.GetAllSchemesAsync();

        var providers = schemes
                        .Where(x => x.DisplayName != null)
                        .Select(x => new ViewModel.ExternalProvider
        {
            DisplayName          = x.DisplayName ?? x.Name,
            AuthenticationScheme = x.Name
        }).ToList();

        var dyanmicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync())
                             .Where(x => x.Enabled)
                             .Select(x => new ViewModel.ExternalProvider
        {
            AuthenticationScheme = x.Scheme,
            DisplayName          = x.DisplayName
        });

        providers.AddRange(dyanmicSchemes);


        var allowLocal = true;

        if (context?.Client.ClientId != null)
        {
            var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

            if (client != null)
            {
                allowLocal = client.EnableLocalLogin;

                if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                {
                    providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                }
            }
        }

        View = new ViewModel
        {
            AllowRememberLogin = LoginOptions.AllowRememberLogin,
            EnableLocalLogin   = allowLocal && LoginOptions.AllowLocalLogin,
            ExternalProviders  = providers.ToArray()
        };
    }
Esempio n. 35
0
 public void OnGet(string returnUrl = null)
 {
     ReturnUrl = returnUrl;
     Input     = new InputModel();
 }
Esempio n. 36
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    CompanyId     = Input.CompanyId,
                    StreetAddress = Input.StreetAddress,
                    City          = Input.City,
                    County        = Input.County,
                    PostCode      = Input.PostCode,
                    Name          = Input.Name,
                    PhoneNumber   = Input.PhoneNumber,
                    Role          = Input.Role
                };
                //Creates User, If Result is successful it sends an email notification to verify email account
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    //if (!await _roleManager.RoleExistsAsync(SD.Role_Admin))
                    //{
                    //    await _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin));
                    //}
                    //if (!await _roleManager.RoleExistsAsync(SD.Role_Employee))
                    //{
                    //    await _roleManager.CreateAsync(new IdentityRole(SD.Role_Employee));
                    //}
                    //if (!await _roleManager.RoleExistsAsync(SD.Role_User_Comp))
                    //{
                    //    await _roleManager.CreateAsync(new IdentityRole(SD.Role_User_Comp));
                    //}
                    //if (!await _roleManager.RoleExistsAsync(SD.Role_User_Indi))
                    //{
                    //    await _roleManager.CreateAsync(new IdentityRole(SD.Role_User_Indi));
                    //}

                    // ↓↓ Registering an Admin User for the first time start of Application
                    // await _userManager.AddToRoleAsync(user, SD.Role_Admin);

                    // role was not selected and user is registerted as individual user (selected roles)
                    if (user.Role == null)
                    {
                        await _userManager.AddToRoleAsync(user, SD.Role_User_Indi);
                    }
                    else
                    {
                        if (user.CompanyId > 0)
                        {
                            await _userManager.AddToRoleAsync(user, SD.Role_User_Comp);
                        }
                        await _userManager.AddToRoleAsync(user, user.Role);
                    }


                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        if (user.Role == null)
                        {
                            await _signInManager.SignInAsync(user, isPersistent : false);

                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            // In this case admin is registering a new user
                            return(RedirectToAction("Index", "User", new { Area = "Admin" }));
                        }
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            // Fixing Error if same email is passed into Register
            Input = new InputModel()
            {
                CompanyList = _unitOfWork.Company.GetAll().Select(i => new SelectListItem
                {
                    Text  = i.Name,
                    Value = i.Id.ToString()
                }),
                RoleList = _roleManager.Roles.Where(u => u.Name != SD.Role_User_Indi).Select(x => x.Name).Select(i => new SelectListItem
                {
                    Text  = i,
                    Value = i
                })
            };

            // If we got this far, something failed, redisplay form
            return(Page());
        }
 public async Task <IActionResult> OnGet()
 {
     Input = new InputModel();
     return(await PageAsync());
 }
Esempio n. 38
0
 public OutputModel DoSomething(InputModel input)
 {
     return(new OutputModel());
 }
Esempio n. 39
0
 public IActionResult OnGet(string email)
 {
     Input       = new InputModel();
     Input.Email = email;
     return(Page());
 }
Esempio n. 40
0
        public async Task <IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            // Sign in the user with this external login provider if the user already has a login.
            #region Custom
            var userLogin = this._playersRepository
                            .AllAsNoTrackingWithDeleted()
                            .Include(x => x.Logins)
                            .SelectMany(x => x.Logins)
                            .Where(x => x.ProviderKey == info.ProviderKey)
                            .SingleOrDefault();

            if (userLogin != null)
            {
                var isPlayerDeleted = (await this._playersRepository
                                       .GetByIdWithDeletedAsync(userLogin.UserId))
                                      .IsDeleted;

                if (isPlayerDeleted)
                {
                    ErrorMessage = $"Account associated with this steam account is deleted. Contact an administrator for restoring.";
                    return(RedirectToPage("./Login", new { ReturnUrl = returnUrl, ErrorMessage = ErrorMessage }));
                }
            }
            #endregion
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);

                return(LocalRedirect(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return(RedirectToPage("./Lockout"));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                var steamId64    = ulong.Parse(info.ProviderKey.Split('/').Last());
                var steamUser    = SteamApiHelper.GetSteamUserInstance(this._configuration);
                var playerResult = await steamUser.GetCommunityProfileAsync(steamId64);

                if (playerResult.IsVacBanned)
                {
                    ErrorMessage = $"VAC banned accounts cannot register!";
                    return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
                }

                ReturnUrl     = returnUrl;
                LoginProvider = info.LoginProvider;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return(Page());
            }
        }
Esempio n. 41
0
 public void put_something(InputModel model)
 {
 }
Esempio n. 42
0
 public void FailOnOpenArray2()
 {
     var array = InputModel.ParseArray("[\"1 \", \"2,2\", \"3,,,4\", \"4]", 0);
 }
 public void SetUp()
 {
     _page = MockRepository.GenerateMock<IFubuPage>();
     _urls = new StubUrlRegistry();
     _model = new InputModel();
     _page.Stub(p => p.Urls).Return(_urls);
 }
Esempio n. 44
0
 public void Go(InputModel model)
 {
 }
 public OutputModel DoSomething(InputModel input)
 {
     return new OutputModel();
 }
Esempio n. 46
0
        public IActionResult OnGet(string type = null, IEnumerable <string> ids = null)
        {
            // Define the JSON serializer options.
            var jsonSerializerOptions = new JsonSerializerOptions
            {
                WriteIndented    = true,
                IgnoreNullValues = true
            };

            // Define the view.
            View = new ViewModel
            {
                JsonModel = JsonSerializer.Serialize(new List <EdgeInputModel>
                {
                    new EdgeInputModel
                    {
                        Id            = "ID",
                        Description   = "Description",
                        DatabaseEdges = new List <DatabaseEdgeInputModel>
                        {
                            new DatabaseEdgeInputModel
                            {
                                Database = new DatabaseInputModel
                                {
                                    Id = "Database ID"
                                }
                            }
                        },
                        EdgeNodes = new List <EdgeNodeInputModel>
                        {
                            new EdgeNodeInputModel
                            {
                                Node = new NodeInputModel
                                {
                                    Id = "Node ID"
                                },
                                Type = "Source"
                            },
                            new EdgeNodeInputModel
                            {
                                Node = new NodeInputModel
                                {
                                    Id = "Node ID"
                                },
                                Type = "Target"
                            }
                        },
                        DatabaseEdgeFieldEdges = new List <DatabaseEdgeFieldEdgeInputModel>
                        {
                            new DatabaseEdgeFieldEdgeInputModel
                            {
                                DatabaseEdgeField = new DatabaseEdgeFieldInputModel
                                {
                                    Id = "Database edge field ID"
                                },
                                Value = "Value"
                            }
                        }
                    }
                }, jsonSerializerOptions)
            };
            // Check if there are any IDs provided.
            ids ??= Enumerable.Empty <string>();
            // Get the database items based on the provided IDs.
            var edges = _context.Edges
                        .Where(item => !item.DatabaseEdges.Any(item => item.Database.DatabaseType.Name == "Generic"))
                        .Where(item => ids.Contains(item.Id))
                        .Include(item => item.EdgeNodes)
                        .ThenInclude(item => item.Node)
                        .Include(item => item.DatabaseEdges)
                        .ThenInclude(item => item.Database)
                        .Include(item => item.DatabaseEdgeFieldEdges);
            // Get the items for the view.
            var items = edges.Select(item => new EdgeInputModel
            {
                Id          = item.Id,
                Description = item.Description,
                EdgeNodes   = item.EdgeNodes.Select(item1 => new EdgeNodeInputModel
                {
                    Node = new NodeInputModel
                    {
                        Id = item1.Node.Id
                    },
                    Type = item1.Type.ToString()
                }),
                DatabaseEdges = item.DatabaseEdges.Select(item1 => new DatabaseEdgeInputModel
                {
                    Database = new DatabaseInputModel
                    {
                        Id = item1.Database.Id
                    }
                }),
                DatabaseEdgeFieldEdges = item.DatabaseEdgeFieldEdges.Select(item1 => new DatabaseEdgeFieldEdgeInputModel
                {
                    DatabaseEdgeField = new DatabaseEdgeFieldInputModel
                    {
                        Id = item1.DatabaseEdgeField.Id
                    },
                    Value = item1.Value
                })
            });

            // Define the input.
            Input = new InputModel
            {
                Type = type,
                Data = JsonSerializer.Serialize(items, jsonSerializerOptions)
            };
            // Return the page.
            return(Page());
        }