aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Web/Tango.MachineService/Controllers
diff options
context:
space:
mode:
authorMirta <mirta@twine-s.com>2020-12-30 16:39:52 +0200
committerMirta <mirta@twine-s.com>2020-12-30 16:39:52 +0200
commit00a491d93733d4625ad329b2ba8237f445364b3f (patch)
tree4b24c6fa78d7648f4bb7cefafa464bb0b063fec4 /Software/Visual_Studio/Web/Tango.MachineService/Controllers
parent124ad4150f80c6846fdee41dbbda9848c105f6e5 (diff)
downloadTango-00a491d9.tar.gz
Tango-00a491d9.zip
merge
Diffstat (limited to 'Software/Visual_Studio/Web/Tango.MachineService/Controllers')
-rw-r--r--Software/Visual_Studio/Web/Tango.MachineService/Controllers/DataStoreController.cs331
-rw-r--r--Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEAccountController.cs67
-rw-r--r--Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEController.cs431
-rw-r--r--Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEDownloadsController.cs60
-rw-r--r--Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs260
-rw-r--r--Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs544
6 files changed, 88 insertions, 1605 deletions
diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/DataStoreController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/DataStoreController.cs
deleted file mode 100644
index 383a59850..000000000
--- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/DataStoreController.cs
+++ /dev/null
@@ -1,331 +0,0 @@
-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.Builders;
-using Tango.BL.Entities;
-using Tango.BL.Enumerations;
-using Tango.Core.Cryptography;
-using Tango.DataStore;
-using Tango.DataStore.EF;
-using Tango.DataStore.Web;
-using Tango.MachineService.Filters;
-using Tango.Web.Controllers;
-using Tango.Web.Helpers;
-using Tango.Web.Security;
-using static Tango.MachineService.Controllers.DataStoreController;
-
-namespace Tango.MachineService.Controllers
-{
- public class DataStoreController : TangoController<TokenObject>
- {
- public class TokenObject
- {
- public String UserGuid { get; set; }
- public List<Permissions> Permissions { get; set; }
-
- public TokenObject()
- {
- Permissions = new List<Permissions>();
- }
- }
-
- private IDataStoreManager _manager;
-
- public DataStoreController()
- {
- _manager = new EFDataStoreManager();
- }
-
- [HttpPost]
- public LoginResponse Login(LoginRequest request)
- {
- User user = null;
-
- IHashGenerator hash = new BasicHashGenerator();
- 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.");
- }
-
- if (!user.HasPermission(Permissions.DataStoreRead))
- {
- throw new AuthenticationException("You are not authorized to access the data store.");
- }
-
- var token = WebToken<TokenObject>.CreateNew(MachineServiceConfig.JWT_TOKEN_SECRET, new TokenObject()
- {
- UserGuid = user.Guid,
- Permissions = user.Permissions.Select(x => (Permissions)x.Code).ToList()
- }, DateTime.UtcNow.AddDays(1));
-
- return new LoginResponse()
- {
- Token = token.AccessToken,
- ExpirationUTC = token.Expiration.Value,
- };
- }
- }
-
- [JwtWebApiTokenFilter]
- public List<DataStoreWebItem> Get(String sn = null, String collection = null, String key = null)
- {
- try
- {
- if (!RequestToken.Object.Permissions.Contains(Permissions.DataStoreRead))
- {
- throw CreateHttpException(new AuthenticationException("The current user was not authorized to read from the data store."), HttpStatusCode.Unauthorized);
- }
-
- if (key != null && collection == null)
- {
- throw CreateHttpException(new ArgumentException(), HttpStatusCode.BadRequest, "When specifying a key, collection must be specified.");
- }
-
- ValidateCollectionAndKey(collection, key);
-
- using (var db = ObservablesContextHelper.CreateContext())
- {
- if (sn != null)
- {
- var machineGuid = db.Machines.Where(x => x.SerialNumber == sn).Select(x => x.Guid).FirstOrDefault();
-
- if (machineGuid == null)
- {
- throw CreateHttpException(new KeyNotFoundException(), HttpStatusCode.NotFound, "The specified machine serial number could not be found.");
- }
-
- var localItems = db.DataStoreItems.Where(x => !x.IsDeleted).Where(x => x.MachineGuid == machineGuid && (collection == null || x.CollectionName == collection) && (key == null || x.Key == key)).ToList();
- var globalItems = db.GlobalDataStoreItems.Where(x => (collection == null || x.CollectionName == collection) && (key == null || x.Key == key)).ToList();
-
- if (localItems.Count == 0 && globalItems.Count == 0 && key != null)
- {
- throw CreateHttpException(new KeyNotFoundException(), HttpStatusCode.NotFound, "The specified key was not found on the data store.");
- }
-
- List<DataStoreWebItem> finalList = new List<DataStoreWebItem>();
-
- foreach (var localItem in localItems)
- {
- var globalItem = globalItems.FirstOrDefault(x => x.CollectionName == localItem.CollectionName && x.Key == localItem.Key);
- finalList.Add(localItem.ToWebItem(globalItem));
- globalItems.Remove(globalItem);
- }
-
- finalList.AddRange(globalItems.Select(x => x.ToWebItem()));
-
- return finalList;
- }
- else
- {
- var globalItems = db.GlobalDataStoreItems.Where(x => (collection == null || x.CollectionName == collection) && (key == null || x.Key == key)).ToList();
-
- var finalList = globalItems.Select(x => x.ToWebItem()).ToList();
-
- return finalList;
- }
- }
- }
- catch (HttpResponseException ex)
- {
- throw ex;
- }
- catch (Exception ex)
- {
- throw CreateHttpException(ex, HttpStatusCode.InternalServerError);
- }
- }
-
- [JwtWebApiTokenFilter]
- public void Put([FromBody]DataStoreWebPutItem item)
- {
- try
- {
- if (!RequestToken.Object.Permissions.Contains(Permissions.DataStoreWrite))
- {
- throw CreateHttpException(new AuthenticationException("The current user was not authorized to write to the data store."), HttpStatusCode.Unauthorized);
- }
-
- if (item.Collection == null || item.Key == null)
- {
- throw CreateHttpException(new AuthenticationException("Collection and key must be specified."), HttpStatusCode.BadRequest);
- }
-
- ValidateCollectionAndKey(item.Collection, item.Key);
-
- using (var db = ObservablesContextHelper.CreateContext())
- {
- if (item.MachineSerialNumber != null)
- {
- var machineGuid = db.Machines.Where(x => x.SerialNumber == item.MachineSerialNumber).Select(x => x.Guid).FirstOrDefault();
-
- if (machineGuid == null)
- {
- throw CreateHttpException(new KeyNotFoundException("The specified machine serial number could not be found."), HttpStatusCode.NotFound);
- }
-
- DataStoreItem dbItem = db.DataStoreItems.FirstOrDefault(x => x.CollectionName == item.Collection && x.Key == item.Key);
-
- if (dbItem == null)
- {
- if (!RequestToken.Object.Permissions.Contains(Permissions.DataStoreCreate))
- {
- throw CreateHttpException(new AuthenticationException("The current user was not authorized to create new items on the data store."), HttpStatusCode.Unauthorized);
- }
-
- dbItem = new DataStoreItem();
- dbItem.Key = item.Key;
- dbItem.CollectionName = item.Collection;
- dbItem.MachineGuid = machineGuid;
- db.DataStoreItems.Add(dbItem);
- }
-
- dbItem.DataType = (int)item.DataType;
- dbItem.IsDeleted = false;
- dbItem.IsSynchronized = false;
- dbItem.LastUpdated = DateTime.UtcNow;
- dbItem.Value = EFDataStoreHelper.CreateBytes(item.DataType, DataStoreHelper.ParseDataStoreValue(item.DataType, item.Value.ToStringSafe(), item.ProtoMessageType));
- }
- else
- {
- if (!RequestToken.Object.Permissions.Contains(Permissions.DataStoreCreateWriteGlobal))
- {
- throw CreateHttpException(new AuthenticationException("The current user was not authorized to write to the global data store."), HttpStatusCode.Unauthorized);
- }
-
- GlobalDataStoreItem dbItem = db.GlobalDataStoreItems.FirstOrDefault(x => x.CollectionName == item.Collection && x.Key == item.Key);
-
- if (dbItem == null)
- {
- if (!RequestToken.Object.Permissions.Contains(Permissions.DataStoreCreate))
- {
- throw CreateHttpException(new AuthenticationException("The current user was not authorized to create new items on the data store."), HttpStatusCode.Unauthorized);
- }
-
- dbItem = new GlobalDataStoreItem();
- dbItem.Key = item.Key;
- dbItem.CollectionName = item.Collection;
- db.GlobalDataStoreItems.Add(dbItem);
- }
-
- dbItem.DataType = (int)item.DataType;
- dbItem.LastUpdated = DateTime.UtcNow;
- dbItem.Value = EFDataStoreHelper.CreateBytes(item.DataType, DataStoreHelper.ParseDataStoreValue(item.DataType, item.Value.ToStringSafe(), item.ProtoMessageType));
- }
-
- db.SaveChanges();
- }
- }
- catch (HttpResponseException ex)
- {
- throw ex;
- }
- catch (Exception ex)
- {
- throw CreateHttpException(ex, HttpStatusCode.InternalServerError);
- }
- }
-
- private HttpResponseException CreateHttpException(Exception ex, HttpStatusCode code, String message = null)
- {
- return new HttpResponseException(new HttpResponseMessage(code)
- {
- Content = new StringContent(message != null ? message : ex.Message),
- ReasonPhrase = ex.FlattenMessage()
- });
- }
-
- private void ValidateCollectionAndKey(String collection = null, String key = null)
- {
- if (collection != null)
- {
- if (!DataStoreHelper.ValidateCollectionOrKeyName(collection))
- {
- throw new ArgumentException("Collection name contains invalid characters.");
- }
- }
-
- if (key != null)
- {
- if (!DataStoreHelper.ValidateCollectionOrKeyName(key))
- {
- throw new ArgumentException("Item key contains invalid characters.");
- }
- }
- }
-
- }
-
- #region Extension Methods
-
- public static class IDataStoreExtensions
- {
- public static DataStoreWebItem ToWebItem(this DataStoreItem item, GlobalDataStoreItem globalItem = null)
- {
- IDataStoreItem dsItem = item.ToDataStoreItem();
- DataStoreWebItem webItem = new DataStoreWebItem();
- webItem.Collection = item.CollectionName;
- webItem.Type = globalItem != null ? DataStoreWebItemType.Overrides : DataStoreWebItemType.Local;
- webItem.DataType = dsItem.Type;
- webItem.Date = dsItem.Date;
- webItem.Key = dsItem.Key;
- webItem.LocalValue = dsItem.Value;
-
- if (webItem.LocalValue is DataStoreProtoObject protoObject)
- {
- webItem.LocalValue = protoObject.Message;
- webItem.ProtoMessageType = protoObject.MessageType;
- }
-
- if (globalItem != null)
- {
- var dsGlobalItem = globalItem.ToDataStoreItem();
-
- webItem.GlobalValue = dsGlobalItem.Value;
-
- if (webItem.GlobalValue is DataStoreProtoObject protoObjectGlobal)
- {
- webItem.GlobalValue = protoObjectGlobal.Message;
- webItem.ProtoMessageType = protoObjectGlobal.MessageType;
- }
- }
-
- return webItem;
- }
-
- public static DataStoreWebItem ToWebItem(this GlobalDataStoreItem item)
- {
- IDataStoreItem dsItem = item.ToDataStoreItem();
- DataStoreWebItem webItem = new DataStoreWebItem();
- webItem.Collection = item.CollectionName;
- webItem.Type = DataStoreWebItemType.Global;
- webItem.DataType = dsItem.Type;
- webItem.Date = dsItem.Date;
- webItem.Key = dsItem.Key;
- webItem.GlobalValue = dsItem.Value;
-
- if (webItem.GlobalValue is DataStoreProtoObject protoObject)
- {
- webItem.GlobalValue = protoObject.Message;
- webItem.ProtoMessageType = protoObject.MessageType;
- }
-
- return webItem;
- }
- }
- #endregion
-}
diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEAccountController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEAccountController.cs
deleted file mode 100644
index b7728af6a..000000000
--- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEAccountController.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web;
-using System.Web.Mvc;
-using Tango.BL;
-using Tango.MachineService.Filters;
-using Tango.MachineService.Models;
-using Tango.Web.Helpers;
-using System.Data.Entity;
-using Tango.Web.Storage;
-using System.IO;
-using Microsoft.WindowsAzure.Storage.Blob;
-using System.Net.Http;
-using System.Net;
-using System.Net.Http.Headers;
-using System.Net.Mime;
-using Tango.MachineService.Views.FSEAccount;
-
-namespace Tango.MachineService.Controllers
-{
- public class FSEAccountController : Controller
- {
- private static Random rnd = new Random();
-
- public ActionResult ResetPassword(String id)
- {
- ResetPasswordVM vm = new ResetPasswordVM();
- vm.FullName = "Full Name";
- vm.Password = "Password";
-
- var reset = FSEController.PendingPasswordResets.SingleOrDefault(x => x.ID == id);
-
- if (reset != null)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var user = db.Users.SingleOrDefault(x => x.Guid == reset.UserGuid);
-
- if (user != null)
- {
- String newPass = GenerateRandomPassword();
- user.Password = Tango.BL.Entities.User.GetPasswordHash(newPass);
- user.PasswordChangeRequired = true;
- vm.Password = newPass;
- vm.FullName = reset.FullName;
- db.SaveChanges();
- }
- }
- }
-
- return View(vm);
- }
-
- private String GenerateRandomPassword()
- {
- String pass = String.Empty;
-
- for (int i = 0; i < 4; i++)
- {
- pass += rnd.Next(0, 9).ToString();
- }
-
- return pass;
- }
- }
-} \ No newline at end of file
diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEController.cs
deleted file mode 100644
index b9dacfcf9..000000000
--- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEController.cs
+++ /dev/null
@@ -1,431 +0,0 @@
-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;
-using Tango.MachineService.Models;
-using Tango.BL.Enumerations;
-
-namespace Tango.MachineService.Controllers
-{
- public class FSEController : TangoController<TokenObject>
- {
- private static List<FSEPendingUpload> _pendingUploads;
-
- 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()
- {
- _pendingUploads = new List<FSEPendingUpload>();
- 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();
- }
-
- #region Version Upload
-
- [HttpPost]
- public LatestVersionResponse GetLatestVersion(LatestVersionRequest request)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var version = db.FseVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
- return new LatestVersionResponse() { Version = version != null ? version.Version : "0.0.0.0" };
- }
- }
-
- [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.FseVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
- Version local_version = Version.Parse(request.Version);
-
- if (latestVersion == null || local_version > Version.Parse(latestVersion.Version))
- {
- var manager = new BlobStorageManager();
- var container = manager.GetContainer(MachineServiceConfig.FSE_VERSIONS_CONTAINER);
- var installerBlob = container.CreateEmptyBlob(request.InstallerBlobName);
-
- response.Token = Guid.NewGuid().ToString();
- response.InstallerBlobAddress = installerBlob.GenerateWriteSignature(TimeSpan.FromMinutes(30));
-
- FSEPendingUpload pending_upload = new FSEPendingUpload()
- {
- UserGuid = user.Guid,
- Comments = request.Comments,
- Token = response.Token,
- Version = request.Version,
- BlobName = "BLOB",
- 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;
- }
-
- [HttpPost]
- [JwtTokenFilter]
- public UploadCompletedResponse NotifyVersionUploadCompleted(UploadCompletedRequest request)
- {
- FSEPendingUpload upload = _pendingUploads.FirstOrDefault(x => x.Token == request.Token);
-
- if (upload != null)
- {
- _pendingUploads.RemoveAll(x => x.Token == upload.Token);
-
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- db.FseVersions.Add(new FseVersion()
- {
- 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.");
- }
- }
-
- #endregion
- }
-}
diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEDownloadsController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEDownloadsController.cs
deleted file mode 100644
index 52eb2bbb5..000000000
--- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/FSEDownloadsController.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web;
-using System.Web.Mvc;
-using Tango.BL;
-using Tango.MachineService.Filters;
-using Tango.MachineService.Models;
-using Tango.Web.Helpers;
-using System.Data.Entity;
-using Tango.Web.Storage;
-using System.IO;
-using Microsoft.WindowsAzure.Storage.Blob;
-using System.Net.Http;
-using System.Net;
-using System.Net.Http.Headers;
-using System.Net.Mime;
-using Tango.MachineService.Views.FSEDownloads;
-
-namespace Tango.MachineService.Controllers
-{
- public class FSEDownloadsController : Controller
- {
- public ActionResult Index()
- {
- IndexViewModel model = new IndexViewModel();
-
- using (var db = ObservablesContextHelper.CreateContext())
- {
- var versions = db.FseVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).Take(6).ToList();
-
- var manager = new BlobStorageManager();
- var container = manager.GetContainer(MachineServiceConfig.FSE_VERSIONS_CONTAINER);
-
- foreach (var item in versions)
- {
- var installerBlob = container.GetBlockBlobReference(item.InstallerBlobName);
-
- model.Downloads.Add(new FSEDownload()
- {
- Name = $"Tango FSE v{Version.Parse(item.Version).ToString(3)}",
- Version = Version.Parse(item.Version).ToString(3),
- Comments = item.Comments,
- Date = item.LastUpdated.ToString("dddd, dd MMMM yyyy"),
- Address = MachineServiceConfig.CDN_ENDPOINT + installerBlob.Uri.AbsolutePath
- });
- }
-
- if (model.Downloads.Count > 0)
- {
- var latest = model.Downloads.First();
- model.Downloads.Remove(latest);
- model.LatestDownload = latest;
- }
- }
-
- return View(model);
- }
- }
-} \ No newline at end of file
diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs
index 5f697f979..dd8401570 100644
--- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs
+++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/MachineStudioController.cs
@@ -23,10 +23,6 @@ using Tango.Web.ActiveDirectory;
using Tango.MachineService.Filters;
using Tango.MachineService.Security;
using Tango.Web.SQLServer;
-using Tango.Core;
-using Tango.Web.SMO;
-using Tango.Core.DB;
-using System.Threading.Tasks;
namespace Tango.MachineService.Controllers
{
@@ -40,6 +36,12 @@ namespace Tango.MachineService.Controllers
public String UserGuid { get; set; }
}
+ public class RefreshTokenObject
+ {
+ public String Email { get; set; }
+ public String Password { get; set; }
+ }
+
#region Constructors
/// <summary>
@@ -89,7 +91,7 @@ namespace Tango.MachineService.Controllers
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)
+ if (latestVersion != null && Version.Parse(latestVersion.Version) > currentVersion)
{
var manager = new BlobStorageManager();
var container = manager.GetContainer(MachineServiceConfig.MACHINE_STUDIO_VERSIONS_CONTAINER);
@@ -97,11 +99,6 @@ namespace Tango.MachineService.Controllers
response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60));
- if (!String.IsNullOrWhiteSpace(MachineServiceConfig.CDN_ENDPOINT))
- {
- response.CdnAddress = MachineServiceConfig.CDN_ENDPOINT + blob.Uri.AbsolutePath;
- }
-
response.IsUpdateAvailable = true;
response.Version = latestVersion.Version;
response.Comments = latestVersion.Comments;
@@ -120,6 +117,8 @@ namespace Tango.MachineService.Controllers
[JwtTokenFilter]
public DownloadLatestVersionResponse DownloadLatestVersion(DownloadLatestVersionRequest request)
{
+ LogManager.Log("Request received...");
+
DownloadLatestVersionResponse response = new DownloadLatestVersionResponse();
using (ObservablesContext db = ObservablesContextHelper.CreateContext())
@@ -134,11 +133,6 @@ namespace Tango.MachineService.Controllers
var container = manager.GetContainer(MachineServiceConfig.MACHINE_STUDIO_VERSIONS_CONTAINER);
var blob = container.GetBlockBlobReference(latestVersion.BlobName);
- if (!String.IsNullOrWhiteSpace(MachineServiceConfig.CDN_ENDPOINT))
- {
- response.CdnAddress = MachineServiceConfig.CDN_ENDPOINT + blob.Uri.AbsolutePath;
- }
-
response.BlobAddress = blob.GenerateReadSignature(TimeSpan.FromMinutes(60));
response.Version = latestVersion.Version;
}
@@ -277,10 +271,12 @@ namespace Tango.MachineService.Controllers
[HttpPost]
public LoginResponse Login(LoginRequest request)
{
- AuthenticationResult authResult = null;
- User user = null;
- DataSource dataSource = null;
- IHashGenerator hash = new BasicHashGenerator();
+ 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;
@@ -291,122 +287,84 @@ namespace Tango.MachineService.Controllers
bool versionChangeRequired = false;
String requiredVersion = null;
- bool isPasswordOK = false;
- try
- {
- authResult = _ad_manager.ValidateUserCredentials(request.Email, request.Password);
- isPasswordOK = true;
- }
- catch { }
+ User user = null;
- //Login via Active Directory
- if (request.Method == LoginMethod.ActiveDirectory)
+ using (ObservablesContext db = ObservablesContextHelper.CreateContext())
{
- try
- {
- authResult = _ad_manager.ValidateUserCredentials(request.Email, request.Password);
- }
- catch (Exception ex)
- {
- throw new AuthenticationException(ex.FlattenMessage());
- }
-
- if (!_ad_manager.CanUserAccessCurrentEnvironment(request.Email))
- {
- throw new AuthenticationException($"You do not have permissions to access the {MachineServiceConfig.DEPLOYMENT_SLOT.ToDescription()} environment.");
- }
+ db.Roles.ToList();
+ db.Permissions.ToList();
+ db.UsersRoles.ToList();
+ db.RolesPermissions.ToList();
- 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();
- user = new UserBuilder(db).Set(x => x.Email.ToLower() == request.Email.ToLower()).WithRolesAndPermissions().WithDeleted().Build();
+ IHashGenerator g = new BasicHashGenerator();
- if (user == null)
+ 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()
{
- user = new User();
- user.Email = request.Email;
- user.Password = hash.Encrypt(request.Password);
- user.Organization = db.Organizations.Include(x => x.Address).Single(x => x.Name == "Twine");
- user.Address = user.Organization.Address.Clone();
- 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 = user,
- Role = db.Roles.Single(x => (Roles)x.Code == Roles.User),
- });
+ FirstName = authResult.UserInfo.GivenName,
+ LastName = authResult.UserInfo.FamilyName,
+ FullName = authResult.UserInfo.GivenName + " " + authResult.UserInfo.FamilyName,
+ Email = request.Email,
+ };
- db.UsersRoles.Add(new UsersRole()
- {
- User = user,
- Role = db.Roles.Single(x => (Roles)x.Code == Roles.MachineStudioUser),
- });
+ db.UsersRoles.Add(new UsersRole()
+ {
+ User = new_user,
+ Role = db.Roles.Single(x => (Roles)x.Code == Roles.User),
+ });
- user.Password = hash.Encrypt(request.Password);
+ db.UsersRoles.Add(new UsersRole()
+ {
+ User = new_user,
+ Role = db.Roles.Single(x => (Roles)x.Code == Roles.MachineStudioUser),
+ });
- db.Users.Add(user);
- }
- else
+ new_user.LastLogin = DateTime.UtcNow;
+ db.Users.Add(new_user);
+ }
+ else
+ {
+ if (user.Deleted)
{
- if (user.Deleted)
- {
- throw new AuthenticationException("Your account has been disabled. Please contact your administrator.");
- }
+ throw new AuthenticationException("Your account has been disabled. Please contact your administrator.");
}
user.LastLogin = DateTime.UtcNow;
-
- db.SaveChanges();
+ user.Password = g.Encrypt(request.Password);
}
- dataSource = new DataSource()
- {
- Address = MachineServiceConfig.DB_ADDRESS,
- Catalog = MachineServiceConfig.DB_CATALOG,
- Type = Core.DataSourceType.Azure,
- IntegratedSecurity = false,
- UserName = request.Email,
- Password = request.Password,
- };
- }
- //Login via Database standard user
- else
- {
- var password = hash.Encrypt(request.Password);
+ db.SaveChanges();
- using (var db = ObservablesContextHelper.CreateContext())
+ if (MachineServiceConfig.ENFORCE_MACHINE_STUDIO_VERSION)
{
- user = new UserBuilder(db).Set(x => x.Email.ToLower() == request.Email.ToLower() && (isPasswordOK || x.Password == password)).WithRolesAndPermissions().WithDeleted().Build();
-
- if (user == null)
- {
- throw new AuthenticationException("Invalid email or password.");
- }
+ var latest_version = db.MachineStudioVersions.ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
- if (user.Deleted)
+ if (latest_version != null && Version.Parse(latest_version.Version) != client_version)
{
- throw new AuthenticationException("Your account has been disabled. Please contact your administrator.");
+ versionChangeRequired = true;
+ requiredVersion = latest_version.Version;
}
-
- user.LastLogin = DateTime.UtcNow;
- db.SaveChanges();
}
+ }
+ Core.DataSource dataSource = null;
+
+ if (MachineServiceConfig.USE_DB_ACCESS_TOKENS)
+ {
SQLServerManager sqlServer = new SQLServerManager();
var accessToken = sqlServer.GetAccessToken();
- dataSource = new DataSource()
+ dataSource = new Core.DataSource()
{
Address = MachineServiceConfig.DB_ADDRESS,
Catalog = MachineServiceConfig.DB_CATALOG,
@@ -416,23 +374,19 @@ namespace Tango.MachineService.Controllers
AccessTokenExpiration = accessToken.ExpiresOn.UtcDateTime
};
}
-
- //Enforce Machine Studio Version ?
- if (MachineServiceConfig.ENFORCE_MACHINE_STUDIO_VERSION)
+ else
{
- using (var db = ObservablesContextHelper.CreateContext())
+ dataSource = new Core.DataSource()
{
- 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;
- }
- }
+ Address = MachineServiceConfig.DB_ADDRESS,
+ Catalog = MachineServiceConfig.DB_CATALOG,
+ Type = Core.DataSourceType.Azure,
+ IntegratedSecurity = false,
+ UserName = request.Email,
+ Password = request.Password,
+ };
}
- //Return data source
return new LoginResponse()
{
DataSource = dataSource,
@@ -442,7 +396,6 @@ namespace Tango.MachineService.Controllers
}, DateTime.UtcNow.AddDays(1)).AccessToken,
VersionChangeRequired = versionChangeRequired,
RequiredVersion = requiredVersion,
- PasswordChangeRequired = request.Method == LoginMethod.StandardUser && user.PasswordChangeRequired
};
}
@@ -462,67 +415,6 @@ namespace Tango.MachineService.Controllers
};
}
- [HttpPost]
- [JwtTokenFilter]
- public DownloadLatestPPCVersionResponse DownloadLatestPPCVersion(DownloadLatestPPCVersionRequest request)
- {
- DownloadLatestPPCVersionResponse response = new DownloadLatestPPCVersionResponse();
-
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber);
-
- if (machine == null)
- {
- throw new AuthenticationException("The specified serial number could not be found.");
- }
-
- var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid);
-
- var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
-
- response.Version = latest_machine_version.Version;
-
- var manager = new BlobStorageManager();
- var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
- var blob = container.GetBlockBlobReference(latest_machine_version.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;
- }
-
#endregion
}
}
diff --git a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs
index 161caaf23..a77212787 100644
--- a/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs
+++ b/Software/Visual_Studio/Web/Tango.MachineService/Controllers/PPCController.cs
@@ -24,16 +24,13 @@ using Tango.Web.ActiveDirectory;
using Tango.Core.Cryptography;
using Tango.MachineService.Filters;
using Tango.BL.DTO;
-using Z.EntityFramework.Plus;
namespace Tango.MachineService.Controllers
{
public class PPCController : TangoController<PPCController.TokenObject>
{
private static List<PPCPendingUpload> _pendingUploads;
- private static List<PPCPendingUpdate> _pendingUpdates;
private ActiveDirectoryManager _ad_manager;
- public const int SQL_TEMP_CREDENTIALS_EXP_MINUTS = 20;
public class TokenObject
{
@@ -47,7 +44,6 @@ namespace Tango.MachineService.Controllers
static PPCController()
{
_pendingUploads = new List<PPCPendingUpload>();
- _pendingUpdates = new List<PPCPendingUpdate>();
}
public PPCController()
@@ -64,7 +60,6 @@ namespace Tango.MachineService.Controllers
public MachineSetupResponse MachineSetup(MachineSetupRequest request)
{
MachineSetupResponse response = new MachineSetupResponse();
- response.NotifyCompletedToken = Guid.NewGuid().ToString();
LogManager.Log("Setup request received: " + request.ToString());
@@ -72,7 +67,7 @@ namespace Tango.MachineService.Controllers
{
String machine_guid = RequestToken.Object.MachineGuid;
- var machine = db.Machines.Include(x => x.Organization).SingleOrDefault(x => x.Guid == machine_guid);
+ var machine = db.Machines.SingleOrDefault(x => x.Guid == machine_guid);
if (machine == null)
{
@@ -103,12 +98,13 @@ namespace Tango.MachineService.Controllers
machine.DeviceId = request.DeviceID;
machine.IsDeviceRegistered = true;
+ db.SaveChanges();
+
var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid);
- var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid && !x.Disabled).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
+ var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
response.Version = latest_machine_version.Version;
- response.FirmwareVersion = latest_machine_version.FirmwareVersion;
var manager = new BlobStorageManager();
var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
@@ -116,18 +112,13 @@ namespace Tango.MachineService.Controllers
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(SQL_TEMP_CREDENTIALS_EXP_MINUTS)).ContinueWith((x) =>
+ Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
{
using (SmoManager m = new SmoManager())
{
@@ -152,55 +143,6 @@ namespace Tango.MachineService.Controllers
response.SetupUWF = machine.SetupUwf;
response.SetupFirmware = machine.SetupFirmware;
response.IsDemo = machine.IsDemo;
- response.Organization = machine.Organization.Name;
-
- TangoUpdate tangoUpdate = new TangoUpdate();
- tangoUpdate.ApplicationVersion = latest_machine_version.Version;
- tangoUpdate.FirmwareVersion = latest_machine_version.FirmwareVersion;
- tangoUpdate.MachineGuid = machine.Guid;
- tangoUpdate.StartDate = DateTime.UtcNow;
- tangoUpdate.UpdateStatus = TangoUpdateStatuses.SetupStarted;
- db.TangoUpdates.Add(tangoUpdate);
-
- machine.ProductionDate = DateTime.UtcNow;
-
- db.SaveChanges();
-
- _pendingUpdates.Add(new PPCPendingUpdate()
- {
- Token = response.NotifyCompletedToken,
- TangoUpdateGuid = tangoUpdate.Guid,
- });
-
- Task.Factory.StartNew(() =>
- {
- using (ObservablesContext b = ObservablesContextHelper.CreateContext())
- {
- //Reset Job Runs.
- try
- {
- b.JobRuns.Where(x => x.MachineGuid == machine.Guid && x.IsSynchronized).Update(x => new JobRun() { IsSynchronized = false });
- }
- catch (Exception ex)
- {
- LogManager.Log(ex, $"Error resetting synchronized job runs for machine '{machine.SerialNumber}'.");
- }
-
- try
- {
- b.DataStoreItems.Where(x => x.MachineGuid == machine.Guid).Update(x => new DataStoreItem() { IsSynchronized = false });
- }
- catch (Exception ex)
- {
- LogManager.Log(ex, $"Error resetting synchronized data store items for machine '{machine.SerialNumber}'.");
- }
-
- //Reset Events.
- //b.MachinesEvents.Where(x => x.MachineGuid == machine.Guid).Update(x => new MachinesEvent() { IsSynchronized = false });
- //Reset Jobs.
- //b.Jobs.Where(x => x.MachineGuid == machine.Guid).Update(x => new Job() { IsSynchronized = false });
- }
- });
}
return response;
@@ -211,7 +153,6 @@ namespace Tango.MachineService.Controllers
public DownloadUpdateResponse MachineUpdate(DownloadUpdateRequest request)
{
DownloadUpdateResponse response = new DownloadUpdateResponse();
- response.NotifyCompletedToken = Guid.NewGuid().ToString();
using (ObservablesContext db = ObservablesContextHelper.CreateContext())
{
@@ -227,10 +168,9 @@ namespace Tango.MachineService.Controllers
var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid);
- var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid && !x.Disabled).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
+ var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
response.Version = latest_machine_version.Version;
- response.FirmwareVersion = latest_machine_version.FirmwareVersion;
var manager = new BlobStorageManager();
var container = manager.GetContainer(MachineServiceConfig.TANGO_VERSIONS_CONTAINER);
@@ -238,18 +178,13 @@ namespace Tango.MachineService.Controllers
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(SQL_TEMP_CREDENTIALS_EXP_MINUTS)).ContinueWith((x) =>
+ Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
{
using (SmoManager m = new SmoManager())
{
@@ -267,22 +202,6 @@ namespace Tango.MachineService.Controllers
IntegratedSecurity = false,
Type = DataSourceType.SQLServer,
};
-
- TangoUpdate tangoUpdate = new TangoUpdate();
- tangoUpdate.ApplicationVersion = latest_machine_version.Version;
- tangoUpdate.FirmwareVersion = latest_machine_version.FirmwareVersion;
- tangoUpdate.MachineGuid = machine.Guid;
- tangoUpdate.StartDate = DateTime.UtcNow;
- tangoUpdate.UpdateStatus = TangoUpdateStatuses.UpdateStarted;
- db.TangoUpdates.Add(tangoUpdate);
-
- db.SaveChanges();
-
- _pendingUpdates.Add(new PPCPendingUpdate()
- {
- Token = response.NotifyCompletedToken,
- TangoUpdateGuid = tangoUpdate.Guid,
- });
}
return response;
@@ -290,40 +209,6 @@ namespace Tango.MachineService.Controllers
[HttpPost]
[JwtTokenFilter]
- public MachineUpdateCompletedResponse NotifyUpdateCompleted(MachineUpdateCompletedRequest request)
- {
- var pendingUpdate = _pendingUpdates.SingleOrDefault(x => x.Token == request.Token);
- if (pendingUpdate != null)
- {
- _pendingUpdates.Remove(pendingUpdate);
-
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var tangoUpdate = db.TangoUpdates.SingleOrDefault(x => x.Guid == pendingUpdate.TangoUpdateGuid);
-
- if (tangoUpdate != null)
- {
- tangoUpdate.LastUpdated = DateTime.UtcNow;
- tangoUpdate.UpdateStatus = request.Status;
- tangoUpdate.EndDate = DateTime.UtcNow;
- tangoUpdate.FailedReason = request.FailedReason;
- tangoUpdate.FailedLog = request.FailedLog;
-
- if (request.ReportsAboutDbCheckNoDifferences)
- {
- db.TangoUpdates.Remove(tangoUpdate);
- }
-
- db.SaveChanges();
- }
- }
- }
-
- return new MachineUpdateCompletedResponse();
- }
-
- [HttpPost]
- [JwtTokenFilter]
public CheckForUpdateResponse CheckForUpdates(CheckForUpdateRequest request)
{
CheckForUpdateResponse response = new CheckForUpdateResponse();
@@ -346,67 +231,14 @@ namespace Tango.MachineService.Controllers
{
var machine_version = db.MachineVersions.SingleOrDefault(x => x.Guid == machine.MachineVersionGuid);
- var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid && !x.Disabled).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
+ var latest_machine_version = db.TangoVersions.Where(x => x.MachineVersionGuid == machine_version.Guid).ToList().OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
if (Version.Parse(latest_machine_version.Version) > Version.Parse(request.Version))
{
response.IsUpdateAvailable = true;
}
- if (!machine.IsDemo && machine.SetupFirmware)
- {
- if (!String.IsNullOrWhiteSpace(request.FirmwareVersion))
- {
- if (Version.Parse(latest_machine_version.FirmwareVersion) > Version.Parse(request.FirmwareVersion))
- {
- response.IsUpdateAvailable = true;
- }
- }
- }
-
response.Version = latest_machine_version.Version;
- response.FirmwareVersion = latest_machine_version.FirmwareVersion;
-
- //Compare database
-
- var rmls = db.Rmls.Select(x => new { x.Guid, x.LastUpdated }).ToList();
- var hardwareVersions = db.HardwareVersions.Select(x => new { x.Guid, x.LastUpdated }).ToList();
- var catalogs = db.ColorCatalogs.Select(x => new { x.Guid, x.LastUpdated }).ToList();
-
- var arr = request.UsedRmlsGuids.ToArray();
- var existingRml = db.Rmls.Where(x => arr.Contains(x.Guid)).Select(x => x.Guid).Distinct().ToList();
- response.UsedNotExistingRmlsGuids = arr.Where(x => !existingRml.Exists(y => y == x)).ToList();
-
- bool hasDatabaseUpdates = false;
-
- hasDatabaseUpdates = machine.LastUpdated > request.MachineLastUpdated;
-
- if (!hasDatabaseUpdates)
- {
- hasDatabaseUpdates = rmls.Exists(x => request.Rmls.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.Rmls.Exists(y => x.Guid == y.Guid));
- }
-
- if (!hasDatabaseUpdates)
- {
- hasDatabaseUpdates = hardwareVersions.Exists(x => request.HardwareVersions.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.HardwareVersions.Exists(y => x.Guid == y.Guid));
- }
-
- if (!hasDatabaseUpdates)
- {
- hasDatabaseUpdates = catalogs.Exists(x => request.Catalogs.Exists(y => x.Guid == y.Guid && x.LastUpdated > y.LastUpdated) || !request.Catalogs.Exists(y => x.Guid == y.Guid));
- }
-
- if (hasDatabaseUpdates)
- {
- response.IsDatabaseUpdateAvailable = true;
- response.UpdateDBResponse = UpdateDB(new UpdateDBRequest()
- {
- ApplicationVersion = request.Version,
- FirmwareVersion = request.FirmwareVersion
- });
- }
-
- //Compare database
if (machine.ForceVersionUpdate)
{
@@ -423,7 +255,6 @@ namespace Tango.MachineService.Controllers
public UpdateDBResponse UpdateDB(UpdateDBRequest request)
{
UpdateDBResponse response = new UpdateDBResponse();
- response.NotifyCompletedToken = Guid.NewGuid().ToString();
using (ObservablesContext db = ObservablesContextHelper.CreateContext())
{
@@ -445,7 +276,7 @@ namespace Tango.MachineService.Controllers
{
credentials = manager.CreateRandomLoginAndUser();
- Task.Delay(TimeSpan.FromMinutes(SQL_TEMP_CREDENTIALS_EXP_MINUTS)).ContinueWith((x) =>
+ Task.Delay(TimeSpan.FromMinutes(10)).ContinueWith((x) =>
{
using (SmoManager m = new SmoManager())
{
@@ -463,354 +294,6 @@ namespace Tango.MachineService.Controllers
IntegratedSecurity = false,
Type = DataSourceType.SQLServer,
};
-
- TangoUpdate tangoUpdate = new TangoUpdate();
- tangoUpdate.ApplicationVersion = request.ApplicationVersion;
- tangoUpdate.FirmwareVersion = request.FirmwareVersion;
- tangoUpdate.MachineGuid = machine.Guid;
- tangoUpdate.StartDate = DateTime.UtcNow;
- tangoUpdate.UpdateStatus = TangoUpdateStatuses.DatabaseStarted;
- db.TangoUpdates.Add(tangoUpdate);
-
- db.SaveChanges();
-
- _pendingUpdates.Add(new PPCPendingUpdate()
- {
- Token = response.NotifyCompletedToken,
- TangoUpdateGuid = tangoUpdate.Guid,
- });
- }
-
- return response;
- }
-
- #endregion
-
- #region Synchronization
-
- [HttpPost]
- [JwtTokenFilter]
- public UploadMachineDataResponse UploadMachineData(UploadMachineDataRequest request)
- {
- UploadMachineDataResponse response = new UploadMachineDataResponse();
- response.NotifyCompletedToken = Guid.NewGuid().ToString();
-
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var machine = db.Machines.SingleOrDefault(x => x.Guid == RequestToken.Object.MachineGuid);
-
- if (machine == null)
- {
- throw new AuthenticationException("The specified machine could not be found.");
- }
-
- TangoUpdate tangoUpdate = new TangoUpdate();
- tangoUpdate.ApplicationVersion = request.ApplicationVersion;
- tangoUpdate.FirmwareVersion = request.FirmwareVersion;
- tangoUpdate.MachineGuid = machine.Guid;
- tangoUpdate.StartDate = DateTime.UtcNow;
- tangoUpdate.UpdateStatus = TangoUpdateStatuses.SynchronizationStarted;
- db.TangoUpdates.Add(tangoUpdate);
- db.SaveChanges();
-
- _pendingUpdates.Add(new PPCPendingUpdate()
- {
- Token = response.NotifyCompletedToken,
- TangoUpdateGuid = tangoUpdate.Guid,
- });
- }
-
- try
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var machine = db.Machines.SingleOrDefault(x => x.Guid == RequestToken.Object.MachineGuid);
-
- if (machine == null)
- {
- throw new AuthenticationException("The specified machine could not be found.");
- }
- }
-
- //Insert/Replace Jobs.
- foreach (var dto in request.Jobs)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- try
- {
- var job = dto.ToObservable();
-
- job.ID = 0;
- job.CustomerGuid = null;
- job.IsSynchronized = true;
-
- var existingJob = db.Jobs.SingleOrDefault(x => x.Guid == job.Guid);
-
- if (existingJob == null)
- {
- db.Jobs.Add(job);
- db.SaveChanges();
- }
- else if (job.LastUpdated > existingJob.LastUpdated)
- {
- job.UserGuid = existingJob.UserGuid;
- existingJob.Delete(db);
- db.Jobs.Add(job);
- db.SaveChanges();
- }
- }
- catch (Exception ex)
- {
- response.FailedJobs.Add(new SynchronizationFailedEntity()
- {
- Guid = dto.Guid,
- Reason = ex.FlattenMessage(),
- });
- }
- }
- }
-
- //Insert Update DataStore Items
- foreach (var dto in request.DataStoreItems)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- try
- {
- var dataStoreItem = dto.ToObservable();
- dataStoreItem.MachineGuid = RequestToken.Object.MachineGuid;
-
- dataStoreItem.ID = 0;
- dataStoreItem.IsSynchronized = true;
-
- var existingItem = db.DataStoreItems.SingleOrDefault(x => x.Guid == dataStoreItem.Guid);
-
- if (existingItem == null)
- {
- db.DataStoreItems.Add(dataStoreItem);
- db.SaveChanges();
- }
- else if (dataStoreItem.LastUpdated >= existingItem.LastUpdated)
- {
- existingItem.DataType = dataStoreItem.DataType;
- existingItem.Value = dataStoreItem.Value;
- existingItem.IsSynchronized = true;
- existingItem.LastUpdated = dataStoreItem.LastUpdated;
- db.SaveChanges();
- }
- }
- catch (Exception ex)
- {
- response.FailedDataStoreItems.Add(new SynchronizationFailedEntity()
- {
- Guid = dto.Guid,
- Reason = ex.FlattenMessage(),
- });
- }
- }
- }
-
- //Insert JobRuns.
- foreach (var dto in request.JobRuns)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- try
- {
- var run = dto.ToObservable();
- run.ID = 0;
- run.IsSynchronized = true;
-
- if (db.JobRuns.SingleOrDefault(x => x.Guid == run.Guid) == null)
- {
- db.JobRuns.Add(run);
- db.SaveChanges();
- }
- }
- catch (Exception ex)
- {
- response.FailedJobRuns.Add(new SynchronizationFailedEntity()
- {
- Guid = dto.Guid,
- Reason = ex.FlattenMessage(),
- });
- }
- }
- }
-
- //Insert TangoUpdates.
- foreach (var dto in request.OfflineUpdates)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- try
- {
- var update = dto.ToObservable();
- update.ID = 0;
- update.IsSynchronized = true;
-
- if (db.TangoUpdates.SingleOrDefault(x => x.Guid == update.Guid) == null)
- {
- db.TangoUpdates.Add(update);
- db.SaveChanges();
- }
- }
- catch (Exception ex)
- {
- response.FailedOfflineUpdates.Add(new SynchronizationFailedEntity()
- {
- Guid = dto.Guid,
- Reason = ex.FlattenMessage(),
- });
- }
- }
- }
-
- //Insert MachineEvents.
- foreach (var dto in request.MachineEvents)
- {
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- try
- {
- var ev = dto.ToObservable();
- ev.ID = 0;
- ev.IsSynchronized = true;
-
- if (db.MachinesEvents.SingleOrDefault(x => x.Guid == ev.Guid) == null)
- {
- db.MachinesEvents.Add(ev);
- db.SaveChanges();
- }
- }
- catch (Exception ex)
- {
- response.FailedMachineEvents.Add(new SynchronizationFailedEntity()
- {
- Guid = dto.Guid,
- Reason = ex.FlattenMessage(),
- });
- }
- }
- }
- }
- catch (Exception ex)
- {
- NotifyUpdateCompleted(new MachineUpdateCompletedRequest()
- {
- Status = TangoUpdateStatuses.SynchronizationFailed,
- FailedReason = ex.FlattenMessage(),
- FailedLog = ex.FlattenException(),
- Token = response.NotifyCompletedToken,
- });
- throw ex;
- }
-
- return response;
- }
-
- [HttpPost]
- [JwtTokenFilter]
- public DownloadMachineDataResponse DownloadMachineData(DownloadMachineDataRequest request)
- {
- DownloadMachineDataResponse response = new DownloadMachineDataResponse();
-
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var machine = db.Machines.SingleOrDefault(x => x.Guid == RequestToken.Object.MachineGuid);
-
- if (machine == null)
- {
- throw new AuthenticationException("The specified machine could not be found.");
- }
-
- //Send Jobs
- if (request.RequestJobs)
- {
- var jobs = new JobsCollectionBuilder(db).Set(x => x.MachineGuid == machine.Guid && !x.IsSynchronized).WithSegments().WithBrushStops().Query(x => x.Take(request.MaxJobs).OrderByDescending(z => z.LastUpdated)).BuildList();
-
- foreach (var job in jobs)
- {
- JobDTO dto = JobDTO.FromObservable(job);
- response.Jobs.Add(dto);
- }
- }
-
- //Send Job Runs
- if (request.RequestJobRuns)
- {
- var jobRuns = db.JobRuns.Where(x => x.MachineGuid == machine.Guid && !x.IsSynchronized).Take(request.MaxJobRuns).OrderByDescending(x => x.LastUpdated).ToList();
-
- foreach (var jobRun in jobRuns)
- {
- JobRunDTO dto = JobRunDTO.FromObservable(jobRun);
- response.JobRuns.Add(dto);
- }
- }
-
- //Send Machine Events
- if (request.RequestMachineEvents)
- {
- var machineEvents = db.MachinesEvents.Where(x => x.MachineGuid == machine.Guid && !x.IsSynchronized).Take(request.MaxMachinesEvents).OrderByDescending(x => x.LastUpdated).ToList();
-
- foreach (var machineEvent in machineEvents)
- {
- MachinesEventDTO dto = MachinesEventDTO.FromObservable(machineEvent);
- response.MachineEvents.Add(dto);
- }
- }
-
- //Send DataStore Items
- if (request.RequestDataStoreItems)
- {
- var dataStoreItems = db.DataStoreItems.Where(x => x.MachineGuid == machine.Guid && !x.IsSynchronized & !x.IsDeleted).Take(request.MaxDataStoreItems).OrderByDescending(x => x.LastUpdated).ToList();
-
- foreach (var item in dataStoreItems)
- {
- DataStoreItemDTO dto = DataStoreItemDTO.FromObservable(item);
- response.DataStoreItems.Add(dto);
- }
- }
- }
-
- return response;
- }
-
- [HttpPost]
- [JwtTokenFilter]
- public NotifyMachineDataDownloadCompletedResponse NotifyMachineDataDownloadCompleted(NotifyMachineDataDownloadCompletedRequest request)
- {
- var response = new NotifyMachineDataDownloadCompletedResponse();
-
- using (ObservablesContext db = ObservablesContextHelper.CreateContext())
- {
- var machine = db.Machines.SingleOrDefault(x => x.Guid == RequestToken.Object.MachineGuid);
-
- if (machine == null)
- {
- throw new AuthenticationException("The specified machine could not be found.");
- }
-
- if (request.SynchronizedJobs.Count > 0)
- {
- db.Database.ExecuteSqlCommand($"UPDATE JOBS SET IS_SYNCHRONIZED = 1 WHERE GUID IN ({String.Join(",", request.SynchronizedJobs.Select(x => "'" + x + "'"))});");
- }
-
- if (request.SynchronizedJobRuns.Count > 0)
- {
- db.Database.ExecuteSqlCommand($"UPDATE JOB_RUNS SET IS_SYNCHRONIZED = 1 WHERE GUID IN ({String.Join(",", request.SynchronizedJobRuns.Select(x => "'" + x + "'"))});");
- }
-
- if (request.SynchronizedMachineEvents.Count > 0)
- {
- db.Database.ExecuteSqlCommand($"UPDATE MACHINES_EVENTS SET IS_SYNCHRONIZED = 1 WHERE GUID IN ({String.Join(",", request.SynchronizedMachineEvents.Select(x => "'" + x + "'"))});");
- }
-
- if (request.SynchronizedDataStoreItems.Count > 0)
- {
- db.Database.ExecuteSqlCommand($"UPDATE DATA_STORE_ITEMS SET IS_SYNCHRONIZED = 1 WHERE GUID IN ({String.Join(",", request.SynchronizedDataStoreItems.Select(x => "'" + x + "'"))});");
- }
}
return response;
@@ -834,13 +317,10 @@ namespace Tango.MachineService.Controllers
return new LatestVersionResponse()
{
Version = "0.0.0.0",
- FirmwareVersion = "0.0.0.0"
};
}
- var latestTangoVersion = versions.OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault();
- response.Version = latestTangoVersion.Version;
- response.FirmwareVersion = latestTangoVersion.FirmwareVersion;
+ response.Version = versions.OrderByDescending(x => Version.Parse(x.Version)).FirstOrDefault().Version;
}
return response;
@@ -1005,11 +485,11 @@ namespace Tango.MachineService.Controllers
}
else if (request.Mode == LoginMode.Machine)
{
- var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber || x.Guid == request.MachineGuid);
+ var machine = db.Machines.SingleOrDefault(x => x.SerialNumber == request.SerialNumber);
if (machine == null)
{
- throw new AuthenticationException("Invalid machine serial number or id.");
+ throw new AuthenticationException("Invalid serial number.");
}
response.AccessToken = WebToken<TokenObject>.CreateNew(MachineServiceConfig.JWT_TOKEN_SECRET, new TokenObject()