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

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Java实现预览与打印功能详解

《Java实现预览与打印功能详解》在Java中,打印功能主要依赖java.awt.print包,该包提供了与打印相关的一些关键类,比如PrinterJob和PageFormat,它们构成... 目录Java 打印系统概述打印预览与设置使用 PageFormat 和 PrinterJob 类设置页面格式与纸张

MySQL 8 中的一个强大功能 JSON_TABLE示例详解

《MySQL8中的一个强大功能JSON_TABLE示例详解》JSON_TABLE是MySQL8中引入的一个强大功能,它允许用户将JSON数据转换为关系表格式,从而可以更方便地在SQL查询中处理J... 目录基本语法示例示例查询解释应用场景不适用场景1. ‌jsON 数据结构过于复杂或动态变化‌2. ‌性能要

SpringBoot整合Dubbo+ZK注册失败的坑及解决

《SpringBoot整合Dubbo+ZK注册失败的坑及解决》使用Dubbo框架时,需在公共pom添加依赖,启动类加@EnableDubbo,实现类用@DubboService替代@Service,配... 目录1.先看下公共的pom(maven创建的pom工程)2.启动类上加@EnableDubbo3.实

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S