Example #1
0
        /// <summary>
        /// Creates an access control rule.
        /// Documentation https://developers.google.com/calendar/v3/reference/acl/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated calendar service.</param>
        /// <param name="calendarId">Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.</param>
        /// <param name="body">A valid calendar v3 body.</param>
        /// <returns>AclRuleResponse</returns>
        public static AclRule Insert(calendarService service, string calendarId, AclRule body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (calendarId == null)
                {
                    throw new ArgumentNullException(calendarId);
                }

                // Make the request.
                return(service.Acl.Insert(body, calendarId).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Acl.Insert failed.", ex);
            }
        }
Example #2
0
 public GoogleCalendar AddPeopleToAcl(string email = "", string id = "", bool isAsync = false)
 {
     //check if calendar with id exist
     if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(id))
     {
         var aclRule = calendarService.Acl.List(id).Execute().Items.Where(c => c.Scope.Value == email).FirstOrDefault();
         var rule    = new AclRule()
         {
             Role = "owner", Scope = new AclRule.ScopeData()
             {
                 Type = "user", Value = email
             }
         };
         var publicRule = new AclRule()
         {
             Role = "reader", Scope = new AclRule.ScopeData()
             {
                 Type = "default"
             }
         };
         var insObjectRule       = calendarService.Acl.Insert(rule, id).Execute();
         var insObjectPublicRule = calendarService.Acl.Insert(publicRule, id).Execute();
     }
     return(this);
 }
 public void AddCalendarAclRule(string customerId, string calendarId, AclRule body, bool sendNotifications)
 {
     using (PoolItem <CalendarService> connection = this.calendarServicePool.Take(NullValueHandling.Ignore))
     {
         AclResource.InsertRequest request = new AclResource.InsertRequest(connection.Item, body, calendarId);
         request.SendNotifications = sendNotifications;
         request.ExecuteWithRetry(RetryEvents.BackoffNotFound);
     }
 }
Example #4
0
        public bool EnsureReadPermissionsForService(string p_GooCalsJson, string p_GooServiceName)
        {
            bool           retval = true;
            List <AclRule> myacl  = new List <AclRule>();
            var            myCals = JsonConvert.DeserializeObject <string[]>(p_GooCalsJson);

            foreach (var item in myCals)
            {
                var request = calendarService.Acl.List(item);
                request.OauthToken = googleAuthToken.access_token;
                try
                {
                    var myaclx = request.Execute();
                    myacl = (List <AclRule>)myaclx.Items;
                }
                catch (Exception ex)
                {
                    retval = false;
                    Logger.Error(ex, "Can't Acl.List(" + item + ")");
                }
                bool serviceFound = false;
                foreach (var myaclrule in myacl)
                {
                    if (myaclrule.Scope.Type == "user" && myaclrule.Scope.Value == p_GooServiceName)
                    {
                        serviceFound = true;
                    }
                }
                if (serviceFound == false)
                {
                    //add p_GooServiceName as writer(?) TODO:reader
                    AclRule newRule = new AclRule();
                    newRule.Role = "writer";
                    AclRule.ScopeData newScope = new AclRule.ScopeData();
                    newScope.Type  = "user";
                    newScope.Value = p_GooServiceName;
                    newRule.Scope  = newScope;
                    var request2 = calendarService.Acl.Insert(newRule, item);
                    request2.OauthToken = googleAuthToken.access_token;
                    try
                    {
                        var mynewacl = request2.Execute();
                    }
                    catch (Exception ex)
                    {
                        retval = false;
                        Logger.Error(ex, "Can't Acl.Insert(" + item + ")");
                    }
                }
            }
            return(retval);
        }
Example #5
0
        /// <summary>
        /// Add user to Calendar!
        /// </summary>
        /// <param name="userName">Webhost User Name</param>
        /// <param name="calendarId">Webhost Calendar Id</param>
        /// <param name="role">Role in the Calendar, "reader" is default, "writer", "none" and "owner" are others.</param>
        public void AddUserToCalendar(String userName, String calendarId, String role = "reader")
        {
            AclRule rule = new AclRule()
            {
                Role  = role,
                Scope = new AclRule.ScopeData()
                {
                    Type = "user", Value = String.Format("{0}@dublinschool.org", userName)
                }
            };

            WebhostEventLog.GoogleLog.LogInformation("Added {0} to access {1} with role {2}.", userName, calendarId, role);
            service.Acl.Insert(rule, calendarId);
        }
        protected void AddEmailToCalendar(string calendarId, string email)
        {
            AclRule userRule = new AclRule()
            {
                Role  = "reader",
                Scope = new AclRule.ScopeData()
                {
                    Type  = "user",
                    Value = email
                }
            };

            CalendarService.Acl.Insert(userRule, calendarId).Execute();
        }
        private IList <ValueChange> DeleteFromRole(AttributeChange change, IList <AclRule> existingRules, string role, string calendarId)
        {
            List <ValueChange> valueChanges = new List <ValueChange>();

            IList <string> deletes;

            if (change.ModificationType == AttributeModificationType.Delete || change.ModificationType == AttributeModificationType.Replace)
            {
                deletes = existingRules.Where(t => t.Role == role).Select(t => t.Scope.Value).ToList();
            }
            else
            {
                deletes = change.GetValueDeletes <string>();
            }

            foreach (string valueToDelete in deletes)
            {
                AclRule matchedRule = existingRules.FirstOrDefault(t => t.Role == role && valueToDelete.Equals(t.Scope.Value, StringComparison.CurrentCultureIgnoreCase));

                if (matchedRule == null)
                {
                    Logger.WriteLine($"{valueToDelete} does not have role {role} on calendar {calendarId}. The request to delete the value will be ignored");
                    valueChanges.Add(ValueChange.CreateValueDelete(valueToDelete));

                    continue;
                }

                if (matchedRule.Role == "owner" && calendarId.Equals(matchedRule.Scope.Value, StringComparison.CurrentCultureIgnoreCase))
                {
                    Debug.WriteLine($"Ignoring default ACL for {valueToDelete} to role {role} on calendar {calendarId}");
                    continue;
                }

                try
                {
                    this.config.ResourcesService.DeleteCalendarAclRule(this.config.CustomerID, calendarId, matchedRule.Id);
                    Logger.WriteLine($"Removed {valueToDelete} from role {role} on calendar {calendarId}");
                }
                catch
                {
                    Logger.WriteLine($"Failed to remove {valueToDelete} to role {role} on calendar {calendarId}");
                    throw;
                }

                valueChanges.Add(ValueChange.CreateValueDelete(valueToDelete));
            }

            return(valueChanges);
        }
        private IList <ValueChange> AddToRole(AttributeChange change, IList <AclRule> existingRules, string role, string calendarId)
        {
            List <ValueChange> valueChanges = new List <ValueChange>();

            foreach (string valueToAdd in change.GetValueAdds <string>())
            {
                AclRule matchedRule = existingRules.FirstOrDefault(t => t.Role == role && valueToAdd.Equals(t.Scope.Value, StringComparison.CurrentCultureIgnoreCase));

                if (matchedRule != null)
                {
                    Logger.WriteLine($"{valueToAdd} already has role {role} on calendar {calendarId}. The request to add the value will be ignored");
                    valueChanges.Add(ValueChange.CreateValueAdd(valueToAdd));
                    continue;
                }

                AclRule rule = new AclRule();
                rule.Role        = role;
                rule.Scope       = new AclRule.ScopeData();
                rule.Scope.Value = valueToAdd;
                rule.Scope.Type  = this.GetScopeType(valueToAdd);

                try
                {
                    this.config.ResourcesService.AddCalendarAclRule(this.config.CustomerID, calendarId, rule, this.config.CalendarSendNotificationOnPermissionChange);
                    Logger.WriteLine($"Added {valueToAdd} to role {role} on calendar {calendarId}");
                }
                catch
                {
                    Logger.WriteLine($"Failed to add {valueToAdd} to role {role} on calendar {calendarId}");
                    throw;
                }

                valueChanges.Add(ValueChange.CreateValueAdd(valueToAdd));
            }

            return(valueChanges);
        }
Example #9
0
        /// <summary>
        /// Updates Calendar Permissions.
        /// </summary>
        /// <param name="doRemovals"></param>
        public void UpdateCalendars(bool doRemovals = true)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                List <String> alreadyMembers = new List <string>();

                List <String> activeStudentEmails = new List <string>();
                foreach (Student student in db.Students.Where(s => s.isActive).ToList())
                {
                    activeStudentEmails.Add(String.Format("{0}@dublinschool.org", student.UserName));
                }

                List <String> activeFacultyEmails = new List <string>();
                foreach (Faculty faculty in db.Faculties.Where(f => f.isActive).ToList())
                {
                    activeFacultyEmails.Add(String.Format("{0}@dublinschool.org", faculty.UserName));
                }

                List <String> inactiveUsers = new List <string>();
                foreach (Faculty faculty in db.Faculties.Where(f => !f.isActive).ToList())
                {
                    inactiveUsers.Add(String.Format("{0}@dublinschool.org", faculty.UserName));
                }

                foreach (Student student in db.Students.Where(f => !f.isActive).ToList())
                {
                    inactiveUsers.Add(String.Format("{0}@dublinschool.org", student.UserName));
                }

                foreach (GoogleCalendar gcal in db.GoogleCalendars.ToList())
                {
                    List <AclRule> rules = service.Acl.List(gcal.CalendarId).Execute().Items.Where(r => r.Scope.Type.Equals("user")).ToList();
                    foreach (AclRule rule in rules)
                    {
                        String userName     = rule.Scope.Value.Substring(0, rule.Scope.Value.IndexOf('@'));
                        Regex  studentEmail = new Regex("[a-z]+_[a-z]+");
                        if (doRemovals &&
                            ((gcal.StudentPermission.Equals("none") &&
                              studentEmail.IsMatch(userName) && !gcal.StudentCalendarSpecialPermissions.Select(p => p.Student.UserName).ToList().Contains(userName))
                             ||
                             inactiveUsers.Contains(rule.Scope.Value)
                            ))
                        {
                            try
                            {
                                service.Acl.Delete(gcal.CalendarId, rule.Id).Execute();
                                WebhostEventLog.GoogleLog.LogInformation("Removed {0} from {1}.", userName, gcal.CalendarName);
                            }
                            catch (Exception e)
                            {
                                WebhostEventLog.GoogleLog.LogError("Could not remove rule {0} for {3} on {4}.{1}{2}", rule.Scope.Value, Environment.NewLine, e.Message, userName, gcal.CalendarName);
                                State.log.WriteLine("Could not remove rule for {0}", rule.Scope.Value);
                                State.log.WriteLine(e.Message);
                            }
                        }

                        if (doRemovals && rule.Scope.Type.Equals("user") && !activeFacultyEmails.Contains(rule.Scope.Value) && !activeStudentEmails.Contains(rule.Scope.Value))
                        {
                            try
                            {
                                service.Acl.Delete(gcal.CalendarId, rule.Id).Execute();
                                WebhostEventLog.GoogleLog.LogInformation("Removed {0} from {1}.", userName, gcal.CalendarName);
                            }
                            catch (Exception e)
                            {
                                State.log.WriteLine("Could not remove rule for {0}", rule.Scope.Value);
                                WebhostEventLog.GoogleLog.LogError("Could not remove rule {0} for {3} on {4}.{1}{2}", rule.Scope.Value, Environment.NewLine, e.Message, userName, gcal.CalendarName);
                                State.log.WriteLine(e.Message);
                            }
                        }
                        else if (activeStudentEmails.Contains(rule.Scope.Value) || activeFacultyEmails.Contains(rule.Scope.Value))
                        {
                            WebhostEventLog.GoogleLog.LogInformation("{0} is already a member of {1}.", rule.Scope.Value, gcal.CalendarName);
                            alreadyMembers.Add(rule.Scope.Value);
                        }
                    }

                    foreach (String email in activeStudentEmails.Concat(activeFacultyEmails))
                    {
                        if (!alreadyMembers.Contains(email))
                        {
                            String userName = email.Substring(0, email.IndexOf('@'));
                            String role     = "reader";

                            if (gcal.Owners.Where(f => f.UserName.Equals(userName)).Count() > 0)
                            {
                                role = "owner";
                            }
                            else if (gcal.StudentCalendarSpecialPermissions.Where(csp => csp.Student.UserName.Equals(userName)).Count() > 0)
                            {
                                StudentCalendarSpecialPermission perm = gcal.StudentCalendarSpecialPermissions.Where(csp => csp.Student.UserName.Equals(userName)).Single();
                                role = perm.Role;
                            }
                            else if (email.Contains('_'))
                            {
                                role = gcal.StudentPermission;
                            }
                            else
                            {
                                role = gcal.FacultyPermission;
                            }

                            if (role.Equals("none"))
                            {
                                State.log.WriteLine("Do not need to create a 'none' rule for {0}", email);
                                continue;
                            }
                            AclRule rule = new AclRule()
                            {
                                Role  = role,
                                Scope = new AclRule.ScopeData()
                                {
                                    Type = "user", Value = email
                                }
                            };
                            WebhostEventLog.GoogleLog.LogInformation("Added {0} to access {1} with role {2}.", email, gcal.CalendarName, role);
                            service.Acl.Insert(rule, gcal.CalendarId).Execute();
                        }
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// Update the Calendar Subscriptions appropriate to a given User.
        /// </summary>
        /// <param name="id">pass either a Faculty.ID or Student.ID</param>
        /// <param name="isFaculty">Indicate if the id is Faculty or Student--will throw an exception if this is wrong</param>
        public void UpdateCalendarsForUser(int id, bool isFaculty)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                String email;
                if (isFaculty)
                {
                    email = String.Format("{0}@dublinschool.org", db.Faculties.Find(id).UserName);
                }
                else
                {
                    email = String.Format("{0}@dublinschool.org", db.Students.Find(id).UserName);
                }

                foreach (GoogleCalendar gcal in db.GoogleCalendars.ToList())
                {
                    String role = isFaculty ? gcal.FacultyPermission : gcal.StudentPermission;
                    if (gcal.Owners.Select(o => o.ID).ToList().Contains(id))
                    {
                        role = "owner";
                    }

                    List <AclRule> rules = service.Acl.List(gcal.CalendarId).Execute().Items.Where(r => r.Scope.Type.Equals("user")).ToList();
                    if (rules.Where(rule => rule.Scope.Value.Equals(email)).Count() > 0)
                    {
                        if (role.Equals("none"))
                        {
                            State.log.WriteLine("{0} has access to calendar they should not:  {1}.  Removing Access.", email, gcal.CalendarName);
                            Console.WriteLine("{0} has access to calendar they should not:  {1}.  Removing Access.", email, gcal.CalendarName);
                            WebhostEventLog.GoogleLog.LogWarning("{0} has access to calendar they should not:  {1}.  Removing Access.", email, gcal.CalendarName);
                            foreach (AclRule rule in rules.Where(rule => rule.Scope.Value.Equals(email)))
                            {
                                String response = service.Acl.Delete(gcal.CalendarId, rule.Id).Execute();
                                State.log.WriteLine("Deleting Calendar ACL rule for {0} in {1}.  Response:  {2}", email, gcal.CalendarName, response);
                                Console.WriteLine("Deleting Calendar ACL rule for {0} in {1}.  Response:  {2}", email, gcal.CalendarName, response);
                                WebhostEventLog.GoogleLog.LogInformation("Deleting Calendar ACL rule for {0} in {1}.  Response:  {2}", email, gcal.CalendarName, response);
                            }
                        }
                        State.log.WriteLine("{0} already has access to {1}", email, gcal.CalendarName);
                        Console.WriteLine("OK - {0} already has access to {1}", email, gcal.CalendarName);
                        WebhostEventLog.GoogleLog.LogInformation("{0} already has access to {1}", email, gcal.CalendarName);
                    }
                    else if (!role.Equals("none"))
                    {
                        AclRule rule = new AclRule()
                        {
                            Role  = role,
                            Scope = new AclRule.ScopeData()
                            {
                                Type = "user", Value = email
                            }
                        };

                        service.Acl.Insert(rule, gcal.CalendarId).Execute();
                        Console.WriteLine("Added {0} as {1} to {2}", email, role, gcal.CalendarName);
                        WebhostEventLog.GoogleLog.LogInformation("Added {0} as {1} to {2}", email, role, gcal.CalendarName);
                    }
                    else // role none.
                    {
                        Console.WriteLine("Skipping Calendar with no Access.");
                        WebhostEventLog.GoogleLog.LogInformation("skipping calendar with no access.");
                    }
                }
            }
        }
 public static string Name(this AclRule rule)
 {
     return(EnumerationExtensions.GetDescription(rule));
 }
Example #12
0
        public async Task <ApiResult <NewAbsenceResponse> > Absence([FromBody] AbsenceEvent absenceEvent)
        {
            try
            {
                var info = await _signInManager.GetExternalLoginInfoAsync();

                var userId = info.Principal.FindFirstValue(ClaimTypes.Email);
                var token2 = info.AuthenticationTokens.Where(u => u.Name == "access_token").FirstOrDefault().Value.ToString();

                Models.Data.AbsenceRequest absenceRequest = _mapper.Map <AbsenceEvent, Models.Data.AbsenceRequest>(absenceEvent);
                absenceRequest.CreatedDateTime = DateTime.Now;
                absenceRequest.StatusDateTime  = DateTime.Now;
                absenceRequest.UserId          = userId;

                var result = _context.AbsenceRequests.Add(absenceRequest);

                await _context.SaveChangesAsync();

                var groupId = _configuration["GroupId"];
                // Create access rule with associated scope
                AclRule rule = new AclRule();
                rule.Role  = "writer";
                rule.Scope = new AclRule.ScopeData()
                {
                    Type = "group", Value = groupId
                };

                var service = GetcalendarService(info);

                var temprule = await service.Acl.List(userId).ExecuteAsync();

                bool flag = false;
                foreach (var item in temprule.Items)
                {
                    if (item.Id.Contains(groupId))
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    // Insert new access rule
                    AclRule res = await service.Acl.Insert(rule, userId).ExecuteAsync();
                }

                return(new ApiResult <NewAbsenceResponse>()
                {
                    Result = new NewAbsenceResponse()
                    {
                        absenceRequestId = result.Entity.AbsenceRequestId
                    },
                    Message = Models.Api.ApiResult <NewAbsenceResponse> .SuccessMessage
                });
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                _logger.LogError(ex.Message, ex);
                return(new ApiResult <NewAbsenceResponse>()
                {
                    Message = Models.Api.ApiResult <NewAbsenceResponse> .ErrorMessage
                });
            }
        }
        /// <summary>
        /// Loads the demo ruleset.
        /// </summary>
        /// <returns>The populated demo ruleset.</returns>
        public Task <Acl> LoadRuleset()
        {
            _logger.Write("Loading default ruleset");

            // Create an ACL using the NSG rules we find
            Acl acl = new Acl();

            // Create some rules
            List <AclRule> rules = new List <AclRule>();

            // Allow VNET traffic
            AclRule vnetTraffic = new AclRule();

            vnetTraffic.Priority  = 100;
            vnetTraffic.Permit    = true;
            vnetTraffic.DstIpLow  = IPAddressUtilities.StringToUint("10.0.1.0");
            vnetTraffic.DstIpHigh = IPAddressUtilities.StringToUint("10.0.1.255");
            vnetTraffic.SrcIpLow  = IPAddressUtilities.StringToUint("10.0.1.0");
            vnetTraffic.SrcIpHigh = IPAddressUtilities.StringToUint("10.0.1.255");
            rules.Add(vnetTraffic);

            // Allow other VNET to talk to us ONLY on port 22 (ssh)
            AclRule otherVnetInbound = new AclRule();

            otherVnetInbound.Priority  = 200;
            otherVnetInbound.Permit    = true;
            otherVnetInbound.DstIpLow  = IPAddressUtilities.StringToUint("10.0.1.0");
            otherVnetInbound.DstIpHigh = IPAddressUtilities.StringToUint("10.0.1.255");
            otherVnetInbound.DstPort   = 22;
            otherVnetInbound.SrcIpLow  = IPAddressUtilities.StringToUint("192.168.1.10");
            otherVnetInbound.SrcIpHigh = IPAddressUtilities.StringToUint("192.168.1.10");
            rules.Add(otherVnetInbound);

            // Can we reach Google DNS? (OUTBOUND)
            AclRule googleTest = new AclRule();

            googleTest.Priority  = 300;
            googleTest.Permit    = true;
            googleTest.SrcIpLow  = IPAddressUtilities.StringToUint("10.0.1.0");
            googleTest.SrcIpHigh = IPAddressUtilities.StringToUint("10.0.1.255");
            googleTest.DstIpLow  = IPAddressUtilities.StringToUint("8.8.8.8");;
            googleTest.DstIpHigh = IPAddressUtilities.StringToUint("8.8.8.8");
            googleTest.DstPort   = 53;
            rules.Add(googleTest);

            // Can an Azure service reach us? (INBOUND)
            AclRule azureSvcTest = new AclRule();

            azureSvcTest.Priority  = 400;
            azureSvcTest.Permit    = true;
            azureSvcTest.SrcIpLow  = IPAddressUtilities.StringToUint("20.60.134.228");
            azureSvcTest.SrcIpHigh = IPAddressUtilities.StringToUint("20.60.134.228");
            azureSvcTest.DstIpLow  = IPAddressUtilities.StringToUint("10.0.1.4");;
            azureSvcTest.DstIpHigh = IPAddressUtilities.StringToUint("10.0.1.8");
            azureSvcTest.DstPort   = 443;
            rules.Add(azureSvcTest);

            // Block all inbound internet traffic
            AclRule internetInbound = new AclRule();

            internetInbound.Priority  = 65000;
            internetInbound.Permit    = false;
            internetInbound.DstIpLow  = IPAddressUtilities.StringToUint("10.0.1.0");
            internetInbound.DstIpHigh = IPAddressUtilities.StringToUint("10.0.1.255");
            internetInbound.SrcIpLow  = IPAddressUtilities.StringToUint("1.0.0.1");
            internetInbound.SrcIpHigh = IPAddressUtilities.StringToUint("223.255.255.255");
            rules.Add(internetInbound);

            acl.Rules = rules.OrderBy(r => r.Priority).ToArray();
            _logger.Write("Default ruleset loaded");
            return(Task.FromResult(acl));
        }
 public void PatchCalendarAclRule(string customerId, string calendarId, string ruleId, AclRule body, bool sendNotifications)
 {
     using (PoolItem <CalendarService> connection = this.calendarServicePool.Take(NullValueHandling.Ignore))
     {
         AclResource.PatchRequest request = new AclResource.PatchRequest(connection.Item, body, calendarId, ruleId);
         request.SendNotifications = sendNotifications;
         request.ExecuteWithRetryOnBackoff();
     }
 }