public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = repository.GetByEmail(model.Email);
                if (user == null)
                {
                    user = new User
                    {
                        Name = model.Name,
                        Email = model.Email,
                        Password = Crypter.Blowfish.Crypt(model.Password),
                        Roles = new List<string>()
                    };

                    repository.Save(user);
                    SetAuthCookie(user);
                    return RedirectToAction("Index", "Home");
                }
                model.Errors = "Det finns redan en användare med den e-post adressen.";
            }
            return View(model);
        }
        public User Save(User item)
        {
            using (var conn = Connection)
            {
                conn.Open();
                var transaction = conn.BeginTransaction();

                var command = new MySqlCommand("INSERT INTO users (id, name, email, password, roles, token) VALUES (@Id, @Name, @Email, @Password, @Roles, @Token) " +
                                               "ON DUPLICATE KEY UPDATE name=VALUES(name), email=VALUES(email), password=VALUES(password), roles=VALUES(roles), token=VALUES(token);", conn, transaction);

                command.Parameters.AddWithValue("@Id", item.Id);
                command.Parameters.AddWithValue("@Name", item.Name);
                command.Parameters.AddWithValue("@Email", item.Email);
                command.Parameters.AddWithValue("@Password", item.Password);
                command.Parameters.AddWithValue("@Roles", string.Join(",", item.Roles));
                command.Parameters.AddWithValue("@Token", item.Token);
                command.ExecuteNonQuery();

                if (item.Id == 0)
                {
                    var idCommand = new MySqlCommand("SELECT LAST_INSERT_ID();", conn, transaction);
                    var id = idCommand.ExecuteScalar();
                    item.Id = Convert.ToInt32(id);
                }

                transaction.Commit();
            }
            return item;
        }
 private void SetAuthCookie(User user)
 {
     var authTicket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddYears(1), true, string.Join(",", user.Roles));
     var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
     cookie.Expires = DateTime.Now.AddYears(1);
     Response.Cookies.Add(cookie);
 }