Ejemplo n.º 1
0
        /// <summary>
        /// Filter what rows are included in the list.
        /// </summary>
        /// <param name="row">The row to examine.</param>
        /// <returns>False if the organization isn't under the parent organization; true otherwise.</returns>
        protected override bool Filter(DataRow row)
        {
            TenantRow tenantRow = null;
            Boolean   include   = false;

            if (row is TenantRow)
            {
                tenantRow = row as TenantRow;
            }
            else
            {
                throw new RowNotHandledException("row isn't the right kind of row");
            }

            if (this.organization == null)
            {
                include = true;
            }
            else
            {
                foreach (TenantTreeRow tenantTreeRow in tenantRow.GetTenantTreeRowsByFK_Tenant_TenantTree_ChildId())
                {
                    if (this.organization == null || tenantTreeRow.ParentId == this.organization)
                    {
                        include = true;
                    }
                }
            }

            return(include);
        }
        public Result <ServiceResponse> EditTenant(EditTenantRequest request)
        {
            return(this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                var perminsion = Dependency.Resolve <IPermissionService>();

                var grantor = new TransientGrantingPermissionService(perminsion);
                grantor.GrantAll();
                try
                {
                    var user = (UserDefinition)Serenity.Authorization.UserDefinition;

                    var tenant = new TenantRow();
                    tenant.TenantId = user.TenantId;

                    if (request.TenantName.IsEmptyOrNull())
                    {
                        throw new ArgumentNullException("name");
                    }

                    tenant.TenantName = request.TenantName;
                    tenant.TenantWebSite = request.TenantWebSite;

                    if (!request.TenantImage.IsNullOrEmpty())
                    {
                        tenant.TenantImage = request.TenantImage;
                    }

                    tenant.OverrideUsersEmailSignature = request.OverrideUsersEmailSignature;
                    tenant.TenantEmailSignature = request.TenantEmailSignature;

                    var saveRequest = new SaveRequest <TenantRow>()
                    {
                        Entity = tenant
                    };

                    var uow = new UnitOfWork(connection);


                    new TenantRepository().Update(uow, saveRequest);
                    uow.Commit();

                    UserRetrieveService.RemoveCachedUser(user.UserId, user.Username);
                }
                finally
                {
                    grantor.UndoGrant();
                }


                return new ServiceResponse();
            }));
        }
Ejemplo n.º 3
0
        public Result <ServiceResponse> SignUp(SignUpRequest request)
        {
            return(this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                Check.NotNullOrWhiteSpace(request.Email, "email");
                Check.NotNullOrEmpty(request.Password, "password");
                UserRepository.ValidatePassword(request.Email, request.Password, true);
                Check.NotNullOrWhiteSpace(request.DisplayName, "displayName");

                if (connection.Exists <UserRow>(
                        UserRow.Fields.Username == request.Email |
                        UserRow.Fields.Email == request.Email))
                {
                    throw new ValidationError("EmailInUse", Texts.Validation.EmailInUse);
                }


                using (var uow = new UnitOfWork(connection))
                {
                    string salt = null;
                    var hash = UserRepository.GenerateHash(request.Password, ref salt);
                    var displayName = request.DisplayName.TrimToEmpty();
                    var email = request.Email;
                    var username = request.Email;

                    var fld = UserRow.Fields;
                    var userModel = new UserRow
                    {
                        Username = username,
                        Source = "sign",
                        DisplayName = displayName,
                        Email = email,
                        PasswordHash = hash,
                        PasswordSalt = salt,
                        IsActive = 0,
                        InsertDate = DateTime.Now,
                        InsertUserId = 1,
                        LastDirectoryUpdate = DateTime.Now
                    };
                    var userId = (int)connection.InsertAndGetID(userModel);
                    userModel.UserId = userId;

                    var tenant = new TenantRow
                    {
                        TenantName = request.TenantName,
                        CurrencyId = 1,
                        SubscriptionRequired = true
                    };
                    tenant.TenantId = Int32.Parse(connection.InsertAndGetID(tenant).ToString());

                    var offer = connection.ById <OffersRow>(request.OfferId);

                    //Insert First subscription directly after you know the TenantId
                    var subscriptionId = (int)connection.InsertAndGetID(new SubscriptionsRow
                    {
                        // TODO Get local string
                        Name = string.Format("{0} - {1}", offer.Name, request.TenantName),
                        OfferId = offer.OfferId,
                        TenantId = Int32.Parse(tenant.TenantId.ToString()),
                        SubscriptionEndDate = DateTime.Now.AddMonths(12),
                        Enabled = 1,
                        IsActive = 1,
                        InsertUserId = userId,
                        InsertDate = DateTime.Now,
                        ActivatedOn = DateTime.Now,
                        FreeDaysFromOffer = offer.MaximumSubscriptionTime ?? 0
                    });
                    tenant.SubscriptionId = subscriptionId;

                    //Update Tenant SubscriptionId .. Is it Needet?
                    connection.UpdateById(tenant, ExpectedRows.One);

                    var userRoleId = (int)connection.InsertAndGetID(new UserRoleRow
                    {
                        UserId = userId,
                        RoleId = offer.RoleId
                    });


                    userModel.TenantId = tenant.TenantId ?? 2;

                    connection.UpdateById(userModel, ExpectedRows.One);

                    byte[] bytes;
                    using (var ms = new MemoryStream())
                        using (var bw = new BinaryWriter(ms))
                        {
                            bw.Write(DateTime.UtcNow.AddHours(3).ToBinary());
                            bw.Write(userId);
                            bw.Flush();
                            bytes = ms.ToArray();
                        }

                    var token = Convert.ToBase64String(HttpContext.RequestServices
                                                       .GetDataProtector("Activate").Protect(bytes));

                    var externalUrl = Config.Get <EnvironmentSettings>().SiteExternalUrl ??
                                      Request.GetBaseUri().ToString();

                    var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t=");
                    activateLink = activateLink + Uri.EscapeDataString(token);

                    var emailModel = new ActivateEmailModel();
                    emailModel.Username = username;
                    emailModel.DisplayName = displayName;
                    emailModel.ActivateLink = activateLink;

                    var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString();
                    var emailBody = TemplateHelper.RenderViewToString(HttpContext.RequestServices,
                                                                      MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel);

                    Common.EmailHelper.Send(emailSubject, emailBody, email);

                    uow.Commit();
                    UserRetrieveService.RemoveCachedUser(userId, username);

                    return new ServiceResponse();
                }
            }));
        }
        /// <summary>
        /// Add default permissions to an object.
        /// </summary>
        /// <param name="dataModel">The data model.</param>
        /// <param name="transaction">The current transaction.</param>
        /// <param name="organizationId">The TenentId of the organization where the scan should start (eg. where the entity is).</param>
        /// <param name="entityId">The entityId of the object to modify.</param>
        ///<param name="tenantId">The root TenantId for which all the records will be created for</param>
        public static void AddGroupPermissions(DataModel dataModel, DataModelTransaction transaction, Guid organizationId, Guid entityId, Guid tenantId)
        {
            TenantRow organizationRow = DataModel.Tenant.TenantKey.Find(organizationId);

            RightsHolderRow[] rightsHolders;
            TenantTreeRow[]   tenantTreeRows;

            if (organizationRow == null)
            {
                throw new FaultException <RecordNotFoundFault>(
                          new RecordNotFoundFault("Organization", new object[] { organizationId }),
                          "The organization has been deleted.");
            }

            organizationRow.AcquireReaderLock(transaction);
            tenantTreeRows = organizationRow.GetTenantTreeRowsByFK_Tenant_TenantTree_ChildId();
            rightsHolders  = organizationRow.GetRightsHolderRows();
            organizationRow.ReleaseLock(transaction.TransactionId);

            foreach (RightsHolderRow rightsHolderRow in rightsHolders)
            {
                GroupRow[] groupRows;

                rightsHolderRow.AcquireReaderLock(transaction);
                groupRows = rightsHolderRow.GetGroupRows();
                rightsHolderRow.ReleaseLock(transaction.TransactionId);

                if (groupRows.Length > 0)
                {
                    Guid         groupId;
                    GroupRow     group = groupRows[0];
                    GroupTypeRow groupType;

                    group.AcquireReaderLock(transaction);
                    groupId   = group.GroupId;
                    groupType = group.GroupTypeRow;
                    group.ReleaseReaderLock(transaction.TransactionId);

                    groupType.AcquireReaderLock(transaction);
                    if (groupType.GroupTypeCode == GroupType.ExchangeAdmin ||
                        groupType.GroupTypeCode == GroupType.FluidTradeAdmin ||
                        groupType.GroupTypeCode == GroupType.SiteAdmin)
                    {
                        dataModel.CreateAccessControl(
                            Guid.NewGuid(),
                            AccessRightMap.FromCode(AccessRight.FullControl),
                            entityId,
                            groupId,
                            tenantId);
                    }
                }
            }

            foreach (TenantTreeRow tenantTreeRow in tenantTreeRows)
            {
                Guid parentId;

                tenantTreeRow.AcquireReaderLock(transaction);
                parentId = tenantTreeRow.ParentId;
                tenantTreeRow.ReleaseLock(transaction.TransactionId);

                AddGroupPermissions(dataModel, transaction, parentId, entityId, tenantId);
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Create a new Organization based on an entity row.
 /// </summary>
 /// <param name="tenantRow">An entity row from the DataModel.</param>
 public Tenant(TenantRow tenantRow) : base()
 {
     this.tenantId = tenantRow.TenantId;
     this.name     = tenantRow.Name;
 }