Exemplo n.º 1
0
        public ActionResult Index(SubscriptionCreateModel model)
        {
            Subscription subscription = new Subscription
            {
                BlobStorageKey = model.BlobStorageKey,
                BlobStorageName = model.BlobStorageName,
                CertificateKey = model.CertificateKey,
                AzureSubscriptionId = model.AzureSubscriptionId
            };

            BinaryReader r = new BinaryReader(Request.Files[0].InputStream);
            subscription.Certificate = r.ReadBytes(Request.Files[0].ContentLength);

            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                context.Subscriptions.Add(subscription);
                context.SaveChanges();
            }

            return View();
        }
Exemplo n.º 2
0
        public void AssignCertificate(int subscriptionId, int identityId)
        {
            //create subscription if doesn't exist, otherwise update with new certificate
            CertificateSet certificateSet = CreateCertificate();

            //save the cer and pfx to local folder for debugging (si it me, or does that sound like a bad idea?)
            SaveCertificatesLocally(subscriptionId.ToString(), certificateSet);

            //TODO: finish implementation - send email

            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Subscription subscription = context.Subscriptions.Single(x => x.SubscriptionId == subscriptionId);
                subscription.CertificateKey = certificateSet.Password;
                subscription.Certificate = certificateSet.PfxRawData;
                context.SaveChanges();

                Identity identity = context.Identities.Single(x => x.IdentityId == identityId);

                Email.BuildAssignCertificateEmail(identity, subscription, certificateSet.CerRawData).Send();
            }
        }
Exemplo n.º 3
0
        public bool AddUserSubscriptionRole(string role, string identityId)
        {
            var success = false;
            try
            {
                if (string.IsNullOrWhiteSpace(role) || string.IsNullOrWhiteSpace(identityId))
                    return false;

                if (role == RoleTypes.Trainer || role == RoleTypes.Owner)
                {
                    using (var context = new ApplicationDbContext())
                    {
                        var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();
                        var identity = context.Identities.Where(x => x.IdentityId.ToString() == identityId).FirstOrDefault();

                        if (subscription != null && identity != null && !context.SubscriptionIdentityRoles.Any(x => x.Role == role &&
                                x.IdentityId == identity.IdentityId && x.SubscriptionId == subscription.SubscriptionId))
                        {
                            context.SubscriptionIdentityRoles.Add(new SubscriptionIdentityRole()
                            {
                                SubscriptionId = subscription.SubscriptionId,
                                IdentityId = identity.IdentityId,
                                Role = role
                            });

                            context.SaveChanges();
                            success = true;
                        }
                    }
                }
                return success;
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemplo n.º 4
0
        public void Start(StartSessionRequest request)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);
                //Session session = context.Sessions.Single(x => x.Version == version);

                //check if the session is canceled or the request is no longer valid
                if (session.Removed ||
                    (session.Version != request.Version.ToString()))
                {
                    _logger.InfoFormat("StartSessionRequest for Sessionid: {0} was ignored because Removed: {1} and Version: {2}",
                        request.SessionId, session.Removed, request.Version);
                    return;
                }

                _logger.InfoFormat("Spawning VMs for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);

                Subscription subscription = context.Subscriptions
                    .Single(x => x.SubscriptionId == session.SubscriptionId);

                IVMManagement vmManagement = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                    subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                    subscription.BlobStorageKey);

                //TODO: remove the hardcoding at some point in time
                string NorthEurope = "North Europe";

                VMConfigModel vmConfig = new VMConfigModel(session.Lab.ImageName, NorthEurope)
                {
                    VmSize = (VmSizeEnum)Enum.Parse(typeof(VmSizeEnum), session.VmSize)
                };

                var sessionUsers = session.SessionUsers.ToList();

                var vmUsers = new List<VMUserModel>();
                sessionUsers.ForEach(x =>
                {
                    //TODO: wrong logic.. not all sessions are based on templates
                    var templateVM = context.TemplateVMs.Where(y => y.IdentityId == x.IdentityId && y.SubscriptionId == subscription.SubscriptionId).FirstOrDefault();
                    if (templateVM != null)
                    {
                        vmUsers.Add(new VMUserModel
                        {
                            IdentityId = x.IdentityId,
                            Username = templateVM.VMAdminUser,
                            Password = templateVM.VMAdminPass
                        });
                    }
                });

                //figure out a URL friendly name for the vm names
                string vmNameBase = "tn" + session.SessionId + "vm";

                var assignedVMs = vmManagement.GenerateVMsForUsers(vmNameBase, vmConfig, vmUsers);

                foreach (var assignedVM in assignedVMs)
                {
                    VirtualMachine virtualMachine = new VirtualMachine
                    {
                        IdentityId = assignedVM.UserId,
                        VmAdminPass = assignedVM.Password,
                        VmAdminUser = assignedVM.UserName,
                        VmName = assignedVM.VmName,
                        VmRdpPort = assignedVM.VmRdpPort
                    };

                    session.VirtualMachines.Add(virtualMachine);
                    context.SaveChanges();
                }

                _logger.InfoFormat("Spawned VMs for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);

                _logger.InfoFormat("Sending emails for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);
                //well.. this is a hack
                //TODO: send the correct service name, that should be returned from the Azure Facade
                Email.BuildSessionEmails(session, vmNameBase).Send();
            }
        }
Exemplo n.º 5
0
        public void End(EndSessionRequest request)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                string version = request.Version.ToString();
                //Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);
                Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);

                //check if the request is no longer valid
                if (session.Version != request.Version.ToString())
                {
                    _logger.InfoFormat("EndSessionRequest for Sessionid: {0} was ignored because Removed: {1} and Version: {2}",
                        request.SessionId, session.Removed, request.Version);
                    return;
                }

                _logger.InfoFormat("Deleting VMs for SessionId: {0} ({1} - {2})",
                        session.SessionId, session.StartDate, session.EndDate);

                Subscription subscription = context.Subscriptions
                    .Single(x => x.SubscriptionId == session.SubscriptionId);

                IVMManagement vmManagement = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                    subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                    subscription.BlobStorageKey);

                //TODO: need to keep service name in the session
                string vmNameBase = "tn" + session.SessionId + "vm";
                vmManagement.DeleteService(vmNameBase);

                foreach (VirtualMachine vm in session.VirtualMachines.Where(x => !x.Deleted))
                {
                    vm.Deleted = true;
                }

                context.SaveChanges();

                _logger.InfoFormat("Deleted VMs for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);
            }
        }
Exemplo n.º 6
0
        public void Start(StartSessionRequest request)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);
                //Session session = context.Sessions.Single(x => x.Version == version);

                Identity trainer = session.TrainerId != 0 ?
                    context.Identities.Where(x => x.IdentityId == session.TrainerId).FirstOrDefault() :
                    context.Identities.Where(x => x.IdentityId ==
                        (context.SubscriptionIdentityRoles.Where(y => y.SubscriptionId == session.SubscriptionId && y.Role == "Owner").FirstOrDefault()).IdentityId).FirstOrDefault();

                //figure out a URL friendly name for the vm names
                string vmNameBase = "tn" + session.SessionId + "vm";

                try
                {
                    //check if the session is canceled or the request is no longer valid
                    if (session.Removed ||
                        (session.Version != request.Version.ToString()))
                    {
                        _logger.InfoFormat("StartSessionRequest for Sessionid: {0} was ignored because Removed: {1} and Version: {2}",
                            request.SessionId, session.Removed, request.Version);
                        return;
                    }

                    _logger.InfoFormat("Spawning VMs for SessionId: {0} ({1} - {2})", session.SessionId, session.StartDate, session.EndDate);

                    Subscription subscription = context.Subscriptions.Single(x => x.SubscriptionId == session.SubscriptionId);

                    IVMManagement vmManagement = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                        subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                        subscription.BlobStorageKey);

                    //TODO: remove the hardcoding at some point in time
                    string NorthEurope = "North Europe";

                    VMConfigModel vmConfig = new VMConfigModel(session.Lab.ImageName, NorthEurope)
                    {
                        VmSize = (VmSizeEnum)Enum.Parse(typeof(VmSizeEnum), session.VmSize)
                    };

                    var sessionUsers = session.SessionUsers.ToList();
                    var vmUsers = new List<VMUserModel>();
                    RandomProvider randomProvider = new RandomProvider();

                    sessionUsers.ForEach(x =>
                    {
                        vmUsers.Add(new VMUserModel
                        {
                            IdentityId = x.IdentityId,
                            Username = x.Identity != null ? string.Format("{0}.{1}", x.Identity.FirstName, x.Identity.LastName) : string.Empty,
                            Password = randomProvider.SecurePassword(8)
                        });
                    });

                    Email.BuildSessionStartVmsEmails(trainer.FirstName, trainer.Email, session, vmNameBase, vmUsers.Count).Send();

                    var assignedVMs = vmManagement.GenerateVMsForUsers(vmNameBase, vmConfig, vmUsers);

                    foreach (var assignedVM in assignedVMs)
                    {
                        VirtualMachine virtualMachine = new VirtualMachine
                        {
                            IdentityId = assignedVM.UserId,
                            VmAdminPass = assignedVM.Password,
                            VmAdminUser = assignedVM.UserName,
                            VmName = assignedVM.VmName,
                            VmRdpPort = assignedVM.VmRdpPort
                        };

                        session.VirtualMachines.Add(virtualMachine);
                        context.SaveChanges();
                    }

                    _logger.InfoFormat("Spawned VMs for SessionId: {0} ({1} - {2})", session.SessionId, session.StartDate, session.EndDate);

                    _logger.InfoFormat("Sending emails for SessionId: {0} ({1} - {2})", session.SessionId, session.StartDate, session.EndDate);
                    //well.. this is a hack
                    //TODO: send the correct service name, that should be returned from the Azure Facade

                    Email.BuildSessionEndVmsEmails(trainer.FirstName, trainer.Email, session.SessionName, vmNameBase, vmUsers.Count, assignedVMs.Count).Send();
                    Email.BuildSessionEmails(session, vmNameBase).Send();
                }
                catch(Exception ex)
                {
                    Email.BuildProblemStartingVmsEmails(trainer.FirstName, trainer.Email, session.SessionName, vmNameBase, ex.InnerException != null ? ex.InnerException.Message : "Error in starting the virtual machine(s).").Send();
                    throw ex;
                }
            }
        }
Exemplo n.º 7
0
        private bool CheckAndHandleUserInvites(int identityId, string email)
        {
            try
            {
                using (var context = new ApplicationDbContext())
                {
                    var invitations = context.Invitations.Where(x => x.Email == email && x.Processed == false);
                    var identity = context.Identities.Where(x => x.IdentityId == identityId).FirstOrDefault();

                    if (!invitations.Any() || identity == null)
                        return false;

                    foreach (var invitation in invitations.ToList())
                    {
                        var subscription = context.Subscriptions.Where(x => x.SubscriptionId == invitation.SubscriptionId).FirstOrDefault();
                        if (subscription != null)
                        {
                            if (!context.SubscriptionIdentityRoles.Any(x => x.IdentityId == identityId &&
                                x.Subscription.SubscriptionId == invitation.SubscriptionId && x.Role == RoleTypes.Member))
                            {
                                context.SubscriptionIdentityRoles.Add(new SubscriptionIdentityRole()
                                {
                                    Subscription = subscription,
                                    IdentityId = identity.IdentityId,
                                    Role = RoleTypes.Member
                                });
                            }

                            invitation.Processed = true;
                            context.Entry(invitation).State = EntityState.Modified;
                            context.SaveChanges();
                        }
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemplo n.º 8
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }

                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        ApplicationDbContext context = new ApplicationDbContext();
                        Core.Repository.Identity identity = new Identity
                        {
                            IdentityProvider = "",
                            NameIdentifier = user.Id,
                            Email = model.Email,
                            DisplayName = "",
                            FirstName = model.FirstName,
                            LastName = model.LastName
                        };
                        context.Identities.Add(identity);
                        context.SaveChanges();

                        Email.BuildSignUpEmail(identity).Send();

                        CheckAndHandleUserInvites(identity.IdentityId, model.Email);

                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Exemplo n.º 9
0
        private void SaveInvites(IList<string> emailList)
        {
            using (var context = new ApplicationDbContext())
            {
                var identity = context.Identities.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId).FirstOrDefault();
                var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();

                if (identity != null && subscription != null)
                {
                    foreach (var email in emailList)
                    {
                        if (!context.Invitations.Where(x => x.Identity.IdentityId == identity.IdentityId &&
                             x.Subscription.SubscriptionId == subscription.SubscriptionId && x.Email == email).Any())
                        {
                            context.Invitations.Add(new Invitation()
                            {
                                Email = email,
                                Identity = identity,
                                Subscription = subscription,
                                IdentityId = identity.IdentityId,
                                SubscriptionId = subscription.SubscriptionId,
                                Processed = false
                            });
                            context.SaveChanges();
                        }
                    }
                }
            }
        }
Exemplo n.º 10
0
        public bool RemoveUserFromSubscription(string identityId)
        {
            var success = false;
            try
            {
                if (string.IsNullOrWhiteSpace(identityId))
                    return false;

                using (var context = new ApplicationDbContext())
                {
                    var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();
                    var identity = context.Identities.Where(x => x.IdentityId.ToString() == identityId).FirstOrDefault();

                    if (subscription == null || identity == null)
                        return false;

                    var subscriptionRoles = context.SubscriptionIdentityRoles.Where(x => x.IdentityId == identity.IdentityId &&
                        x.SubscriptionId == subscription.SubscriptionId);

                    foreach (var subscriptionRole in subscriptionRoles.ToList())
                    {
                        context.SubscriptionIdentityRoles.Remove(context.SubscriptionIdentityRoles.Where(x =>
                            x.SubscriptionIdentityRoleId == subscriptionRole.SubscriptionIdentityRoleId).FirstOrDefault());
                        context.SaveChanges();
                        success = true;
                    }
                }
                return success;
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemplo n.º 11
0
 private void CreateSubscriptionIdentityMap(Subscription subscription, int identityId)
 {
     using (ApplicationDbContext context = new ApplicationDbContext())
     {
         CreateSubscriptionIdentityMap(subscription, context, RoleTypes.Member);
         CreateSubscriptionIdentityMap(subscription, context, RoleTypes.Owner);
         CreateSubscriptionIdentityMap(subscription, context, RoleTypes.Trainer);
         context.SaveChanges();
     }
 }
Exemplo n.º 12
0
		public async Task<string> ReadyForCapture(string templateVmKey)
		{
			_logger.Info("Entering AzureManagement.ReadyForCapture");

			string result = "OK";

			try
			{
				using (ApplicationDbContext repository = new ApplicationDbContext())
				{
					Guid key = new Guid(templateVmKey);
					TemplateVM templateVM = repository.TemplateVMs.Single(x => x.Key == key);
					templateVM.State = (int)TemplateVMStatusEnum.ReadyToCapture;
					templateVM.StateChangedTimestamp = DateTimeOffset.Now;
					repository.SaveChanges();

					//schedule the check and capture in 5 minutes
					await Messaging.SendAsync(new VMReadyForCaptureRequest 
						{ TemplateVMId = templateVM.TemplateVMId },
						DateTime.UtcNow.AddMinutes(5));
				}
			}
			catch (Exception ex)
			{
				_logger.Fatal("Exception when marking VM for capture.", ex);
				result = "Error";
			}

			_logger.Info("Exiting AzureManagement.ReadyForCapture");

			return result;
		}