Exemple #1
0
        public ActionResult Index()
        {
            Debug("Get ~/Administration/User/Index()");

            // Retrieve the user

            UserRecord user;

            if (int.Parse(HttpContext.User.Identity.Name) == -1)
            {
                user = UserRecord.CreateDefaultAdministrator();
            }
            else
            {
                user = _userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) as UserRecord;
            }

            // If the login doesn't exist, it is the administrator by default (due to RoleFilter)

            if (user == null)
            {
                FormsAuthentication.SignOut();
                return(RedirectToAction("SignIn"));
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            // the user exists, check if it's already connected
            // In case of reloading page, the connection can't be disconnected as quick as expected ...

            if (DatabaseHub.IsAlreadyConnected(user.Id))
            {
                FormsAuthentication.SignOut();
                Debug($"The user '{user.Id}' is already connected on another support");
                return(View("AlreadyConnected", new UserViewModel(ressources, user, false)));
            }

            // Show the screen on depends on the user's profile

            if (user.CustomerId == 1)
            {
                return(RedirectToAction("Index", "Customer"));
            }

            // Look for the default functional module for the current user

            ModuleRecord module = _userManager.GetDefaultModule(user);

            if (module == null)
            {
                FormsAuthentication.SignOut();
                return(RedirectToAction("SignIn"));
            }

            return(RedirectToAction("Index", module.Module.ToString(), new { area = module.Module.ToString(), moduleId = module.Id }));
        }
Exemple #2
0
        public ActionResult ForgetPassword(string login)
        {
            Debug($"Post ~/Administration/User/ForgetPassword({login})");

            // check the value by itself

            Errors errors = new Errors();

            if (string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{USER_LOGIN}" });
            }

            if (errors.HasError)
            {
                // read the multilingual dictionary

                LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);
                ressources.Load(_userManager.Database, 1);

                SetModelState(ModelState, ressources, errors);
                return(View(new UserViewModel(ressources, new UserRecord(), false)));
            }

            // ask for a new password due to forget password

            SendNewPassword(login);

            // Go to SingIn

            return(RedirectToAction("SignIn"));
        }
Exemple #3
0
        /// <summary>
        /// On depends on the current context, build the view model of the index page for a module (except Administration or Customer)
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public UserViewModel BuildUserViewModel(int?moduleId)
        {
            // Retrieve the user

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user))
            {
                return(null);
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            // the user exists, check if it's already connected
            // In case of reloading page, the connection can't be disconnected as quick as expected ...

            if (Database.DatabaseHub.IsAlreadyConnected(user.Id))
            {
                FormsAuthentication.SignOut();
                Debug($"The user '{user.Id}' is already connected on another support");
                return(new UserViewModel(ressources, user, false));
            }

            // Show the screen on depends on the user's profile

            return(new UserViewModel(ressources, user, HttpContext.User.Identity.IsAuthenticated, moduleId));
        }
Exemple #4
0
        public ActionResult Index(int?moduleId)
        {
            Debug($"Get ~/Administration/Administration/Index({moduleId})");

            // If the login doesn't exist, it is the administrator by default (due to RoleFilter)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user))
            {
                user = UserRecord.CreateDefaultAdministrator();
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            // the user exists, check if it's already connected
            // In case of reloading page, the connection can't be disconnected as quick as expected ...

            if (DatabaseHub.IsAlreadyConnected(user.Id))
            {
                FormsAuthentication.SignOut();
                Debug($"The user '{user.Id}' is already connected on another support");
                return(View("AlreadyConnected", new UserViewModel(ressources, user, false)));
            }

            return(View("Index", new UserViewModel(ressources, user, HttpContext.User.Identity.IsAuthenticated, moduleId)));
        }
        public Form1()
        {
            InitializeComponent();
            languageDictionary.Load("english", "alpha");
            writingObserver.Initialize(languageDictionary);
            Logger.Initialize(lastMessageLabel);
            StatusManager.Initialize(statusLabel);
            UIUpdater.Initialize(this, predictedWordsTextBox, writingObserver);
            MessagesInterpreter.Initialize(connectedComponentsTool, writingObserver);

            Logger.LogInfo("app started");

            this.FormClosed += Form1_FormClosed;

            this.drawPanelPublic           = this.drawPanel;
            drawPanelPaintEventHandler     = new PaintEventHandler(this.drawPanel_Paint);
            drawPanelMouseUpEventHandler   = new MouseEventHandler(this.drawPanel_MouseUp);
            drawPanelMouseMoveEventHandler = new MouseEventHandler(this.drawPanel_MouseMove);
            drawPanelMouseDownEventHandler = new MouseEventHandler(this.drawPanel_MouseDown);

            ApplicationUseManager appUseManagerInstance = ApplicationUseManager.Instance;

            appUseManagerInstance.Initialize(this);
            appUseManagerInstance.TriggerApplicationNotReady();

            ConnectionManager.StartListeningToConnections();
            // !!!!!!!!!!!!!!!!!!!!!!!!!  LET THE CLIENT START ALONG WITH THE MAIN APP!!!!!!!!!!!!!!
            ApplicationStarter.StartPythonClientFromStartingPoint();

            m_connectedComponents  = new List <ConnectedComponent>();
            this.m_auxiliaryBitmap = new Bitmap(drawPanel.Width, drawPanel.Height, drawPanel.CreateGraphics());
            Graphics.FromImage(m_auxiliaryBitmap).Clear(Color.White);
            connectedComponentsTool.Initialize(m_auxiliaryBitmap);
        }
Exemple #6
0
        public ActionResult Delete(int id)
        {
            Debug($"Get ~/Administration/Customer/Delete(id={id})");

            // Only for administrator from the first customer (Syncytium)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user) || user.CustomerId != 1)
            {
                return(HttpNotFound());
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            // get the current customer

            CustomerViewModel viewModel = new CustomerViewModel(ressources, user, _userManager.Database.Customer.Find(id));

            if (viewModel.Customer == null)
            {
                return(HttpNotFound());
            }

            return(View(viewModel));
        }
Exemple #7
0
        public ActionResult Index()
        {
            Debug("Get ~/Administration/Customer/Index()");

            // Only for administrator from the first customer (Syncytium)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user) || user.CustomerId != 1)
            {
                return(HttpNotFound());
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            // load all existing customers

            CustomerViewModel viewModel = new CustomerViewModel(ressources, user);

            foreach (CustomerRecord customer in _userManager.Database.Customer)
            {
                viewModel.Customers.Add(customer);
            }

            return(View("Index", viewModel));
        }
Exemple #8
0
        /// <summary>
        /// Send an email on asking a new password
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public UserRecord SendNewPassword(string login)
        {
            // ask for a new password due to forget password

            try
            {
                UserRecord user = _userManager.AskNewPassword(login);

                // read the multilingual dictionary

                LanguageDictionary ressources = new LanguageDictionary(Server?.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);
                ressources.Load(_userManager.Database, user.CustomerId);

                // Send an email to the user within a link towards the new password page

                MailMessage message = new MailMessage();
                message.To.Add(new MailAddress(user.Email));
                message.Subject = ressources.GetLabel(user.Language, "USER_NEW_PASSWORD");

                string body;
                // TODO: Replace this code by a render HTML
                UserViewModel Model = new UserViewModel(ressources, user, false);
                // message.Body = RenderManager.RenderView("~/Areas/Administration/Views/User/MailNewPassword.cshtml", new UserViewModel(ressources, user, false));
                body =
                    $"<center><img src=\"{Model.UrlRoot}Content/Images/Areas/Administration/User/MailNewPassword/Logo.png\" width=\"200px\" height=\"50px\"/></center>" +
                    "<p>" +
                    "Pour réinitialiser le mot de passe, veuillez cliquer sur le lien suivant:" +
                    "<ul>" +
                    $"<li><a href=\"{Model.UrlRoot}Administration/User/NewPassword?key={Model.UserProfile.NewPasswordKey}\">Réinitialisation du mot de passe</a></li>" +
                    $"<li>Identifiant : {Model.UserProfile.Login}</li>";
                if (Model.Mode != "PROD")
                {
                    body += $"<li>Instance : <a href=\"{Model.UrlRoot}\">{Model.UrlRoot}</a></li>";
                    body += $"<li>Mode : {Model.Mode}</li>";
                }
                body += "</ul></p>";

                message.Body         = body;
                message.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
                message.IsBodyHtml   = true;

                using (var smtp = new SmtpClient())
                    smtp.Send(message);

                return(user);
            }
            catch (System.Exception ex)
            {
                Exception($"An exception occurs on asking for a new password due to {ex.Message}", ex);
                return(null);
            }
        }
Exemple #9
0
        /// <summary>
        /// URL ~/Administration/User/NewPassword?key
        /// </summary>
        /// <param name="key">Key of the asking of changing password</param>
        /// <returns></returns>
        public ActionResult NewPassword(string key)
        {
            Debug($"Get ~/Administration/User/NewPassword({key})");

            if (key == null)
            {
                return(HttpNotFound());
            }

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            // Look for the new password key

            UserRecord user = _userManager.Database.User.FirstOrDefault(u => u.NewPasswordKey.Equals(key));

            if (user == null)
            {
                return(HttpNotFound());
            }

            if (user.NewPasswordDate == null)
            {
                Info($"No date for asking a new password for the key '{key}' ...");
                user.NewPasswordDate = null;
                _userManager.Database.SaveChanges();
                return(HttpNotFound());
            }

            // Check if the max days expiricy is not reached

            if ((DateTime.Now - user.NewPasswordDate.Value).TotalDays > ConfigurationManager.ConnectionMaxWaiting)
            {
                Info($"The date for setting a new password has expired for the key '{key}' ...");
                user.NewPasswordDate = null;
                user.NewPasswordKey  = null;
                _userManager.Database.SaveChanges();
                return(HttpNotFound());
            }

            // Open the new password screen

            ressources.Load(_userManager.Database, 1);

            return(View(new UserViewModel(ressources, new UserRecord(), false)));
        }
Exemple #10
0
        /// <summary>
        /// URL ~/Administration/User/ForgetPassword
        /// </summary>
        /// <returns></returns>
        public ActionResult ForgetPassword()
        {
            Debug("Get ~/Administration/User/ForgetPassword()");

            // if the user is authenticated, redirect to ~/Administration/User/Index

            if (HttpContext.User.Identity.IsAuthenticated)
            {
                Debug($"The current user '{HttpContext.User.Identity.Name}' is still authenticated ... go directly to Index");
                return(RedirectToAction("Index"));
            }

            // the user exists

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, 1);

            return(View(new UserViewModel(ressources, new UserRecord(), false)));
        }
Exemple #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Loading dictionary (will take a while)");
            LanguageDictionary dic = LanguageDictionaryFactory.fromGCIDE_XML();

            Console.WriteLine("Done.");
            Console.WriteLine(dic.Count() + " words imported.");
            Console.WriteLine();

            string fileName = "English.dic";

            Console.WriteLine("Saving file: " + fileName);
            dic.Save(fileName);
            Console.WriteLine();

            Console.WriteLine("Loading file: " + fileName);
            LanguageDictionary engLoad = LanguageDictionary.Load(fileName);

            Console.WriteLine(engLoad.Count() + " words loaded.");
            Console.WriteLine();

            string checkFileName = "English2.dic";

            Console.WriteLine("Comparing saved loaded file against original.");
            engLoad.Save(checkFileName);
            if (File.ReadAllText(fileName) == File.ReadAllText(checkFileName))
            {
                Console.WriteLine("\tSucsess");
            }
            else
            {
                Console.WriteLine("\tFailed");
            }
            Console.WriteLine();
            dic.Save(@"X:\Programming\Resources\dictionaries\English.dic");

            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
        }
Exemple #12
0
        /// <summary>
        /// URL ~/Administration/User/SignIn
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public ActionResult SignIn(string returnUrl, string error)
        {
            Debug($"Get ~/Administration/User/SignIn({returnUrl}, {error})");

            if (StatusManager.Status == StatusManager.EStatus.STATUS_OK)
            {
                // if the user is authenticated, redirect to ~/Administration/User/Index

                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    Debug($"The current user '{HttpContext.User.Identity.Name}' is already authenticated ... go directly to Index");
                    return(RedirectToAction("Index"));
                }

                // the user doesn't exist, create an empty user

                LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);
                ressources.Load(_userManager.Database, 1);

                if (!String.IsNullOrWhiteSpace(error))
                {
                    SetModelState(ModelState, ressources, new Errors(error));
                }

                // Show the SignIn screen

                return(View(new UserViewModel(ressources,
                                              new UserRecord(),
                                              HttpContext.User.Identity.IsAuthenticated)));
            }

            if (StatusManager.Status == StatusManager.EStatus.STATUS_UPGRADING)
            {
                // The database must be upgraded before continuing ... only the administrator defined into web.config has the ability to connect to the application

                if (HttpContext.User.Identity.IsAuthenticated && HttpContext.User.Identity.Name.Equals("-1"))
                {
                    Debug("A upgrading process must be run ...");

                    return(View("Upgrading", new UserViewModel(new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage),
                                                               UserRecord.CreateDefaultAdministrator(),
                                                               true)));
                }

                // If it's another user, sign out the current user ...

                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    Debug($"The current user '{HttpContext.User.Identity.Name}' is already authenticated and its session can't be open due to the upgrading process");
                    FormsAuthentication.SignOut();
                }

                // Set ressources within default value for some screen

                Debug("Only the default administrator is allowed to connect to the application");

                return(View("SignInAdministration", new UserViewModel(new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage),
                                                                      new UserRecord(),
                                                                      HttpContext.User.Identity.IsAuthenticated)));
            }

            return(HttpNotFound());
        }
Exemple #13
0
        public ActionResult NewPassword(string key, string login, string newPassword1, string newPassword2)
        {
            Debug($"Post ~/Administration/User/NewPassword({login}, {key})");

            bool loginIncorrect = false;

            // read the multilingual dictionary

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, 1);

            // check the value by itself

            Errors errors = new Errors();

            if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{USER_LOGIN}" });
            }
            else
            {
                // Check if the login exists ...

                UserRecord user = _userManager.GetByLogin(login, false);
                if (user == null || String.IsNullOrEmpty(user.NewPasswordKey) || !user.NewPasswordKey.Equals(key))
                {
                    loginIncorrect = true;
                    errors.AddGlobal("ERR_LOGIN_INCORRECT");
                }
            }

            if (string.IsNullOrWhiteSpace(newPassword1))
            {
                errors.AddField("NewPassword1", "ERR_FIELD_REQUIRED", new object[] { "{USER_NEW_PASSWORD}" });
            }

            if (string.IsNullOrWhiteSpace(newPassword2))
            {
                errors.AddField("NewPassword2", "ERR_FIELD_REQUIRED", new object[] { "{USER_RETYPE_PASSWORD}" });
            }

            if (!loginIncorrect &&
                !string.IsNullOrWhiteSpace(newPassword1) &&
                !string.IsNullOrWhiteSpace(newPassword2) &&
                !newPassword1.Equals(newPassword2))
            {
                errors.AddGlobal("ERR_LOGIN_INCORRECT");
            }

            if (errors.HasError)
            {
                SetModelState(ModelState, ressources, errors);
                return(View(new UserViewModel(ressources, new UserRecord(), false)));
            }

            // Update the password

            try
            {
                _userManager.SetNewPassword(login, newPassword1);
            }
            catch (System.Exception ex)
            {
                Error($"An exception occurs on updating the password: {ex.Message}");
            }

            // Sign out the user and resign the user

            FormsAuthentication.SignOut();
            return(RedirectToAction("SignIn"));
        }
Exemple #14
0
        public ActionResult SignIn(string login, string password, bool?rememberMe, string returnUrl)
        {
            // TODO : Nettoyage des traces de cette fonction lors de la résolution de l'anomalie #248

            Debug($"Post ~/Administration/User/SignIn({login}, {password}, {rememberMe}, {returnUrl})");

            // check the value by itself

            Errors errors = new Errors();

            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                Debug($"Login '{login}' or password '{password}' not defined !");

                // no login set

                if (string.IsNullOrWhiteSpace(login))
                {
                    errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{USER_LOGIN}" });
                }

                // no password set

                if (string.IsNullOrWhiteSpace(password))
                {
                    errors.AddField("Password", "ERR_FIELD_REQUIRED", new object[] { "{USER_PASSWORD}" });
                }
            }
            else if (StatusManager.Status == StatusManager.EStatus.STATUS_OK)
            {
                Debug($"Status '{StatusManager.Status}' is OK !");

                // authentication of the user

                UserRecord userAuthenticated = _userManager.Authenticate(login, password);

                if (userAuthenticated != null)
                {
                    FormsAuthentication.SetAuthCookie(userAuthenticated.Id.ToString(), (rememberMe != null && rememberMe.Value));

                    Debug("Authentication OK");

                    if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }

                    return(RedirectToAction("Index"));
                }

                errors.AddGlobal("ERR_LOGIN_INCORRECT");
            }
            else
            {
                Debug($"Status '{StatusManager.Status}' is not OK !");

                // it is due to a upgrading process ... no error because StatusFilterAttribute has already rejected the action

                UserRecord administrator = UserRecord.CreateDefaultAdministrator();

                if (administrator.Login.Equals(login) && administrator.Password.Equals(password))
                {
                    FormsAuthentication.SetAuthCookie(administrator.Id.ToString(), false);
                    return(View("Upgrading", new UserViewModel(new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage),
                                                               administrator,
                                                               true)));
                }

                errors.AddGlobal("ERR_LOGIN_INCORRECT");
            }

            Debug("Authentication fail");

            // load multilingual dictionary

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            if (StatusManager.Status == StatusManager.EStatus.STATUS_OK)
            {
                using (DatabaseContext database = new DatabaseContext())
                    ressources.Load(database, 1);
            }

            // update ModelState on depends on errors

            SetModelState(ModelState, ressources, errors);

            // show the same screen until the user success

            if (StatusManager.Status == StatusManager.EStatus.STATUS_UPGRADING)
            {
                return(View("SignInAdministration", new UserViewModel(ressources,
                                                                      new UserRecord {
                    Login = login, Password = password
                },
                                                                      false,
                                                                      null,
                                                                      rememberMe: rememberMe != null && rememberMe.Value)));
            }

            return(View(new UserViewModel(ressources,
                                          new UserRecord {
                Login = login, Password = password
            },
                                          false,
                                          null,
                                          rememberMe: rememberMe != null && rememberMe.Value)));
        }
Exemple #15
0
        public ActionResult Update(int id, string name, string login, string email, string address, string comment)
        {
            Debug($"Get ~/Administration/Customer/Update(id={id}, name={name}, login={login}, email={email}, address={address}, comment={comment})");

            // Only for administrator from the first customer (Syncytium)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user) || user.CustomerId != 1)
            {
                return(HttpNotFound());
            }

            // The customer has to exist

            CustomerRecord customer = _userManager.Database.Customer.Find(id);

            if (customer == null)
            {
                return(HttpNotFound());
            }

            // check the value by itself

            Errors errors = new Errors();

            // no name set

            if (string.IsNullOrWhiteSpace(name))
            {
                errors.AddField("Name", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_NAME}" });
            }
            name = name.Trim();

            // no login set

            if (string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_LOGIN}" });
            }
            login = login.Trim();

            // no email set

            if (string.IsNullOrWhiteSpace(email))
            {
                errors.AddField("Email", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_EMAIL}" });
            }
            email = email.Trim();

            // check if the name already exists

            if (_userManager.Database.Customer.Where(c => c.Name.Equals(name) && c.Id != customer.Id).Any())
            {
                errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_NAME}" });
            }

            if (!customer.Login.Equals(login))
            {
                // check if the new login already exists

                bool loginExist = false;
                foreach (UserRecord record in _userManager.Database.User.Where(u => u.Login.Equals(login) && u.CustomerId != customer.Id).ToList())
                {
                    // User deleted ?

                    InformationRecord information = _userManager.Database._Information.FirstOrDefault(info => info.Id == record.Id && info.Table.Equals("User"));
                    if (information == null || information.DeleteTick == null)
                    {
                        loginExist = true;
                        break;
                    }
                }

                if (loginExist)
                {
                    errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_LOGIN}" });
                }
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            if (errors.HasError)
            {
                // update ModelState on depends on errors

                SetModelState(ModelState, ressources, errors);
                return(View(new CustomerViewModel(ressources, user, new CustomerRecord {
                    Name = name, Login = login, Email = email, Address = address, Comment = comment
                })));
            }

            // Update the customer

            Info($"Updating the customer ({customer}) within ('{name}', '{login}', '{email}', '{address}', '{comment}') ...");

            // look for the administrator exists

            UserRecord administrator = null;

            foreach (UserRecord record in _userManager.Database.User.Where(u => u.Login.Equals(customer.Login) && u.CustomerId == customer.Id).ToList())
            {
                // User deleted ?

                InformationRecord information = _userManager.Database._Information.FirstOrDefault(info => info.Id == record.Id && info.Table.Equals("User"));
                if (information == null || information.DeleteTick == null)
                {
                    administrator = record;
                    break;
                }
            }

            bool sendEmail = false;

            if (administrator == null)
            {
                Info($"The administrator '{customer.Login}' was removed!");

                administrator = new UserRecord()
                {
                    Login        = login,
                    Registration = name,
                    Name         = name,
                    Email        = email,
                    Language     = user.Language,
                    CustomerId   = customer.Id
                };
                Info($"Creating a new administrator {administrator} ...");

                _userManager.Database.User.Add(administrator);
                _userManager.Database.SaveChanges();

                sendEmail = true;
            }
            else if (!administrator.Login.Equals(login) || !administrator.Email.Equals(email))
            {
                Info($"The administrator '{administrator}' has to be updated!");

                if (!administrator.Login.Equals(login))
                {
                    administrator.Login = login;
                }

                if (administrator.Registration.Equals(customer.Name))
                {
                    administrator.Registration = name;
                }

                if (administrator.Name.Equals(customer.Name))
                {
                    administrator.Name = name;
                }

                if (!administrator.Email.Equals(email))
                {
                    administrator.Email = email;
                    sendEmail           = administrator.Password == null;
                }

                _userManager.Database.SaveChanges();

                Info($"The administrator '{administrator}' is updated!");
            }
            else
            {
                Debug($"The administrator {administrator} doesn't change");
            }

            // check if the administration module is defined and assigned to the user

            ModuleRecord moduleAdministration = null;

            foreach (ModuleRecord record in _userManager.Database.Module.Where(m => m.Module == ModuleRecord.EModule.Administration &&
                                                                               m.Profile == UserProfile.EUserProfile.Administrator &&
                                                                               m.CustomerId == customer.Id).ToList())
            {
                // Module deleted ?

                InformationRecord information = _userManager.Database._Information.Find("Module", record.Id);

                if (information != null && information.IsDeleted)
                {
                    continue;
                }

                moduleAdministration = record;
                if (!moduleAdministration.Enable)
                {
                    Info($"The module administrator '{moduleAdministration}' is enabled!");
                    moduleAdministration.Enable = true;
                    _userManager.Database.SaveChanges();
                }
            }

            if (moduleAdministration == null)
            {
                Debug($"Creation of the module administrator");
                moduleAdministration = new ModuleRecord()
                {
                    Name       = "Administration",
                    Module     = ModuleRecord.EModule.Administration,
                    Profile    = UserProfile.EUserProfile.Administrator,
                    Enable     = true,
                    CustomerId = customer.Id
                };
                _userManager.Database.Module.Add(moduleAdministration);
                _userManager.Database.SaveChanges();
                Info($"Module({moduleAdministration.Id}) created");
            }

            // check if the module administration is assigned to the administrator

            UserModuleRecord userModuleAdministration = null;

            foreach (UserModuleRecord record in _userManager.Database.UserModule.Where(a => a.ModuleId == moduleAdministration.Id &&
                                                                                       a.UserId == administrator.Id &&
                                                                                       a.CustomerId == customer.Id).ToList())
            {
                // Module deleted ?

                InformationRecord information = _userManager.Database._Information.Find("UserModule", record.Id);

                if (information != null && information.IsDeleted)
                {
                    continue;
                }

                userModuleAdministration = record;
            }

            if (userModuleAdministration == null)
            {
                Debug($"Creation of the association between the user and the module administration");
                userModuleAdministration = new UserModuleRecord()
                {
                    ModuleId   = moduleAdministration.Id,
                    UserId     = administrator.Id,
                    CustomerId = customer.Id
                };
                _userManager.Database.UserModule.Add(userModuleAdministration);
                _userManager.Database.SaveChanges();
                Info($"UserModule({userModuleAdministration.Id}) created");
            }

            // update the customer

            customer.Name    = name;
            customer.Login   = login;
            customer.Email   = email;
            customer.Address = address;
            customer.Comment = comment;

            _userManager.Database.SaveChanges();

            if (sendEmail)
            {
                // send a mail for the new user

                Info($"Sending an email to create the password ...");

                using (UserController controller = new UserController(_userManager))
                    controller.SendNewPassword(administrator.Login);
            }

            Info($"Customer updated ...");

            return(RedirectToAction("Index"));
        }
Exemple #16
0
        public ActionResult Add(string name, string login, string email, string address, string comment)
        {
            Debug($"Get ~/Administration/Customer/Add(name={name}, login={login}, email={email}, address={address}, comment={comment})");

            // Only for administrator from the first customer (Syncytium)

            if (!(_userManager.GetById(int.Parse(HttpContext.User.Identity.Name)) is UserRecord user) || user.CustomerId != 1)
            {
                return(HttpNotFound());
            }

            // check the value by itself

            Errors errors = new Errors();

            // no name set

            if (string.IsNullOrWhiteSpace(name))
            {
                errors.AddField("Name", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_NAME}" });
            }
            name = name.Trim();

            // no login set

            if (string.IsNullOrWhiteSpace(login))
            {
                errors.AddField("Login", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_LOGIN}" });
            }
            login = login.Trim();

            // no email set

            if (string.IsNullOrWhiteSpace(email))
            {
                errors.AddField("Email", "ERR_FIELD_REQUIRED", new object[] { "{CUSTOMER_EMAIL}" });
            }
            email = email.Trim();

            // check if the name already exists

            if (_userManager.Database.Customer.Where(c => c.Name.Equals(name)).Any())
            {
                errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_NAME}" });
            }

            // check if the login already exists

            bool loginExist = false;

            foreach (UserRecord record in _userManager.Database.User.Where(u => u.Login.Equals(login)).ToList())
            {
                // User deleted ?

                InformationRecord information = _userManager.Database._Information.FirstOrDefault(info => info.Id == record.Id && info.Table.Equals("User"));
                if (information == null || information.DeleteTick == null)
                {
                    loginExist = true;
                    break;
                }
            }

            if (loginExist)
            {
                errors.AddField("Name", "ERR_FIELD_UNIQUE", new object[] { "{CUSTOMER_LOGIN}" });
            }

            // load ressources before designing the screen fitted to the user's profile

            LanguageDictionary ressources = new LanguageDictionary(Server.MapPath(LanguageDictionary.DIRECTORY_IMAGE), ConfigurationManager.DefaultLanguage);

            ressources.Load(_userManager.Database, user.CustomerId);

            if (errors.HasError)
            {
                // update ModelState on depends on errors

                SetModelState(ModelState, ressources, errors);
                return(View(new CustomerViewModel(ressources, user)));
            }

            // Create a new customer

            Info($"Creating of a new customer ('{name}', '{login}', '{email}', '{address}', '{comment}') ...");

            CustomerRecord newCustomer = new CustomerRecord()
            {
                Name    = name,
                Login   = login,
                Email   = email,
                Address = address,
                Comment = comment
            };

            _userManager.Database.Customer.Add(newCustomer);
            _userManager.Database.SaveChanges();

            Info($"Customer created {newCustomer}");

            // Add the parameter "Language.Tick.<customerId>" into the parameter table

            _userManager.Database._Parameter.Add(new ParameterRecord()
            {
                Key = $"Language.Tick.{newCustomer.Id}", Value = "0"
            });

            // Duplicate multilanguage dictionary (from the customer 1 to the new one)

            Info($"Duplicating multilanguage labels ...");

            int nbLabels = 0;

            foreach (LanguageRecord languageRecord in _userManager.Database.Language.Where(l => l.CustomerId == 1).ToList())
            {
                LanguageRecord newLanguageRecord = LanguageRecord.Copy(languageRecord) as LanguageRecord;
                newLanguageRecord.CustomerId = newCustomer.Id;
                _userManager.Database.Language.Add(newLanguageRecord);
                nbLabels++;
            }

            Info($"{nbLabels} labels duplicated");

            // Create the administrator for this new customer

            UserRecord newUser = new UserRecord()
            {
                Login        = login,
                Registration = name,
                Name         = name,
                Email        = email,
                Language     = user.Language,
                CustomerId   = newCustomer.Id
            };

            _userManager.Database.User.Add(newUser);
            _userManager.Database.SaveChanges();
            Info($"Creating a new user {newUser} ...");

            ModuleRecord newModule = new ModuleRecord()
            {
                Name       = "Administration",
                Module     = ModuleRecord.EModule.Administration,
                Profile    = UserProfile.EUserProfile.Administrator,
                Enable     = true,
                CustomerId = newCustomer.Id
            };

            _userManager.Database.Module.Add(newModule);
            _userManager.Database.SaveChanges();
            Info($"Module({newModule.Id}) created");

            UserModuleRecord newUserModule = new UserModuleRecord()
            {
                UserId     = newUser.Id,
                ModuleId   = newModule.Id,
                Default    = true,
                CustomerId = newCustomer.Id
            };

            _userManager.Database.UserModule.Add(newUserModule);
            _userManager.Database.SaveChanges();
            Info($"UserModule({newUserModule.Id}) created");

            // send a mail for the new user

            Info($"Sending an email to create the password ...");

            using (UserController controller = new UserController(_userManager))
                controller.SendNewPassword(newUser.Login);

            Info($"Customer created ...");

            return(RedirectToAction("Index"));
        }