odoo10 短信注册、修改密码功能

2024-06-18 03:44

本文主要是介绍odoo10 短信注册、修改密码功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、编写模型层

完整代码:

# -*- coding: utf-8 -*-
import httplib
import random
import urllib
from datetime import datetime, timedeltafrom odoo import modelsclass User(models.Model):_inherit = 'res.users'from odoo import models, fields, apiclass ResUsers(models.Model):_inherit = "res.users"use_community_id = fields.Many2one("community", string=u"所属小区")@api.multidef context_get(self):user = self.env.userresult = super(ResUsers, self).context_get()result["self_community_id"] = user.use_community_id.idreturn resultclass SmsVerification(models.Model):_name = 'sms.verification'_description = 'SMS Verification'phone_number = fields.Char("手机号", required=True)code = fields.Char("验证码", required=True)expiration = fields.Datetime("过期时间")@api.modeldef create_verification_code(self, phone_number):existing_record = self.search([('phone_number', '=', phone_number)], limit=1)if existing_record:# 更新现有记录code = str(random.randint(100000, 999999))expiration = datetime.now() + timedelta(hours=1)existing_record.write({'code': code,'expiration': expiration,})else:# 创建新记录code = str(random.randint(100000, 999999))expiration = datetime.now() + timedelta(hours=1)self.create({'phone_number': phone_number,'code': code,'expiration': expiration,})# 发送短信send_sms("您的验证码是:{}。请不要把验证码泄露给其他人。".format(code), phone_number)

这段代码包含两个部分:一个是对 res.users 模型的扩展,另一个是定义一个新的 sms.verification 模型。

1. 扩展 res.users 模型

class ResUsers(models.Model):_inherit = "res.users"use_community_id = fields.Many2one("community", string=u"所属小区")@api.multidef context_get(self):user = self.env.userresult = super(ResUsers, self).context_get()result["self_community_id"] = user.use_community_id.idreturn result
解释:
  • 字段 use_community_id:

    • 添加了一个新字段 use_community_id,这是一个指向 community 模型的 Many2one 字段,用于存储用户所属的小区信息。
  • 方法 context_get:

    • 重写了 context_get 方法,在调用原有方法的基础上,添加了当前用户的社区 ID 到上下文中。

2. 新模型 sms.verification

class SmsVerification(models.Model):_name = 'sms.verification'_description = 'SMS Verification'phone_number = fields.Char("手机号", required=True)code = fields.Char("验证码", required=True)expiration = fields.Datetime("过期时间")@api.modeldef create_verification_code(self, phone_number):existing_record = self.search([('phone_number', '=', phone_number)], limit=1)if existing_record:# 更新现有记录code = str(random.randint(100000, 999999))expiration = datetime.now() + timedelta(hours=1)existing_record.write({'code': code,'expiration': expiration,})else:# 创建新记录code = str(random.randint(100000, 999999))expiration = datetime.now() + timedelta(hours=1)self.create({'phone_number': phone_number,'code': code,'expiration': expiration,})# 发送短信send_sms("您的验证码是:{}。请不要把验证码泄露给其他人。".format(code), phone_number)
解释:
  • 字段 phone_number, code, expiration:

    • phone_number: 存储手机号码。
    • code: 存储验证码。
    • expiration: 存储验证码的过期时间。
  • 方法 create_verification_code:

    • 生成一个新的验证码,并在数据库中查找是否已有该号码的记录。
    • 如果存在,更新记录的验证码和过期时间。
    • 如果不存在,创建新记录。
    • 发送包含验证码的短信到指定手机号码。

这个代码的目的是扩展用户模型以包含社区信息,并提供一个用于生成和管理短信验证码的模型。

二、编写控制层

完整代码:

import json
import traceback
from datetime import datetime, timedeltafrom odoo import http, models, fields, api
from odoo.http import request, _loggerdef Success(message="成功!", data=''):response_data = json.dumps({"status": 200,"message": message,"data": data})return http.Response(response_data, status=200, mimetype='application/json')def Failure(message="失败!", data=''):response_data = json.dumps({"status": 400,"message": message,"data": data})return http.Response(response_data, status=400, mimetype='application/json')class User(http.Controller):@http.route('/user/signup/', auth='public', methods=["post"], csrf=False)def signup(self, **kw):""" 注册"""try:# 确保传入了必需的参数phone_number = kw.get('phone_number')password = kw.get('password')use_community_id = kw.get('use_community_id')verification_code = kw.get('verification_code')  # 获取验证码grop = kw.get('grop')  # 获取用户组print(use_community_id)error = User.signupCheck(phone_number, password, verification_code)if error:return Failure(error)# 创建新用户new_obj = request.env['res.users'].sudo().create({'name': phone_number,'login': phone_number,'password': password,  # 实际应用中应使用哈希处理密码'lang': 'zh_CN','tz': 'Asia/Shanghai','use_community_id':int(use_community_id),grop: True,})# # 更新 use_community_id 字段# if use_community_id:#     new_obj.sudo().write({'use_community_id': int(use_community_id)})return Success(message="注册成功")except Exception as e:traceback.print_exc()_logger.info(e)return json.dumps({"code": 400, "message": u"操作失败,未知错误,请咨询管理员"})# 修改密码@http.route('/user/change_password/', auth='public', methods=["post"], csrf=False)def change_password(self, **kw):""" 修改密码"""try:# 确保传入了必需的参数phone_number = kw.get('phone_number')new_password = kw.get('new_password')verification_code = kw.get('verification_code')# 短信验证码校验stored_code = request.env['sms.verification'].sudo().search([('phone_number', '=', phone_number)], limit=1)if not stored_code or stored_code.code != verification_code:return Failure("验证码无效或不匹配")# 验证用户是否存在user = request.env['res.users'].sudo().search([('name', '=', phone_number)], limit=1)if not user.exists():return Failure("用户不存在")# 校验验证码有效期if stored_code.expiration < fields.Datetime.now():return Failure("验证码已过期")user.write({'password': new_password})stored_code.write({'expiration': datetime.now() - timedelta(minutes=1)})  # 更新验证码有效期return Success(message="密码修改成功")except Exception as e:traceback.print_exc()_logger.info(e)return Failure("操作失败,未知错误,请咨询管理员")@staticmethoddef signupCheck(phone_number, password, verification_code):""" 注册数据检测"""if not phone_number or not password:return "必须输入手机号或者密码"# 验证账号是否已存在if request.env['res.users'].sudo().search_count([('login', '=', phone_number)]) > 0:return "账号已存在"# 短信验证码校验if not verification_code:return "必须输入验证码"stored_code = request.env['sms.verification'].sudo().search([('phone_number', '=', phone_number)], limit=1)if not stored_code or stored_code.code != verification_code:return "验证码无效或不匹配"# 校验验证码有效期if stored_code.expiration < fields.Datetime.now():return "验证码已过期"return None@http.route('/user/send_verification_code/', auth='public', methods=["post"], csrf=False)def send_verification_code(self, **kw):""" 发送验证码 """try:phone_number = kw.get('phone_number')if not phone_number:return json.dumps({"code": 400, "message": "必须提供手机号"})# 调用 create_verification_code 方法生成并发送验证码request.env['sms.verification'].sudo().create_verification_code(phone_number)return Success(message="验证码已发送")except Exception as e:traceback.print_exc()_logger.info(e)return Failure("操作失败,未知错误,请咨询管理员")

这段代码定义了一个 Odoo HTTP 控制器类 User,用于处理用户注册、修改密码和发送验证码的请求。以下是每个方法的简要解释:

1. 注册用户 (/user/signup/)

@http.route('/user/signup/', auth='public', methods=["post"], csrf=False)def signup(self, **kw):""" 注册"""try:# 确保传入了必需的参数phone_number = kw.get('phone_number')password = kw.get('password')use_community_id = kw.get('use_community_id')verification_code = kw.get('verification_code')  # 获取验证码grop = kw.get('grop')  # 获取用户组print(use_community_id)error = User.signupCheck(phone_number, password, verification_code)if error:return Failure(error)# 创建新用户new_obj = request.env['res.users'].sudo().create({'name': phone_number,'login': phone_number,'password': password,  # 实际应用中应使用哈希处理密码'lang': 'zh_CN','tz': 'Asia/Shanghai','use_community_id':int(use_community_id),grop: True,})return Success(message="注册成功")except Exception as e:traceback.print_exc()_logger.info(e)return json.dumps({"code": 400, "message": u"操作失败,未知错误,请咨询管理员"})
解释:
  • 处理注册请求:从请求中获取手机号、密码、社区ID、验证码和用户组等参数。
  • 调用 signupCheck 方法:检查输入的手机号、密码和验证码是否有效。
  • 创建新用户:如果没有错误,创建一个新的用户,并根据需要更新 use_community_id 字段。
  • 返回结果:返回 JSON 格式的成功或失败消息。

2. 修改密码 (/user/change_password/)

@http.route('/user/change_password/', auth='public', methods=["post"], csrf=False)
def change_password(self, **kw):try:phone_number = kw.get('phone_number')new_password = kw.get('new_password')verification_code = kw.get('verification_code')stored_code = request.env['sms.verification'].sudo().search([('phone_number', '=', phone_number)], limit=1)if not stored_code or stored_code.code != verification_code:return Failure("验证码无效或不匹配")user = request.env['res.users'].sudo().search([('name', '=', phone_number)], limit=1)if not user.exists():return Failure("用户不存在")if stored_code.expiration < fields.Datetime.now():return Failure("验证码已过期")user.write({'password': new_password})stored_code.write({'expiration': datetime.now() - timedelta(minutes=1)})return Success(message="密码修改成功")except Exception as e:traceback.print_exc()_logger.info(e)return Failure("操作失败,未知错误,请咨询管理员")
解释:
  • 处理修改密码请求:从请求中获取手机号、新密码和验证码。
  • 验证验证码:检查验证码是否匹配且未过期。
  • 验证用户存在:检查用户是否存在。
  • 更新密码:如果验证通过,更新用户密码,并使验证码失效。
  • 返回结果:返回 JSON 格式的成功或失败消息。

3. 注册数据检查 (signupCheck 方法)

@staticmethod
def signupCheck(phone_number, password, verification_code):if not phone_number or not password:return "必须输入手机号或者密码"if request.env['res.users'].sudo().search_count([('login', '=', phone_number)]) > 0:return "账号已存在"if not verification_code:return "必须输入验证码"stored_code = request.env['sms.verification'].sudo().search([('phone_number', '=', phone_number)], limit=1)if not stored_code or stored_code.code != verification_code:return "验证码无效或不匹配"if stored_code.expiration < fields.Datetime.now():return "验证码已过期"return None
解释:
  • 检查注册数据:验证手机号和密码是否存在,账号是否已存在,验证码是否有效及未过期。
  • 返回错误消息:如果有错误,返回相应的错误信息;否则返回 None

4. 发送验证码 (/user/send_verification_code/)

@http.route('/user/send_verification_code/', auth='public', methods=["post"], csrf=False)
def send_verification_code(self, **kw):try:phone_number = kw.get('phone_number')if not phone_number:return json.dumps({"code": 400, "message": "必须提供手机号"})request.env['sms.verification'].sudo().create_verification_code(phone_number)return Success(message="验证码已发送")except Exception as e:traceback.print_exc()_logger.info(e)return Failure("操作失败,未知错误,请咨询管理员")
解释:
  • 处理发送验证码请求:从请求中获取手机号。
  • 生成并发送验证码:调用 sms.verification 模型中的 create_verification_code 方法生成并发送验证码。
  • 返回结果:返回 JSON 格式的成功或失败消息。

5. SuccessFailure 函数

假设 SuccessFailure 是定义在其他地方的帮助函数,用于返回统一格式的成功和失败消息。

这段代码主要是处理用户的注册、修改密码和发送验证码功能,确保用户输入的数据有效,并提供相应的反馈消息。

这篇关于odoo10 短信注册、修改密码功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1071210

相关文章

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

MySQL8 密码强度评估与配置详解

《MySQL8密码强度评估与配置详解》MySQL8默认启用密码强度插件,实施MEDIUM策略(长度8、含数字/字母/特殊字符),支持动态调整与配置文件设置,推荐使用STRONG策略并定期更新密码以提... 目录一、mysql 8 密码强度评估机制1.核心插件:validate_password2.密码策略级

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

基于Java和FFmpeg实现视频压缩和剪辑功能

《基于Java和FFmpeg实现视频压缩和剪辑功能》在视频处理开发中,压缩和剪辑是常见的需求,本文将介绍如何使用Java结合FFmpeg实现视频压缩和剪辑功能,同时去除数据库操作,仅专注于视频处理,需... 目录引言1. 环境准备1.1 项目依赖1.2 安装 FFmpeg2. 视频压缩功能实现2.1 主要功

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦

MySQL设置密码复杂度策略的完整步骤(附代码示例)

《MySQL设置密码复杂度策略的完整步骤(附代码示例)》MySQL密码策略还可能包括密码复杂度的检查,如是否要求密码包含大写字母、小写字母、数字和特殊字符等,:本文主要介绍MySQL设置密码复杂度... 目录前言1. 使用 validate_password 插件1.1 启用 validate_passwo

Java实现TXT文件导入功能的详细步骤

《Java实现TXT文件导入功能的详细步骤》在实际开发中,很多应用场景需要将用户上传的TXT文件进行解析,并将文件中的数据导入到数据库或其他存储系统中,本文将演示如何用Java实现一个基本的TXT文件... 目录前言1. 项目需求分析2. 示例文件格式3. 实现步骤3.1. 准备数据库(假设使用 mysql

Springboot项目登录校验功能实现

《Springboot项目登录校验功能实现》本文介绍了Web登录校验的重要性,对比了Cookie、Session和JWT三种会话技术,分析其优缺点,并讲解了过滤器与拦截器的统一拦截方案,推荐使用JWT... 目录引言一、登录校验的基本概念二、HTTP协议的无状态性三、会话跟android踪技术1. Cook