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

相关文章

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境

MySQL底层文件的查看和修改方法

《MySQL底层文件的查看和修改方法》MySQL底层文件分为文本类(可安全查看/修改)和二进制类(禁止手动操作),以下按「查看方法、修改方法、风险管控三部分详细说明,所有操作均以Linux环境为例,需... 目录引言一、mysql 底层文件的查看方法1. 先定位核心文件路径(基础前提)2. 文本类文件(可直

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

SpringBoot整合Apache Spark实现一个简单的数据分析功能

《SpringBoot整合ApacheSpark实现一个简单的数据分析功能》ApacheSpark是一个开源的大数据处理框架,它提供了丰富的功能和API,用于分布式数据处理、数据分析和机器学习等任务... 目录第一步、添加android依赖第二步、编写配置类第三步、编写控制类启动项目并测试总结ApacheS

nacos服务无法注册到nacos服务中心问题及解决

《nacos服务无法注册到nacos服务中心问题及解决》本文详细描述了在Linux服务器上使用Tomcat启动Java程序时,服务无法注册到Nacos的排查过程,通过一系列排查步骤,发现问题出在Tom... 目录简介依赖异常情况排查断点调试原因解决NacosRegisterOnWar结果总结简介1、程序在

Python实现繁体转简体功能的三种方案

《Python实现繁体转简体功能的三种方案》在中文信息处理中,繁体字与简体字的转换是一个常见需求,无论是处理港澳台地区的文本数据,还是开发面向不同中文用户群体的应用,繁简转换都是不可或缺的功能,本文将... 目录前言为什么需要繁简转换?python实现方案方案一:使用opencc库方案二:使用zhconv库

kingbase修改权限实现方式

《kingbase修改权限实现方式》该文章详细介绍了如何在数据库中创建用户并赋予其相应的权限,包括创建用户、回收默认权限、创建数据库、赋权数据库权限、创建只读用户以及回收权限等步骤... 目录前言使用步骤总结前言创建用户后对数据库对象的读写权限进行修改使用步骤1、创建用户create user cs

linux实现对.jar文件的配置文件进行修改

《linux实现对.jar文件的配置文件进行修改》文章讲述了如何使用Linux系统修改.jar文件的配置文件,包括进入文件夹、编辑文件、保存并退出编辑器,以及重新启动项目... 目录linux对.jar文件的配置文件进行修改第一步第二步 第三步第四步总结linux对.jar文件的配置文件进行修改第一步进

Qt实现删除布局与布局切换功能

《Qt实现删除布局与布局切换功能》在Qt应用开发中,动态管理布局是一个常见需求,比如根据用户操作动态删除某个布局,或在不同布局间进行切换,本文将详细介绍如何实现这些功能,并通过完整示例展示具体操作,需... 目录一、Qt动态删除布局1. 布局删除的注意事项2. 动态删除布局的实现步骤示例:删除vboxLay

Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)

《Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)》在职场中,Word文档是公认的好伙伴,但你有没有被它折磨过?批量生成合同、制作报告以及发放证书/通知等等,这些重复、低效... 目录重复性文档制作,手动填充模板,效率低下还易错1.python-docx入门:Word文档的“瑞士