public IHttpResponse Register(IHttpRequest req) { //slagame imenata na inputite ot formata v konstanti zashtoto po dobre const string formNameKey = "name"; const string formUsernameKey = "username"; const string formPasswordKey = "password"; const string formConfirmPasswordKey = "confirmpassword"; //Proverqvame dali FormData sudurja nashite kluchove ot formichkata if (!req.FormData.ContainsKey(formNameKey) || !req.FormData.ContainsKey(formUsernameKey) || !req.FormData.ContainsKey(formPasswordKey) || !req.FormData.ContainsKey(formConfirmPasswordKey)) { RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } //AKO GI IMA TRQBVA DA SUZDADEM USER V BAZATA DANNI. //Vzimame si stoinostite ot formichkata var name = req.FormData[formNameKey]; var username = req.FormData[formUsernameKey]; var password = req.FormData[formPasswordKey]; var confirmpassword = req.FormData[formConfirmPasswordKey]; //Proverqvame dali ne sa null ili "" if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(confirmpassword)) { //Ako e tuka slagame greshkite i se redirektvame kum /register RejectLoginAttempt(EMPTY_FIELDS_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } if (name.Length < 3 || username.Length < 3) { RejectLoginAttempt(NAME_AND_USERNAME_VALIDATION_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } //Proverqvame dali parolite suvpadat if (password != confirmpassword) { RejectLoginAttempt(PASSWORD_MATCH_ERROR_MESSAGE); return(this.FileViewResponse(@"account\register")); } //Trqbva da keshirame parolata predi da registrirame daden user User user = new User() { Name = name, Username = username, PasswordHash = PasswordUtilities.GenerateHash256(password), //keshirame parolata kato polzvame PaswordUtilities klasa DateOfRegistration = DateTime.UtcNow }; //TRQBVA DA SLOJIM USERA V BAZATA, POLZVAME KONTEXTA: using (var context = new ByTheCakeContext()) { context.Users.Add(user); context.SaveChanges(); } //Ako vsichko mine dobre, avtomatichno se logvame s imeto si kato suzdavame sesiq return(LoginUser(req, user)); }
/// <summary> /// Execute the background task /// </summary> /// <param name="context"></param> public void Run(BackgroundTaskExecuteContext context) { var logger = HostContainer.GetInstance <ILogger>(); if (Interlocked.CompareExchange(ref _hasActiveTask, 1, 0) == 0) { var countUsers = 0; try { logger.Info(string.Format("[{0}] Start account expires notification task", EzCMSContants.AccountExpiresNotificationTaskName)); //Update the background task last running time var backgroundTaskService = HostContainer.GetInstance <IEzBackgroundTaskService>(); backgroundTaskService.UpdateLastRunningTimeTask(GetType()); var userService = HostContainer.GetInstance <IUserService>(); var emailLogService = HostContainer.GetInstance <IEmailLogService>(); var emailTemplateService = HostContainer.GetInstance <IEmailTemplateService>(); var nearExpirationDateUsers = userService.GetUsersNearExpirationDate().ToList(); foreach (var user in nearExpirationDateUsers) { if (user.AccountExpiresDate.HasValue) { var authorizeCode = PasswordUtilities.EncryptString(String.Format("{0}{1}{2}", user.Id, FrameworkConstants.UniqueLinkSeparator, user.Email)); var extendExpirationDateLink = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "Account", "ExtendAccountExpiresDate", new { area = "Admin", authorizeCode = authorizeCode }, true); var model = new NotifyAccountExpiredEmailModel { FullName = user.FullName, Username = user.Username, Email = user.Email, ExpirationDate = user.AccountExpiresDate.Value, ExtendExpirationDateLink = extendExpirationDateLink }; var emailResponse = emailTemplateService.ParseEmail(EmailEnums.EmailTemplateType.AccountExpiredNotification, model); var emailLog = new EmailLog { To = user.Email, ToName = user.FullName, From = emailResponse.From, FromName = emailResponse.FromName, CC = emailResponse.CC, Bcc = emailResponse.BCC, Subject = emailResponse.Subject, Body = emailResponse.Body, Priority = EmailEnums.EmailPriority.Medium }; emailLogService.CreateEmail(emailLog, true); countUsers++; } } } catch (Exception exception) { logger.Error(exception); } logger.Info(string.Format("[{0}] End account expires notification task. Notify to {1} account(s) near expiration date", EzCMSContants.AccountExpiresNotificationTaskName, countUsers)); Interlocked.Exchange(ref _hasActiveTask, 0); } }
public static bool CheckLogin(string TenDangNhap, string MatKhau) { return(DataProvider.DataProvider.ExecuteDataReader("Select * From TAIKHOAN Where TENDANGNHAP = @1 And MATKHAU = @2", TenDangNhap, PasswordUtilities.EncodingPassword(MatKhau)).Read()); }
public IActionResult Register(RegisterUserBindingModel model) { if (this.User.IsAuthenticated) { return(this.RedirectToHome()); } if (!this.IsValidModel(model)) { this.ShowError("Invalid register details."); return(this.View()); } var username = model.Username; var password = PasswordUtilities.GetPasswordHash(model.Password); var fullName = model.FullName; var email = model.Email; if (this.Context.Users.FirstOrDefault(u => u.Username == username) != null) { this.ShowError("User already exists."); return(this.View()); } var user = new User { Username = username, Password = password, FullName = fullName, Email = email }; this.Context.Users.Add(user); this.Context.SaveChanges(); if (this.Context.Users.Count() == 1) { var admin = this.Context.Users.First(); var role = new Role { UserId = admin.Id, Name = "Admin" }; admin.Role = role; this.Context.Roles.Add(role); this.Context.SaveChanges(); } else { var notAdmin = this.Context.Users .FirstOrDefault(u => u.Username == username); var role = new Role { UserId = notAdmin.Id, Name = "User" }; this.Context.Roles.Add(role); this.Context.SaveChanges(); } var currentUser = this.Context .Users .FirstOrDefault(u => u.Username == username); var roles = this.Context .Roles .Where(r => r.UserId == currentUser.Id) .Select(r => r.Name); this.SignIn(user.Username, user.Id, roles); return(this.RedirectToHome()); }
/// <summary> /// Get authorize url /// </summary> /// <param name="clientId"></param> /// <param name="callbackUrl"></param> /// <returns></returns> public static string GetLinkedInAuthorizeUrl(string clientId, string callbackUrl) { return(string.Format(AuthorizationUrl, clientId, callbackUrl, PasswordUtilities.GetRandomString())); }
public static bool AddNewAccount(string TenDangNhap, string MatKhau, string HoTen) { return(DataProvider.DataProvider.ExecuteNonQuery("Insert into TAIKHOAN(TENDANGNHAP, MATKHAU, HOTEN) Values(@1, @2, @3)", TenDangNhap, PasswordUtilities.EncodingPassword(MatKhau), HoTen)); }
public IActionResult Register(RegisterUserBindingModel registerUserBindingModel) { if (this.User.IsAuthenticated) { return(RedirectToAction("/")); } this.Model["isAdmin"] = userIsAdmin() ? "block" : "none"; if (registerUserBindingModel.Password == "" || registerUserBindingModel.ConfirmPassword == "" || registerUserBindingModel.Username == "" || registerUserBindingModel.Email == "" || registerUserBindingModel.FullName == "") { this.Model["error"] = "Empty input fields !"; return(View()); } if (registerUserBindingModel.Password != registerUserBindingModel.ConfirmPassword) { this.Model["error"] = "Passwords must match !"; return(View()); } if (!this.IsValidModel(registerUserBindingModel)) { this.Model["error"] = "Something went wrong !"; return(View()); } var users = this.Context.Users.ToList(); Role role = this.Context.Roles.FirstOrDefault(r => r.Name == "User"); if (users.Count < 1) { role = this.Context.Roles.FirstOrDefault(r => r.Name == "Admin"); } var user = new User() { RoleId = role.Id, Email = registerUserBindingModel.Email, Username = registerUserBindingModel.Username, Password = PasswordUtilities.GenerateHash256(registerUserBindingModel.Password), FullName = registerUserBindingModel.FullName, Orders = new List <Order>() }; using (this.Context) { if (Context.Users.Any(u => u.Email == registerUserBindingModel.Email)) { this.Model["error"] = "Email is taken !"; return(View()); } if (Context.Users.Any(u => u.Username == registerUserBindingModel.Username)) { this.Model["error"] = "Username is taken !"; return(View()); } Context.Users.Add(user); Context.SaveChanges(); this.SignIn(user.Username); return(RedirectToAction("/")); } }
protected override void Seed(GymContext context) { #region Clients var passwordSalt1 = PasswordUtilities.CreateSalt(16); var password1 = PasswordUtilities.GenerateSHA256Hash("12345", passwordSalt1); var passwordSalt2 = PasswordUtilities.CreateSalt(16); var password2 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt2); var passwordSalt3 = PasswordUtilities.CreateSalt(16); var password3 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt3); var passwordSalt4 = PasswordUtilities.CreateSalt(16); var password4 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt4); var passwordSalt5 = PasswordUtilities.CreateSalt(16); var password5 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt5); var passwordSalt6 = PasswordUtilities.CreateSalt(16); var password6 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt6); var passwordSalt7 = PasswordUtilities.CreateSalt(16); var password7 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt7); var passwordSalt8 = PasswordUtilities.CreateSalt(16); var password8 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt8); var passwordSalt9 = PasswordUtilities.CreateSalt(16); var password9 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt9); var passwordSalt10 = PasswordUtilities.CreateSalt(16); var password10 = PasswordUtilities.GenerateSHA256Hash("335588", passwordSalt10); var clients = new List <Client> { new Client { FirstName = "John", LastName = "Doe", DocType = "DNI", DocNumber = 34578800, BirthDate = new DateTime(1990, 12, 31), DateFrom = new DateTime(2008, 09, 01), Email = "*****@*****.**", Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre }, new Client { FirstName = "Cristian", LastName = "Piqué", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1989, 12, 31), DateFrom = new DateTime(2008, 09, 01), Email = "*****@*****.**", Password = password2, PasswordSalt = passwordSalt2, Role = Catalog.Roles.Admin, Sexo = Catalog.Genre.Hombre }, new Client { FirstName = "José", LastName = "Pérez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1982, 12, 31), DateFrom = new DateTime(2014, 09, 01), Email = "*****@*****.**", Password = password3, PasswordSalt = passwordSalt3, Role = Catalog.Roles.Instructor, Sexo = Catalog.Genre.Hombre }, new Client { FirstName = "Ray", LastName = "Allen", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1992, 12, 31), DateFrom = new DateTime(2014, 09, 01), Email = "*****@*****.**", Password = password4, PasswordSalt = passwordSalt4, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre }, new Client { FirstName = "Enzo", LastName = "Gutiérrez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1991, 12, 31), DateFrom = new DateTime(2014, 09, 01), Email = "*****@*****.**", Password = password5, PasswordSalt = passwordSalt5, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre }, new Client { FirstName = "Juana", LastName = "Pérez", DocType = "DNI", DocNumber = 33123654, BirthDate = new DateTime(1979, 08, 11), DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**", Password = password6, PasswordSalt = passwordSalt6, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Mujer }, new Client { FirstName = "Carolina", LastName = "García", DocType = "DNI", DocNumber = 12345678, BirthDate = new DateTime(1971, 11, 15), DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**", Password = password7, PasswordSalt = passwordSalt7, Role = Catalog.Roles.Instructor, Sexo = Catalog.Genre.Mujer }, new Client { FirstName = "Martina", LastName = "Núñez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1981, 02, 01), DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**", Password = password8, PasswordSalt = passwordSalt8, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Mujer }, new Client { FirstName = "Sol", LastName = "Rodríguez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1991, 12, 31), DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**", Password = password9, PasswordSalt = passwordSalt9, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Mujer }, new Client { FirstName = "José", LastName = "García", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1986, 12, 31), DateFrom = new DateTime(2016, 09, 01), Email = "*****@*****.**", Password = password10, PasswordSalt = passwordSalt10, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre } }; clients.ForEach(c => context.Clients.Add(c)); context.SaveChanges(); #endregion #region Routines var routines = new List <Routine> { new Routine { ClientID = 1, NameFile = "CristianPique v1.0", Description = "Rutina personalizada", Files = new List <File>(), CreationDate = DateTime.Now, DaysInWeek = 5, Level = Catalog.LevelRoutine.Medium, Status = Catalog.Status.Active }, new Routine { ClientID = 1, NameFile = "RutinaBegginers", Description = "Rutina nivel princiante", Files = new List <File>(), CreationDate = DateTime.Now, DaysInWeek = 3, Level = Catalog.LevelRoutine.Begginer, Status = Catalog.Status.Active }, new Routine { ClientID = 1, NameFile = "Cardio rutina", Description = "Rutina intensiva cardio", Files = new List <File>(), CreationDate = DateTime.Now, DaysInWeek = 4, Level = Catalog.LevelRoutine.Medium, Status = Catalog.Status.Active }, new Routine { ClientID = 1, NameFile = "AbdominalesRutina", Description = "Rutina abdominales", Files = new List <File>(), CreationDate = DateTime.Now, DaysInWeek = 4, Level = Catalog.LevelRoutine.Expert, Status = Catalog.Status.Active } }; routines.ForEach(r => context.Routines.Add(r)); context.SaveChanges(); #endregion #region MedicalRecords var medicalRecords = new List <MedicalRecord> { new MedicalRecord { ClientID = 1, Age = 26, Gender = 'M', Heigth = 1.81, Weight = 75 }, }; medicalRecords.ForEach(m => context.MedicalRecords.Add(m)); context.SaveChanges(); #endregion #region Activities var clientsForActivities = new List <Client>(); clientsForActivities.Add(clients.Where(x => x.ClientID == 1).FirstOrDefault()); clientsForActivities.Add(clients.Where(x => x.ClientID == 1).FirstOrDefault()); var activities = new List <Activity> { new Activity { Name = "Gimnasio", Description = "Gimnasio, pesas, bicicletas, máquinas para correr" }, new Activity { Name = "Pilates", Description = "Sistema de entrenamiento físico y mental" }, new Activity { Name = "Boxeo", Description = "Deporte de combate" } }; activities.ForEach(a => context.Activities.Add(a)); context.SaveChanges(); #endregion #region ActivitySchedules var activitySchedules = new List <ActivitySchedule> { new ActivitySchedule { ActivityID = 2, Day = "Lunes", HourFrom = 11, HourTo = 12 }, new ActivitySchedule { ActivityID = 2, Day = "Lunes", HourFrom = 16, HourTo = 17 }, new ActivitySchedule { ActivityID = 2, Day = "Miércoles", HourFrom = 19, HourTo = 21 }, new ActivitySchedule { ActivityID = 3, Day = "Miércoles", HourFrom = 9, HourTo = 10 }, new ActivitySchedule { ActivityID = 3, Day = "Miércoles", HourFrom = 20, HourTo = 21 }, }; activitySchedules.ForEach(actS => context.ActivitySchedules.Add(actS)); context.SaveChanges(); #endregion #region Files var files = new List <File> { new File { RoutineID = 1, ExerciseName = "Pecho inclinado", MuscleName = "Pecho", Peso = "20", Repetitions = "3x10", Day = "Lunes" }, new File { RoutineID = 1, ExerciseName = "Pecho con mancuernas", MuscleName = "Pecho", Peso = "15", Repetitions = "3x12", Day = "Martes" }, new File { RoutineID = 1, ExerciseName = "Pecho con mancuernas", MuscleName = "Pecho", Peso = "20", Repetitions = "3x8", Day = "Martes" }, new File { RoutineID = 1, ExerciseName = "Bíceps con mancuernas", MuscleName = "Bíceps", Peso = "8", Repetitions = "3x12", Day = "Miércoles" }, new File { RoutineID = 1, ExerciseName = "Bíceps con mancuernas", MuscleName = "Bíceps", Peso = "10", Repetitions = "3x12", Day = "Jueves" }, new File { RoutineID = 1, ExerciseName = "Francés", MuscleName = "Tríceps", Peso = "8", Repetitions = "3x12", Day = "Jueves" }, new File { RoutineID = 1, ExerciseName = "Tríceps con mancuernas", MuscleName = "Tríceps", Peso = "8", Repetitions = "3x12", Day = "Viernes" }, new File { RoutineID = 1, ExerciseName = "Press militar", MuscleName = "Hombros", Peso = "8", Repetitions = "3x12", Day = "Viernes" }, new File { RoutineID = 2, ExerciseName = "Pecho inclinado", MuscleName = "Pecho", Peso = "20", Repetitions = "3x10", Day = "Lunes" }, new File { RoutineID = 2, ExerciseName = "Pecho con mancuernas", MuscleName = "Pecho", Peso = "15", Repetitions = "3x12", Day = "Martes" }, new File { RoutineID = 2, ExerciseName = "Pecho con mancuernas", MuscleName = "Pecho", Peso = "20", Repetitions = "3x8", Day = "Martes" }, new File { RoutineID = 2, ExerciseName = "Bíceps con mancuernas", MuscleName = "Bíceps", Peso = "8", Repetitions = "3x12", Day = "Miércoles" }, new File { RoutineID = 2, ExerciseName = "Bíceps con mancuernas", MuscleName = "Bíceps", Peso = "10", Repetitions = "3x12", Day = "Jueves" }, new File { RoutineID = 2, ExerciseName = "Francés", MuscleName = "Tríceps", Peso = "8", Repetitions = "3x12", Day = "Jueves" }, new File { RoutineID = 2, ExerciseName = "Tríceps con mancuernas", MuscleName = "Tríceps", Peso = "8", Repetitions = "3x12", Day = "Viernes" }, new File { RoutineID = 2, ExerciseName = "Press militar", MuscleName = "Hombros", Peso = "8", Repetitions = "3x12", Day = "Viernes" }, new File { RoutineID = 3, ExerciseName = "Biclicleta", MuscleName = "Piernas", Peso = "-", Repetitions = "20 min", Day = "Lunes" }, new File { RoutineID = 3, ExerciseName = "Cinta", MuscleName = "Piernas", Peso = "15", Repetitions = "3x12", Day = "Lunes" }, new File { RoutineID = 3, ExerciseName = "Pecho con mancuernas", MuscleName = "Pecho", Peso = "20", Repetitions = "3x8", Day = "Martes" }, new File { RoutineID = 3, ExerciseName = "Abdominales oblicuos", MuscleName = "Abdominales", Peso = "-", Repetitions = "3x20", Day = "Martes" }, new File { RoutineID = 3, ExerciseName = "Abdominales bajos", MuscleName = "Abdominales", Peso = "-", Repetitions = "3x30", Day = "Míércoles" }, new File { RoutineID = 3, ExerciseName = "Saltar soga", MuscleName = "Piernas", Peso = "-", Repetitions = "15 min", Day = "Míércoles" }, new File { RoutineID = 3, ExerciseName = "Tríceps con mancuernas", MuscleName = "Tríceps", Peso = "8", Repetitions = "3x12", Day = "Jueves" }, new File { RoutineID = 3, ExerciseName = "Biclicleta", MuscleName = "Pecho", Peso = "-", Repetitions = "20 min", Day = "Lunes" }, new File { RoutineID = 3, ExerciseName = "Biclicleta", MuscleName = "Piernas", Peso = "-", Repetitions = "20 min", Day = "Lunes" }, new File { RoutineID = 3, ExerciseName = "Cinta", MuscleName = "Piernas", Peso = "15", Repetitions = "3x12", Day = "Lunes" }, }; files.ForEach(f => context.Files.Add(f)); context.SaveChanges(); #endregion #region PaymentType var paymentType = new List <PaymentType> { new PaymentType { Description = "Gimnasio mensual", Status = Catalog.Status.Active, ActivityID = 1, DurationInMonths = 1 }, new PaymentType { Description = "Gimnasio anual", Status = Catalog.Status.Active, ActivityID = 1, DurationInMonths = 12 }, new PaymentType { Description = "Pilates mensual", Status = Catalog.Status.Active, ActivityID = 2, DurationInMonths = 1 }, new PaymentType { Description = "Boxeo mensual", Status = Catalog.Status.Active, ActivityID = 3, DurationInMonths = 1 }, }; paymentType.ForEach(p => context.PaymentTypes.Add(p)); context.SaveChanges(); #endregion #region Payment var payments = new List <Payment> { new Payment { ClientID = 1, PaymentTypeID = 1, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 2, PaymentTypeID = 2, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 4, PaymentTypeID = 1, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 4, PaymentTypeID = 2, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 5, PaymentTypeID = 3, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 5, PaymentTypeID = 3, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 6, PaymentTypeID = 4, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now }, new Payment { ClientID = 6, PaymentTypeID = 4, Status = Catalog.Status.Active, ExpirationDate = new DateTime(2016, 12, 12), CreationDate = DateTime.Now } }; payments.ForEach(p => context.Payments.Add(p)); context.SaveChanges(); #endregion #region PaymentTypePrices var paymentTypePrices = new List <PaymentTypePrice> { new PaymentTypePrice { DateFrom = new DateTime(2016, 01, 01), PaymentTypeID = 1, Price = 200 }, new PaymentTypePrice { DateFrom = new DateTime(2016, 05, 01), PaymentTypeID = 1, Price = 300 }, new PaymentTypePrice { DateFrom = new DateTime(2016, 01, 01), PaymentTypeID = 1, Price = 2000 } }; paymentTypePrices.ForEach(ptp => context.PaymentTypePrices.Add(ptp)); context.SaveChanges(); #endregion #region Suppliers var suppliers = new List <Supplier> { new Supplier { Address = "Entre Rios 2456", BusinessName = "EuroGym", City = "Rosario", Country = "Argentina", Email = "*****@*****.**", PhoneNumber = "(341) 42145580", PostalCode = 2000, WebSite = "http://www.eurogym.com.ar" }, new Supplier { Address = "Santa Fé Av 1052", BusinessName = "Total Gym", City = "Buenos Aires", Country = "Argentina", Email = "*****@*****.**", PhoneNumber = "(011) 5445-7189", PostalCode = 1059, WebSite = "http://www.totalgym.com.ar" }, new Supplier { Address = "V. Cardoso 1401", BusinessName = "e-punto Fitness", City = "Ramos Mejia", Country = "Argentina", Email = "*****@*****.**", PhoneNumber = "(011) 4654-2160", PostalCode = 1059, WebSite = "http://www.e-puntofitness.com.ar/" }, new Supplier { Address = "La Paz 138", BusinessName = "Distribuidora Boom S.R.L", City = "Rosario", Country = "Argentina", Email = "*****@*****.**", PhoneNumber = "(341) 1564895212", PostalCode = 2000, WebSite = "http://www.boomsrl.com.ar/" }, }; suppliers.ForEach(s => context.Suppliers.Add(s)); context.SaveChanges(); #endregion #region Products var products = new List <Product> { new Product { Name = "Cama de Pilates", Description = "Cama de pilates + tabla de salto + tabla de extensión + box Garantía 1 año", Price = 8000, PurchaseDate = new DateTime(2014, 05, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 3 }, new Product { Name = "Sillón de cuadriceps", Description = "Sillon de cuadriceps c/75kgrs.Linea Exclusive", Price = 25560, PurchaseDate = new DateTime(2015, 08, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 3 }, new Product { Name = "Bicicleta Indoor", Description = "Transmisión a cadena Volante de inercia de 20Kg. balanceado dinámicamente cromado y pintado en el centro. Asiento prostático. Manubrio regulable en altura.", Price = 6099, PurchaseDate = new DateTime(2015, 07, 22), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 3 }, new Product { Name = "Cinta Profesional", Description = "Motor 3hp corriente alterna uso industrial 24hs - Velocidad de 0,8 a 16 km/h programable hasta 20km/h- Banda de doble tela antideslizante y antiestática con carbono .", Price = 37550, PurchaseDate = new DateTime(2014, 05, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 3 }, new Product { Name = "Complejo Multiestación", Description = "El complejo de cuatro estaciones de uso profesional esta compuesto por una Camilla femoral y sillon de cuadriceps con una carga de 50 Kg mas una polea simple alta y baja de 10 regulaciones y 50 Kg de carga mas una pectoralera con 50 Kg de carga y una Dorsalera con 75 kg de carga. ", Price = 97500, PurchaseDate = new DateTime(2014, 05, 02), Status = Utils.Catalog.ProductStatus.Deteriorated, Type = Utils.Catalog.ProductType.Machine, SupplierID = 1 }, new Product { Name = "Polea simple regulable 12 niveles", Description = "Polea simple con lingotera de 75 kilos y 12 regulaciones línea profesional Exclusive.", Price = 6512, PurchaseDate = new DateTime(2014, 05, 02), Status = Utils.Catalog.ProductStatus.Broken, Type = Utils.Catalog.ProductType.Machine, SupplierID = 1 }, new Product { Name = "Pectoralera c/75kgrs", Description = "Pectoralera mariposa con lingotera de 75 kilos línea profesional Exclusive", Price = 5300, PurchaseDate = new DateTime(2014, 05, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 2 }, new Product { Name = "Remo Bajo", Description = "Press de pecho con lingotera de 100 kilos línea profesional Exclusive.", Price = 6100, PurchaseDate = new DateTime(2014, 05, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 4 }, new Product { Name = "Agua Villavicencio 500ml", Description = "Botella de agua mineral Villavicencio", Price = 1050, PurchaseDate = new DateTime(2016, 09, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Article, SupplierID = 4 }, new Product { Name = "Gatorade 750ml", Description = "Gatorade 750ml Naranja", Price = 20, PurchaseDate = new DateTime(2016, 09, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Article, SupplierID = 4 }, new Product { Name = "Banco Pecho Modulo", Description = "Banco regulable que permite ejercicios con barra y camilla de cuadriceps y femoral a discos.", Price = 2300, PurchaseDate = new DateTime(2016, 09, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 1 }, new Product { Name = "Banco Pecho Regulable", Description = "Banco de pecho regulable standard", Price = 3100, PurchaseDate = new DateTime(2016, 09, 02), Status = Utils.Catalog.ProductStatus.Ok, Type = Utils.Catalog.ProductType.Machine, SupplierID = 2 }, }; products.ForEach(p => context.Products.Add(p)); context.SaveChanges(); #endregion #region Assistances var assistances = new List <Assistance> { new Assistance { assistanceDate = new DateTime(2016, 01, 01), ClientID = 1 }, new Assistance { assistanceDate = new DateTime(2015, 01, 01), ClientID = 1 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 1 }, new Assistance { assistanceDate = new DateTime(2016, 01, 01), ClientID = 2 }, new Assistance { assistanceDate = new DateTime(2015, 01, 01), ClientID = 2 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 2 }, new Assistance { assistanceDate = new DateTime(2016, 01, 01), ClientID = 3 }, new Assistance { assistanceDate = new DateTime(2015, 01, 01), ClientID = 3 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 3 }, new Assistance { assistanceDate = new DateTime(2015, 01, 01), ClientID = 4 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 4 }, new Assistance { assistanceDate = new DateTime(2015, 01, 01), ClientID = 5 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 5 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 6 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 6 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 6 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 8 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 8 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 8 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 8 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 8 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 7 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 7 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 7 }, new Assistance { assistanceDate = new DateTime(2016, 02, 01), ClientID = 7 } }; assistances.ForEach(a => context.Assistances.Add(a)); context.SaveChanges(); #endregion }
/// <summary> /// Submit form /// </summary> /// <param name="formId"></param> /// <param name="contact"></param> /// <param name="communication"></param> /// <param name="collection"></param> /// <returns></returns> public ResponseModel SubmitForm(string formId, Contact contact, ContactCommunication communication, NameValueCollection collection) { try { var id = PasswordUtilities.ComplexDecrypt(formId).ToInt(); var form = GetById(id); if (form != null) { var formData = collection.AllKeys.SelectMany(collection.GetValues, (k, v) => new ContactInformation { Key = k, Value = v }).ToList(); //Save contact and communication contact = _contactService.SaveForm(contact, communication, formData); #region Form Data var formEmailModel = collection.AllKeys.SelectMany(collection.GetValues, (k, v) => new ContactInformation { Key = k.CamelFriendly(), Value = v }).ToList(); var formBuilderSetting = _siteSettingService.LoadSetting <FormBuilderSetting>(); var cacheName = SettingNames.FormBuilderSetting.GetTemplateCacheName(formBuilderSetting.SubmitFormBodyTemplate); var formDataBody = RazorEngineHelper.CompileAndRun(formBuilderSetting.SubmitFormBodyTemplate, formEmailModel, null, cacheName); #endregion if (form.SendSubmitFormEmail && !string.IsNullOrEmpty(form.EmailTo)) { var email = new EmailLog { From = form.FromEmail, FromName = form.FromName, To = form.EmailTo, ToName = form.EmailTo, Subject = formBuilderSetting.SubmitFormSubject, Body = formDataBody }; _emailLogService.CreateEmail(email, true); } if (form.SendNotificationEmail && !string.IsNullOrEmpty(form.NotificationEmailTo)) { var notificationBodyStringBuilder = new StringBuilder(); notificationBodyStringBuilder.AppendLine(form.NotificationBody); notificationBodyStringBuilder.AppendLine(formDataBody); var email = new EmailLog { From = form.FromEmail, FromName = form.FromName, To = form.NotificationEmailTo, ToName = form.NotificationEmailTo, Subject = form.NotificationSubject, Body = notificationBodyStringBuilder.ToString() }; _emailLogService.CreateEmail(email, true); } if (form.SendAutoResponse) { // Get email from form data var emailAddress = formData.FirstOrDefault( f => f.Key.Contains("Email", StringComparison.CurrentCultureIgnoreCase)); if (emailAddress != null && !string.IsNullOrEmpty(emailAddress.Value)) { var toName = contact.FullName; var email = new EmailLog { From = form.FromEmail, FromName = form.FromName, To = emailAddress.Value, ToName = string.IsNullOrWhiteSpace(toName) ? emailAddress.Value : toName, Subject = form.AutoResponseSubject, Body = form.AutoResponseBody }; _emailLogService.CreateEmail(email, true); } } return(new ResponseModel { Success = true, Message = form.ThankyouMessage }); } } catch (Exception) { // Form parameters invalid } return(new ResponseModel { Success = false, Message = T("Form_Message_InvalidFormId") }); }
public IHttpResponse Register(IHttpRequest req) { const string formNameKey = "name"; const string formUsernameKey = "username"; const string formPasswordKey = "password"; const string formConfirmPasswordKey = "confirmpassword"; if (!req.FormData.ContainsKey(formNameKey) || !req.FormData.ContainsKey(formPasswordKey) || !req.FormData.ContainsKey(formConfirmPasswordKey) || !req.FormData.ContainsKey(formUsernameKey)) { return(new BadRequestResponse()); } var name = req.FormData[formNameKey]; var username = req.FormData[formUsernameKey]; var password = req.FormData[formPasswordKey]; var confirmPassword = req.FormData[formConfirmPasswordKey]; if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(confirmPassword) || string.IsNullOrWhiteSpace(username)) { this.ViewData["error"] = "You have empty fields"; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\register")); } int userId = 0; using (ByTheCakeContext context = new ByTheCakeContext()) { bool userExists = context.Users.Any(x => x.Username == username); if (userExists) { this.ViewData["error"] = "The username is taken."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\register")); } bool passwordsMatch = password.Equals(confirmPassword); if (!passwordsMatch) { this.ViewData["error"] = "Password do not match."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\register")); } User userToRegister = new User() { Name = name, Username = username, PasswordHash = PasswordUtilities.GenerateHash(password), RegistrationDate = DateTime.Now }; context.Users.Add(userToRegister); context.SaveChanges(); userId = userToRegister.Id; } req.Session.Add(SessionStore.CurrentUserKey, userId); req.Session.Add(ShoppingCart.SessionKey, new ShoppingCart()); return(new RedirectResponse("/")); }
public IHttpResponse Login(IHttpRequest req) { const string formNameKey = "username"; const string formPasswordKey = "password"; if (!req.FormData.ContainsKey(formNameKey) || !req.FormData.ContainsKey(formPasswordKey)) { this.ViewData["error"] = "You have empty fields"; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\login")); } var userName = req.FormData[formNameKey]; var password = req.FormData[formPasswordKey]; if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) { this.ViewData["error"] = "You have empty fields"; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\login")); } User userToLog = default(User); using (ByTheCakeContext context = new ByTheCakeContext()) { userToLog = context.Users.FirstOrDefault(x => x.Username == userName); } bool userExists = ValidateUserExistence(userToLog); if (!userExists) { this.ViewData["error"] = "Invalid credentials."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(new RedirectResponse("/register")); } string hashedPassword = PasswordUtilities.GenerateHash(password); bool passwordIsCorrect = userToLog.PasswordHash.Equals(hashedPassword); if (!passwordIsCorrect) { this.ViewData["error"] = "Invalid credentials."; this.ViewData["showError"] = "block"; this.ViewData["authDisplay"] = "none"; return(this.FileViewResponse(@"account\login")); } req.Session.Add(SessionStore.CurrentUserKey, userToLog.Id); req.Session.Add(ShoppingCart.SessionKey, new ShoppingCart()); return(new RedirectResponse("/")); }
public void HashPassword(Client client) { client.PasswordSalt = PasswordUtilities.CreateSalt(16); client.Password = PasswordUtilities.GenerateSHA256Hash(client.Password, client.PasswordSalt); }
public static void Main(string[] args) { InitializeLogging(); // construct libwarty dependencies ICollectionFactory collectionFactory = new CollectionFactory(); // construct libwarty-proxies dependencies IStreamFactory streamFactory = new StreamFactory(); IFileSystemProxy fileSystemProxy = new FileSystemProxy(streamFactory); IThreadingFactory threadingFactory = new ThreadingFactory(); ISynchronizationFactory synchronizationFactory = new SynchronizationFactory(); IThreadingProxy threadingProxy = new ThreadingProxy(threadingFactory, synchronizationFactory); IDnsProxy dnsProxy = new DnsProxy(); ITcpEndPointFactory tcpEndPointFactory = new TcpEndPointFactory(dnsProxy); INetworkingInternalFactory networkingInternalFactory = new NetworkingInternalFactory(threadingProxy, streamFactory); ISocketFactory socketFactory = new SocketFactory(tcpEndPointFactory, networkingInternalFactory); INetworkingProxy networkingProxy = new NetworkingProxy(socketFactory, tcpEndPointFactory); IProcessProxy processProxy = new ProcessProxy(); // construct Castle.Core dependencies ProxyGenerator proxyGenerator = new ProxyGenerator(); // construct Platform Root Portable Object Format dependencies IPofContext pofContext = new PlatformPofContext(); IPofSerializer pofSerializer = new PofSerializer(pofContext); // construct libdargon.management dependencies var managementServerEndpoint = tcpEndPointFactory.CreateAnyEndPoint(kPlatformManagementPort); IMessageFactory managementMessageFactory = new MessageFactory(); IManagementSessionFactory managementSessionFactory = new ManagementSessionFactory(collectionFactory, threadingProxy, pofSerializer, managementMessageFactory); ILocalManagementServerContext managementServerContext = new LocalManagementServerContext(collectionFactory, managementSessionFactory); IManagementContextFactory managementContextFactory = new ManagementContextFactory(pofContext); ILocalManagementRegistry localManagementServerRegistry = new LocalManagementRegistry(pofSerializer, managementContextFactory, managementServerContext); IManagementServerConfiguration managementServerConfiguration = new ManagementServerConfiguration(managementServerEndpoint); var server = new LocalManagementServer(threadingProxy, networkingProxy, managementSessionFactory, managementServerContext, managementServerConfiguration); server.Initialize(); // construct system-state dependencies ICache <string, string> systemStateCache = new InMemoryCache <string, string>("SystemState", new ICacheIndex[0]); var platformSystemState = new PlatformSystemStateImpl(systemStateCache); localManagementServerRegistry.RegisterInstance(new PlatformSystemStateMob(platformSystemState)); // construct platform foundational dependencies ICacheFactory cacheFactory = new CacheFactory(); PlatformCacheService platformCacheService = new PlatformCacheServiceImpl(collectionFactory, cacheFactory).With(x => x.Initialize()); Caches specializedCaches = new Caches(platformCacheService); SpecializedCacheService specializedCacheService = new SpecializedCacheServiceImpl(specializedCaches); // construct backend account service dependencies ICache <string, long> emailToAccountIdCache = new InMemoryCache <string, long>(Accounts.Hydar.CacheNames.kEmailToAccountIdCache, new ICacheIndex[0]); ICache <long, AccountInformation> accountInfoByIdCache = new InMemoryCache <long, AccountInformation>(Accounts.Hydar.CacheNames.kAccountInfoByIdCache, new ICacheIndex[0]); IDistributedCounter accountIdCounter = specializedCacheService.GetCountingCache(Accounts.Hydar.CacheNames.kAccountIdCountingCacheName); IPasswordUtilities passwordUtilities = new PasswordUtilities(); AccountCache accountCache = new AccountCache(emailToAccountIdCache, accountInfoByIdCache, accountIdCounter, passwordUtilities); var accountService = new AccountServiceImpl(accountCache); localManagementServerRegistry.RegisterInstance(new AccountCacheMob(accountCache)); // construct frontend identity service dependencies ICache <string, Identity> identityByTokenHydarCache = new InMemoryCache <string, Identity>(Draek.Identities.Hydar.CacheNames.kIdentityByTokenCache, new ICacheIndex[0]); AuthenticationTokenFactory authenticationTokenFactory = new AuthenticationTokenFactoryImpl(); IdentityByTokenCache identityByTokenCache = new IdentityByTokenCacheImpl(identityByTokenHydarCache); IAuthenticationServiceConfiguration authenticationServiceConfiguration = new AuthenticationServiceConfiguration(platformSystemState); AuthenticationService authenticationService = new AuthenticationServiceImpl(accountService, authenticationTokenFactory, identityByTokenCache, authenticationServiceConfiguration); var identityService = new IdentityServiceProxyImpl(authenticationService); localManagementServerRegistry.RegisterInstance(new AuthenticationServiceMob(authenticationService)); localManagementServerRegistry.RegisterInstance(new IdentityCacheMob(identityByTokenCache)); localManagementServerRegistry.RegisterInstance(new AuthenticationServiceConfigurationMob(authenticationServiceConfiguration)); Application.Run(); }