Skip to content

Fixed login artifacts #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Union, Dict
from pydantic import EmailStr

from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
Expand Down Expand Up @@ -33,14 +34,14 @@


@router.post("/magic/{email}", response_model=schemas.WebToken)
def login_with_magic_link(*, db: Session = Depends(deps.get_db), email: str) -> Any:
def login_with_magic_link(*, db: Session = Depends(deps.get_db), email: EmailStr) -> Any:
"""
First step of a 'magic link' login. Check if the user exists and generate a magic link. Generates two short-duration
jwt tokens, one for validation, one for email. Creates user if not exist.
"""
user = crud.user.get_by_email(db, email=email)
if not user:
user_in = schemas.UserCreate(**{email: email})
user_in = schemas.UserCreate(**{"email": email})
user = crud.user.create(db, obj_in=user_in)
if not crud.user.is_active(user):
# Still permits a timed-attack, but does create ambiguity.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from app.core.config import settings
from app.core import security
from app.utilities import (
send_email_validation_email,
send_new_account_email,
)

Expand Down Expand Up @@ -111,48 +110,6 @@ def request_new_totp(
return obj_in


# @router.post("/send-validation-email", response_model=schemas.Msg, status_code=201)
# def send_validation_email(
# *,
# current_user: models.User = Depends(deps.get_current_active_user),
# ) -> Any:
# """
# Send validation email.
# """
# password_validation_token = generate_password_reset_token(email=current_user.email)
# data = schemas.EmailValidation(
# **{
# "email": current_user.email,
# "subject": "Validate your email address",
# "token": password_validation_token,
# }
# )
# # EmailValidation
# send_email_validation_email(data=data)
# return {"msg": "Password validation email sent. Check your email and respond."}


@router.post("/validate-email", response_model=schemas.Msg)
def validate_email(
*,
db: Session = Depends(deps.get_db),
payload: dict = Body(...),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Reset password
"""
# https://stackoverflow.com/a/65114346/295606
email = verify_password_reset_token(payload["validation"])
if not email or current_user.email != email:
raise HTTPException(
status_code=400,
detail="Invalid token",
)
crud.user.validate_email(db=db, db_obj=current_user)
return {"msg": "Email address validated successfully."}


@router.post("/toggle-state", response_model=schemas.Msg)
def toggle_state(
*,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
def create(self, db: Session, *, obj_in: UserCreate) -> User:
db_obj = User(
email=obj_in.email,
hashed_password=get_password_hash(obj_in.password),
full_name=obj_in.full_name,
is_superuser=obj_in.is_superuser,
)
if obj_in.password:
db_obj.hashed_password = get_password_hash(obj_in.password)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
Expand Down
17 changes: 0 additions & 17 deletions {{cookiecutter.project_slug}}/frontend/api/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,23 +146,6 @@ export const apiAuth = {
}
)
},
async requestValidationEmail(token: string) {
return await useFetch<IMsg>(`${apiCore.url()}/users/send-validation-email`,
{
method: "POST",
headers: apiCore.headers(token)
}
)
},
async validateEmail(token: string, validation: string) {
return await useFetch<IMsg>(`${apiCore.url()}/users/validate-email`,
{
method: "POST",
body: { validation },
headers: apiCore.headers(token)
}
)
},
// ADMIN USER MANAGEMENT
async getAllUsers(token: string) {
return await useFetch<IUserProfile[]>(`${apiCore.url()}/users/all`,
Expand Down

This file was deleted.

34 changes: 11 additions & 23 deletions {{cookiecutter.project_slug}}/frontend/pages/settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,22 @@
<div class="lg:grid lg:grid-cols-12 lg:gap-x-5">
<aside class="py-6 px-2 sm:px-6 lg:col-span-3 lg:py-0 lg:px-0">
<nav class="space-y-1" aria-label="tabs">
<button
v-for="item in navigation"
:key="`settings-${item.id}`"
:class="[item.id === selected
? 'text-rose-700 hover:text-rose-700'
: 'text-gray-900 hover:text-gray-900', 'group rounded-md px-3 py-2 flex items-center text-sm font-medium']"
@click.prevent="changeSelection(item.id)"
>
<component
:is="item.icon"
:class="[item.id === selected
? 'text-rose-700 group-hover:text-rose-700'
: 'text-gray-400 group-hover:text-gray-500', 'flex-shrink-0 -ml-1 mr-3 h-6 w-6']" aria-hidden="true"
/>
<button v-for="item in navigation" :key="`settings-${item.id}`"
:class="[item.id === selected
? 'text-ochre-700 hover:text-ochre-700'
: 'text-gray-900 hover:text-gray-900', 'group rounded-md px-3 py-2 flex items-center text-sm font-medium']" @click.prevent="changeSelection(item.id)">
<component :is="item.icon" :class="[item.id === selected
? 'text-ochre-700 group-hover:text-ochre-700'
: 'text-gray-400 group-hover:text-gray-500', 'flex-shrink-0 -ml-1 mr-3 h-6 w-6']" aria-hidden="true" />
<span class="truncate">{{ item.name }}</span>
</button>
<button
v-if="auth.is_superuser"
<button v-if="auth.is_superuser"
class="text-gray-900 hover:text-gray-900 group rounded-md px-3 py-2 flex items-center text-sm font-medium cursor-pointer"
@click.prevent="navigateTo('/moderation')"
>
<component
:is="UsersIcon"
class="text-gray-400 group-hover:text-gray-500 flex-shrink-0 -ml-1 mr-3 h-6 w-6" aria-hidden="true"
/>
@click.prevent="navigateTo('/moderation')">
<component :is="UsersIcon" class="text-gray-400 group-hover:text-gray-500 flex-shrink-0 -ml-1 mr-3 h-6 w-6"
aria-hidden="true" />
<span class="truncate">Moderation</span>
</button>
<SettingsValidateEmailButton v-if="!auth.profile.email_validated"/>
</nav>
</aside>
<div class="space-y-6 ml-3 sm:px-6 lg:col-span-9 min-w-full lg:px-0">
Expand Down
46 changes: 0 additions & 46 deletions {{cookiecutter.project_slug}}/frontend/stores/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,52 +191,6 @@ export const useAuthStore = defineStore("authUser", {
this.password = payload.password
this.totp = payload.totp
},
async sendEmailValidation() {
await this.authTokens.refreshTokens()
if (this.authTokens.token && !this.email_validated) {
try {
const { data: response } = await apiAuth.requestValidationEmail(this.authTokens.token)
if (response.value) {
toasts.addNotice({
title: "Validation sent",
content: response.value.msg,
})
}
} catch (error) {
toasts.addNotice({
title: "Validation error",
content: "Please check your email and try again.",
icon: "error"
})
}
}
},
async validateEmail(validationToken: string) {
await this.authTokens.refreshTokens()
if (this.authTokens.token && !this.email_validated) {
try {
const { data: response } = await apiAuth.validateEmail(
this.authTokens.token,
validationToken
)
if (response.value) {
this.email_validated = true
if (response.value) {
toasts.addNotice({
title: "Success",
content: response.value.msg,
})
}
}
} catch (error) {
toasts.addNotice({
title: "Validation error",
content: "Invalid token. Check your email and resend validation.",
icon: "error"
})
}
}
},
async recoverPassword(email: string) {
if (!this.loggedIn) {
try {
Expand Down