aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/Notifications/MessageBoxWindow.xaml
blob: a89f8eeca7364c4fd355cb890fc8b01dbc92971e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<Window x:Class="Tango.MachineStudio.UI.Notifications.MessageBoxWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Tango.MachineStudio.UI.Notifications"
        xmlns:mahapps="http://metro.mahapps.com/winfx/xaml/controls"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:converters="clr-namespace:Tango.SharedUI.Converters;assembly=Tango.SharedUI"
        mc:Ignorable="d"
        Title="Machine Studio" MinHeight="220" MaxHeight="600" SizeToContent="Height" Width="570" Opacity="0" AllowsTransparency="True" WindowStyle="None" WindowStartupLocation="CenterOwner" Background="Transparent">

    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"></BooleanToVisibilityConverter>
    </Window.Resources>

    <Grid>
        <Border Background="White" CornerRadius="10" Padding="10" Margin="20">
            <Border.Effect>
                <DropShadowEffect ShadowDepth="0" BlurRadius="10"></DropShadowEffect>
            </Border.Effect>
            <DockPanel LastChildFill="True">
                <StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right" DockPanel.Dock="Bottom">
                    <Button Style="{StaticResource MaterialDesignFlatButton}" IsDefault="True" Margin="0 8 8 0" Click="OnOKClicked">
                        ACCEPT
                    </Button>
                    <Button Visibility="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=HasCancel,Converter={StaticResource BooleanToVisibilityConverter}}" Style="{StaticResource MaterialDesignFlatButton}" IsCancel="False" Margin="0 8 8 0" Click="OnCancelClicked">
                        CANCEL
                    </Button>
                </StackPanel>
                <Grid>
                    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="0 30 0 0">
                        <materialDesign:PackIcon Kind="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=IconKind}" VerticalAlignment="Top" Width="50" Height="50" Foreground="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=IconColor}" />
                        <TextBlock Padding="0 10 0 0" TextWrapping="Wrap" Margin="10 0 0 0" VerticalAlignment="Top" FontSize="14" Text="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=Message}" Width="400"></TextBlock>
                    </StackPanel>
                </Grid>
            </DockPanel>
        </Border>
    </Grid>
</Window>
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.Entities;
using Tango.Core;
using Tango.Core.Cryptography;
using Tango.Core.DB;
using Tango.FSE.Web.Messages;
using Tango.MachineService.Filters;
using Tango.Web.Controllers;
using Tango.Web.Helpers;
using Tango.Web.Security;
using Tango.Web.SMO;
using Tango.Web.SQLServer;
using Tango.Web.Storage;
using System.Data.Entity;
using static Tango.MachineService.Controllers.FSEController;

namespace Tango.MachineService.Controllers
{
    public class FSEController : TangoController<TokenObject>
    {
        public class TokenObject
        {
            public String UserGuid { get; set; }
        }

        public class PasswordReset
        {
            public String ID { get; set; }
            public String UserGuid { get; set; }
            public String FullName { get; set; }
        }

        public static List<PasswordReset> PendingPasswordResets { get; set; }

        static FSEController()
        {
            PendingPasswordResets = new List<PasswordReset>();
        }

        [HttpPost]
        public LoginResponse Login(LoginRequest request)
        {
            User user = null;
            DataSource dataSource = null;
            IHashGenerator hash = new BasicHashGenerator();

            Version client_version;

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

            var password = hash.Encrypt(request.Password);

            using (var db = ObservablesContextHelper.CreateContext())
            {
                user = new UserBuilder(db).Set(x => x.Email.ToLower() == request.Email.ToLower() && x.Password == password).WithRolesAndPermissions().WithDeleted().Build();

                if (user == null)
                {
                    throw new AuthenticationException("Invalid email or password.");
                }

                if (user.Deleted)
                {
                    throw new AuthenticationException("Your account has been disabled. Please contact your administrator.");
                }

                user.LastLogin = DateTime.UtcNow;
                db.SaveChanges();
            }

            SQLServerManager sqlServer = new SQLServerManager();
            var accessToken = sqlServer.GetAccessToken();

            dataSource = new DataSource()
            {
                Address = MachineServiceConfig.DB_ADDRESS,
                Catalog = MachineServiceConfig.DB_CATALOG,
                Type = DataSourceType.AccessToken,
                IntegratedSecurity = false,
                AccessToken = accessToken.AccessToken,
                AccessTokenExpiration = accessToken.ExpiresOn.UtcDateTime
            };

            //Return data source
            return new LoginResponse()
            {
                DataSource = dataSource,
                AccessToken = WebToken<TokenObject>.CreateNew(MachineServiceConfig.JWT_TOKEN_SECRET, new TokenObject()
                {
                    UserGuid = user.Guid,
                }, DateTime.UtcNow.AddDays(1)).AccessToken,
                PasswordChangeRequired = user.PasswordChangeRequired
            };
        }

        [HttpPost]
        [JwtTokenFilter]
        public BugReportingInfoResponse GetBugReportInfo(BugReportingInfoRequest request)
        {
            return new BugReportingInfoResponse()
            {
                CollectionUrl = MachineServiceConfig.TFS_COLLECTION_URL,
                PersonalToken = MachineServiceConfig.TFS_PERSONAL_TOKEN,
                UserEmail = MachineServiceConfig.FSE_TFS_USER_EMAIL
            };
        }

        [HttpPost]
        [JwtTokenFilter]
        public DownloadTangoVersionResponse DownloadTangoVersion(DownloadTangoVersionRequest request)
        {
            DownloadTangoVersionResponse response = new DownloadTangoVersionResponse();

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                var tangoVersion = db.TangoVersions.SingleOrDefault(x => x.Guid == request.TangoVersionGuid);

                if (tangoVersion == null)
                {
                    throw new ArgumentException("Could not locate the specified Tango version.");
                }

                response.Version = tangoVersion.Version;

                var manager = new BlobStorageManager();
                var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
                var blob = container.GetBlockBlobReference(tangoVersion.BlobName);

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

                if (!String.IsNullOrWhiteSpace(MachineServiceConfig.CDN_ENDPOINT))
                {
                    response.CdnAddress = MachineServiceConfig.CDN_ENDPOINT + blob.Uri.AbsolutePath;
                }

                DbCredentials credentials = new DbCredentials();

                using (SmoManager smo = new SmoManager())
                {
                    credentials = smo.CreateRandomLoginAndUser();

                    Task.Delay(TimeSpan.FromMinutes(PPCController.SQL_TEMP_CREDENTIALS_EXP_MINUTS)).ContinueWith((x) =>
                    {
                        using (SmoManager m = new SmoManager())
                        {
                            m.DeleteLoginAndUser(credentials.UserName);
                        }
                    });
                }

                response.DataSource = new DataSource()
                {
                    Address = MachineServiceConfig.DB_ADDRESS,
                    Catalog = MachineServiceConfig.DB_CATALOG,
                    UserName = credentials.UserName,
                    Password = credentials.Password,
                    IntegratedSecurity = false,
                    Type = DataSourceType.SQLServer,
                };
            }

            return response;
        }

        [HttpPost]
        [JwtTokenFilter]
        public CheckForUpdatesResponse CheckForUpdates(CheckForUpdatesRequest request)
        {
            CheckForUpdatesResponse response = new CheckForUpdatesResponse();

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

                FseVersion 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.FSE_VERSIONS_CONTAINER);
                    //var blob = container.GetBlockBlobReference(latestVersion.BlobName);
                    var installerBlob = container.GetBlockBlobReference(latestVersion.InstallerBlobName);

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

                    if (!String.IsNullOrWhiteSpace(MachineServiceConfig.CDN_ENDPOINT))
                    {
                        //response.CdnAddress = MachineServiceConfig.CDN_ENDPOINT + blob.Uri.AbsolutePath;
                        response.InstallerCdnAddress = MachineServiceConfig.CDN_ENDPOINT + installerBlob.Uri.AbsolutePath;
                    }

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

            return response;
        }

        [HttpPost]
        [JwtTokenFilter]
        public RefreshTokenResponse RefreshToken(RefreshTokenRequest request)
        {
            SQLServerManager sqlServer = new SQLServerManager();
            var accessToken = sqlServer.GetAccessToken();

            return new RefreshTokenResponse()
            {
                AccessToken = accessToken.AccessToken,
                Expiration = accessToken.ExpiresOn.UtcDateTime,
            };
        }

        [HttpPost]
        [JwtTokenFilter]
        public UserInvitationEmailResponse SendUserInvitationEmail(UserInvitationEmailRequest request)
        {
            User user;

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                user = db.Users.Include(x => x.Contact).SingleOrDefault(x => x.Guid == request.UserGuid);

                if (user == null)
                {
                    throw new InvalidOperationException("User not found.");
                }
            }

            var client = new SendGridClient(MachineServiceConfig.SEND_GRID_API_KEY);
            SendGridMessage msg = new SendGridMessage();
            msg.SetFrom("info@twine-s.com", "Twine Solutions LTD");
            msg.AddTo(user.Email);
            msg.Subject = "Welcome To Tango FSE";
            msg.SetTemplateId("d-2af42ed0ea3c44b3abaa61016223555a");

            var dynamicTemplateData = new
            {
                DownloadUrl = $"{request.MachineServiceAddress}/fse",
                FullName = user.Contact.FirstName,
                Password = request.Password,
            };

            msg.SetTemplateData(dynamicTemplateData);

            var result = client.SendEmailAsync(msg).GetAwaiter().GetResult();

            if (result.StatusCode != HttpStatusCode.Accepted)
            {
                throw new HttpException(result.StatusCode.ToString());
            }

            return new UserInvitationEmailResponse();
        }

        [HttpPost]
        public ForgotPasswordResponse SendForgotPasswordEmail(ForgotPasswordRequest request)
        {
            User user;

            using (ObservablesContext db = ObservablesContextHelper.CreateContext())
            {
                user = db.Users.Include(x => x.Contact).SingleOrDefault(x => x.Email.ToLower() == request.Email.ToLower());

                if (user == null)
                {
                    throw new InvalidOperationException("User not found.");
                }
            }

            String resetId = Guid.NewGuid().ToString();

            var client = new SendGridClient(MachineServiceConfig.SEND_GRID_API_KEY);
            SendGridMessage msg = new SendGridMessage();
            msg.SetFrom("info@twine-s.com", "Twine Solutions LTD");
            msg.AddTo(request.Email);
            msg.Subject = "Tango FSE Password Reset";
            msg.SetTemplateId("d-18065487dae4456b8684d4b47a91e4a6");

            var dynamicTemplateData = new
            {
                ResetPasswordUrl = $"{request.MachineServiceAddress}/FSEAccount/ResetPassword?id={resetId}",
                FullName = user.Contact.FirstName,
            };

            msg.SetTemplateData(dynamicTemplateData);

            var result = client.SendEmailAsync(msg).GetAwaiter().GetResult();

            if (result.StatusCode != HttpStatusCode.Accepted)
            {
                throw new HttpException(result.StatusCode.ToString());
            }

            PendingPasswordResets.Add(new PasswordReset()
            {
                ID = resetId,
                UserGuid = user.Guid,
                FullName = user.Contact.FirstName,
            });

            return new ForgotPasswordResponse();
        }
    }
}