Esempio n. 1
0
        public override void AddUsersToRoles(string[] userEmails, string[] roleNames)
        {
            using (var context = new DatabaseContext())
            {
                var roles = context.Roles.GetByNames(roleNames);

                foreach (var email in userEmails)
                {
                    User user;
                    if (context.Users.TryGetByEmail(email, out user))
                    {
                        var rolesToAdd = roles.Except(user.Roles);
                        foreach (var role in rolesToAdd)
                        {
                            user.Roles.Add(role);
                        }
                    }
                    else
                    {
                        //TODO: Log exception.
                    }
                }

                context.SaveChanges();
            }
        }
Esempio n. 2
0
        public void Execute(IJobExecutionContext jobContext)
        {
            try
            {
                var backupDirectory = Configuration.Backup.Directory.EndsWith(@"\") ?
                        Configuration.Backup.Directory.TrimEnd('\\') :
                        Configuration.Backup.Directory;

                if (!Directory.Exists(backupDirectory))
                    Directory.CreateDirectory(backupDirectory);

                BackupRequest request;
                using (var context = new DatabaseContext())
                {
                    context.BackupRequests.TryGetNext(out request);
                }

                if (request != null)
                {
                    var backupName = string.Format(@"{0}\{1}-{2}-{3}.bak", backupDirectory, Configuration.Backup.FileName, request.Schedule.ToString(), DateTime.UtcNow.ToString("yyyy-MM-dd-H-mm"));

                    ConsoleHelper.WriteLine(ConsoleColor.Green, string.Format("Backup Job: Starting backup '{0}'", backupName));

                    var backup = new Backup();
                    backup.Action = BackupActionType.Database;
                    backup.Database = Configuration.Backup.DatabaseName;
                    backup.Devices.AddDevice(backupName, DeviceType.File);
                    backup.BackupSetName = "TeamMashup Backup";
                    backup.BackupSetDescription = "TeamMashup Backup";
                    backup.ExpirationDate = DateTime.UtcNow.AddMonths(1);

                    var server = new Server(Configuration.Backup.ServerName);
                    backup.SqlBackup(server);

                    using (var context = new DatabaseContext())
                    {
                        var storedRequest = context.BackupRequests.GetById(request.Id);
                        storedRequest.State = BackupState.Completed;
                        storedRequest.Path = backupName;
                        context.SaveChanges();
                    }

                    Console.WriteLine("Backup Job: Successfuly finished backup '{0}'", backupName);
                }
                else
                {
                    Console.WriteLine("Backup Job: No backup requests found.");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                ConsoleHelper.WriteLine(ConsoleColor.Magenta, "Backup Job: " + ex.Message);
            }
        }
Esempio n. 3
0
        public ActionResult ConfirmRestore(RestorePasswordViewDto dto)
        {
            if (dto == null)
                return View("Error");

            try
            {
                using (var context = new DatabaseContext())
                {
                    PasswordRecovery recovery;
                    if (!context.PasswordRecoveries.TryGetByCode(dto.Token, out recovery))
                    {
                        //TODO: Log Error.
                        return View("Error");
                    }

                    if (recovery.IsExpiredOrClaimed())
                    {
                        //TODO: Log Error.
                        return View("Error");
                    }

                    var subscription = context.Subscriptions.Single(x => x.Id == recovery.SubscriptionId);
                    var user = context.Users.Single(x => x.Id == subscription.Subscriptor.Id);

                    recovery.Claimed = true;
                    user.Password = dto.NewPassword;

                    context.SaveChanges();
                }

                return RedirectToAction("SignIn");
            }
            catch (Exception)
            {
                //TODO: Log exception
                return View("Error");
            }
        }
Esempio n. 4
0
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            using (var context = new DatabaseContext())
            {
                Role role;
                if (context.Roles.TryGetByName(roleName, out role))
                {
                    if(role.Users.Any() && throwOnPopulatedRole)
                        throw new InvalidOperationException("Cannot delete a role that contains users");

                    context.Roles.Remove(role);
                    context.SaveChanges();

                    return true;
                }
                else
                {
                    //TODO: Log role not found.
                    return false;
                }
            }
        }
Esempio n. 5
0
        public ActionResult SendRestorePasswordEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
                return View("Error");

            try
            {
                using (var context = new DatabaseContext())
                {
                    User user;
                    if (!context.Users.TryGetByEmail(email, out user))
                    {
                        //TODO: Log Error.
                        return View("Error");
                    }

                    //TODO: enforce the requirement that the email address is unique across the whole platform.
                    //If a user has two subscriptions, then he has to use two differente emails.
                    TMSubscription subscription;
                    if (!context.Subscriptions.TryGetBySubscriptor(user, out subscription))
                    {
                        //The user that rquested password recovery exists on the database but he is not a subscriptor.

                        //TODO: Log Error.
                        return View("Error");
                    }

                    var token = SecurityManager.GenerateToken();

                    var recovery = new PasswordRecovery
                    {
                        Code = token.Code,
                        SubscriptionId = subscription.Id,
                        Expires = token.Expires
                    };

                    context.PasswordRecoveries.Add(recovery);
                    context.SaveChanges();

                    string mailBody = recovery.Code.ToString();
                    string from = string.Empty;
                    string to = string.Empty;

                    //The subscriptor will receive an email with a link including the security code to restore his account.
                    EmailHelper.Send(mailBody, to, from);

                    return View("PasswordRecoveryEmailSent");
                }
            }
            catch (Exception)
            {
                //TODO: Log exception
                return View("Error");
            }
        }
Esempio n. 6
0
        public void Execute(IJobExecutionContext jobContext)
        {
            try
            {
                const int MaxSubscriptions = 10; //TODO: move this into a configuration file.
                using (var context = new DatabaseContext())
                {
                    var subscriptions = context.Subscriptions.GetSubscriptionsToBill(MaxSubscriptions).ToList();

                    if (!subscriptions.Any())
                    {
                        Console.WriteLine("Billing Job: No Subscriptions to process");
                        return;
                    }

                    ConsoleHelper.WriteLine(ConsoleColor.Green, string.Format("Billing Job: Processing {0} subscriptions", subscriptions.Count));

                    foreach (var s in subscriptions)
                    {
                        string operationCode;
                        if (Payment.TryAuthenticate(Constants.SystemId, Constants.Password, out operationCode))
                        {
                            if (Payment.TryExecutePayment(s.CreditCardNumber, s.CreditCardExpireDate, s.SecurityCode, s.SubscriptionPlan.Price, operationCode))
                            {
                                ConsoleHelper.WriteLine(ConsoleColor.Green, string.Format("Billing Job: Payment successful for subscription {0}", s.CompanyName));

                                s.CurrentPeriodStartDate = DateTime.UtcNow;
                                s.CurrentPeriodEndDate = DateTime.UtcNow.AddMonths(1);
                                s.State = SubscriptionState.Active;

                                string body = string.Empty;

                                //TODO: Implement this in another way, an excepction in email should not cause the entire payment to fail.
                                //EmailHelper.Send(body, s.Subscriptor.Email, Constants.BillingEmailAddress);

                                s.HasPendingBills = true;

                                string token;
                                if (Billing.TryAuthenticate(Constants.SystemId, Constants.Password, out token))
                                {
                                    ConsoleHelper.WriteLine(ConsoleColor.Green, string.Format("Billing Job: Billed successfuly emited for subscription {0}", s.CompanyName));

                                    var exportType = s.Country.Name.Equals(Core.Constants.LocalCountryName, StringComparison.InvariantCultureIgnoreCase) ? null : "Services";

                                    var bill = new Bill
                                    {
                                        Date = DateTime.UtcNow,
                                        TributaryId = Constants.TributaryId,
                                        Subscription = s,
                                        CustomerAddress = s.CompanyAddress,
                                        CustomerName = s.Subscriptor.Name,
                                        CustomerCountry = s.Country,
                                        ExportType = exportType,
                                        Items = new List<BillItem>
                                        {
                                            new BillItem
                                            {
                                                Description = string.Format("Subscription to TeamMashup, plan {0}", s.SubscriptionPlan.Name),
                                                Price = s.SubscriptionPlan.Price,
                                                Quantity = 1
                                            }
                                        }
                                    };

                                    string billingCode;
                                    if (Billing.TryEmitBill(bill, out billingCode))
                                    {
                                        context.Bills.Add(bill);
                                        s.HasPendingBills = false;

                                        string body2 = string.Empty;

                                        //TODO: Implement this in another way, an excepction in email should not cause the entire payment to fail.
                                        //EmailHelper.Send(body2, s.Subscriptor.Email, Constants.BillingEmailAddress);
                                    }
                                    else //TryEmitBill
                                    {
                                        //TODO: Log error.
                                    }
                                }
                                else //TryAuthenticate
                                {
                                    //TODO: Log error.
                                }
                            }
                            else //TryExecutePayment
                            {
                                s.SetNextState();
                                //TODO: Log error.
                            }
                        }
                        else //TryAuthenticate
                        {
                        }
                    }

                    context.SaveChanges();
                }
            }
            catch (Exception)
            {
                //TODO: Log exeption
            }
        }
Esempio n. 7
0
        public override void RemoveUsersFromRoles(string[] userEmails, string[] roleNames)
        {
            using (var context = new DatabaseContext())
            {
                var roles = context.Roles.GetByNames(roleNames);

                foreach (var role in roles)
                {
                    foreach (var email in userEmails)
                    {
                        User user;
                        if (context.Users.TryGetByEmail(email, out user))
                        {
                            role.Users.Remove(user);
                        }
                    }
                }

                context.SaveChanges();
            }
        }
Esempio n. 8
0
        public ActionResult CreateSubscription(CreateSubscriptionModel model)
        {
            using (var context = new DatabaseContext())
            {
                string tenantName;
                if (!StringExtensions.TryParseTenantName(model.Email, out tenantName))
                    throw new InvalidOperationException("cannot parse tenant name from email");

                if (context.Subscriptions.Any(x => x.TenantName.Equals(tenantName, StringComparison.InvariantCultureIgnoreCase)))
                {
                    ModelState.AddModelError("email", string.Format("Company name: {0} is already registered", tenantName));
                    model.Countries = new SelectList(context.Countries.ToList(), "Id", "Name");
                    return View(model);
                }

                string emailDomain;
                if (!StringExtensions.TryParseEmailDomain(model.Email, out emailDomain))
                    throw new InvalidOperationException("cannot parse domain name from email");

                var subscription = new TMSubscription(model.CompanyName, tenantName, model.Email, emailDomain, model.PlanId, model.CountryId, model.CompanyAddress)
                {
                    BillingAddress = model.BillingAddress,
                    CreditCardNumber = model.CreditCardNumber,
                    CreditCardExpireDate = model.CreditCardExpireDate,
                    SecurityCode = model.CreditCardSecurityCode,
                };

                context.Subscriptions.Add(subscription);
                context.SaveChanges();

                MembershipCreateStatus status;
                var subscriptor = WebSecurity.Membership.CreateUser(subscription.Id, model.Name, model.Email, model.Password, out status);

                if (status != MembershipCreateStatus.Success)
                    throw new MembershipCreateUserException(status);

                subscription.SubscriptorId = subscriptor.Id;
                subscription.State = SubscriptionState.Active;
                context.SaveChanges();

                WebSecurity.Login(subscriptor.Email, model.Password);

                return this.RedirectToAction<RegisterController>(x => x.Congratulations());

            }
        }
        public WebMembershipUser CreateUser(long subscriptionId, string name, string email, string password, out MembershipCreateStatus status, long languageId = Constants.InvalidId)
        {
            var args = new ValidatePasswordEventArgs(email, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && IsEmailInUse(email))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            var membershipUser = GetUser(email);

            if (membershipUser == null)
            {
                try
                {
                    using (var context = new DatabaseContext())
                    {
                        Language language;
                        if(languageId == Constants.InvalidId)
                            language = context.Languages.GetByName("English");
                        else
                            language = context.Languages.GetById(languageId);

                        if(language == null)
                        {
                            language = new Language("en", "English");
                            context.Languages.Add(language);
                            context.SaveChanges();
                        }

                        var user = new User(name, email, SecurityManager.Hash(password), subscriptionId);

                        context.Users.Add(user);
                        context.SaveChanges();

                        var profile = new UserProfile(user.Id, language.Id);
                        context.UserProfiles.Add(profile);
                        context.SaveChanges();

                        status = MembershipCreateStatus.Success;

                        return GetUser(email);
                    }
                }
                catch
                {
                    status = MembershipCreateStatus.ProviderError;
                }
            }
            else
            {
                status = MembershipCreateStatus.DuplicateEmail;
            }

            return null;
        }
Esempio n. 10
0
        public override bool ChangePassword(string email, string oldPassword, string newPassword)
        {
            if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(oldPassword) || string.IsNullOrWhiteSpace(newPassword)) return false;

            if (oldPassword == newPassword) return false;

            try
            {
                using (var context = new DatabaseContext())
                {
                    var user = (from u in context.Users
                                where u.Email.Equals(email, StringComparison.InvariantCultureIgnoreCase) && !u.Deleted
                                select u).FirstOrDefault();

                    if (user == null)
                        return false;

                    if (string.IsNullOrWhiteSpace(user.Password))
                        return false;

                    user.Password = HashPassword(newPassword);

                    context.SaveChanges();

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }