コード例 #1
0
        public async Task <ActionResult> ModifyTimeLog(int id)
        {
            ViewBag.SyncType = "Asynchronous";
            int     hours   = Int32.Parse(Request["Time.Hour"]) * 3600;
            int     minutes = Int32.Parse(Request["Time.Minute"]) * 60;
            int     seconds = Int32.Parse(Request["Time.Second"]);
            TimeLog timeLog = new TimeLog();

            timeLog.Time     = DateTime.MinValue + TimeSpan.FromSeconds(hours + minutes + seconds);
            timeLog.Username = GetUsername();
            if (await TimeLogService.SetTimeLog(GetUsername(), timeLog, id))
            {
                return(Redirect(Request.UrlReferrer.ToString()));
            }
            else
            {
                return(View("Error", new ErrorMessageModel()
                {
                    Message = "Time was not modified!"
                }));
            }
        }
コード例 #2
0
 public UpdateDeletionsTests()
 {
     TimeService.UtcNow = TestUtcNow;
     _poll    = DefaultPoll;
     _service = new TimeLogService(TimeService, new NullUserEventsService());
 }
コード例 #3
0
ファイル: Startup.cs プロジェクト: ikhramts/maesure-oss
        // This method gets called by the runtime. Use this method to add services
        // to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Basic config
            services.AddSingleton(Configuration);
            services.AddOptions();

            var backendRoutes = new BackendRoutes();

            Configuration.GetSection("BackendRoutes").Bind(backendRoutes);
            services.AddSingleton(backendRoutes);

            var stackdriverOptions = new StackdriverOptions();

            Configuration.Bind("Stackdriver", stackdriverOptions);
            services.AddSingleton(stackdriverOptions);

            // Set up the shared DataProtection keystorage when running on Google Cloud.
            if (!Environment.IsDevelopment())
            {
                services.AddDataProtection()
                // Store keys in Cloud Storage so that multiple instances
                // of the web application see the same keys.
                .PersistKeysToGoogleCloudStorage(
                    Configuration["DataProtection:Bucket"],
                    Configuration["DataProtection:Object"])
                // Protect the keys with Google KMS for encryption and fine-
                // grained access control.
                .ProtectKeysWithGoogleKms(
                    Configuration["DataProtection:KmsKeyName"]);
            }

            // Set up user event tracking.
            IUserEventsService userEventsService;

            if (!Environment.IsDevelopment())
            {
                userEventsService = new UserEventsService(stackdriverOptions);
            }
            else
            {
                userEventsService = new NullUserEventsService();
            }

            services.AddSingleton(userEventsService);

            // App services
            var restClient = new RestClient();

            services.AddSingleton <IRestClient>(restClient);

            var timerFactory = new SystemTimerFactory(new NullLogger()); // Use NullLogger until we get problems.

            services.AddSingleton <ITimerFactory>(timerFactory);

            var timeService = new SystemTimeService();

            services.AddSingleton <ITimeService>(timeService);

            var tokenService = new Auth0TokenService(restClient,
                                                     timerFactory,
                                                     LoggerFactory.CreateLogger <Auth0TokenService>());
            var auth0Client = new Auth0Client(tokenService, restClient);

            services.AddSingleton <IAuth0Client>(auth0Client);

            _accountService = new AccountService(userEventsService, LoggerFactory, timeService);
            services.AddSingleton(_accountService);

            var timeLogServie = new TimeLogService(timeService, userEventsService);

            services.AddSingleton <ITimeLogService>(timeLogServie);

            // Paddle config.
            var paddleClient = new PaddleClient(Configuration["Paddle:VendorId"],
                                                Configuration["Paddle:VendorAuthCode"],
                                                restClient,
                                                LoggerFactory);

            services.AddSingleton <IPaddleClient>(paddleClient);

            services.AddSingleton <IPaddleWebhookSignatureVerifier>(new PaddleWebhookSignatureVerifier());

            // Configure Google App Engine logging
            if (!Environment.IsDevelopment())
            {
                services.Configure <StackdriverOptions>(Configuration.GetSection("Stackdriver"));

                services.AddGoogleExceptionLogging(options =>
                {
                    options.ProjectId   = stackdriverOptions.ProjectId;
                    options.ServiceName = stackdriverOptions.ServiceName;
                    options.Version     = stackdriverOptions.Version;
                });

                services.AddGoogleTrace(options =>
                {
                    options.ProjectId = stackdriverOptions.ProjectId;
                    options.Options   = TraceOptions.Create(bufferOptions: BufferOptions.NoBuffer());
                });
            }

            services.AddEntityFrameworkNpgsql()
            .AddDbContext <MainDbContext>()
            .BuildServiceProvider();

            // ======= Authentication config =======
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority = "https://maesure.auth0.com/";
                options.Audience  = "https://maesure.com/api/";
            })
            .AddCookie(options =>
            {
                options.LoginPath          = "/api/auth/login";
                options.LogoutPath         = "/api/auth/logout";
                options.SlidingExpiration  = true;
                options.ExpireTimeSpan     = TimeSpan.FromDays(90);
                options.Cookie.Expiration  = TimeSpan.FromDays(90);
                options.Cookie.SameSite    = SameSiteMode.Lax; // OAuth login will not work with "strict"
                options.Cookie.IsEssential = true;
            })
            .AddOpenIdConnect("Auth0", options =>
            {
                // Set the authority to your Auth0 domain
                options.Authority = $"https://{Configuration["Auth0:Domain"]}";

                // Configure the Auth0 Client ID and Client Secret
                options.ClientId     = Configuration["Auth0:ClientId"];
                options.ClientSecret = Configuration["Auth0:ClientSecret"];

                // Set response type to code
                options.ResponseType = "code";

                // Configure the scope
                options.Scope.Clear();
                options.Scope.Add("openid email profile");

                // Set the callback path, so Auth0 will call back to http://localhost:5000/callback
                // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard

                // WARNING: here, "callback" is not some placeholder URL. ASP.NET expects the user to be
                // sent litteral "/callback" URL. Do not change this.
                options.CallbackPath = new PathString("/callback");

                // Configure the Claims Issuer to be Auth0
                options.ClaimsIssuer = "Auth0";

                options.Events = new OpenIdConnectEvents
                {
                    // handle the logout redirection
                    OnRedirectToIdentityProviderForSignOut = (context) =>
                    {
                        var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

                        var postLogoutUri = context.Properties.RedirectUri;
                        if (!string.IsNullOrEmpty(postLogoutUri))
                        {
                            if (postLogoutUri.StartsWith("/"))
                            {
                                // transform to absolute
                                var request   = context.Request;
                                postLogoutUri = request.Scheme + "://" + request.Host + postLogoutUri;
                            }
                            logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
                        }

                        context.Response.Redirect(logoutUri);
                        context.HandleResponse();

                        return(Task.CompletedTask);
                    },
                    OnRedirectToIdentityProvider = (context) =>
                    {
                        // Check if we need to tell Auth0 explicitly which
                        // connection to use.
                        var properties = context.Properties;
                        var connection = properties.GetString("connection");

                        if (connection != null)
                        {
                            context.ProtocolMessage.SetParameter("connection", connection);
                        }

                        return(Task.CompletedTask);
                    },
                    OnTokenValidated = async(context) =>
                    {
                        // Ensure that the user exists in our database.
                        using (var db = new MainDbContext())
                        {
                            // Get the Auth0 user details.
                            var userClaims = context.SecurityToken.Claims;
                            var auth0Id    = userClaims.FirstOrDefault(c => c.Type == "sub").Value;
                            _log.LogInformation($"Ensuring account exists for '{auth0Id}'");

                            // See if there's a temp account session here.
                            var cookies = context.HttpContext.Request.Cookies;
                            cookies.TryGetValue(PublicWebProxyController.VisitorSessionKey, out var sessionId);

                            await _accountService.EnsureAccountEsists(db, auth0Id, sessionId);
                            _log.LogInformation($"Finished login for '{auth0Id}'");
                        }
                    },
                };
コード例 #4
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTimesheetOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTimesheetOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;
                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;

                    var             nowDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, DateTimeKind.Local);
                    List <DateTime> last7Days = Enumerable.Range(0, 7).Select(i => nowDate.AddDays(-6).Date.AddDays(i)).ToList();
                    var             startDate = new DateTime(last7Days[0].Year, last7Days[0].Month, last7Days[0].Day, 0, 0, 0, DateTimeKind.Local);
                    var             endDate   = nowDate.AddDays(1);       //Get End of current date

                    var projectTimelogs = new TimeLogService().GetTimelogsForPeriod(projectId, userId, startDate, endDate);

                    var users = new UserService().GetAll();

                    #region << Generate Grid Columns >>
                    var gridColumns = new List <GridColumn>()
                    {
                        new GridColumn()
                    };
                    foreach (var date in last7Days)
                    {
                        gridColumns.Add(new GridColumn()
                        {
                            Label = date.ToString("dd MMM"),
                            Width = "10%",
                            Class = "text-right"
                        });
                    }
                    gridColumns.Add(new GridColumn()
                    {
                        Label = "Total",
                        Width = "10%",
                        Class = "font-weight-bold text-right"
                    });
                    ViewBag.GridColumns = gridColumns;
                    #endregion

                    var records = new List <EntityRecord>();                    //id and other fields
                    #region << Init Rows >>
                    {
                        var billableRow = new EntityRecord();
                        billableRow["id"]    = "billable";
                        billableRow["label"] = "Billable";
                        billableRow["total"] = (decimal)0;
                        records.Add(billableRow);
                        var nonbillableRow = new EntityRecord();
                        nonbillableRow["id"]    = "nonbillable";
                        nonbillableRow["label"] = "Non-Billable";
                        nonbillableRow["total"] = (decimal)0;
                        records.Add(nonbillableRow);
                        var totalRow = new EntityRecord();
                        totalRow["id"]    = "total";
                        totalRow["label"] = "Total";
                        totalRow["total"] = (decimal)0;
                        records.Add(totalRow);
                    }
                    #endregion

                    var timelogsGroupByDate = projectTimelogs.GroupBy(x => (((DateTime?)x["logged_on"]).ConvertToAppDate() ?? DateTime.Now).ToString("dd-MM")).ToList();

                    for (int i = 0; i < 7; i++)
                    {
                        var billableRow    = records.First(x => (string)x["id"] == "billable");
                        var nonbillableRow = records.First(x => (string)x["id"] == "nonbillable");
                        var totalRow       = records.First(x => (string)x["id"] == "total");

                        billableRow.Properties.Add("day" + (i + 1), (decimal)0);
                        nonbillableRow.Properties.Add("day" + (i + 1), (decimal)0);
                        totalRow.Properties.Add("day" + (i + 1), (decimal)0);

                        var dateString   = last7Days[i].ToString("dd-MM");
                        var dateLogGroup = timelogsGroupByDate.FirstOrDefault(x => x.Key == dateString);
                        if (dateLogGroup != null)
                        {
                            var dateLogs = dateLogGroup.ToList();
                            foreach (var timelog in dateLogs)
                            {
                                totalRow["day" + (i + 1)] = (decimal)totalRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                if ((bool)timelog["is_billable"])
                                {
                                    billableRow["day" + (i + 1)] = (decimal)billableRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                    billableRow["total"]         = (decimal)billableRow["total"] + (decimal)timelog["minutes"];
                                }
                                else
                                {
                                    nonbillableRow["day" + (i + 1)] = (decimal)nonbillableRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                    nonbillableRow["total"]         = (decimal)nonbillableRow["total"] + (decimal)timelog["minutes"];
                                }
                                totalRow["total"] = (decimal)totalRow["total"] + (decimal)timelog["minutes"];
                            }
                        }
                    }

                    if (userId == null)
                    {
                        var timelogsGroupByCreator = projectTimelogs.GroupBy(x => (Guid)x["created_by"]).ToList();
                        foreach (var userGroup in timelogsGroupByCreator)
                        {
                            var user      = users.First(x => (Guid)x["id"] == userGroup.Key);
                            var imagePath = "/assets/avatar.png";
                            if (user["image"] != null && (string)user["image"] != "")
                            {
                                imagePath = "/fs" + (string)user["image"];
                            }

                            var userTimelogs            = userGroup.ToList();
                            var userTimelogsGroupByDate = userTimelogs.GroupBy(x => (((DateTime?)x["logged_on"]).ConvertToAppDate() ?? DateTime.Now).ToString("dd-MM")).ToList();
                            var userRow = new EntityRecord();
                            userRow["id"]    = (string)user["username"];
                            userRow["label"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                            userRow["total"] = (decimal)0;

                            for (int i = 0; i < 7; i++)
                            {
                                userRow.Properties.Add("day" + (i + 1), (decimal)0);
                                var dateString   = last7Days[i].ToString("dd-MM");
                                var dateLogGroup = userTimelogsGroupByDate.FirstOrDefault(x => x.Key == dateString);
                                if (dateLogGroup != null)
                                {
                                    var dateLogs = dateLogGroup.ToList();
                                    foreach (var timelog in dateLogs)
                                    {
                                        userRow["day" + (i + 1)] = (decimal)userRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                        userRow["total"]         = (decimal)userRow["total"] + (decimal)timelog["minutes"];
                                    }
                                }
                            }
                            records.Add(userRow);
                        }
                    }
                    ViewBag.Records = records;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
コード例 #5
0
 public GetTests()
 {
     _poll    = DefaultPoll;
     _service = new TimeLogService(TimeService, new NullUserEventsService());
 }
コード例 #6
0
        public ActionResult SubmitTimeLog(TimeLogViewModel log)
        {
            TimeLogService.SubmitTimeLog(log);

            return(RedirectToAction("Index", "Home"));
        }
コード例 #7
0
        public ActionResult Index()
        {
            List <TimeLogViewModel> entries = TimeLogService.GetFiveLatestEntries();

            return(View(entries));
        }
コード例 #8
0
 public void InitBeforeEachTest()
 {
     tls = new TimeLogService();
 }
コード例 #9
0
 public UndoTests()
 {
     TimeService.UtcNow = TestUtcNow;
     _service           = new TimeLogService(TimeService, new NullUserEventsService());
 }