public IEnumerable <dynamic> CollectionFromSql(string sql, Dictionary <string, object> parameters = null, CommandType commandType = CommandType.Text)
        {
            using (var mbosContext = new MBOSContext())
            {
                using (var cmd = mbosContext.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.CommandType = commandType;
                    if (cmd.Connection.State != ConnectionState.Open)
                    {
                        cmd.Connection.Open();
                    }

                    if (parameters != null)
                    {
                        foreach (var param in parameters)
                        {
                            var dbParameter = cmd.CreateParameter();
                            dbParameter.ParameterName = param.Key;
                            dbParameter.Value         = param.Value;
                            cmd.Parameters.Add(dbParameter);
                        }
                    }


                    using (var dataReader = cmd.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            var dataRow = GetDataRow(dataReader);
                            yield return(dataRow);
                        }
                    }
                }
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //var allowedOrigin = "*";
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new { allowedOrigin });
            var  userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            User user        = new User();

            user = await userManager.FindAsync(context.UserName, context.Password);

            var mapper = new DiObjectMapper();
            ApplicationLogViewModel logViewModel = new ApplicationLogViewModel()
            {
                Action = "Login",
                Data   = user,
                Entity = "User"
            };

            if (user == null)
            {
                logViewModel.Data = new { UserName = context.UserName }
            }
            ;

            var appLog = mapper.Map <ApplicationLogViewModel, ApplicationLog>(logViewModel);

            appLog.IpAddress = GeneralService.ClientIpFromHeader;
            appLog.LogType   = General.Enums.LogType.System;
            appLog.Date      = GeneralService.CurrentDate;

            var mbosContext = MBOSContext.Create();

            if (user == null)
            {
                appLog.Description = "Invalid username or password";
                mbosContext.ApplicationLogs.Add(appLog);
                mbosContext.SaveChanges();
                context.SetError("invalid_grant", "The username or password is incorrect.");
                return;
            }
            if (!user.EmailConfirmed)
            {
                appLog.Description = "Account email is not confirmed.";
                mbosContext.ApplicationLogs.Add(appLog);
                mbosContext.SaveChanges();
                context.SetError("invalid_grant", "Email is not confirmed yet.");
                return;
            }
            if (user.AccessFailedCount >= 3)
            {
                appLog.Description = "Account is locked.";
                mbosContext.ApplicationLogs.Add(appLog);
                mbosContext.SaveChanges();
                context.SetError("invalid_grant", "Your account has been locked. Please contact the administrator!");
                return;
            }
            appLog.UserId      = user.Id;
            appLog.Description = "Login successful.";
            mbosContext.ApplicationLogs.Add(appLog);
            mbosContext.SaveChanges();
            var loginInfo = new LoginInfo()
            {
                UserId            = user.Id,
                FullName          = user.FullName,
                DisplayPicture    = string.IsNullOrEmpty(user.DisplayPicture) ? "Resources/DisplayPictures/noimage.jpg" : user.DisplayPicture,
                LoginUserBranches = user.UserBranches.Select(c => new LoginUserBranch()
                {
                    Id = (Guid)c.BranchId, Name = c.Branch.Name, ShortName = c.Branch.ShortName
                }).ToList(),
                RoleId       = user.Roles.Select(c => c.RoleId).FirstOrDefault(),
                RoleType     = user.Roles.Select(c => c.Role.RoleType).FirstOrDefault(),
                DepartmentId = user.DepartmentId, Role = user.Roles.Select(c => c.Role.Name).FirstOrDefault()
            };
            var loginInfoValue = Newtonsoft.Json.JsonConvert.SerializeObject(loginInfo);
            IDictionary <string, string> authProp = new Dictionary <string, string>
            {
                { "LoginInfo", loginInfoValue }
            };
            var claims = new List <Claim>()
            {
                new Claim("LoginInfo", loginInfoValue)
            };
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType, claims);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType, claims);


            AuthenticationProperties properties = new AuthenticationProperties(authProp);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
 public GenericRepository(MBOSContext dataContext)
 {
     _dataContext = dataContext;
     _dbSet       = _dataContext.Set <TEntity>();
 }
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <User, Role, Guid, UserLogin, UserRole, UserClaim>(MBOSContext.Create()));

            manager.UserValidator = new UserValidator <User, Guid>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };
            //Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true
            };
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <User, Guid>(dataProtectionProvider.Create("MBOS"))
                {
                    TokenLifespan = TimeSpan.FromHours(48)
                };
            }
            return(manager);
        }