public void Execute(IJobExecutionContext jobContext) { try { using (var context = new DatabaseContext()) { int defaultInterval = 1440; //One day in minutes. int interval; SystemSetting intervalSettings; if (!context.SystemSettings.TryGet("BackupIntervalInMinutes", out intervalSettings)) interval = defaultInterval; if (!int.TryParse(intervalSettings.Value, out interval)) interval = defaultInterval; BackupRequest request; if (context.BackupRequests.TryGetNext(BackupSchedule.Automatic, out request)) { } else { //This is the first automatic backup. } } } catch (Exception ex) { LogHelper.Error(ex); ConsoleHelper.WriteLine(ConsoleColor.Magenta, ex.Message); } }
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(); } }
public ActionResult Login(LoginModel model) { if (ModelState.IsValid) { if (WebSecurity.Login(model.Email, model.Password, model.RememberMe)) { var userId = WebSecurity.CurrentUserId; using (var context = new DatabaseContext()) { var subscription = context.Subscriptions.Single(x => x.Id == WebSecurity.CurrentUserSubscriptionId); LogHelper.Info(string.Format(LogConstants.LoginSuccessful, model.Email)); return Redirect("~/Private/" + subscription.TenantName); } } else { LogHelper.Info(string.Format(LogConstants.LoginFailed, model.Email)); ModelState.AddModelError("email", "Invalid Email or Password"); ModelState.AddModelError("password", "Invalid Email or Password"); } } ViewBag.ShowLogin = true; ViewBag.Email = model.Email; return View("Home"); }
public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (!filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated) return; //Verify if the user is associated to a valid account. using (var context = new DatabaseContext()) { var userEmail = filterContext.RequestContext.HttpContext.User.Identity.Name; var user = context.Users.SingleOrDefault(x => x.Email.Equals(userEmail, StringComparison.InvariantCultureIgnoreCase)); if (user == null) { FormsAuthentication.SignOut(); HttpContext.Current.User = (IPrincipal)new GenericPrincipal(new GenericIdentity(string.Empty), new string[] { }); } } //Verify if the user is authorized. string[] claims; if (!string.IsNullOrEmpty(Claims)) { claims = Claims.Split(','); if (!WebSecurity.AccessControl.UserHasClaims(WebSecurity.CurrentUserId, claims)) throw new HttpException(403, "Unauthorized"); } }
private void SetDatabaseAsSingleUser() { using (var context = new DatabaseContext()) { context.Database.ExecuteSqlCommand("ALTER DATABASE TeamMashup SET SINGLE_USER WITH ROLLBACK IMMEDIATE"); } }
private void SetDatabaseAsMultiUser() { using (var context = new DatabaseContext()) { context.Database.ExecuteSqlCommand("ALTER DATABASE TeamMashup SET MULTI_USER"); } }
public override void CreateRole(string roleName) { using (var context = new DatabaseContext()) { var role = new Role(roleName); context.Roles.Add(role); } }
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); } }
public ActionResult Congratulations() { using (var context = new DatabaseContext()) { var subscription = context.Subscriptions.GetById(WebSecurity.CurrentUserSubscriptionId); ViewBag.TenantName = subscription.TenantName; return View(); } }
public void CreateDatabase() { Database.SetInitializer(new DatabaseContextInitializer()); //This is to force other active connections to close so the database can be droped/created SetDatabaseAsSingleUser(); using (var context = new DatabaseContext()) { context.Database.Initialize(true); } SetDatabaseAsMultiUser(); }
public void LeaveChat() { var onlineUsersDictionary = LeaveChat(WebSecurity.CurrentUserId); var ids = onlineUsersDictionary.Select(x => x.Key).ToList(); using (var context = new DatabaseContext()) { var onlineUsers = context.Users.FilterByIds(ids) .Select(x => new UserChatModel { Id = x.Id, Name = x.Name }).ToList(); Clients.All.refreshOnlineUsers(onlineUsers); } }
public void JoinChat() { var onlineUsersDictionary = JoinChat(WebSecurity.CurrentUserId, Context.ConnectionId); var ids = onlineUsersDictionary.Select(x => x.Key).ToList(); using (var context = new DatabaseContext()) { var onlineUsers = (from u in context.Users.FilterByIds(ids) select new UserChatModel { Id = u.Id, Name = u.Name }).ToList(); Clients.All.refreshOnlineUsers(onlineUsers); } }
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 ActionResult GetBackupRequestItems(int iDisplayStart, int iDisplayLength, string sEcho) { using (var context = new DatabaseContext()) { var query = context.BackupRequests.OrderByDescending(x => x.CreatedDate); var totalRecords = query.Count(); var page = query.Skip(iDisplayStart).Take(iDisplayLength).ToList(); var model = new DataTablePage { sEcho = sEcho, iTotalRecords = totalRecords, iTotalDisplayRecords = totalRecords }; var backupRequests = (from x in page select new BackupRequestModel { Path = x.Path, Schedule = x.Schedule, State = x.State, Type = x.Type, CreatedDate = x.CreatedDate }).ToList(); foreach (var backup in backupRequests) { var item = new Dictionary<string, string> { {"Path", backup.Path}, {"Schedule", backup.Schedule.ToString()}, {"State", backup.State.ToString()}, {"Type", backup.Type.ToString()}, {"CreatedDate", backup.CreatedDate.ToString()}, {"DT_RowId", "roleItem_" + backup.Id} }; model.aaData.Add(item); } return Json(model, JsonRequestBehavior.AllowGet); } }
public void Send(long callerId, long receiverId, string message) { var onlineUsers = GetOnlineUsers(); using (var context = new DatabaseContext()) { User caller; if (context.Users.TryGetById(callerId, out caller)) { if (onlineUsers.ContainsKey(receiverId)) { var connectionId = onlineUsers[receiverId]; Clients.Client(connectionId).showMessage(caller.Id, caller.FirstName, message); } } } }
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e) { using (var context = new DatabaseContext()) { UserProfile profile = null; User user; if (WebSecurity.TryGetCurrentUser(out user)) profile = context.UserProfiles.SingleOrDefault(x => x.UserId == user.Id); CultureInfo culture; if (profile == null) culture = new CultureInfo("en"); else culture = new CultureInfo(profile.Language.Code); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } }
public ActionResult CreateSubscription(long planId) { using (var context = new DatabaseContext()) { SubscriptionPlan plan; if (!context.SubscriptionPlans.TryGetById(planId, out plan)) throw new ApplicationException("plan with id = " + planId + " was not found!"); var countries = context.Countries.ToList(); var model = new CreateSubscriptionModel { PlanId = plan.Id, PlanName = plan.Name, Countries = new SelectList(countries, "Id", "Name") }; return View(model); } }
private static void Log(string message, LogEntryLevel level, long subscriptionId, IDatabaseContext context = null) { var log = new Log { SubscriptionId = subscriptionId, Message = message, Level = level }; if (context != null) { Log(log, context); } else { using (var newContext = new DatabaseContext()) { Log(log, newContext); } } }
public ActionResult RestorePassword(string recoveryLink) { if (string.IsNullOrWhiteSpace(recoveryLink)) return View("Error"); try { using (var context = new DatabaseContext()) { //recoveryLink format: http://teammashup.com/signin/restorepassword?token=2456C5CE-E935-434A-962B-DD9675A688B4 Guid token; if (!SecurityManager.TryGetToken(recoveryLink, out token)) { //TODO: Log Error. return View("Error"); } PasswordRecovery recovery; if (!context.PasswordRecoveries.TryGetByCode(token, out recovery)) { //TODO: Log Error. return View("Error"); } if (recovery.IsExpiredOrClaimed()) { //TODO: Log Error. return View("Error"); } var model = new RestorePasswordViewDto(); return View(model); } } catch (Exception) { //TODO: Log exception return View("Error"); } }
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"); } }
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; } } }
public override bool IsUserInRole(string userEmail, string roleName) { using (var context = new DatabaseContext()) { User user; if (context.Users.TryGetByEmail(userEmail, out user)) { return user.Roles.Any(x => x.Name.Equals(roleName, StringComparison.InvariantCultureIgnoreCase)); } else { //TODO: log user not found. return false; } } }
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"); } }
public static bool TryGetCurrentUser(out User user) { user = null; try { using (var context = new DatabaseContext()) { user = context.Users.GetById(CurrentUserId); return user != null; } } catch { return false; } }
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 } }
public override string[] GetAllRoles() { using (var context = new DatabaseContext()) { return context.Roles.Select(x => x.Name).ToArray(); } }
public override string[] GetRolesForUser(string userEmail) { using (var context = new DatabaseContext()) { User user; if (context.Users.TryGetByEmail(userEmail, out user)) { return user.Roles.Select(x => x.Name).ToArray(); } else { //TODO: log user not found. return new List<string>().ToArray(); } } }
public bool UserHasClaims(long userId, params string[] claims) { var userClaims = new List<string>(); using (var context = new DatabaseContext()) { User user; if (!context.Users.TryGetById(userId, out user)) return false; userClaims = (from r in user.Roles from c in r.Claims select c.Name).ToList(); } foreach (var claim in claims) { if (!userClaims.Contains(claim)) return false; } return true; }
public override bool RoleExists(string roleName) { using (var context = new DatabaseContext()) { return context.Roles.Any(x => x.Name.Equals(roleName, StringComparison.InvariantCultureIgnoreCase)); } }
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(); } }