public static void Login <T, U>(this HttpContext HttpContext, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, PortableRecipesContext _context, string entity_name, U entity, T payload) where U : IEntity
        {
            HttpContext.Logout(_context);
            var now = DateTime.Now;

            _context.Session.RemoveRange(
                from s in _context.Session
                where (s.LoggedEntityId == entity.Id && s.LoggedEntityName == entity_name) ||
                (s.LoggedEntityId == null || s.LoggedEntityName == null) ||
                (now - s.CreatedAt).TotalDays >= 30
                select s);
            _context.SaveChanges();
            var random_id = PasswordHasher.RandomString;

            HttpContext.Response.Cookies.Append("PortableRecipesContext", random_id,
                                                new Microsoft.AspNetCore.Http.CookieOptions()
            {
                Expires  = DateTimeOffset.Now.AddDays(30),
                HttpOnly = true,
                Secure   = !env.IsDevelopment()
            });
            var new_session = new Session()
            {
                CookieName       = random_id,
                LoggedEntityId   = entity.Id,
                LoggedEntityName = entity_name,
                AdditionalInfo   = HttpContext.Connection.RemoteIpAddress.ToString(),
                Content          = JsonConvert.SerializeObject(payload),
                CreatedAt        = DateTime.Now
            };

            _context.Session.Add(new_session);
            _context.SaveChanges();
        }
예제 #2
0
    public AdminViewData Register([FromBody] RegistrationData registration_data)
    {
        string username           = registration_data.Username,
               email              = registration_data.Email,
               email_confirmation = registration_data.EmailConfirmation;

        if (username != null && username != "" && email != null && email != "" && email == email_confirmation)
        {
            var item = _context.Admin.FirstOrDefault(t => t.Username == username || t.Email == email);
            if (item == null)
            {
                var new_password_text = PasswordHasher.RandomPassword;
                var new_password      = PasswordHasher.Hash(new_password_text);
                item = new Admin()
                {
                    Id = _context.Admin.Max(i => i.Id) + 1, Username = username, Email = email, PasswordHash = new_password.PasswordHash, PasswordSalt = new_password.PasswordSalt
                };
                var apiKey           = StaticMailer._mailOptions.MailApiToken;
                var client           = new SendGridClient(apiKey);
                var from             = new EmailAddress(StaticMailer._mailOptions.MailFrom);
                var subject          = "Admin account created with temporary password.";
                var to               = new EmailAddress(item.Email);
                var plainTextContent = $"Your Admin temporary password has set. Your username and password combination is \n\nUsername: {item.Username}\nPassword: {new_password_text}\n";
                var htmlContent      = $"Your Admin temporary password has set. Your username and password combination is <br />Username: {item.Username}<br />Password: {new_password_text}<br />";
                var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                var response         = client.SendEmailAsync(msg).Result;

                _context.Admin.Add(item);
                _context.SaveChanges();

                return(AdminViewData.FromAdmin(item));
            }
        }
        throw new Exception("Cannot register.");
    }
 public static void Logout(this HttpContext HttpContext, PortableRecipesContext _context)
 {
     if (HttpContext.Request.Cookies.ContainsKey("PortableRecipesContext"))
     {
         var old_cookie  = HttpContext.Request.Cookies["PortableRecipesContext"];
         var old_session = _context.Session.FirstOrDefault(s => s.CookieName == old_cookie);
         if (old_session != null)
         {
             _context.Session.Remove(old_session);
             _context.SaveChanges();
             if (new Random().Next(100) < 10)
             {
                 var now       = DateTime.Now;
                 var to_remove = _context.Session.Where(s => now - s.CreatedAt > TimeSpan.FromDays(365)).ToList();
                 _context.Session.RemoveRange(to_remove);
                 _context.SaveChanges();
             }
         }
         HttpContext.Response.Cookies.Delete("PortableRecipesContext");
     }
 }
        public static void Deleted <U>(this HttpContext HttpContext, PortableRecipesContext _context, string entity_name, U entity) where U : IEntity
        {
            var now = DateTime.Now;

            _context.Session.RemoveRange(
                from s in _context.Session
                where (s.LoggedEntityId == entity.Id && s.LoggedEntityName == entity_name) ||
                (s.LoggedEntityId == null || s.LoggedEntityName == null) ||
                (now - s.CreatedAt).TotalDays >= 30
                select s);
            _context.SaveChanges();
        }
예제 #5
0
    public IActionResult /*American*/ Create()
    {
        var session             = HttpContext.Get <LoggableEntities>(_context);
        var current_User        = session == null ? null : session.User;
        var current_Admin       = session == null ? null : session.Admin;
        var can_create_by_token = ApiTokenValid || true;

        if (!can_create_by_token)
        {
            return(Unauthorized());
        }
        // throw new Exception("Unauthorized create attempt");
        var item = new American()
        {
            CreatedDate = DateTime.Now, Id = _context.Categorie.Max(i => i.Id) + 1
        };

        _context.American.Add(PortableRecipes.Models.American.FilterViewableAttributesLocal(current_User, current_Admin)(item));
        _context.SaveChanges();
        item = PortableRecipes.Models.American.WithoutImages(item);
        return(Ok(item));
    }
        public static void Set <T>(this HttpContext HttpContext, PortableRecipesContext _context, T payload)
        {
            var cookie  = HttpContext.Request.Cookies["PortableRecipesContext"];
            var session = _context.Session.FirstOrDefault(s => s.CookieName == cookie);

            if (session != null)
            {
                session.Content = JsonConvert.SerializeObject(payload);
            }
            else
            {
                session = new Session()
                {
                    CookieName = cookie, Content = JsonConvert.SerializeObject(payload), CreatedAt = DateTime.Now
                };
                _context.Session.Add(session);
            }
            _context.SaveChanges();
        }
예제 #7
0
    public void UserRating(int rating, int recipe_id, int user_id)
    {
        var stored_rating = (from recipe_rating in _context.Recipe_Rating
                             where (recipe_rating.RecipeId == recipe_id)
                             from user_rating in _context.User_Rating
                             where (user_rating.UserId == user_id) && (recipe_rating.RatingId == user_rating.RatingId)
                             from Rating in _context.Rating
                             where (Rating.Id == user_rating.RatingId && Rating.Id == recipe_rating.RatingId)
                             select Rating).FirstOrDefault();

        if (stored_rating == null)
        {
            System.Console.WriteLine("did not found one!");

            Rating newRating = new Rating()
            {
                rating = rating, Id = _context.Rating.Max(elem => elem.Id) + 1
            };
            _context.Rating.Add(newRating);

            User_Rating newUser_Rating = new User_Rating()
            {
                UserId = user_id, RatingId = newRating.Id
            };
            _context.User_Rating.Add(newUser_Rating);

            Recipe_Rating newRecipe_Rating = new Recipe_Rating()
            {
                RecipeId = recipe_id, RatingId = newRating.Id
            };
            _context.Recipe_Rating.Add(newRecipe_Rating);
        }
        else
        {
            System.Console.WriteLine("found one!");
            stored_rating.rating = rating;
        }


        _context.SaveChanges();
    }
예제 #8
0
    public IActionResult /*IEnumerable<American>*/ CreateNewCategorie_Meal_American(int Meal_id)
    {
        var session             = HttpContext.Get <LoggableEntities>(_context);
        var current_User        = session == null ? null : session.User;
        var current_Admin       = session == null ? null : session.Admin;
        var allowed_sources     = ApiTokenValid ? _context.Meal : _context.Meal;
        var source              = allowed_sources.FirstOrDefault(s => s.Id == Meal_id);
        var can_create_by_token = ApiTokenValid || true;

        if (source == null || !can_create_by_token)
        {
            return(Unauthorized());
        }
        // throw new Exception("Cannot create item in relation Categorie_Meals");
        var can_link_by_token = ApiTokenValid || true;

        if (!CanAdd_Meal_Categorie_Meals(source) || !can_link_by_token)
        {
            return(Unauthorized());
        }
        //throw new Exception("Cannot add item to relation Categorie_Meals");
        var new_target = new American()
        {
            CreatedDate = DateTime.Now, Id = _context.Categorie.Max(i => i.Id) + 1
        };

        _context.American.Add(new_target);
        _context.SaveChanges();
        var link = new Categorie_Meal()
        {
            Id = _context.Categorie_Meal.Max(l => l.Id) + 1, MealId = source.Id, CategorieId = new_target.Id
        };

        _context.Categorie_Meal.Add(link);
        _context.SaveChanges();
        return(Ok(new American[] { new_target }));
    }
예제 #9
0
    public IActionResult /*IEnumerable<UserViewData>*/ CreateNewUser_Rating_User(int Rating_id)
    {
        var session             = HttpContext.Get <LoggableEntities>(_context);
        var current_User        = session == null ? null : session.User;
        var current_Admin       = session == null ? null : session.Admin;
        var allowed_sources     = ApiTokenValid ? _context.Rating : _context.Rating;
        var source              = allowed_sources.FirstOrDefault(s => s.Id == Rating_id);
        var can_create_by_token = ApiTokenValid || true;

        if (source == null || !can_create_by_token)
        {
            return(Unauthorized());
        }
        // throw new Exception("Cannot create item in relation User_Ratings");
        var can_link_by_token = ApiTokenValid || true;

        if (!CanAdd_Rating_User_Ratings(source) || !can_link_by_token)
        {
            return(Unauthorized());
        }
        //throw new Exception("Cannot add item to relation User_Ratings");
        var new_target = new User()
        {
            CreatedDate = DateTime.Now, Id = _context.User.Max(i => i.Id) + 1
        };

        _context.User.Add(new_target);
        _context.SaveChanges();
        var link = new User_Rating()
        {
            Id = _context.User_Rating.Max(l => l.Id) + 1, RatingId = source.Id, UserId = new_target.Id
        };

        _context.User_Rating.Add(link);
        _context.SaveChanges();
        return(Ok(new UserViewData[] { UserViewData.FromUser(new_target) }));
    }