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

相关文章

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

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

Golang如何用gorm实现分页的功能

《Golang如何用gorm实现分页的功能》:本文主要介绍Golang如何用gorm实现分页的功能方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景go库下载初始化数据【1】建表【2】插入数据【3】查看数据4、代码示例【1】gorm结构体定义【2】分页结构体

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

PostgreSQL数据库密码被遗忘时的操作步骤

《PostgreSQL数据库密码被遗忘时的操作步骤》密码遗忘是常见的用户问题,因此提供一种安全的遗忘密码找回机制是十分必要的,:本文主要介绍PostgreSQL数据库密码被遗忘时的操作步骤的相关资... 目录前言一、背景知识二、Windows环境下的解决步骤1. 找到PostgreSQL安装目录2. 修改p

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名