Exemplo n.º 1
0
        private List <TaskReportRecordModel> LoadDailyData(DateTime start, Account user)
        {
            // Initialization.
            List <TaskReportRecordModel> lst = new List <TaskReportRecordModel>();

            try
            {
                DateTime end = start.AddDays(1);
                List <TaskReportRecordModel> dataList = (from wt in repository.Worktasks
                                                         where (
                                                             (wt.CreationDate >= start && wt.CreationDate < end || wt.LastUpdateDateTime >= start && wt.LastUpdateDateTime < end) &&
                                                             (UserPermissionService.GetInstance().isManager(user.Role) || (UserPermissionService.GetInstance().isUser(user.Role) && user.UID == wt.Assignee))
                                                             )
                                                         orderby wt.TaskType
                                                         select new TaskReportRecordModel()
                {
                    TaskType = wt.TaskType,
                    Title = wt.Title,
                    AssigneeName = wt.AssigneeAcc.DisplayName2,
                    Status = wt.Status,
                    CreationDate = wt.CreationDate,
                    LastUpdateDate = (wt.LastUpdateDateTime ?? wt.CreationDate)
                }).ToList <TaskReportRecordModel>();
                return(dataList);
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }
            // info.
            return(lst);
        }
Exemplo n.º 2
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (ValidateLogin())
            {
                User us = new UserService().GetUser(txtUsername.Value.ToString());
                Session["username"] = us.UserName.ToString();
                Session["userid"]   = us.UserId;
                Session["usertype"] = us.UserType;
                List <UserPermission> pm = new UserPermissionService().GetUserPermissions(us.UserId, us.UserId);
                Session["Role"] = pm;

                new AuditLogService().AddAuditLog("LOGIN ATTEMPT", us.UserId, us.UserName, "Successfully Logged in", DateTime.Now);


                if (us.UserType == "Administrator" || us.UserType == "System")
                {
                    Tutor st = new TutorService().GetTutor(Session["userid"].ToString());
                    Session["userfname"] = st.FNames != null?st.FNames.ToString() : "ComSoft";

                    if (us.DateCreated.Date >= us.LastModify.Date)
                    {
                    }
                    else
                    {
                        Response.Redirect("~/home.aspx");
                    }
                }
                else if (us.UserType == "Tutor")
                {
                    Tutor st = new TutorService().GetTutor(Session["userid"].ToString());
                    Session["userfname"] = st.FNames.ToString();
                    Response.Redirect("~/teachingstaffdashboard.aspx");
                }
                else if (us.UserType == "Administrator & Tutor")
                {
                    Tutor st = new TutorService().GetTutor(Session["userid"].ToString());
                    Session["userfname"] = st.FNames.ToString();
                    Response.Redirect("~/admintutordashboard.aspx");
                }
                else if (us.UserType == "Student")
                {
                    Student st = new StudentService().GetStudent(Session["userid"].ToString());
                    Session["userfname"] = st.FNames.ToString();
                    Response.Redirect("~/studentdashboard.aspx");
                }
                else if (us.UserType == "Parent")
                {
                    Response.Redirect("~/parentdashboard.aspx");
                }
            }
            else
            {
                txtPassword.Focus();
                txtUsername.Focus();
                txtUsername.Style.Add("border-color", "red");
                txtPassword.Style.Add("border-color", "red");
                //UpdatePanelLogin.Update();
            }
        }
Exemplo n.º 3
0
    /// <summary>
    /// Get all users based on filter criteria
    /// </summary>
    /// <param name="db">dataContext</param>
    /// <param name="ups">IUserPermissionService</param>
    /// <param name="activeOnly">if true, then return active only</param>
    /// <returns>IQueryable of User</returns>
    public static IQueryable <User> UsersByFilter(this DataContext db, UserPermissionService ups, bool activeOnly)
    {
        var query = db.RoleRestrictedUsers(ups);

        if (activeOnly)
        {
            query = query.Where(w => !w.AuditFields.InactiveDateTime.HasValue);
        }
        return(query);
    }
Exemplo n.º 4
0
    /// <summary>
    /// Get all General role restricted roles
    /// </summary>
    /// <param name="db">dataContext</param>
    /// <param name="ups">IUserPermissionService</param>
    /// <param name="viewOnly">if View only then entity change tracking is turned off</param>
    /// <returns>IQueryable of Role</returns>
    public static IQueryable <Role> RoleRestrictedRoles(this DataContext db, UserPermissionService ups, bool grantingRoles, bool viewOnly = true)
    {
        var query = ups.RoleRestrictRoles(db.Roles.AsQueryable(), grantingRoles, viewOnly);

        if (viewOnly)
        {
            query = query.AsNoTracking();
        }
        return(query);
    }
Exemplo n.º 5
0
    /// <summary>
    /// Get all restricted users
    /// </summary>
    /// <param name="db">dataContext</param>
    /// <param name="ups">IUserPermissionService</param>
    /// <param name="viewOnly">if View only then entity change tracking is turned off</param>
    /// <returns>IQueryable of Launch</returns>
    public static IQueryable <Launch> RoleRestrictedLaunches(this DataContext db, UserPermissionService ups, bool viewOnly = true)
    {
        var query = ups.RoleRestrictLaunches(db.Launches.AsQueryable(), viewOnly);

        if (viewOnly)
        {
            query = query.AsNoTracking();
        }
        return(query);
    }
Exemplo n.º 6
0
        public JsonResult SendDailyReport(string date)
        {
            try
            {
                if (null == date || date.Trim().Length == 0)
                {
                    date = DateTime.Now.ToString("dd-MM-yyyy");
                }
                string[] val = date.Split('-');

                DateTime start = new DateTime(Convert.ToInt32(val[2]), Convert.ToInt32(val[1]), Convert.ToInt32(val[0]));

                Account[] lstAccount = accRepository.Accounts.ToArray();

                foreach (Account item in lstAccount)
                {
                    if ((!String.IsNullOrEmpty(item.Email)) && !UserPermissionService.GetInstance().isAdmin(item.Role))
                    {
                        List <TaskReportRecordModel> data     = this.LoadDailyData(start, item);
                        List <TaskReportRecordModel> dataPrev = this.LoadTillThisTimeData(start);
                        TaskDailyReport rp = new TaskDailyReport(start, item);
                        rp.prepareReport();
                        string outputfile = rp.loadReportFile(data, dataPrev);
                        if (outputfile.Length > 0)
                        {
                            string filename = Path.GetFileName(outputfile);

                            MailMessage mail       = new MailMessage();
                            SmtpClient  smtpCLient = new SmtpClient(WebConfigurationManager.AppSettings["EmailReportServer"]);
                            mail.From = new MailAddress(WebConfigurationManager.AppSettings["EmailReportFrom"], "No Reply");
                            mail.To.Add(item.Email);
                            mail.Subject = "Báo cáo công văn ngày " + String.Format("{0:dd-MM-yyyy}", start);
                            mail.Body    = Path.GetFileNameWithoutExtension(outputfile);

                            System.Net.Mail.Attachment attachment;
                            attachment = new System.Net.Mail.Attachment(outputfile);
                            mail.Attachments.Add(attachment);

                            smtpCLient.Port        = Convert.ToInt32(WebConfigurationManager.AppSettings["EmailReportPort"]);
                            smtpCLient.Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["EmailReportFrom"], WebConfigurationManager.AppSettings["EmailReportPass"]);
                            smtpCLient.EnableSsl   = Convert.ToBoolean(WebConfigurationManager.AppSettings["EmailReportSSL"]);

                            smtpCLient.Send(mail);
                            smtpCLient.Dispose();
                        }
                    }
                }
            }
            catch
            {
            }
            return(Json(new { message = "Đã tạo xong báo cáo ngày" }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 7
0
    public static IQueryable <User> RoleRestrictUsers(this UserPermissionService ups, IQueryable <User> query, bool viewOnly)
    {
        if (ups.UserClaimModel.IsAdmin)
        { /* do nothing */
        }
        else
        {
            query = query.Where(w => w.UserId == ups.UserClaimModel.UserId); // They don't have access, filter them out.
        }

        return(query);
    }
Exemplo n.º 8
0
    public static IQueryable <Report> RoleRestrictReports(this UserPermissionService ups, IQueryable <Report> query, bool viewOnly)
    {
        if (!viewOnly)
        {
            query = query.Where(w => w.UserId == ups.UserClaimModel.UserId);
        }
        else
        {
            query = query.Where(w => w.UserId == ups.UserClaimModel.UserId || w.IsShared);
        }

        return(query);
    }
Exemplo n.º 9
0
    public static IQueryable <Role> RoleRestrictRoles(this UserPermissionService ups, IQueryable <Role> query, bool grantingRoles, bool viewOnly)
    {
        if (grantingRoles && ups.UserClaimModel.RoleData != null && ups.UserClaimModel.RoleData.GrantableRoleIds != null)
        {
            query = query.Where(w => ups.UserClaimModel.RoleData.GrantableRoleIds.Contains(w.RoleId));
        }
        else if (grantingRoles || !viewOnly)
        {
            query = query.Where(w => false);
        }

        return(query.OrderBy(o => o.Level));
    }
Exemplo n.º 10
0
    public static IQueryable <Launch> RoleRestrictLaunches(this UserPermissionService ups, IQueryable <Launch> query, bool viewOnly)
    {
        if (ups.UserClaimModel.IsAdmin)
        { /* do nothing */
        }
        else
        {
            if (!viewOnly)
            {
                query = query.Where(w => w.Rocket !.UserId == ups.UserClaimModel.UserId);
            }
        }

        return(query);
    }
        public DataContext CreateDbContext(string[] args)
        {
            //if (!System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Launch();
            var builder = new DbContextOptionsBuilder<DataContext>();

            string projectPath = AppDomain.CurrentDomain.BaseDirectory!.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0];
            IConfigurationRoot configBuilder = new ConfigurationBuilder()
                .SetBasePath(projectPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddUserSecrets(Assembly.GetExecutingAssembly())
                .Build();
            
            builder.UseSqlServer(configBuilder.GetConnectionString("DefaultConnection"));

            var ups = new UserPermissionService();
            ups.Setup(new UserClaimModel());
            return new DataContext(ups, builder.Options, null);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Sets up the data context and UserPermissionService for the service and all services injected in the service
        /// </summary>
        /// <param name="dataContext">data context</param>
        /// <param name="userPermissionService">UserPermissionService</param>
        public void SetupService(DataContext dataContext, ILoggingContext loggingDb, UserPermissionService userPermissionService)
        {
            db                    = dataContext;
            LoggingDb             = loggingDb;
            UserPermissionService = userPermissionService;

            // go through all fields, if any of them are a BaseService Setup DB and UPS
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
                                 BindingFlags.Static | BindingFlags.Instance |
                                 BindingFlags.DeclaredOnly;
            var fields = this.GetType().UnderlyingSystemType.GetFields(flags).Where(w => w.FieldType.BaseType == typeof(BaseService)).ToList();

            foreach (var item in fields)
            {
                var baseService = (item.GetValue(this) as BaseService);
                baseService?.SetupService(db, LoggingDb, UserPermissionService);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Services that the system uses that are added
        /// </summary>
        private void DeveloperAddedServices(IServiceCollection services)
        {
            services.Configure<Services.Email.MailSettings>(Configuration.GetSection(nameof(Services.Email.MailSettings)));
            services.AddTransient<Services.Email.IEmailer, Services.Email.Emailer>();

            services.AddScoped<UserPermissionService>((s) =>
            {
                var contextAccessor = s.GetService<IHttpContextAccessor>();
                //string ipAddress = "N/A";

                //if (contextAccessor.HttpContext != null)
                //{
                //    if (contextAccessor.HttpContext.Connection.RemoteIpAddress.IsIPv4MappedToIPv6)
                //        ipAddress = contextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                //    else
                //        ipAddress = contextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv6().ToString();
                //}
                var ups = new UserPermissionService();
                ups.Setup(new UserClaimBuilder(contextAccessor!.HttpContext?.User));
                return ups;
            });

            var dbConnection = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<DataContext>(options => options.UseSqlServer(dbConnection));
            services.AddDbContext<ILoggingContext, DataContext>(options => options.UseSqlServer(dbConnection));

            //services.Configure<ReCAPTCHASettings>(Configuration.GetSection(nameof(ReCAPTCHASettings)));

            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Templates.Emails.EmailsCreate>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Launches.LaunchesCreateUpdate>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Launches.LaunchesGet>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Logs.APILogsCreateUpdate>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Logs.SystemLogsCreate>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Rockets.RocketsCreateUpdate>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Rockets.RocketsGet>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Adhoc.AdhocCreateUpdate>();
            services.AddTransient<RocketLaunchJournal.Infrastructure.Services.Adhoc.AdhocGet>();
            services.AddTransient<UsersCreateUpdate>();
            services.AddTransient<UsersGet>();
        }
Exemplo n.º 14
0
 public DataContext(UserPermissionService ups, DbContextOptions <DataContext> options, ILogger <DataContext>?logger) : base(options)
 {
     _userPermissionService = ups;
     _logger = logger;
 }
Exemplo n.º 15
0
        async static Task Main(string[] args)
        {
            System.Console.WriteLine("Seeder Started...");
            System.Console.WriteLine("Type: ");
            System.Console.WriteLine(" 1 - \"enum\" to seed enum values.");
            System.Console.WriteLine(" 2 - \"rcu\" to seed roles and users data.");
            System.Console.WriteLine(" 3 - to seed rockets/launches.");

            var builder = new DbContextOptionsBuilder <DataContext>();

            string             projectPath   = AppDomain.CurrentDomain.BaseDirectory !.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0];
            IConfigurationRoot configBuilder = new ConfigurationBuilder()
                                               .SetBasePath(projectPath)
                                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                               .AddUserSecrets(typeof(Program).Assembly)
                                               .Build();

            builder.UseSqlServer(configBuilder.GetConnectionString("DefaultConnection"));

            var ups = new UserPermissionService();

            ups.Setup(new UserClaimBuilderTester());

            var context = new DataContext(ups, builder.Options, null);

            SeedBase?seeder = null;

            while (true)
            {
                var command = System.Console.ReadLine();

                switch (command.ToLower())
                {
                case "1":
                case "enum":
                    seeder = new SeedEnums(context);
                    await seeder.Seed();

                    System.Console.WriteLine("Seed complete");
                    break;

                case "2":
                case "rcu":
                    seeder = new SeedRolesUsers(context);
                    await seeder.Seed();

                    System.Console.WriteLine("Seed complete");
                    break;

                case "3":
                    seeder = new SeedRocketsLaunches(context);
                    await seeder.Seed();

                    System.Console.WriteLine("Seed complete");
                    break;

                default:
                    System.Console.WriteLine("bye");
                    return;
                }
            }
        }
 public async Task Invoke(HttpContext context, SystemLogsCreate systemLogsCreate, DataContext spudContext, ILoggingContext loggingDb, UserPermissionService userPermissionService)
 {
     try
     {
         await _next.Invoke(context);
     }
     catch (Exception ex)
     {
         systemLogsCreate.SetupService(spudContext, loggingDb, userPermissionService);
         await HandleExceptionAsync(context, ex, systemLogsCreate);
     }
 }
Exemplo n.º 17
0
 protected override void OnInitialize()
 {
     _service = new UserPermissionService(Database, UserService);
 }
Exemplo n.º 18
0
 public UserPermissionController()
 {
     this.userPermissionService = new UserPermissionService();
 }
Exemplo n.º 19
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="apiLogsCreateUpdate"></param>
 /// <param name="db"></param>
 /// <param name="loggingDb"></param>
 /// <param name="userPermissionService"></param>
 public LogRequestResponseFilter(APILogsCreateUpdate apiLogsCreateUpdate, DataContext db, ILoggingContext loggingDb, UserPermissionService userPermissionService)
 {
     apiLogsCreateUpdate.SetupService(db, loggingDb, userPermissionService);
     _apiLogsCreateUpdate = apiLogsCreateUpdate;
 }