Feature/misc tasks (#864)

* feat(backend): 🌐 make foods/ingredients translatable

* feat(backend):  add remember me support for login - 14 days

* feat(frontend): 💄 add persistent darkmode for user sessions

* capture #859

* feat(frontend): 💄 add basic open-graph data for site links
This commit is contained in:
Hayden 2021-12-04 16:06:24 -09:00 committed by GitHub
parent c32d7d7486
commit ba4107348f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 323 additions and 1054 deletions

View file

@ -1,69 +0,0 @@
# frontend
## Build Setup
```bash
# install dependencies
$ yarn install
# serve with hot reload at localhost:3000
$ yarn dev
# build for production and launch server
$ yarn build
$ yarn start
# generate static project
$ yarn generate
```
For detailed explanation on how things work, check out the [documentation](https://nuxtjs.org).
## Special Directories
You can create the following extra directories, some of which have special behaviors. Only `pages` is required; you can delete them if you don't want to use their functionality.
### `assets`
The assets directory contains your uncompiled assets such as Stylus or Sass files, images, or fonts.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/directory-structure/assets).
### `components`
The components directory contains your Vue.js components. Components make up the different parts of your page and can be reused and imported into your pages, layouts and even other components.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/directory-structure/components).
### `layouts`
Layouts are a great help when you want to change the look and feel of your Nuxt app, whether you want to include a sidebar or have distinct layouts for mobile and desktop.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/directory-structure/layouts).
### `pages`
This directory contains your application views and routes. Nuxt will read all the `*.vue` files inside this directory and setup Vue Router automatically.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/get-started/routing).
### `plugins`
The plugins directory contains JavaScript plugins that you want to run before instantiating the root Vue.js Application. This is the place to add Vue plugins and to inject functions or constants. Every time you need to use `Vue.use()`, you should create a file in `plugins/` and add its path to plugins in `nuxt.config.js`.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/directory-structure/plugins).
### `static`
This directory contains your static files. Each file inside this directory is mapped to `/`.
Example: `/static/robots.txt` is mapped as `/robots.txt`.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/directory-structure/static).
### `store`
This directory contains your Vuex store files. Creating a file in this directory automatically activates Vuex.
More information about the usage of this directory in [the documentation](https://nuxtjs.org/docs/2.x/directory-structure/store).

View file

@ -19,12 +19,6 @@
background-color: var(--v-background-base, #121212) !important;
}
/* 1E1E1E */
.theme--dark.v-card {
background-color: #2b2b2b !important;
}
.theme--light.v-application {
background-color: var(--v-background-base, white) !important;
}

View file

@ -62,6 +62,7 @@
<script lang="ts">
import { computed, defineComponent, onMounted, ref, useContext } from "@nuxtjs/composition-api";
import { useDark } from "@vueuse/core";
import AppHeader from "@/components/Layout/AppHeader.vue";
import AppSidebar from "@/components/Layout/AppSidebar.vue";
import TheSnackbar from "@/components/Layout/TheSnackbar.vue";
@ -78,7 +79,10 @@ export default defineComponent({
const isAdmin = computed(() => $auth.user?.admin);
const isDark = useDark();
function toggleDark() {
isDark.value = !$vuetify.theme.dark;
$vuetify.theme.dark = !$vuetify.theme.dark;
console.log("toggleDark");
}
@ -180,11 +184,5 @@ export default defineComponent({
],
};
},
head: {
title: "Home",
},
});
</script>
<style scoped>
</style>+
</script>

View file

@ -1,13 +1,25 @@
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
titleTemplate: "%s | Mealie",
title: "Home",
meta: [
{ hid: "og:type", property: "og:type", content: "website" },
{ hid: "og:title", property: "og:title", content: "Mealie" },
{ hid: "og:site_name", property: "og:site_name", content: "Mealie" },
{ hid: "og:desc", property: "og:description", content: "Mealie is a recipe management app for your kitchen." },
{
hid: "og-image",
property: "og:image",
content:
"https://raw.githubusercontent.com/hay-kot/mealie/dev/frontend/public/img/icons/android-chrome-512x512.png",
},
{ charset: "utf-8" },
{ name: "viewport", content: "width=device-width, initial-scale=1" },
{ hid: "description", name: "description", content: "" },
{ name: "format-detection", content: "telephone=no" },
{
hid: "description",
name: "description",
content: "Mealie is a recipe management app for your kitchen.",
},
],
link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }],
},
@ -30,7 +42,7 @@ export default {
css: [{ src: "~/assets/main.css" }, { src: "~/assets/style-overrides.scss" }],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ["~/plugins/globals.ts", "~/plugins/theme.ts", "~/plugins/toast.client.ts"],
plugins: ["~/plugins/globals.ts", "~/plugins/theme.ts", "~/plugins/toast.client.ts", "~/plugins/dark-mode.client.ts"],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,

View file

@ -172,7 +172,7 @@
label="Password"
type="password"
/>
<v-checkbox class="ml-2 mt-n4" label="Remember Me"></v-checkbox>
<v-checkbox v-model="form.remember" class="ml-2 mt-n4" label="Remember Me"></v-checkbox>
<v-card-actions class="justify-center">
<div class="max-button">
<v-btn :loading="loggingIn" color="primary" type="submit" large rounded class="rounded-xl" block>
@ -204,6 +204,7 @@ export default defineComponent({
const form = reactive({
email: "changeme@email.com",
password: "MyPassword",
remember: false,
});
const loggingIn = ref(false);
@ -215,15 +216,15 @@ export default defineComponent({
const formData = new FormData();
formData.append("username", form.email);
formData.append("password", form.password);
formData.append("remember_me", String(form.remember));
try {
await $auth.loginWith("local", { data: formData });
} catch (error) {
if (error.response.status === 401) {
alert.error("Invalid Credentials");
}
else {
alert.error("Something Went Wrong!")
} else {
alert.error("Something Went Wrong!");
}
}
loggingIn.value = false;

View file

@ -0,0 +1,12 @@
import { useDark } from "@vueuse/core";
export default ({ $vuetify }: any) => {
const isDark = useDark();
console.log("isDark Plugin", isDark);
if (isDark.value) {
$vuetify.theme.dark = true;
} else {
$vuetify.theme.dark = false;
}
};

View file

@ -3,6 +3,7 @@ from pathlib import Path
from mealie.core.root_logger import get_logger
from mealie.db.data_access_layer.access_model_factory import Database
from mealie.schema.recipe import CreateIngredientFood, CreateIngredientUnit
CWD = Path(__file__).parent
logger = get_logger(__name__)
@ -14,21 +15,26 @@ def get_default_foods():
return foods
def get_default_units():
def get_default_units() -> dict[str, str]:
with open(CWD.joinpath("resources", "units", "en-us.json"), "r") as f:
units = json.loads(f.read())
return units
def default_recipe_unit_init(db: Database) -> None:
for unit in get_default_units():
for unit in get_default_units().values():
try:
db.ingredient_units.create(unit)
db.ingredient_units.create(
CreateIngredientUnit(
name=unit["name"], description=unit["description"], abbreviation=unit["abbreviation"]
)
)
except Exception as e:
logger.error(e)
for food in get_default_foods():
try:
db.ingredient_foods.create(food)
db.ingredient_foods.create(CreateIngredientFood(name=food, description=""))
except Exception as e:
logger.error(e)

File diff suppressed because it is too large Load diff

View file

@ -1,122 +1,102 @@
[
{
{
"teaspoon": {
"name": "teaspoon",
"description": "",
"fraction": true,
"abbreviation": "tsp"
},
{
"tablespoon": {
"name": "tablespoon",
"description": "",
"fraction": true,
"abbreviation": "tbsp"
},
{
"cup": {
"name": "cup",
"description": "",
"fraction": true,
"abbreviation": "cup"
},
{
"fluid-ounce": {
"name": "fluid ounce",
"description": "",
"fraction": true,
"abbreviation": "fl oz"
},
{
"pint": {
"name": "pint",
"description": "",
"fraction": true,
"abbreviation": "pt"
},
{
"quart": {
"name": "quart",
"description": "",
"fraction": true,
"abbreviation": "qt"
},
{
"gallon": {
"name": "gallon",
"description": "",
"fraction": true,
"abbreviation": "gal"
},
{
"milliliter": {
"name": "milliliter",
"description": "",
"fraction": true,
"abbreviation": "ml"
},
{
"liter": {
"name": "liter",
"description": "",
"fraction": true,
"abbreviation": "l"
},
{
"pound": {
"name": "pound",
"description": "",
"fraction": true,
"abbreviation": "lb"
},
{
"ounce": {
"name": "ounce",
"description": "",
"fraction": true,
"abbreviation": "oz"
},
{
"gram": {
"name": "gram",
"description": "",
"fraction": true,
"abbreviation": "g"
},
{
"kilogram": {
"name": "kilogram",
"description": "",
"fraction": true,
"abbreviation": "kg"
},
{
"milligram": {
"name": "milligram",
"description": "",
"fraction": true,
"abbreviation": "mg"
},
{
"splash": {
"name": "splash",
"description": "",
"fraction": true,
"abbreviation": ""
},
{
"dash": {
"name": "dash",
"description": "",
"fraction": true,
"abbreviation": ""
},
{
"serving": {
"name": "serving",
"description": "",
"fraction": true,
"abbreviation": ""
},
{
"head": {
"name": "head",
"description": "",
"fraction": true,
"abbreviation": ""
},
{
"clove": {
"name": "clove",
"description": "",
"fraction": true,
"abbreviation": ""
},
{
"can": {
"name": "can",
"description": "",
"fraction": true,
"abbreviation": ""
}
]
}

View file

@ -1,4 +1,7 @@
from fastapi import APIRouter, BackgroundTasks, Depends, Request, status
from datetime import timedelta
from typing import Optional
from fastapi import APIRouter, BackgroundTasks, Depends, Form, Request, status
from fastapi.exceptions import HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm.session import Session
@ -15,12 +18,31 @@ public_router = APIRouter(tags=["Users: Authentication"])
user_router = UserAPIRouter(tags=["Users: Authentication"])
@public_router.post("/token/long")
class CustomOAuth2Form(OAuth2PasswordRequestForm):
def __init__(
self,
grant_type: str = Form(None, regex="password"),
username: str = Form(...),
password: str = Form(...),
remember_me: bool = Form(False),
scope: str = Form(""),
client_id: Optional[str] = Form(None),
client_secret: Optional[str] = Form(None),
):
self.grant_type = grant_type
self.username = username
self.password = password
self.remember_me = remember_me
self.scopes = scope.split()
self.client_id = client_id
self.client_secret = client_secret
@public_router.post("/token")
def get_token(
background_tasks: BackgroundTasks,
request: Request,
data: OAuth2PasswordRequestForm = Depends(),
data: CustomOAuth2Form = Depends(),
session: Session = Depends(generate_session),
):
email = data.username
@ -37,7 +59,8 @@ def get_token(
headers={"WWW-Authenticate": "Bearer"},
)
access_token = security.create_access_token(dict(sub=user.email))
duration = timedelta(days=14) if data.remember_me else None
access_token = security.create_access_token(dict(sub=user.email), duration)
return {"access_token": access_token, "token_type": "bearer"}

View file

@ -55,6 +55,8 @@ def scrape_image(image_url: str, slug: str) -> Path:
all_image_requests = []
for url in image_url:
if isinstance(url, dict):
url = url.get("url", "")
try:
r = requests.get(url, stream=True, headers={"User-Agent": _FIREFOX_UA})
except Exception: