private Data.Registration _Map(Models.Registration registration)
        {
            var data = new Data.Registration
            {
                ID       = registration.ID,
                User_ID  = registration.User_ID,
                Event_ID = registration.Event_ID,
                Type     = registration.Type
            };

            return(data);
        }
        private Models.Registration _Map(Data.Registration source)
        {
            var model = new Models.Registration
            {
                ID       = source.ID,
                User_ID  = source.User_ID,
                Event_ID = source.Event_ID,
                Type     = source.Type
            };

            return(model);
        }
        private async Task SendPasswordResetEmail(string email, Data.Registration user)
        {
            string url  = Url.Action(nameof(FinalizeResetPassword), "Login", new { id = user.Id, secret = user.PasswordResetSecret });
            string link = Environment.GetEnvironmentVariable("BASE_URL") + url;

            Logger.LogTrace(LoggingEvents.Email, "Destination URL {0}, final link {1}", url, link);

            using (var client = new SmtpClient()) {
                var credentials = new NetworkCredential(
                    Environment.GetEnvironmentVariable("SMTP_USERNAME"),
                    Environment.GetEnvironmentVariable("SMTP_PASSWORD")
                    );

                client.EnableSsl      = true;
                client.Host           = Environment.GetEnvironmentVariable("SMTP_HOST");
                client.Port           = Convert.ToInt32(Environment.GetEnvironmentVariable("SMTP_PORT"));
                client.Credentials    = credentials;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Timeout        = 5000;

                Logger.LogTrace(LoggingEvents.Email, "SMTP host {0}:{1} username {2} SSL {3}", client.Host, client.Port, credentials.UserName, client.EnableSsl);

                var noReplyAddress = new MailAddress(Environment.GetEnvironmentVariable("MAIL_FROM"), "CodeMOOC.net");
                var msg            = new MailMessage {
                    From       = noReplyAddress,
                    Subject    = "Richiesta nuova password",
                    IsBodyHtml = false,
                    Body       = $"Ciao {user.Name}!\n\nHai richiesto che la tua password di accesso a CodeMOOC.net sia reimpostata. Per proseguire con la procedura, ti preghiamo di cliccare sul seguente collegamento:\n{link}\n\nA presto!\nCodeMOOC.net"
                };
                msg.To.Add(new MailAddress(email, $"{user.Name} {user.Surname}"));
                if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CONFIRMATION_MAIL_BCC")))
                {
                    msg.Bcc.Add(Environment.GetEnvironmentVariable("CONFIRMATION_MAIL_BCC"));
                }
                msg.ReplyToList.Add(noReplyAddress);

                Logger.LogTrace(LoggingEvents.Email, "Sending e-mail");

                try {
                    await client.SendMailAsync(msg);
                }
                catch (Exception ex) {
                    Logger.LogError(LoggingEvents.Email, ex, "Failed to send e-mail");
                }

                Logger.LogDebug(LoggingEvents.Email, "E-mail sent");
            }
        }
Example #4
0
        private async Task SendConfirmationEmail(Data.Registration user, Data.Email email)
        {
            string url  = Url.Action(nameof(Validate), "Register", new { id = user.Id, secret = user.ConfirmationSecret });
            string link = Environment.GetEnvironmentVariable("BASE_URL") + url;

            Logger.LogTrace(LoggingEvents.Email, "Destination URL {0}, final link {1}", url, link);

            using (var client = new SmtpClient()) {
                var credentials = new NetworkCredential(
                    Environment.GetEnvironmentVariable("SMTP_USERNAME"),
                    Environment.GetEnvironmentVariable("SMTP_PASSWORD")
                    );

                client.EnableSsl      = true;
                client.Host           = Environment.GetEnvironmentVariable("SMTP_HOST");
                client.Port           = Convert.ToInt32(Environment.GetEnvironmentVariable("SMTP_PORT"));
                client.Credentials    = credentials;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Timeout        = 5000;

                Logger.LogTrace(LoggingEvents.Email, "SMTP host {0}:{1} username {2} SSL {3}", client.Host, client.Port, credentials.UserName, client.EnableSsl);

                var noReplyAddress = new MailAddress(Environment.GetEnvironmentVariable("MAIL_FROM"), "CodeMOOC.net");
                var msg            = new MailMessage {
                    From       = noReplyAddress,
                    Subject    = "Verifica indirizzo e-mail",
                    IsBodyHtml = false,
                    Body       = $"Ciao {user.Name} {user.Surname}!\n\nGrazie per esserti registrato/a su CodeMOOC.net. Ti preghiamo di verificare il tuo indirizzo e-mail cliccando sul seguente link:\n{link}\n\nA presto!\nCodeMOOC.net"
                };
                msg.To.Add(new MailAddress(email.Address, $"{user.Name} {user.Surname}"));
                if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CONFIRMATION_MAIL_BCC")))
                {
                    msg.Bcc.Add(Environment.GetEnvironmentVariable("CONFIRMATION_MAIL_BCC"));
                }
                msg.ReplyToList.Add(noReplyAddress);

                Logger.LogTrace(LoggingEvents.Email, "Sending e-mail");

                try {
                    await client.SendMailAsync(msg);
                }
                catch (Exception ex) {
                    Logger.LogError(LoggingEvents.Email, ex, "Failed to send e-mail");
                }

                Logger.LogDebug(LoggingEvents.Email, "E-mail sent");
            }
        }
Example #5
0
        public void Load(bool useConfig, Guid?objectID, Guid?userID, Guid?communityID, int objectType, int[] objectTypes, List <TagWord> tagWords, Guid currentUserID, bool global)
        {
            ConfigurationList listConfig = new ConfigurationList();

            listConfig.Load(rootFolder);
            user.Load();

            if (useConfig)
            {
                RegistrationDefaultList listDefault = new RegistrationDefaultList(currentUserID, currentRoles, rootFolder);
                listDefault.Load();

                foreach (KeyValuePair <EventIdentifier, Configuration> kvp in listConfig)
                {
                    Configuration itemConfig = kvp.Value;
                    if (!itemConfig.IsEventAvailably(objectType, global))
                    {
                        continue;
                    }

                    Role itemRole = itemConfig.FindRole(currentRoles);
                    if (itemRole == null)
                    {
                        continue;
                    }

                    if (itemRole.Range == ObjectRange.MyObject && this.currentUserID != currentUserID)
                    {
                        continue;
                    }

                    RegistrationDefault itemDefault = listDefault.Item(kvp.Key);

                    Registration itemReg = new Registration(currentUserID);
                    itemReg.IsGlobal   = global;
                    itemReg.Identifier = itemConfig.Identifier;
                    foreach (CarrierType soll in itemRole.CarrierTypes)
                    {
                        Carrier itemCarr = new Carrier(itemReg.Carriers);
                        itemCarr.Type      = soll;
                        itemCarr.Availably = user.Carriers.Item(soll).IsValid;

                        if (itemDefault != null)
                        {
                            Carrier itemCarrDefault = itemDefault.Carriers.Item(soll);
                            if (itemCarrDefault != null)
                            {
                                itemCarr.Checked = itemCarrDefault.Checked;
                                itemCarr.Collect = itemCarrDefault.Collect;
                            }
                        }

                        itemReg.Carriers.Add(itemCarr);
                    }

                    foreach (ObjType itemObjectType in itemConfig.ObjTypes)
                    {
                        ObjType objType = new ObjType(itemReg.ObjectTypeList, itemObjectType.Identifier);
                        if (!itemConfig.IsObjectTypeAvailably(itemObjectType.Identifier, global))
                        {
                            objType.Availably = false;
                        }
                        else if (!global && itemObjectType.Identifier != objectType)
                        {
                            objType.Availably = false;
                        }

                        itemReg.ObjectTypeList.Add(objType);
                    }
                    itemReg.ObjectTypeList.SetChecked(itemReg.ObjectTypeList.GetChecked());

                    this.Add(itemReg);
                }
            }

            Data.Registration objData = new Data.Registration();
            objData.Load(useConfig, this, currentUserID, objectID, userID, communityID, objectTypes, tagWords, global);
        }
Example #6
0
 public void Save()
 {
     Data.Registration objData = new Data.Registration();
     objData.Save(this);
 }
Example #7
0
 public static bool HasLocalRegistration(string userID, string objectID)
 {
     Data.Registration objData = new Data.Registration();
     return(objData.HasRegistration(userID, objectID, false));
 }
Example #8
0
        // Returns the view of all of the events the user is registered for.
        public EventsViewModels RegisterUserForEvent(Container_Classes.Event containerEvent, Container_Classes.User containerUser)
        {
            int foodID = int.Parse(containerUser.Foods);

            // Get the food ID from the database using the containerUser object
            Data.Food dataFood = _repository.Get <Data.Food>(x => x.FoodID == foodID);
            // Ensure that we found the food in the database
            if (dataFood == null)
            {
                return(null);
            }

            // Ensure that the user exists in the database
            Data.User dataUser = Container_Classes.User.UserToDataUser(containerUser, dataFood.FoodID);
            dataUser = _repository.Get <Data.User>(x => x.UserID == dataUser.UserID);

            if (dataUser == null)
            {
                // The user was not found in the database
                return(null);
            }

            // Grab the Category and type from the database so we can read an event from the database
            Data.Category dataCategory = _repository.Get <Data.Category>(x => x.Category1.Equals(containerEvent.Category));
            if (dataCategory == null)
            {
                // We could not find the category in the database
                return(null);
            }

            Data.Type dataType = _repository.Get <Data.Type>(x => x.Type1.Equals(containerEvent.Type));
            if (dataType == null)
            {
                // We could not find the type in the database
                return(null);
            }

            // Ensure that the event exists in the database
            Data.Event dataEvent = Container_Classes.Event.ContainerEventToDataEvent(containerEvent, dataCategory.CategoryID, dataType.TypeID, dataUser.UserID);
            dataEvent = _repository.Get <Data.Event>(x => x.EventID == dataEvent.EventID);

            if (dataEvent == null)
            {
                // The user was not found in the database
                return(null);
            }

            // Prepare the information to be updated in the database
            Data.Registration registration = new Data.Registration();
            registration.User_ID  = dataUser.UserID;
            registration.Event_ID = dataEvent.EventID;

            // Add the registration to the database
            _repository.Add <Data.Registration>(registration);

            _repository.SaveChanges();

            // Get all of the users registered events
            List <Data.Registration> registrations = DatabaseToDataRegistration(_repository.GetAll <Data.Registration>(x => x.User_ID == dataUser.UserID));
            List <Data.Event>        dataEvents    = new List <Data.Event>();

            // Create a list of all events this user is attending
            foreach (Data.Registration dataRegistration in registrations)
            {
                dataEvents.Add(_repository.Get <Data.Event>(x => x.EventID == dataRegistration.Event_ID));
            }

            // Conver the list of dataEvents to containerEvents
            List <Container_Classes.Event> containerEvents = new List <Container_Classes.Event>();

            foreach (Data.Event dataEvent2 in dataEvents)
            {
                dataType     = _repository.Get <Data.Type>(x => x.TypeID == dataEvent2.Type_ID);
                dataCategory = _repository.Get <Data.Category>(x => x.CategoryID == dataEvent2.Category_ID);
                containerEvents.Add(Container_Classes.Event.DataEventToContainerEvent(dataEvent2, dataUser.UserID, dataCategory.Category1, dataType.Type1));
            }

            EventsViewModels model = new EventsViewModels();

            model.Events = containerEvents;

            return(model);
        }
Example #9
0
        public async Task <IActionResult> Process(RegistrationViewModel model, [FromForm(Name = "g-recaptcha-response")] string recaptchaResponse)
        {
            Logger.LogInformation(LoggingEvents.Registration, "Received registration request");

            // Check e-mail
            if (!string.IsNullOrWhiteSpace(model.Email))
            {
                var existingMailUser = (from e in Database.Emails
                                        where e.Address == model.Email.ToLowerInvariant()
                                        select e).SingleOrDefault();
                if (existingMailUser != null)
                {
                    Logger.LogInformation(LoggingEvents.Registration, "E-mail already registered");
                    ModelState.AddModelError(nameof(RegistrationViewModel.Email), "Indirizzo e-mail già registrato");
                }
            }

            // Check fiscal code
            if (!string.IsNullOrWhiteSpace(model.FiscalCode))
            {
                var existingCodeUser = (from r in Database.Registrations
                                        where r.FiscalCode == model.FiscalCode.ToUpperInvariant()
                                        where r.ConfirmationTimestamp != null
                                        select r).SingleOrDefault();
                if (existingCodeUser != null)
                {
                    Logger.LogInformation(LoggingEvents.Registration, "Fiscal code already registered");
                    ModelState.AddModelError(nameof(RegistrationViewModel.FiscalCode), "Codice fiscale già registrato");
                }
            }

            // Check birthday
            if (!DateTime.TryParseExact(model.Birthday, "dd-MM-yyyy", new CultureInfo("it-IT"), DateTimeStyles.AssumeLocal, out var birthday))
            {
                Logger.LogInformation(LoggingEvents.Registration, "Birthday {0} not valid", model.Birthday);
                ModelState.AddModelError(nameof(RegistrationViewModel.Birthday), "Inserire data di nascita nel formato GG-MM-AAAA");
            }

            // Check ReCaptcha
            Logger.LogTrace(LoggingEvents.Registration, "Checking ReCaptcha token");
            var rest    = new RestClient("https://www.google.com/recaptcha/api/siteverify");
            var restReq = new RestRequest(Method.POST);

            restReq.AddParameter("response", recaptchaResponse);
            restReq.AddParameter("secret", Environment.GetEnvironmentVariable("GOOGLE_RECAPTCHA_SECRET"));
            var recaptchaResult = rest.Execute <ReCaptchaResponse>(restReq);

            if (!recaptchaResult.IsSuccessful || !recaptchaResult.Data.Success)
            {
                Logger.LogInformation(LoggingEvents.Registration, "ReCaptcha verification failed");
                ModelState.AddModelError("ReCaptcha", "Attiva il controllo anti-spam ReCaptcha");

                return(View("Create", model));
            }
            Logger.LogDebug(LoggingEvents.Registration, "ReCaptcha verification succeeded for hostname {0}", recaptchaResult.Data.Hostname);

            // Final validity check
            if (!ModelState.IsValid)
            {
                Logger.LogDebug(LoggingEvents.Registration, "Model binding failed");

                return(View("Create", model));
            }

            Logger.LogDebug("Input validated, proceeding with registration");
            var hashedPassword = BCrypt.Net.BCrypt.EnhancedHashPassword(model.Password);

            var user = new Data.Registration {
                Name                  = model.Name.Trim(),
                Surname               = model.Surname.Trim(),
                Birthday              = birthday.Date,
                Birthplace            = model.Birthplace,
                FiscalCode            = model.FiscalCode.ToUpperInvariant(),
                AddressStreet         = model.AddressStreet,
                AddressCity           = model.AddressCity,
                AddressCap            = model.AddressCap,
                AddressCountry        = model.AddressCountry,
                PasswordSchema        = "bcrypt.net", // hard-coded to hash function
                PasswordHash          = hashedPassword,
                Category              = model.Category,
                HasAttendedMooc       = model.HasAttendedMooc,
                HasCompletedMooc      = model.HasCompletedMooc,
                RegistrationTimestamp = DateTime.UtcNow,
                ConfirmationSecret    = Startup.GenerateSecret()
            };

            Database.Registrations.Add(user);

            var email = new Data.Email {
                Address              = model.Email.Trim().ToLowerInvariant(),
                IsPrimary            = true,
                AssociationTimestamp = user.RegistrationTimestamp,
                Registration         = user
            };

            Database.Emails.Add(email);

            int changes = Database.SaveChanges();

            if (changes != 2)
            {
                throw new InvalidOperationException("Expected changes equal to 2 when registering user");
            }

            await SendConfirmationEmail(user, email);

            // Confirmation view
            ViewData["email"] = email.Address;
            return(View("Confirm"));
        }