vapor 邮件发送确认码
2018-10-06 本文已影响1人
搞好关系
接上节发送邮件,这次我们结合数据库实现发送邮件验证码
我们假设的是用户注册验证码:
首先邮箱唯一,其次验证码有有效期默认一天
struct SKRegistVerfiy: SQLiteModel {
var id: Int?
var email: String
var verfiyCode: String = VerfiyCodeRender.renderInstance.default
var create: TimeInterval = Date().timeIntervalSince1970
var expri: Double = 60 * 60 * 24
}
extension SKRegistVerfiy{
/// 邮箱验证入库
///
/// - Parameters:
/// - email: 接受验证码的邮箱
/// - code: 随机验证码 默认6位数字
/// - expri: 有效期默认1天
init(email: String, verfiyCode code:String = VerfiyCodeRender.renderInstance.default, expri: Double = 24 * 60 * 60){
let time = Date().timeIntervalSince1970
self.init(id: nil,
email: email,
verfiyCode: code,
create: time,
expri: expri)
}
}
extension SKRegistVerfiy{
var isCodeAvailable: Bool{
return Date().timeIntervalSince1970 - create <= expri
}
var message:String{
return "您的确认码已经发到:\(self.email) 确认码是:\(verfiyCode) 将在\(expri/(24*60*60))天过期"
}
}
extension SKRegistVerfiy: All{}
All是个组合protocol:typealias All = Migration&Content&Parameter
我们需要在configure.swift中配置:migrations.add(model: SKRegistVerfiy.self, database: .sqlite)
注册验证码发送
router.get("email") { req -> EventLoopFuture<String> in
struct Email: Content {
var email: String
}
let email: Email = try req.query.decode(Email.self)
return SKRegistVerfiy.query(on: req).filter(\.email, .equal, email.email).first().flatMap({ (verfiy) -> EventLoopFuture<String> in
if let v = verfiy {//已经存在
let result = req.eventLoop.newPromise(String.self)
result.succeed(result: v.emailExistMessage)
return result.futureResult
}else{
let reg = SKRegistVerfiy.init(email: email.email)
return reg.save(on: req).flatMap({ (skVer) -> EventLoopFuture<String> in
let smtp: SMTP = SMTP.init(hostname: "smtp.163.com", email: "lylapp@163.com", password: "301324lee")
let fromUser = Mail.User(name: "注册码确认邮件", email: "lylapp@163.com")
let email = skVer.email
let toUser = Mail.User.init(email: email)
let mail = Mail(from: fromUser
, to: [toUser]
, cc: [], bcc: []
, subject: "欢迎®️"
, text: skVer.message
, attachments: []
, additionalHeaders: [:])
let result = req.eventLoop.newPromise(String.self)
smtp.send(mail, completion: { (error) in
print(error as Any)
if let error = error {
result.fail(error: error)
}else{
result.succeed(result: skVer.message)
}
})
return result.futureResult
})
}
})
}
查询中输出的sql log:
WX20181006-122354@2x.png