接上一篇文章FastAPI(六十六)实战开发《在线课程学习系统》接口开发--用户注册接口开发。这次我们分享实际开发--用户登陆接口开发。

我们先来梳理下逻辑

1.查询用户是否存在2.校验密码是否正确3.密码校验失败记录失败次数4.失败次数大于10次,当天不能登陆5.密码校验通过产生对应的token返回

接着我们去设计pydantic,用于校验用户登陆

class UserLogin(UserBase):
password: str

  

这里我们继承的是之前的UserBase。

对应操作数据库的curd我们用之前注册的时候使用的get_user_username即可。

我们把密码输入失败和token放在redis中,那么redis对应的配置。

config.py配置
redishost='127.0.0.1'
redisport='6379'
redisdb=0

     我们在main.py增加配置

from fastapi import FastAPI
from aioredis import create_redis_pool, Redis
from routers.user import usersRouter
from routers.websoocket import socketRouter
from routers.file import fileRouter
from config import *
app = FastAPI()
async def get_redis_pool() -> Redis:
redis = await create_redis_pool(f"redis://:@"+redishost+":"+redisport+"/"+redisdb+"?encoding=utf-8")
return redis @app.on_event("startup")
async def startup_event():
app.state.redis = await get_redis_pool() @app.on_event("shutdown")
async def shutdown_event():
app.state.redis.close()
await app.state.redis.wait_closed()

  我们把产生token的配置也一并配置进去

#config.py
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

  那么产生token的代码如何实现呢。

from jose import JWTError, jwt
#routers/user.py
def create_access_token(data: dict):
to_encode = data.copy()
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

  接下来我们就是去根据逻辑去实现最后的代码了。

@usersRouter.post("/login", response_model=UsersToken)
async def login(request: Request, user: UserCreate, db: Session = Depends(get_db)):
db_crest = get_user_username(db, user.username)
if not db_crest:
logger.info("login:"+user.username+"不存在")
return reponse(code=100205,message='用户不存在',data="")
verifypassowrd = verify_password(user.password, db_crest.password)
if verifypassowrd:
useris = await request.app.state.redis.get(user.username)
if not useris:
try:
token = create_access_token(data={"sub": user.username})
except Exception as e:
logger.exception(e)
return reponse(code=100203,message='产生token失败',data='')
request.app.state.redis.set(user.username, token, expire=ACCESS_TOKEN_EXPIRE_MINUTES * 60)
return reponse(code=200,message='成功',data={"token":token})
return reponse(code=100202,message='重复登陆',data='')
else:
result=await request.app.state.redis.hgetall(user.username+"_password", encoding='utf8')
if not result:
times = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
request.app.state.redis.hmset_dict(user.username+"_password",num=0,time=times)
else:
errornum=int(result['num'])
numtime=(datetime.now() - datetime.strptime(result['time'],'%Y-%m-%d %H:%M:%S')).seconds / 60
if errornum<10 and numtime<30:
#更新错误次数
errornum += 1
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum)
return reponse(code=100206,data='',message='密码错误')
elif errornum<10 and numtime>30:
#次数置于1,时间设置现在时间
errornum=1
times = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum,time=times)
return reponse(code=100206,data='',message='密码错误')
elif errornum>10 and numtime<30:
#次数设置成最大,返回
errornum+=1
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum)
return reponse(code=100204,message='输入密码错误次数过多,账号暂时锁定,请30min再来登录',data='')
else:
errornum = 1
times = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
request.app.state.redis.hmset_dict(user.username + "_password", num=errornum, time=times)
return reponse(code=100206, data='', message='密码错误')

  

我们按照最后的代码逻辑实现去完成。

一个完整的登陆接口就实现完毕了。

FastAPI(六十七)实战开发《在线课程学习系统》接口开发--用户登陆接口开发的更多相关文章

  1. FastAPI(六十八)实战开发《在线课程学习系统》接口开发--用户 个人信息接口开发

    在之前的文章:FastAPI(六十七)实战开发<在线课程学习系统>接口开发--用户登陆接口开发,今天实战:用户 个人信息接口开发. 在开发个人信息接口的时候,我们要注意了,因为我们不一样的 ...

  2. FastAPI(六十三)实战开发《在线课程学习系统》梳理系统需要接口

    针对上一篇FastAPI(六十二)实战开发<在线课程学习系统>需求分析需求的功能,我们对需要的接口进行梳理,大概的规划出来现有的接口,作为我们第一版的接口的设计出版,然后我们根据设计的接口 ...

  3. FastAPI(六十二)实战开发《在线课程学习系统》需求分析

    前言 基础的分享我们已经分享了六十篇,那么我们这次分享开始将用一系列的文章分享实战课程.我们分享的系统是在线学习系统.我们会分成不同的模块进行分享.我们的目的是带着大家去用fastapi去实战一次,开 ...

  4. FastAPI(六十九)实战开发《在线课程学习系统》接口开发--修改密码

    之前我们分享了FastAPI(六十八)实战开发<在线课程学习系统>接口开发--用户 个人信息接口开发.这次我们去分享实战开发<在线课程学习系统>接口开发--修改密码 我们梳理一 ...

  5. FastAPI(七十)实战开发《在线课程学习系统》接口开发--留言功能开发

    在之前的文章:FastAPI(六十九)实战开发<在线课程学习系统>接口开发--修改密码,这次分享留言功能开发 我们能梳理下对应的逻辑 1.校验用户是否登录 2.校验留言的用户是否存在 3. ...

  6. FastAPI(七十四)实战开发《在线课程学习系统》接口开发-- 删除留言

    之前文章FastAPI(七十三)实战开发<在线课程学习系统>接口开发-- 回复留言,那么我们这次分享删除留言接口的开发 可以对留言进行删除,这里的删除,我们使用的是逻辑的删除,不是物理删除 ...

  7. FastAPI(七十三)实战开发《在线课程学习系统》接口开发-- 回复留言

    之前文章分享FastAPI(七十二)实战开发<在线课程学习系统>接口开发-- 留言列表开发,这次我们分享如何回复留言 按照惯例,我们还是去分析这里面的逻辑. 1.判断用户是否登录 2.用户 ...

  8. FastAPI(七十二)实战开发《在线课程学习系统》接口开发-- 留言列表开发

    之前我们分享了FastAPI(七十一)实战开发<在线课程学习系统>接口开发-- 查看留言,这次我们分享留言列表开发. 列表获取,也需要登录,根据登录用户来获取对应的留言.逻辑梳理如下. 1 ...

  9. FastAPI(七十一)实战开发《在线课程学习系统》接口开发-- 查看留言

    之前FastAPI(七十)实战开发<在线课程学习系统>接口开发--留言功能开发分享了留言开发,这次我们分享查看留言 梳理这里的逻辑,这个接口要依赖登录. 1.判断用户是否登录 2.判断对应 ...

随机推荐

  1. tensorflow源码解析之distributed_runtime

    本篇主要介绍TF的分布式运行时的基本概念.为了对TF的分布式运行机制有一个大致的了解,我们先结合/tensorflow/core/protobuf中的文件给出对TF分布式集群的初步理解,然后介绍/te ...

  2. Docker的4种网络模式详细介绍

    docker run创建Docker容器时,可以用–net选项指定容器的网络模式,Docker有以下4种网络模式: bridge模式:使用–net =bridge指定: host模式:使用–net = ...

  3. Java基础—构造方法

    1.构造方法概述 构造方法是一种特殊的方法,用来创建对象,当我们不定义时,系统会默认给出一个无参构造方法:一旦我们定义了任意的构造方法,系统就不会给出默认的无参构造方法 格式如下: public ca ...

  4. spring——通过xml文件配置IOC容器

    创建相关的类(这里是直接在之前类的基础上进行修改) package com.guan.dao; public interface Fruit { String getFruit(); } packag ...

  5. 使用阿里云镜像站NTP服务搭建NTP服务器(基于CentOS 7系统)

    镜像下载.域名解析.时间同步请点击 阿里云开源镜像站 一.NTP服务器介绍 网络时间协议(Network Time Protocol,NTP)服务器,也就是日常所说的NTP服务器,用来提供同步时间服务 ...

  6. 常见的url编码

    URL编码值 字符 %20 空格 %22 " %23 # %25 % %26 &; %28 ( %29 ) %2B + %2C , %2F / %3A : %3B ; %3C < ...

  7. winform 学习之qq邮箱正则验证及常用正则

    这段时间一直再做winform相关的项目,记录了一些东西 qq邮箱正则表达式: 第一种:字母和数字组合邮箱判断 string str = "justin1107@qq.com"; ...

  8. MATLAB奔溃仅左上角显示关闭界面X

    一  问题描述 今天在MATLAB调试图像增强程序时,忽然间点了MATLAB向下还原,奇怪的一幕发生了,电脑左上角仅显示关闭图标X.我就搜了MATLAB中文论坛(https://www.ilovema ...

  9. UVA1389 Hard Life (01分数规划+最大流)

    UVA1389 Hard Life (01分数规划+最大流) Luogu 题目描述略 题解时间 $ (\frac{\Sigma EdgeCount}{\Sigma PointCount})_{max} ...

  10. springBoot集成Elasticsearch抛出Factory method 'restHighLevelClient' threw exception; nested exception is java.lang.NoSuchFieldError: IGNORE_DEPRECATIONS

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restHighLeve ...