)
from sqlalchemy.orm import Session

from . import crud
from .deps import Settings, get_db, get_settings
from .schemas import (
    Auth,
    AuthToken,
    Ticket,
    User,
    UserCreate,
    UserUpdate,
)
from .util import InvalidToken, create_token, extract_payload

router = APIRouter(prefix="/users")


@router.get("", response_model=list[User], tags=["Users"])
def get_users(db: Session = Depends(get_db), email: Optional[str] = None):
    return crud.get_users(db=db, email=email)


@router.get("/{user_id}", response_model=User, tags=["Users"])
def get_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db=db, user_id=user_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"User {user_id} not found.",
        )
Exemplo n.º 2
0
from django.utils.functional import cached_property
from fastapi import APIRouter, Depends, status, Request

from django_etebase import app_settings, models
from django_etebase.token_auth.models import AuthToken
from django_etebase.models import UserInfo
from django_etebase.signals import user_signed_up
from django_etebase.utils import create_user, get_user_queryset, CallbackContext
from myauth.models import UserType, get_typed_user_model
from ..exceptions import AuthenticationFailed, transform_validation_error, HttpError
from ..msgpack import MsgpackRoute
from ..utils import BaseModel, permission_responses, msgpack_encode, msgpack_decode, get_user_username_email_kwargs
from ..dependencies import AuthData, get_auth_data, get_authenticated_user

User = get_typed_user_model()
authentication_router = APIRouter(route_class=MsgpackRoute)


class LoginChallengeIn(BaseModel):
    username: str


class LoginChallengeOut(BaseModel):
    salt: bytes
    challenge: bytes
    version: int


class LoginResponse(BaseModel):
    username: str
    challenge: bytes
Exemplo n.º 3
0
from fastapi import Depends, APIRouter
from sqlalchemy.orm import Session
from app import schemas
from app.database import get_db
from app.repositories import user
router = APIRouter(
    prefix='/user',
    tags=['Users']
)


@router.post('/', response_model=schemas.ShowUser)
def create_user(new_user: schemas.User, db: Session = Depends(get_db)):
    return user.create(new_user, db)


@router.get('/{id}', response_model=schemas.ShowUser)
def get_user(id: int, db: Session = Depends(get_db)):
    return user.get(id, db)
Exemplo n.º 4
0
import asyncpg
from fastapi import APIRouter, HTTPException, Request, status
from pydantic.error_wrappers import ValidationError

from app.entities.user import CreateUser, User, UserDoesNotExist
from app.entities.wallet import WalletEnrollParams
from app.usecases.user import UserUsecase
from app.usecases.wallet import WalletUsecase

router = APIRouter(prefix="/users", tags=["users"])


@router.post("", response_model=User, status_code=status.HTTP_201_CREATED)
async def create_user(request: Request, params: CreateUser) -> User:
    """Creates new user and its wallet."""

    try:
        usecase: UserUsecase = request.app.state.user_usecase
        user = await usecase.create(params.email)
        if not user:
            raise HTTPException(status_code=400, detail="User create error.")
        return user
    except asyncpg.exceptions.UniqueViolationError as unique_exception:
        raise HTTPException(
            status_code=400, detail="User with this email already exists."
        ) from unique_exception
    except asyncpg.exceptions.NotNullViolationError as not_null_exception:
        raise (
            HTTPException(status_code=400, detail="Error of wallet's creation.")
        ) from not_null_exception
Exemplo n.º 5
0
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from datetime import datetime

from api.models.user import Artist, Profile, Client
from api.models.booking import Booking
from api.models.responses import BookingListResponse, SuccessResponse, TimeSlotListResponse
from api.models.requests import CreateBookingRequest, ScheduleBookingRequest, CreateClientRequest, SelectTimeSlotRequest
from api.services.booking import create_booking, get_times, get_user_bookings, booking_exists, select_time, set_price, approve_price, approve_design, schedule_booking, get_artist_bookings
from api.services.dependencies import get_current_artist, get_current_user, get_current_client
from api.services.auth import create_client

router = APIRouter(prefix="/booking", tags=["Booking"])


@router.post("/create", response_model=Booking)
async def new_booking(request: CreateBookingRequest,
                      current_user: Profile = Depends(get_current_user),
                      client: Client = Depends(get_current_client)):
    if client is None:
        client = await create_client(current_user, CreateClientRequest())
    assert client is not None

    booking = await create_booking(request, current_user)
    if booking is None:
        raise HTTPException(status_code=400, detail="Whoops!")
    return Booking(**dict(booking))


@router.get("/list", response_model=BookingListResponse)
async def list_bookings(current_user: Profile = Depends(get_current_user)):
Exemplo n.º 6
0
from fastapi import APIRouter, Form, HTTPException
from fastapi.responses import ORJSONResponse

from src.business.exceptions import ShortTextException, DocumentNotFound
from src.models.documents import Document, NewDocument
from src.business import documents as business_documents

api_router = APIRouter(default_response_class=ORJSONResponse)


@api_router.get("/{document_id}/summary/", response_model=Document)
async def get_document(document_id: int):
    """
    Get document summary
    """
    try:
        summary = business_documents.get_document_summary(document_id)
    except DocumentNotFound as e:
        raise HTTPException(status_code=404, detail={"document_id": str(e)})
    return Document(document_id=document_id, summary=summary)


@api_router.post("/", response_model=NewDocument)
async def create_document(text: str = Form(...)):
    """
    Create document
    """
    try:
        document_id = business_documents.create_document(text)
    except ShortTextException as e:
        raise HTTPException(status_code=422, detail={"text": str(e)})
Exemplo n.º 7
0
from fastapi import APIRouter, HTTPException, Request, status

from app.entities.user import User, UserDoesNotExist
from app.entities.wallet import WalletDoesNotExist, WalletTransferParams
from app.usecases.wallet import WalletUsecase

router = APIRouter(prefix="/wallets", tags=["wallets"])


@router.post("/transfer", response_model=User, status_code=status.HTTP_200_OK)
async def transfer(request: Request, params: WalletTransferParams):
    """Handler for routing of funds from one wallet to another."""

    try:
        usecase: WalletUsecase = request.app.state.wallet_usecase
        user = await usecase.transfer(
            source_wallet_id=params.wallet_from,
            destination_wallet_id=params.wallet_to,
            amount=params.amount,
        )
        return user
    except UserDoesNotExist as user_not_exist:
        raise HTTPException(
            status_code=404,
            detail=f"User does not exists. Full error: {user_not_exist}",
        ) from user_not_exist
    except WalletDoesNotExist as wallet_not_exist:
        raise HTTPException(
            status_code=404,
            detail=f"Wallet does not exists. Full error: {wallet_not_exist}",
        ) from wallet_not_exist
Exemplo n.º 8
0
from fastapi import APIRouter

from micro_blog import blog

routers = APIRouter()

routers.include_router(blog.router, prefix='/blog')
Exemplo n.º 9
0
import uuid
from typing import Optional, List

from fastapi import APIRouter, Depends, Header, HTTPException
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from starlette import status
from starlette.responses import JSONResponse

from rest_introduction_app.api.challenges.challenge_4.model import UserRegistration, User, to_base64, rot13, HQMessage, \
    un_rot13, un_base64

challenge_tag = "Challenge - Cryptography agency that just loooooooves acronyms."
router = APIRouter(prefix="/challenge/acronym_agency")
security = HTTPBasic()


@router.get("/information", status_code=status.HTTP_200_OK)
async def get_information():
    """
    Get this resource to obtain mission debrief
    """
    return {
        "message":
        f"You are an Agent in Bureau of People's Internet Network Deciphering Agency. "
        f"You have received several messages that are currently stored in our system."
        f"Use /encrypted_message to retrieve message. "
        f"Then use your knowledge and tools at your disposal (other endpoints) "
        f"to decipher those messages. "
        f"Hurry though, the timer is set to 2 hours. After that time the messages "
        f"will be wiped out due to security reasons. "
        f"There are six flags waiting. "
Exemplo n.º 10
0
from fastapi import APIRouter, Depends, HTTPException
from mealie.db.database import db
from mealie.db.db_setup import generate_session
from mealie.routes.deps import get_current_user
from mealie.schema.meal import MealPlanIn, MealPlanInDB
from mealie.schema.snackbar import SnackResponse
from mealie.schema.user import GroupInDB, UserInDB
from mealie.services.image import image
from mealie.services.meal_services import get_todays_meal, process_meals
from sqlalchemy.orm.session import Session
from starlette.responses import FileResponse

router = APIRouter(prefix="/api/meal-plans", tags=["Meal Plan"])


@router.get("/all", response_model=list[MealPlanInDB])
def get_all_meals(
    current_user: UserInDB = Depends(get_current_user),
    session: Session = Depends(generate_session),
):
    """ Returns a list of all available Meal Plan """

    return db.groups.get_meals(session, current_user.group)


@router.post("/create")
def create_meal_plan(
    data: MealPlanIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user)
):
    """ Creates a meal plan database entry """
    processed_plan = process_meals(session, data)
Exemplo n.º 11
0
import json
from attr import dataclass

from fastapi import APIRouter, Security, Query
from typing import List, Optional
from fastapi.exceptions import HTTPException
from pydantic.main import BaseModel

from pydantic.tools import parse_obj_as
from . import Reference, NewReference, UpdateReference
from ..users import User
from splash.api.auth import get_current_user
from .references_service import ReferencesService
from splash.service.base import UidInDictError

references_router = APIRouter()


class CreateReferenceResponse(BaseModel):
    uid: str


@dataclass
class Services():
    references: ReferencesService


services = Services(None)


def set_references_service(references_svc: ReferencesService):
Exemplo n.º 12
0
import uvicorn

from fastapi import APIRouter
from pydantic import BaseModel

from ..src.provider import app, fakedb, router as main_router

pact_router = APIRouter()


class ProviderState(BaseModel):
    state: str  # noqa: E999


@pact_router.post("/_pact/provider_states")
async def provider_states(provider_state: ProviderState):
    mapping = {
        'UserA does not exist': setup_no_user_a,
        'UserA exists and is not an administrator':
        setup_user_a_nonadmin
    }
    mapping[provider_state.state]()

    return {'result': mapping[provider_state.state]}


def run_server():
    app.include_router(main_router)
    app.include_router(pact_router)

    uvicorn.run(app)
Exemplo n.º 13
0
from fastapi import APIRouter, Request, Query
from main import templates

router = APIRouter(prefix="/items", tags=["items"])


@router.get('/')
async def items(request: Request):
    return templates.TemplateResponse('index.html', {
        "request": request,
        "for": "items router"
    })


@router.put('/{item_id}')
async def item(item_id: int, q: str = Query(None, min_length=5,
                                            max_length=50)):
    return {"Item": f"You item is {item_id}", "query": q}
Exemplo n.º 14
0
from fastapi import APIRouter, UploadFile, File, Query
from pydantic import BaseModel
from starlette.responses import StreamingResponse

from api.utils import get_projectless_db_connection
from api.utils.db import (
    get_project_readonly_connection,
    get_project_write_connection,
    Connection,
)
from api.utils.extensions import guess_delimiter_by_filename
from db.python.layers.family import FamilyLayer, PedRow
from models.models.family import Family
from models.models.sample import sample_id_transform_to_raw_list

router = APIRouter(prefix='/family', tags=['family'])


class ContentType(Enum):
    """Enum for available content type options for get pedigree endpoint"""

    CSV = 'csv'
    TSV = 'tsv'
    JSON = 'json'


class FamilyUpdateModel(BaseModel):
    """Model for updating a family"""

    id: int
    external_id: Optional[str] = None
Exemplo n.º 15
0
"""
Module with routes regarding the User entity.
"""
from typing import List
from typing import Optional

from fastapi import APIRouter
from pydantic.types import UUID4

from src.core.boundaries.base_schemas import LimitOffsetPaginationResult
from src.core.boundaries.schemas import ChatUserCreationRequest
from src.core.boundaries.schemas import ChatUserResponse
from src.core.services import chatuser_service

chatuser_router = APIRouter()


@chatuser_router.get("/{chatuser_id}", response_model=ChatUserResponse)
async def get_chatuser_by_id(chatuser_id: UUID4):
    """
    Gets a chat user by its id.
    """
    user = await chatuser_service.get_user_by_id(chatuser_id)

    return user


@chatuser_router.get(
    "/", response_model=LimitOffsetPaginationResult[List[ChatUserResponse]])
async def get_chatusers(offset: int = 0,
                        limit: int = 10,
Exemplo n.º 16
0
from fastapi import APIRouter

from app.routers import external_apis, accounts, platforms, transactions

api_router = APIRouter()
api_router.include_router(external_apis.router)
api_router.include_router(accounts.router)
api_router.include_router(platforms.router)
api_router.include_router(transactions.router)
Exemplo n.º 17
0
Arquivo: stats.py Projeto: theMoe/vite
from routers.tokens import get_token_info_list
from routers.sbp import get_sbp
from routers.prices import load_exchangerate
from database.repositories.fullnoderepository import get_active_node_count
from database.models import SessionLocal, get_db
from database.repositories.transactionsrepository import get_disctinct_accounts_by_transaction, get_last_transaction, get_transaction_count_since_last_day
from fastapi import APIRouter, Depends
from dependencies import get_token_header
from routers.net import load_syncInfo
from nodeFunctions import get_node_ip
from datetime import datetime, time

router = APIRouter(
    prefix="/stats",
    tags=["stats"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)

@router.get('/', description='Returns a summary of stats')
async def get_all_stats(db: SessionLocal = Depends(get_db)):
    ip = get_node_ip()
    sync_info = await load_syncInfo(ip)

    block_height = sync_info['result']['current']
    transaction_count = await get_transaction_count_since_last_day(db)
    active_node_count = await get_active_node_count(db)
    total_accounts = await get_disctinct_accounts_by_transaction(db)
    total_super_nodes = len(await get_sbp(ip, False))
    token_list = await get_token_info_list(ip)
    total_tokens = len(token_list)
Exemplo n.º 18
0
from fastapi import FastAPI, APIRouter, Depends
from sqlalchemy.orm import Session

from api.model import crud, models, schemas
from api.model.export_data import data_alimentos
from api.model.database import SessionLocal, engine

data = APIRouter()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@data.get("/export_data/")
def export_data(db: Session = Depends(get_db)):
    data_alimentos.export_data(db)

Exemplo n.º 19
0
)
from fastapi.templating import Jinja2Templates

from ..applogger import rslogger
from ..config import settings
from ..crud import create_useinfo_entry
from ..models import UseinfoValidation
from ..schemas import PeerMessage

# from ..session import auth_manager

# Routing
# =======
# See `APIRouter config` for an explanation of this approach.
# Remove the "discuss" prefix until PR #2640 of FastAPI is merged
router = APIRouter(tags=["discuss"], )

templates = Jinja2Templates(
    directory=f"{settings._book_server_path}/templates/discuss")


class ConnectionManager:
    def __init__(self):
        self.active_connections: Dict[str, WebSocket] = {}

    async def connect(self, user: str, websocket: WebSocket):
        await websocket.accept()
        self.active_connections[user] = websocket

    def disconnect(self, sockid: str):
        del self.active_connections[sockid]
Exemplo n.º 20
0
from hashlib import sha512
import logging

from fastapi import APIRouter
from fastapi.responses import JSONResponse
from requests import get

from app.utils.complexity.squad_score import squad_score, scaler
from app.utils.img_processing.google_api import GoogleAPI, NoTextFoundException
from app.utils.security.header_checking import AuthRouteHandler
from app.api.models import Submission, ImageSubmission

# global variables and services
router = APIRouter(route_class=AuthRouteHandler)
log = logging.getLogger(__name__)
vision = GoogleAPI()


@router.post("/submission/text")
async def submission_text(sub: Submission):
    """Takes a Submission Object and calls the Google Vision API to text annotate
    the passed s3 link, then passes those concatenated transcriptions to the SquadScore
    method, returns:

    Arguments:
    ---
    `sub`: Submission - Submission object **see `help(Submission)` for more info**
    Returns:
    ---
    ```
    {"SubmissionID": int, "IsFlagged": boolean,"LowConfidence": boolean, "Complexity": int}
Exemplo n.º 21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time         : 2021/2/7 10:02
# @Author       : xwh
# @File         : service.py
# @Description  :

from fastapi import APIRouter
from requests import get, post

service_router = APIRouter()


@service_router.get("/status/{name}")
def get_systemd_service_status():
    return
Exemplo n.º 22
0
from fastapi import APIRouter
from sqlalchemy.sql.expression import text
from Application.user.login import login

login_routers = APIRouter()


@login_routers.post("/login")
def _login(username: str, password: str):
    return login(username, password)
Exemplo n.º 23
0
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Path

from .controllers import PostCtrl

post_router = APIRouter(prefix='/posts')


@post_router.get('', summary="获取文章列表")
async def get_posts_list(page: int = 1, per_page: int = 10):
    pagination = PostCtrl().get_posts_paginate(page=page, per_page=per_page)

    return {
        "r": {
            "items": pagination.items,
            "page": pagination.page,
            "per_page": pagination.per_page,
            "total_page": pagination.pages
        },
        "msg": "",
        "code": 0
    }


@post_router.get('/{post_id}', summary="查看文章详情")
async def get_post_detail(post_id: int = Path(...)):
    post = PostCtrl().get_one_post(post_id)
    return {"r": post or {}, "msg": "", "code": 0}
Exemplo n.º 24
0
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import timedelta

from ..schemas import Login
from ..database import get_db
from ..models import User
from ..hashing import Hash
from ..token import create_access_token

router = APIRouter(tags=["Auth"])


@router.post('/login')
def login(req: OAuth2PasswordRequestForm = Depends(),
          db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == req.username).first()
    if not user:
        raise HTTPException(
            status_code=401,
            detail="Incorrect email or password, please try again.")
    if not Hash.verify(req.password, user.password):
        raise HTTPException(
            status_code=401,
            detail="Incorrect email or password, please try again.")
    if Hash.verify(req.password, user.password):
        # access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_access_token(data={"sub": user.email})
        return {"access_token": access_token, "token_type": "bearer"}
Exemplo n.º 25
0
from blog import schemas, database, models, token
from fastapi import APIRouter, Depends, status, HTTPException
from fastapi.security import OAuth2PasswordRequestForm 
from sqlalchemy.orm import Session
from blog.hashing import Hash

# from .. import models
# from ..database import engine
# from .routers import blog, user, authentication

router = APIRouter(
    tags= ['authentication']
)

@router.post('/login')
def login(request:OAuth2PasswordRequestForm = Depends(), db: Session = Depends(database.get_db)):
    user = db.query(models.User).filter(models.User.email == request.username).first()
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Invalid Credentials")
    if not Hash.verify(user.password, request.password):
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Invalid Passowrd")
        
    # access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = token.create_access_token(
        data={"sub": user.name}, 
        # expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}
Exemplo n.º 26
0
from fastapi import APIRouter, Depends, HTTPException
from typing import List
from sqlalchemy.orm import Session
from datetime import timezone

from backend.crud import transaction as trans_crud
from backend.crud import user as user_crud
from backend.schemas import TransactionIn, TransactionOut
from backend import get_db


router = APIRouter(prefix="/transactions", tags=["transactions"])


@router.get("/{user_id}", response_model=List[TransactionOut])
def get_transactions(user_id: str, skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    """
    Route to grab all transactions
    """
    db_user = user_crud.get_user(db=db, user_id=user_id)

    if not db_user:
        raise HTTPException(status_code=400, detail="User does not exist")
        
    return trans_crud.get_transactions(db=db, skip=skip, limit=limit, user_id=user_id)


@router.post("/{user_id}", response_model=TransactionOut)
def create_transaction(user_id: str, transaction: TransactionIn, db: Session = Depends(get_db)):
    """
    Route to create a new transaction
Exemplo n.º 27
0
#  *
#  *      http://www.apache.org/licenses/LICENSE-2.0
#  *
#  * Unless required by applicable law or agreed to in writing, software
#  * distributed under the License is distributed on an "AS IS" BASIS,
#  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  * See the License for the specific language governing permissions and
#  * limitations under the License.

from fastapi import APIRouter
from pydantic import BaseModel, Field

from pims import __api_version__, __version__
from pims.config import ReadableSettings, get_settings

router = APIRouter()


class ServerInfo(BaseModel):
    version: str = Field(..., description='PIMS version')
    api_version: str = Field(..., description='PIMS API specification version')
    settings: ReadableSettings


@router.get('/info', response_model=ServerInfo, tags=['Server'])
def show_status() -> ServerInfo:
    """
    PIMS Server status.
    """
    return ServerInfo(version=__version__,
                      api_version=__api_version__,
Exemplo n.º 28
0
from typing import List

from fastapi import APIRouter, HTTPException, Depends
from starlette.status import (HTTP_201_CREATED, HTTP_409_CONFLICT,
                              HTTP_403_FORBIDDEN, HTTP_200_OK)

from models.user import User
from objects import USER_CLIENT, JWT_SERVICE

app = APIRouter()


@app.post('/user', status_code=HTTP_201_CREATED, tags=['User'])
async def post_user(user: User,
                    roles: List[str] = Depends(JWT_SERVICE.check_jwt_token)):
    if 'admin' not in roles:
        raise HTTPException(HTTP_403_FORBIDDEN,
                            detail='Only admin can create new user')

    if USER_CLIENT.create_user(user):
        return {'msg': 'User has been successfully created'}
    else:
        raise HTTPException(HTTP_409_CONFLICT, detail='User already existed')


@app.delete('/user/{username}', status_code=HTTP_200_OK, tags=['User'])
async def delete_user(username: str,
                      roles: List[str] = Depends(JWT_SERVICE.check_jwt_token)):
    if 'admin' not in roles:
        raise HTTPException(HTTP_403_FORBIDDEN,
                            detail='Only admin can delete new user')
Exemplo n.º 29
0
from api.utils.db import (
    get_projectless_db_connection,
    get_project_readonly_connection,
    get_project_write_connection,
    Connection,
)
from db.python.layers.analysis import AnalysisLayer
from db.python.tables.project import ProjectPermissionsTable
from models.enums import AnalysisType, AnalysisStatus
from models.models.analysis import Analysis
from models.models.sample import (
    sample_id_transform_to_raw_list,
    sample_id_format_list,
)

router = APIRouter(prefix='/analysis', tags=['analysis'])


class AnalysisModel(BaseModel):
    """
    Model for 'createNewAnalysis'
    """

    sample_ids: List[str]
    type: AnalysisType
    status: AnalysisStatus
    meta: Optional[Dict[str, Any]] = None
    output: Optional[str] = None
    active: bool = True
    # please don't use this, unless you're the analysis-runner,
    # the usage is tracked ... (Ծ_Ծ)
Exemplo n.º 30
0
from fastapi import APIRouter
from fastapi_plus.utils.custom_route import CustomRoute

from ..schema.auth import AuthDataSchema, LoginInputSchema
from ..service.user import UserService

router = APIRouter(route_class=CustomRoute)


@router.post('/login', response_model=AuthDataSchema, response_model_exclude_unset=True)
async def login(*, login_input: LoginInputSchema):
    """
    用户登录
    :param login_input: 登录结构
    :return:
    """
    if login_input.type == 'token':
        return UserService().login_by_token(login_input.key)
    elif login_input.type == 'openid':
        return UserService().login_by_openid(login_input.key)
    elif login_input.type == 'code':
        return UserService().login_by_code(login_input.key)
    elif login_input.type == 'password':
        return UserService().login_by_password(login_input.key, login_input.password)
    else:
        return {
            'code': 500,
            'message': '登录错误',
        }