aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs
blob: b718887af2cac5b316467e6c281909c6aced38e5 (plain)
1
2
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Scripting.IDE
{
    public interface ISolution :ISolutionItem
    {
        ObservableCollection<IProject> Projects { get; }
    }
}
25 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Web.Http;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.Entities;
using Tango.BL.Enumerations;
using Tango.Core.Cryptography;
using Tango.MachineService.Models;
using Tango.MachineStudio.Common.Authentication;
using System.Data.Entity;
using Tango.MachineStudio.Common.Web;
using Tango.Web.Controllers;
using Tango.Web.Helpers;
using Tango.Web.Storage;
using Tango.Web.Security;
using Tango.Web.ActiveDirectory;
using Tango.MachineService.Filters;
using Tango.MachineService.Security;

namespace Tango.MachineService.Controllers
{
    public class MachineStudioController : TangoController<MachineStudioController.TokenObject>
    {
        private static List<MachineStudioPendingUpload> _pendingUploads;
        private ActiveDirectoryManager _ad_manager;

        public class TokenObject
        {
            public String UserGuid { get; set; }
        }

        public class RefreshTokenObject
        {
            public String Email { get; set; }
            public String Password { get; set; }
        }

        #region Constructors

        /// <summary>
        /// Initializes the <see cref="MachineStudioController"/> class.
        /// </summary>
        static MachineStudioController()
        {
            _pendingUploads = new List<MachineStudioPendingUpload>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MachineStudioController"/> class.
        /// </summary>
        public MachineStudioController() : base()
        {
            _ad_manager = new ActiveDirectoryManager();
        }

        #endregion

        #region Actions

        /// <summary>
        /// Checks for updates.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        [HttpPost]
        [JwtTokenFilter]
        public CheckForUpdatesResponse CheckForUpdates(CheckForUpdatesRequest request)
        {
            LogManager.Log("Request received...");

            var userID = RequestToken.Object.UserGuid;

            CheckForUpdatesResponse response = new CheckForUpdatesResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                var versions = db.MachineStudioVersions.ToList();

                MachineStudioVersion latestVersion = null;

                latestVersion = versions.OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();

                Version currentVersion = Version.Parse(request.Version);

                String comments = String.Join(Environment.NewLine, versions.OrderBy(x => Version.Parse(x.Version)).Where(x => Version.Parse(x.Version) > currentVersion).Select(x => x.Comments));

                if (latestVersion != null && Version.Parse(latestVersion.Version) > currentVersion)
                {
                    var manager = new BlobStorageManager();
                    var container = manager.GetContainer(MachineServiceConfig.MACHINE_STUDIO_VERSIONS_CONTAINER);
                    var blob = container.GetBlockBlobReference(latestVersion.BlobName);

                    response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60));

                    response.IsUpdateAvailable = true;
                    response.Version = latestVersion.Version;
                    response.Comments = latestVersion.Comments;
                }
            }

            return response;
        }

        /// <summary>
        /// Downloads the latest version.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        [HttpPost]
        [JwtTokenFilter]
        public DownloadLatestVersionResponse DownloadLatestVersion(DownloadLatestVersionRequest request)
        {
            LogManager.Log("Request received...");

            DownloadLatestVersionResponse response = new DownloadLatestVersionResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                var versions = db.MachineStudioVersions.ToList();

                MachineStudioVersion latestVersion = versions.OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();

                if (latestVersion != null)
                {
                    var manager = new BlobStorageManager();
                    var container = manager.GetContainer(MachineServiceConfig.MACHINE_STUDIO_VERSIONS_CONTAINER);
                    var blob = container.GetBlockBlobReference(latestVersion.BlobName);

                    response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60));
                    response.Version = latestVersion.Version;
                }
            }

            return response;
        }

        /// <summary>
        /// Uploads a version.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">New version must be greater than latest version.</exception>
        /// <exception cref="AuthenticationException">Invalid user credentials.</exception>
        [HttpPost]
        [JwtTokenFilter]
        public UploadVersionResponse UploadVersion(UploadVersionRequest request)
        {
            UploadVersionResponse response = new UploadVersionResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                String userID = RequestToken.Object.UserGuid;

                var user = new UserBuilder(db).Set(userID).WithRolesAndPermissions().Build();

                if (user != null && user.HasPermission(Permissions.PublishMachineStudioVersions))
                {
                    var latestVersion = db.MachineStudioVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
                    Version local_version = Version.Parse(request.Version);

                    if (latestVersion == null || local_version > Version.Parse(latestVersion.Version))
                    {
                        String newVersionFileName = "Machine Studio v" + local_version.ToString() + ".zip";

                        var manager = new BlobStorageManager();
                        var container = manager.GetContainer(MachineServiceConfig.MACHINE_STUDIO_VERSIONS_CONTAINER);
                        var blob = container.CreateEmptyBlob(newVersionFileName);

                        response.Token = Guid.NewGuid().ToString();
                        response.BlobAddress = blob.GenerateWriteSignature(TimeSpan.FromMinutes(30));

                        MachineStudioPendingUpload pending_upload = new MachineStudioPendingUpload()
                        {
                            UserGuid = user.Guid,
                            Comments = request.Comments,
                            Token = response.Token,
                            Version = request.Version,
                            BlobName = blob.Name,
                        };

                        if (request.WithInstaller)
                        {
                            String installerVersionFileName = "Machine Studio v" + local_version.ToString() + ".exe";
                            var installerBlob = container.CreateEmptyBlob(installerVersionFileName);
                            response.InstallerBlobAddress = installerBlob.GenerateWriteSignature(TimeSpan.FromMinutes(30));
                            pending_upload.InstallerBlobName = installerBlob.Name;
                        }

                        _pendingUploads.Add(pending_upload);
                    }
                    else
                    {
                        throw new ArgumentException("New version must be greater than latest version.");
                    }
                }
                else
                {
                    throw new AuthenticationException("Invalid user credentials.");
                }
            }

            return response;
        }

        /// <summary>
        /// Notifies about a version upload completion.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">Invalid Token.</exception>
        [HttpPost]
        [JwtTokenFilter]
        public UploadCompletedResponse NotifyVersionUploadCompleted(UploadCompletedRequest request)
        {
            MachineStudioPendingUpload upload = _pendingUploads.FirstOrDefault(x => x.Token == request.Token);

            if (upload != null)
            {
                _pendingUploads.RemoveAll(x => x.Token == upload.Token);

                using (ObservablesContext db = ObservablesContextHelper.CreateContext())
                {
                    db.MachineStudioVersions.Add(new MachineStudioVersion()
                    {
                        Comments = upload.Comments,
                        BlobName = upload.BlobName,
                        InstallerBlobName = upload.InstallerBlobName,
                        UserGuid = upload.UserGuid,
                        Version = upload.Version,
                    });

                    db.SaveChanges();
                }

                return new UploadCompletedResponse();
            }
            else
            {
                throw new ArgumentException("Invalid Token.");
            }
        }

        /// <summary>
        /// Gets the latest version.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        [HttpPost]
        public LatestVersionResponse GetLatestVersion(LatestVersionRequest request)
        {
            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                var version = db.MachineStudioVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
                return new LatestVersionResponse() { Version = version != null ? version.Version : "0.0.0.0" };
            }
        }

        /// <summary>
        /// Login to the service.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        /// <exception cref="AuthenticationException"></exception>
        [HttpPost]
        public LoginResponse Login(LoginRequest request)
        {
            var authResult = _ad_manager.ValidateUserCredentials(request.Email, request.Password);

            if (!_ad_manager.CanUserAccessCurrentEnvironment(request.Email))
            {
                throw new AuthenticationException($"You do not have permissions to access the {MachineServiceConfig.DEPLOYMENT_SLOT.ToDescription()} environment.");
            }

            Version client_version;

            if (!Version.TryParse(request.Version, out client_version))
            {
                client_version = new Version("1.0.0.0");
            }

            bool versionChangeRequired = false;
            String requiredVersion = null;

            User user = null;

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                db.Roles.ToList();
                db.Permissions.ToList();
                db.UsersRoles.ToList();
                db.RolesPermissions.ToList();

                user = new UserBuilder(db).Set(x => x.Email.ToLower() == request.Email.ToLower()).WithRolesAndPermissions().WithDeleted().Build();

                IHashGenerator g = new BasicHashGenerator();

                if (user == null)
                {
                    //Than add the user !!
                    User new_user = new User();
                    new_user.Email = request.Email;
                    new_user.Password = g.Encrypt(request.Password);
                    new_user.Organization = db.Organizations.Include(x => x.Address).Single(x => x.Name == "Twine");
                    new_user.Address = new_user.Organization.Address.Clone();
                    new_user.Contact = new Contact()
                    {
                        FirstName = authResult.UserInfo.GivenName,
                        LastName = authResult.UserInfo.FamilyName,
                        FullName = authResult.UserInfo.GivenName + " " + authResult.UserInfo.FamilyName,
                        Email = request.Email,
                    };

                    db.UsersRoles.Add(new UsersRole()
                    {
                        User = new_user,
                        Role = db.Roles.Single(x => (Roles)x.Code == Roles.User),
                    });

                    db.UsersRoles.Add(new UsersRole()
                    {
                        User = new_user,
                        Role = db.Roles.Single(x => (Roles)x.Code == Roles.MachineStudioUser),
                    });

                    new_user.LastLogin = DateTime.UtcNow;
                    db.Users.Add(new_user);
                }
                else
                {
                    if (user.Deleted)
                    {
                        throw new AuthenticationException("Your account has been disabled. Please contact your administrator.");
                    }

                    user.LastLogin = DateTime.UtcNow;
                    user.Password = g.Encrypt(request.Password);
                }

                db.SaveChanges();

                if (MachineServiceConfig.ENFORCE_MACHINE_STUDIO_VERSION)
                {
                    var latest_version = db.MachineStudioVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();

                    if (latest_version != null && Version.Parse(latest_version.Version) != client_version)
                    {
                        versionChangeRequired = true;
                        requiredVersion = latest_version.Version;
                    }
                }
            }

            return new LoginResponse()
            {
                DataSource = new Core.DataSource()
                {
                    Address = MachineServiceConfig.DB_ADDRESS,
                    Catalog = MachineServiceConfig.DB_CATALOG,
                    Type = Core.DataSourceType.Azure,
                    IntegratedSecurity = false,
                    UserName = request.Email,
                    Password = request.Password,
                },

                AccessToken = WebToken<TokenObject>.CreateNew(MachineServiceConfig.JWT_TOKEN_SECRET, new TokenObject()
                {
                    UserGuid = user.Guid,
                }, DateTime.UtcNow.AddDays(1)).AccessToken,
                VersionChangeRequired = versionChangeRequired,
                RequiredVersion = requiredVersion,
            };
        }

        #endregion
    }
}