Exemplo n.º 1
0
 public async Task <EmployeeRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
 {
     return((await roles.FetchEmployeeRole(int.Parse(roleId)).ConfigureAwait(false))
            .Ensure(e => e.HasValue, "Role is available")
            .OnBoth(e => e.IsFailure
             ? null
             : e.Value.Value));
 }
Exemplo n.º 2
0
        public async Task <IList <string> > GetRolesAsync(Employee user, CancellationToken cancellationToken)
        {
            var results = await roles.FetchEmployeeRole(user.RoleId)
                          .Ensure(e => e.HasValue, "Role is available")
                          .OnSuccess(e => e.Value)
                          .ConfigureAwait(false);

            if (results.IsFailure)
            {
                return(new List <string>());
            }

            return(new List <string> {
                results.Value.RoleName
            });
        }
Exemplo n.º 3
0
        public async Task <IActionResult> SubmitToken([FromQuery] string code, [FromQuery] string response_type, [FromQuery] string state)
        {
            if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(response_type) || string.IsNullOrWhiteSpace(state) || !string.Equals(response_type, "code", StringComparison.OrdinalIgnoreCase))
            {
                return(RedirectToPage("/Index"));
            }

            var employeeId = await cache.GetStringAsync($"company-square-verify-{state}").ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(employeeId))
            {
                return(RedirectToPage("/Index"));
            }

            int rawEmployeeId = -1;

            if (!int.TryParse(employeeId, out rawEmployeeId))
            {
                return(RedirectToPage("/Index"));
            }

            if (rawEmployeeId == -1)
            {
                return(RedirectToPage("/Index"));
            }

            var employee = await employees.FetchEmployee(rawEmployeeId)
                           .Ensure(e => e.HasValue, "Employee found")
                           .OnSuccess(e => e.Value)
                           .ConfigureAwait(false);

            if (employee.IsFailure)
            {
                return(RedirectToPage("/Index"));
            }

            var role = await roles.FetchEmployeeRole(employee.Value.RoleId)
                       .Ensure(r => r.HasValue, "Role found")
                       .OnSuccess(r => r.Value)
                       .ConfigureAwait(false);

            if (role.IsFailure || !role.Value.CanAdministerCompany)
            {
                return(RedirectToPage("/Index"));
            }

            var company = await companies.FetchCompany(employee.Value.CompanyId)
                          .Ensure(c => c.HasValue, "Company found")
                          .OnSuccess(c => c.Value)
                          .ConfigureAwait(false);

            if (company.IsFailure)
            {
                return(RedirectToPage("/Index"));
            }

            var client = new SquareClient.Builder()
                         .Environment(settings.Connection.SquarePaymentsSandbox ? Square.Environment.Sandbox : Square.Environment.Production)
                         .Build();

            var body = new ObtainTokenRequest(settings.Connection.SquareAppId, settings.Connection.SquareAccessToken, "authorization_code", code);

            ObtainTokenResponse response = null;

            try
            {
                response = await client.OAuthApi.ObtainTokenAsync(body).ConfigureAwait(false);
            }
            catch (Exception)
            {
                return(RedirectToPage("/Index"));
            }

            if (response == null)
            {
                return(RedirectToPage("/Index"));
            }

            var accessToken  = response.AccessToken;
            var refreshToken = response.RefreshToken;
            var expiresAt    = response.ExpiresAt;
            var merchantId   = response.MerchantId;

            DateTime tokenExpiry;

            if (!DateTime.TryParse(response.ExpiresAt, out tokenExpiry))
            {
                return(RedirectToPage("/Index"));
            }

            var companyId = company.Value.CompanyId;

            SynchVenuesWithExternalPaymentProvider(accessToken, company.Value);

            accessToken = await EncryptString(accessToken).ConfigureAwait(false);

            refreshToken = await EncryptString(refreshToken).ConfigureAwait(false);

            return(await companies.UpdateCompany(new CompanyPatch
            {
                ResourceId = companyId,
                ExternalAccessToken = new PatchOperation <string> {
                    Operation = OperationKind.Update, Value = accessToken
                },
                ExternalRefreshToken = new PatchOperation <string> {
                    Operation = OperationKind.Update, Value = refreshToken
                },
                ExternalAccountId = new PatchOperation <string> {
                    Operation = OperationKind.Update, Value = merchantId
                },
                ExternalTokenExpiry = new PatchOperation <DateTime> {
                    Operation = OperationKind.Update, Value = tokenExpiry
                }
            }).OnBoth(u => RedirectToPage("/Index")).ConfigureAwait(false));
        }
Exemplo n.º 4
0
        private async Task<AuthorisationResult> EnforceRBACRequirements(AuthContext authContext, Microsoft.AspNetCore.Routing.RouteData routeData)
        {
            var userType = authContext.UserType;

            // Grab the route name via the [ActionName(...)] annotation on a controller method.
            // If you don't annotate your methods, or have not configured this route as authenticated, we won't apply any auth restrictions.
            var routeName = (string)routeData.Values["action"];

            if (routeName == null || !settings.Meta.AuthRequirements.ContainsKey(routeName))
            {
                return AuthorisationResult.InjectAndContinue;
            }

            var requirements = settings.Meta.AuthRequirements[routeName];

            Maybe<Employee> employee = null;
            Maybe<EmployeeRole> employeeRole = null;
            Maybe<User> user = null;

            if (userType != settings.Meta.AuthRequirements[routeName].UserType && UserType.Any != settings.Meta.AuthRequirements[routeName].UserType)
            {
                return AuthorisationResult.AbortUnauthorised;
            }

            if (authContext.AuthToken.HasNoValue)
            {
                return AuthorisationResult.AbortUnauthorised;
            }

            var authToken = authContext.AuthToken.Value;

            // Depending on the session type, attempt to fetch the equivalent model (User or Employee).
            if (userType == UserType.Employee)
            {
                employee = (await employeeSessions.FetchEmployeeSessionAndEmployeeFromToken(authToken).ConfigureAwait(false))
                  .OnBoth(x => x.IsSuccess
                    ? x.Value
                    : Maybe<Employee>.None
                  );

                if (employee.HasNoValue)
                {
                    return AuthorisationResult.AbortUnauthorised;
                }

                // For employees, their permissions are scoped to an employee role. First we fetch the role.
                employeeRole = (await employeeRoles.FetchEmployeeRole(employee.Value.RoleId).ConfigureAwait(false))
                  .OnBoth(x => x.IsSuccess
                    ? x.Value
                    : Maybe<EmployeeRole>.None
                  );

                // If the employee role wasn't found but the route didn't require any permissions, we let them through.
                if (employeeRole.HasNoValue && RouteRequiresAtLeastOnePermission(requirements))
                {
                    return AuthorisationResult.AbortUnauthorised;
                }

                // Verify each of the role permissions in turn, if one is missing and the route requires it, deny access.
                if (!RoleHasCorrectPermissions(employeeRole.Value, requirements))
                {
                    return AuthorisationResult.AbortUnauthorised;
                }
            }
            else if (userType == UserType.User)
            {
                user = (await userSessions.FetchUserSessionAndUserFromToken(authToken, (int)authContext.AuthType).ConfigureAwait(false))
                  .OnBoth(x => x.IsSuccess
                    ? x.Value
                    : Maybe<User>.None
                  );

                if (user.HasNoValue)
                {
                    return AuthorisationResult.AbortUnauthorised;
                }
            }

            // After verifying the user's permissions, update the context with relevant user data and continue.
            authContext.Employee = employee;
            authContext.EmployeeRole = employeeRole;
            authContext.User = user;

            return AuthorisationResult.Continue;
        }