private async Task OnTweets(Tweet[] tweets)
        {
            if (tweets.Length == 0)
            {
                return;
            }

            try
            {
                using (var context = new ApplicationIdentityContext())
                {
                    var repository = new UserRepository(context);
                    var users      = await repository.GetUsersWithNotificationsAsync(); // Can be cached

                    foreach (var tweet in tweets)
                    {
                        foreach (var user in users)
                        {
                            SendNotification(tweet, user);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "An error occured while processing recieved tweets");
            }
        }
Exemple #2
0
        public static void Exist()
        {
            var context = ApplicationIdentityContext.Create();

            IndexChecks.EnsureUniqueIndexOnUserName(context.ApplicationUsers);
            IndexChecks.EnsureUniqueIndexOnRoleName(context.IdentityRoles);
        }
        //DangVH. Create. End (02/11/2016)

        public static List <Category> ListAllCategory()
        {
            ApplicationIdentityContext Context    = ApplicationIdentityContext.Create();
            List <Category>            categories = Context.Categories.Find(_ => true).ToList();

            return(categories);
        }
Exemple #4
0
 public UsersController(ApplicationIdentityContext _context,
                        UserManager <ApplicationUser> _userManager,
                        SignInManager <ApplicationUser> _signInManager)
 {
     context       = _context;
     userManager   = _userManager;
     signInManager = _signInManager;
 }
        public static int GetGroupJustCreatedNumber()
        {
            ApplicationIdentityContext Context = ApplicationIdentityContext.Create();
            var groups = Context.Groups.Find(_ => true).ToList();
            var a      = groups.Where(x => x.CreatedDate.ToShortDateString().Equals(DateTime.Now.ToShortDateString()));

            return((int)a.Count());
        }
        public static List <Group> SuggestGroup(string id)
        {
            ApplicationIdentityContext Context = ApplicationIdentityContext.Create();
            List <Group> suggestGroups         = new List <Group>();
            var          groups = Context.Groups.Find(x => x.Tag.Equals(id)).ToList();

            suggestGroups = groups.Take(4).ToList();
            return(suggestGroups);
        }
Exemple #7
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            var optionBuilder = new DbContextOptionsBuilder <ApplicationIdentityContext>();

            optionBuilder.UseSqlServer(configuration.GetConnectionString("IotIdentityContext"));

            using (ApplicationIdentityContext context = new ApplicationIdentityContext(optionBuilder.Options)) context.Database.EnsureCreated();
            services.AddTransient(_ => new ApplicationIdentityContext(optionBuilder.Options));

            services.AddIdentity <AppUser, IdentityRole>(cfg =>
            {
                cfg.User.RequireUniqueEmail = true;
            })
            .AddEntityFrameworkStores <ApplicationIdentityContext>();
        }
Exemple #8
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            var context             = ApplicationIdentityContext.Create();
            var userManager         = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context.Users));
            var usuarioIdentityName = requestContext.HttpContext.User.Identity.Name;

            if (!string.IsNullOrWhiteSpace(usuarioIdentityName))
            {
                var usuario = userManager.FindByName(requestContext.HttpContext.User.Identity.Name);
                if (usuario != null)
                {
                    UserBase = usuario.UserInfo;
                }
            }
            base.Initialize(requestContext);
        }
Exemple #9
0
        public static List <Book> LastestBookInteracted(string userId)
        {
            List <Book> listBook = new List <Book>();
            ApplicationIdentityContext Context = ApplicationIdentityContext.Create();
            var user        = Context.Users.Find(x => x.Id.Equals(userId)).FirstOrDefault();
            var currentDate = DateTime.Now;

            foreach (var interactBook in user.Interacbook.DistinctBy(x => x.BookId).ToList())
            {
                if (interactBook.InteractTime.Date > currentDate.AddDays(-7).Date)
                {
                    listBook.Add(Context.Books.Find(x => x.Id.Equals(interactBook.BookId)).FirstOrDefault());
                }
            }
            listBook = listBook.Take(4).ToList();
            return(listBook);
        }
Exemple #10
0
 public OrderController(IService <OrderDTO> _orderService,
                        IService <AddressDTO> _addressService,
                        Basket _basket,
                        ApplicationIdentityContext _context,
                        UserManager <ApplicationUser> _userManager,
                        SignInManager <ApplicationUser> _signInManager,
                        IConfiguration _configuration,
                        IEmailSender _emailSender)
 {
     orderService   = _orderService;
     addressService = _addressService;
     basket         = _basket;
     context        = _context;
     userManager    = _userManager;
     signInManager  = _signInManager;
     configuration  = _configuration;
     emailSender    = _emailSender;
 }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        public virtual void ConfigureAuth(IAppBuilder app)
        {
            PublicClientId = "self";

            var appcontext = ApplicationIdentityContext.Create();

            UserManagerFactory =
                () => new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(appcontext.Users));
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath           = new PathString("/Token"),
                Provider                    = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath       = new PathString("/api/UserProfile/ExternalLogin"),
                AccessTokenExpireTimeSpan   = TimeSpan.FromDays(30),
                AllowInsecureHttp           = true,
                ApplicationCanDisplayErrors = true
            };

            app.CreatePerOwinContext(ApplicationIdentityContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                LoginPath = new PathString("/home/index"),
                Provider  = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                            TimeSpan.FromMinutes(30),
                            (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            app.UseOAuthBearerTokens(OAuthOptions);


            app.UseRbacPermissions();
        }
Exemple #12
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityResult result;

            using (var context = ApplicationIdentityContext.Create())
            {
                var roleStore   = new RoleStore <IdentityRole>(context.Roles);
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                await roleManager.CreateAsync(new IdentityRole()
                {
                    Name = "User"
                });

                var userStore   = new UserStore <ApplicationUser>(context.Users);
                var userManager = new UserManager <ApplicationUser>(userStore);

                var newUser = new ApplicationUser()
                {
                    UserName = model.Name, Email = model.Email
                };

                result = await UserManager.CreateAsync(newUser, model.Password);

                await userManager.AddToRoleAsync(newUser.Id, "Admin");
            }


            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
        public static void RegisterDI(HttpConfiguration config, IAppBuilder app)
        {
            // Register dependencies, then...
            string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            var    builder = new ContainerBuilder();

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            // OPTIONAL: Register the Autofac model binder provider.
            builder.RegisterWebApiModelBinderProvider();
            builder.RegisterModule(new service.ServiceModule(connStr));
            var x = new ApplicationIdentityContext(connStr);

            builder.Register(c => x);
            //builder.Register(c => new UserStore<ApplicationUser>(x)).AsImplementedInterfaces();
            builder.RegisterType <UserStore <ApplicationUser, ApplicationRole, Guid, CustomUserLogin, CustomUserRole, CustomUserClaim> >().As <IUserStore <ApplicationUser, Guid> >();
            builder.Register(c => new IdentityFactoryOptions <ApplicationUserManager>()
            {
                DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ApplicationName"),
            });
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As <IAuthenticationManager>().AsImplementedInterfaces();;
            builder.RegisterType <UserManager <ApplicationUser, Guid> >();
            builder.RegisterType <SignInManager <ApplicationUser, Guid> >();
            builder.RegisterType <ApplicationUserManager>();
            builder.RegisterType <ApplicationSignInManager>();

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            app.UseAutofacMiddleware(container);
            var csl = new AutofacServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => csl);
        }
Exemple #14
0
 public AccountController()
 {
     _ctx = ApplicationIdentityContext.Create();
     _whiteLabelService = new WhiteLabelService();
 }
 public EFBasketRepository(Context _context, ApplicationIdentityContext _appContext)
 {
     context    = _context;
     appContext = _appContext;
 }
        //DangVH. Create. Start (02/11/2016)
        public static int GetBookNumber()
        {
            ApplicationIdentityContext Context = ApplicationIdentityContext.Create();

            return((int)Context.Books.Find(_ => true).Count());
        }
Exemple #17
0
        public static void Seed(ApplicationIdentityContext context,
                                UserManager <ApplicationUser> userManager,
                                RoleManager <ApplicationRole> roleManager,
                                SignInManager <ApplicationUser> _signInManager)
        {
            context.Database.EnsureCreated();

            if (context.Users.Any() || context.Roles.Any())
            {
                return;
            }

            if (!roleManager.RoleExistsAsync("Administrator").Result)
            {
                var role = new ApplicationRole {
                    Name = "Administrator"
                };
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("Manager").Result)
            {
                var role = new ApplicationRole {
                    Name = "Manager"
                };
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("User").Result)
            {
                var role = new ApplicationRole {
                    Name = "User"
                };
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (userManager.FindByNameAsync("40pyd").Result == null)
            {
                var user = new ApplicationUser
                {
                    UserName             = "******",
                    FirstName            = "Andrey",
                    LastName             = "40Pyd",
                    Birthday             = new DateTime(1985, 09, 04),
                    Email                = "*****@*****.**",
                    EmailConfirmed       = true,
                    NormalizedEmail      = ("*****@*****.**").ToUpper(),
                    NormalizedUserName   = ("Andrey").ToUpper(),
                    PhoneNumberConfirmed = true
                };

                IdentityResult result = userManager.CreateAsync(user, "123qweASD@").Result;

                if (result.Succeeded)
                {
                    var code = userManager.GenerateEmailConfirmationTokenAsync(user);
                    _signInManager.SignInAsync(user, isPersistent: false);
                    userManager.AddToRoleAsync(user, "Administrator").Wait();
                }
            }
        }
 public ReservationController()
 {
     _ctx = ApplicationIdentityContext.Create();
     _reservationService = new ReservationService();
 }
Exemple #19
0
 public WhiteLabelController()
 {
     _ctx = ApplicationIdentityContext.Create();
     _reservationService = new ReservationService();
     _whiteLabelService  = new WhiteLabelService();
 }
 public UnitOfWork(ApplicationContext applicationContext, ApplicationIdentityContext applicationIdentityContext)
 {
     database         = applicationContext;
     identityDatabase = applicationIdentityContext;
 }
 public WhiteLabelService()
 {
     _ctx = ApplicationIdentityContext.Create();
 }
 public TransactionsRepository()
 {
     _ctx = new AuthContext();
 }
 public UserRepository(ApplicationIdentityContext conBus)
 {
     this.database = conBus;
 }
Exemple #24
0
        //DangVH. Create. Start (02/11/2016)
        private static ApplicationIdentityContext Context()
        {
            ApplicationIdentityContext context = ApplicationIdentityContext.Create();

            return(context);
        }