Ejemplo n.º 1
0
 public ActionResult Registration(Models.RegistrationModel model)
 {
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     try
     {
         var salt     = BLL.Hash.CreateSalt(16);
         var passhash = BLL.Hash.GenerateSaltedHash(model.password, salt);
         var res      = BLL.Data.UserData.CreateUpdateUser(new BLL.DTO.UserDTO
         {
             passwordSalt  = Convert.ToBase64String(salt),
             passwordHash  = Convert.ToBase64String(passhash),
             email         = model.email,
             name          = model.name,
             regDate       = DateTime.Now,
             birthDate     = model.birthDate,
             emailVerified = true,
             role          = model.role
         });
         if (res == -1)
         {
             ModelState.AddModelError("email", "Email уже занят");
         }
         BLL.Data.UserData.ConnectRole(res);
     }
     catch (Exception ex)
     {
         ViewBag.Message = ex.Message;
     }
     LoginAfterRegistration(model);
     return(RedirectToAction("Index", "Home"));;
 }
Ejemplo n.º 2
0
        public bool LoginAfterRegistration(Models.RegistrationModel model)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.email, model.password))
                {
                    var user = (CustomMembershipUser)Membership.GetUser(model.email, false);
                    if (user != null)
                    {
                        CustomSerializeModel userModel = new Models.CustomSerializeModel()
                        {
                            UserId   = user.UserId,
                            Nickname = user.UserName,
                            Email    = user.Email,
                        };

                        string userData = JsonConvert.SerializeObject(userModel);
                        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket
                                                               (
                            1, model.email, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData
                                                               );

                        string     enTicket = FormsAuthentication.Encrypt(authTicket);
                        HttpCookie faCookie = new HttpCookie("TicketCookie", enTicket);
                        Response.Cookies.Add(faCookie);
                    }

                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 3
0
        public ActionResult Registration(Models.RegistrationModel reg_model)
        {
            if (Session["session_key"] != null)
            {
                return(RedirectToAction("index"));
            }
            using (NHibernate.ISession session = NHibernateSessionManeger.OpenSession())
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }
                else
                {
                    NHibernate.IQuery query = session.CreateQuery("FROM Users WHERE name = '" + reg_model.Name + "'");
                    if (query.List <Models.Users>().Count() > 0)
                    {
                        ViewData["ErrorMessage"] = "    Пользователь с ником " + reg_model.Name + " уже занят   ";
                        return(View());
                    }

                    var usr = new Models.Users();
                    usr.Email = reg_model.Email;
                    usr.Name  = reg_model.Name;
                    var    salt             = Guid.NewGuid().ToByteArray();
                    string hashsed_password = Convert.ToBase64String(CryptSharp.Utility.SCrypt.ComputeDerivedKey(System.Text.UTF8Encoding.UTF8.GetBytes(reg_model.Password), salt, 16384, 8, 1, null, 128));
                    usr.HashPassword = hashsed_password;
                    usr.Salt         = Convert.ToBase64String(salt);
                    session.Save(usr);

                    return(RedirectToAction("authorization"));
                }
            }
        }
Ejemplo n.º 4
0
        // GET: User
        public ActionResult Registration()
        {
            var model = new Models.RegistrationModel()
            {
            };

            return(View(model));
        }
Ejemplo n.º 5
0
        public IActionResult Registration(Models.RegistrationModel model)
        {
            //Проверка правильности переданной модели
            if (ModelState.IsValid)
            {
                //проверка эл. ящика
                if (!NameValidation.ValidateEmail(model.Email))
                {
                    ModelState.AddModelError("", "Введённый почтовый адрес не прошёл валидацию.");
                    return(RedirectToAction("Registration", model));
                }
                //добавление пользователя в бд
                db.Users.Add(new Data.User()
                {
                    Email    = NameValidation.idn.GetAscii(model.Email),
                    Login    = Utils.GetHash(model.Email),
                    Password = Utils.GetHash(model.Password),
                    Person   = new Person()
                    {
                        DateOfBirth = DateTime.Now,
                        FirstName   = "Тест",
                        LastName    = "Кейсов",
                        Patronymic  = "Тестович"
                    },
                    Role       = Roles.Ученик,
                    UniqueCode = new UniqueKey()
                    {
                        UniqueKeyString = Utils.GetHash(DateTime.Now.ToShortTimeString())
                    }
                });
                db.SaveChanges();
                //отправка письма
                MailAddress from = new MailAddress("unnamed2@тестовая-зона.рф");
                MailAddress to   = new MailAddress(model.Email);

                MailMessage message = new MailMessage(from, to);
                message.Subject    = "Благодарим за регистрацию на сайте ИТ-Дневник!" + DateTime.Now;
                message.Body       = $"Вы зарегистрировались по уникальному ключу {model.UniqueKey}";
                message.IsBodyHtml = true;
                //настройка smtp-клиента
                SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
                //пока что используется аккаунт почты гугла
                smtp.Credentials    = new NetworkCredential("*****@*****.**", "bfd20380a6");
                smtp.EnableSsl      = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Send(message);
                //вход под пользователем
                Authenticate(model.Email, model.Password);
                return(RedirectToAction("Index"));
            }
            return(RedirectToAction("Registration", model));
        }
Ejemplo n.º 6
0
        public ActionResult Register(Models.RegistrationModel collection)
        {
            try
            {
                using (ContextBLL ctx = new ContextBLL())
                {
                    if (!ModelState.IsValid)
                    {
                        ViewBag.Games = GetGameItems(ctx);
                        return(View(collection));
                    }
                    UserBLL user = ctx.FindUserByUserName(collection.UserName);
                    if (user != null)
                    {
                        collection.Message = $"The UserName  '{collection.UserName}' already exists in the database";
                        ViewBag.Games      = GetGameItems(ctx);
                        return(View(collection));
                    }
                    user = new UserBLL();
                    CommentBLL comment = new CommentBLL();
                    user.FirstName   = collection.FirstName;
                    user.LastName    = collection.LastName;
                    user.UserName    = collection.UserName;
                    user.DateOfBirth = collection.DateOfBirth;
                    user.SALT        = System.Web.Helpers.Crypto.GenerateSalt(Constants.SaltSize);
                    user.HASH        = System.Web.Helpers.Crypto.HashPassword(collection.Password + user.SALT);
                    user.Email       = collection.Email;
                    user.RoleID      = 3;
                    //comment.Liked = collection.Liked;
                    comment.Liked       = true;
                    comment.GameID      = collection.GameID;
                    comment.GameName    = collection.GameName;
                    comment.GameComment = "User Initial Comment";
                    comment.UserID      = ctx.CreateUser(user);

                    ctx.CreateComment(comment);
                    Session["AUTHUserName"] = user.UserName;
                    Session["AUTHRoles"]    = user.RoleName;
                    Session["AUTHTYPE"]     = "HASHED";
                }
                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception ex)
            {
                ViewBag.Exception = ex;
                return(View("Error"));
            }
        }