Răsfoiți Sursa

邮箱验证码

wangqifan 4 ani în urmă
părinte
comite
ef8008c416

+ 5 - 0
pom.xml

@@ -266,6 +266,11 @@
             <version>2.0</version>
         </dependency>
 
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-mail</artifactId>
+        </dependency>
+
         <!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
         <dependency>
             <groupId>com.belerweb</groupId>

+ 33 - 0
src/main/java/com/izouma/nineth/domain/MailRecord.java

@@ -0,0 +1,33 @@
+package com.izouma.nineth.domain;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import java.time.LocalDateTime;
+
+@Data
+@Entity
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+@ApiModel("邮件记录")
+public class MailRecord extends BaseEntity {
+    @ApiModelProperty(value = "会话ID", name = "sessionId")
+    private String        sessionId;
+    @ApiModelProperty(value = "邮箱号", name = "phone;")
+    private String        mail;
+    @ApiModelProperty(value = "验证码", name = "code")
+    private String        code;
+    @ApiModelProperty(value = "过期时间", name = "expiresAt")
+    private LocalDateTime expiresAt;
+    @ApiModelProperty(value = "是否过期", name = "expired")
+    private Boolean       expired;
+    @ApiModelProperty(value = "验证码用途", name = "scope")
+    private String        scope;
+}

+ 22 - 0
src/main/java/com/izouma/nineth/repo/MailRecordRepo.java

@@ -0,0 +1,22 @@
+package com.izouma.nineth.repo;
+
+import com.izouma.nineth.domain.Like;
+import com.izouma.nineth.domain.MailRecord;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+
+import javax.transaction.Transactional;
+import java.util.List;
+
+public interface MailRecordRepo extends JpaRepository<MailRecord, Long>, JpaSpecificationExecutor<MailRecord> {
+    @Query("update MailRecord t set t.del = true where t.id = ?1")
+    @Modifying
+    @Transactional
+    void softDelete(Long id);
+
+    MailRecord findFirstByMailOrderByExpiresAtDesc(String mail);
+
+    List<MailRecord> findAllByMailAndExpired(String mail, boolean expired);
+}

+ 76 - 0
src/main/java/com/izouma/nineth/service/MailRecordService.java

@@ -0,0 +1,76 @@
+package com.izouma.nineth.service;
+
+import com.izouma.nineth.domain.MailRecord;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.repo.MailRecordRepo;
+import com.izouma.nineth.utils.JpaUtils;
+import lombok.AllArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.mail.SimpleMailMessage;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+
+@Service
+@AllArgsConstructor
+public class MailRecordService {
+
+    private final JavaMailSenderImpl mailSender;
+    private final MailRecordRepo     mailRecordRepo;
+
+    public Page<MailRecord> all(PageQuery pageQuery) {
+        return mailRecordRepo
+                .findAll(JpaUtils.toSpecification(pageQuery, MailRecord.class), JpaUtils.toPageRequest(pageQuery));
+    }
+
+    public void sendCode(String mailAddress) {
+        String code = String.valueOf(((Math.random() * 9 + 1) * 1000));
+        SimpleMailMessage message = new SimpleMailMessage();
+        message.setSubject("注册验证码");
+        message.setText("邮箱验证码是:" + code);
+        message.setTo(mailAddress);
+        message.setFrom("modernPoint01@163.com");
+        mailSender.send(message);
+        MailRecord mailRecord = new MailRecord();
+        mailRecord.setMail(mailAddress);
+        mailRecord.setExpiresAt(LocalDateTime.now().plusMinutes(5));
+        mailRecord.setExpired(false);
+        mailRecord.setCode(code);
+        mailRecordRepo.save(mailRecord);
+        List<MailRecord> mailRecords = mailRecordRepo.findAllByMailAndExpired(mailAddress, false);
+        List<MailRecord> recordShouldExpired = new ArrayList<>();
+        mailRecords.forEach(mailRecord1 -> {
+            if (!code.equals(mailRecord1.getCode())) {
+                mailRecord1.setExpired(true);
+                recordShouldExpired.add(mailRecord1);
+            }
+        });
+        if (recordShouldExpired.size() > 0) {
+            mailRecordRepo.saveAll(recordShouldExpired);
+        }
+    }
+
+    public boolean verifyCode(String code, String mailAddress) {
+        MailRecord mailRecord = mailRecordRepo.findFirstByMailOrderByExpiresAtDesc(mailAddress);
+        if (mailRecord != null) {
+            String origCode = mailRecord.getCode();
+            LocalDateTime now = LocalDateTime.now();
+            if (now.isAfter(mailRecord.getExpiresAt())) {
+                if (StringUtils.equals(code, origCode)) {
+                    mailRecord.setExpired(true);
+                    mailRecordRepo.save(mailRecord);
+                    return true;
+                }
+            } else {
+                mailRecord.setExpired(true);
+                mailRecordRepo.save(mailRecord);
+            }
+        }
+        return false;
+    }
+}

+ 73 - 0
src/main/java/com/izouma/nineth/web/MailRecordController.java

@@ -0,0 +1,73 @@
+package com.izouma.nineth.web;
+
+import com.izouma.nineth.domain.MailRecord;
+import com.izouma.nineth.service.MailRecordService;
+import com.izouma.nineth.dto.PageQuery;
+import com.izouma.nineth.exception.BusinessException;
+import com.izouma.nineth.repo.MailRecordRepo;
+import com.izouma.nineth.utils.ObjUtils;
+import com.izouma.nineth.utils.excel.ExcelUtils;
+import lombok.AllArgsConstructor;
+import org.springframework.data.domain.Page;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.List;
+
+@RestController
+@RequestMapping("/mailRecord")
+@AllArgsConstructor
+public class MailRecordController extends BaseController {
+    private MailRecordService mailRecordService;
+    private MailRecordRepo    mailRecordRepo;
+
+    //@PreAuthorize("hasRole('ADMIN')")
+    @PostMapping("/save")
+    public MailRecord save(@RequestBody MailRecord record) {
+        if (record.getId() != null) {
+            MailRecord orig = mailRecordRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
+            ObjUtils.merge(orig, record);
+            return mailRecordRepo.save(orig);
+        }
+        return mailRecordRepo.save(record);
+    }
+
+
+    //@PreAuthorize("hasRole('ADMIN')")
+    @PostMapping("/all")
+    public Page<MailRecord> all(@RequestBody PageQuery pageQuery) {
+        return mailRecordService.all(pageQuery);
+    }
+
+    @GetMapping("/get/{id}")
+    public MailRecord get(@PathVariable Long id) {
+        return mailRecordRepo.findById(id).orElseThrow(new BusinessException("无记录"));
+    }
+
+    @PostMapping("/del/{id}")
+    public void del(@PathVariable Long id) {
+        mailRecordRepo.softDelete(id);
+    }
+
+    @GetMapping("/excel")
+    @ResponseBody
+    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
+        List<MailRecord> data = all(pageQuery).getContent();
+        ExcelUtils.export(response, data);
+    }
+
+    //发送邮箱验证码
+    @PostMapping("/sendCode")
+    public void sendCode(String mailAddress) {
+        mailRecordService.sendCode(mailAddress);
+    }
+
+    //邮箱认证
+    @PostMapping("/verify")
+    public void verify(String code, String mailAddress) {
+        mailRecordService.verifyCode(code, mailAddress);
+    }
+}
+

+ 6 - 0
src/main/resources/application.yaml

@@ -9,6 +9,12 @@ server:
     whitelabel:
       enabled: false
 spring:
+  #    开启邮箱服务--发送邮件功能
+  mail:
+    username: modernPoint01@163.com
+    #    password不是QQ密码是邮箱验证的授权码(填写刚刚获取的授权码)
+    password: ESBVMEKEBGBLELFJ
+    host: smtp.163.com
   profiles:
     active: dev
   datasource:

+ 120 - 0
src/main/vue/src/views/MailRecordEdit.vue

@@ -0,0 +1,120 @@
+<template>
+    <div class="edit-view">
+        <page-title>
+            <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
+            <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
+                删除
+            </el-button>
+            <el-button @click="onSave" :loading="saving" type="primary">保存</el-button>
+        </page-title>
+        <div class="edit-view__content-wrapper">
+            <div class="edit-view__content-section">
+                <el-form :model="formData" :rules="rules" ref="form" label-width="94px" label-position="right"
+                         size="small"
+                         style="max-width: 500px;">
+                        <el-form-item prop="sessionId" label="会话ID">
+                                    <el-input v-model="formData.sessionId"></el-input>
+                        </el-form-item>
+                        <el-form-item prop="mail" label="邮箱号">
+                                    <el-input v-model="formData.mail"></el-input>
+                        </el-form-item>
+                        <el-form-item prop="code" label="验证码">
+                                    <el-input v-model="formData.code"></el-input>
+                        </el-form-item>
+                        <el-form-item prop="expiresAt" label="过期时间">
+                                    <el-date-picker
+                                            v-model="formData.expiresAt"
+                                            type="datetime"
+                                            value-format="yyyy-MM-dd HH:mm:ss"
+                                            placeholder="选择日期时间">
+                                    </el-date-picker>
+                        </el-form-item>
+                        <el-form-item prop="expired" label="是否过期">
+                                    <el-switch v-model="formData.expired"></el-switch>
+                        </el-form-item>
+                        <el-form-item prop="scope" label="验证码用途">
+                                    <el-input v-model="formData.scope"></el-input>
+                        </el-form-item>
+                    <el-form-item class="form-submit">
+                        <el-button @click="onSave" :loading="saving" type="primary">
+                            保存
+                        </el-button>
+                        <el-button @click="onDelete" :disabled="saving" type="danger" v-if="formData.id">
+                            删除
+                        </el-button>
+                        <el-button @click="$router.go(-1)" :disabled="saving">取消</el-button>
+                    </el-form-item>
+                </el-form>
+            </div>
+        </div>
+    </div>
+</template>
+<script>
+    export default {
+        name: 'MailRecordEdit',
+        created() {
+            if (this.$route.query.id) {
+                this.$http
+                    .get('mailRecord/get/' + this.$route.query.id)
+                    .then(res => {
+                        this.formData = res;
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.$message.error(e.error);
+                    });
+            }
+        },
+        data() {
+            return {
+                saving: false,
+                formData: {
+                },
+                rules: {
+                },
+            }
+        },
+        methods: {
+            onSave() {
+                this.$refs.form.validate((valid) => {
+                    if (valid) {
+                        this.submit();
+                    } else {
+                        return false;
+                    }
+                });
+            },
+            submit() {
+                let data = {...this.formData};
+
+                this.saving = true;
+                this.$http
+                    .post('/mailRecord/save', data, {body: 'json'})
+                    .then(res => {
+                        this.saving = false;
+                        this.$message.success('成功');
+                        this.$router.go(-1);
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.saving = false;
+                        this.$message.error(e.error);
+                    });
+            },
+            onDelete() {
+                this.$confirm('删除将无法恢复,确认要删除么?', '警告', {type: 'error'}).then(() => {
+                    return this.$http.post(`/mailRecord/del/${this.formData.id}`)
+                }).then(() => {
+                    this.$message.success('删除成功');
+                    this.$router.go(-1);
+                }).catch(e => {
+                    if (e !== 'cancel') {
+                        console.log(e);
+                        this.$message.error((e || {}).error || '删除失败');
+                    }
+                })
+            },
+        }
+    }
+</script>
+<style lang="less" scoped></style>

+ 181 - 0
src/main/vue/src/views/MailRecordList.vue

@@ -0,0 +1,181 @@
+<template>
+    <div  class="list-view">
+        <page-title>
+            <el-button @click="addRow" type="primary" icon="el-icon-plus" :disabled="fetchingData || downloading" class="filter-item">
+                新增
+            </el-button>
+            <el-button @click="download" icon="el-icon-upload2" :loading="downloading" :disabled="fetchingData" class="filter-item">
+                导出
+            </el-button>
+        </page-title>
+        <div class="filters-container">
+            <el-input
+                    placeholder="搜索..."
+                    v-model="search"
+                    clearable
+                    class="filter-item search"
+                    @keyup.enter.native="getData"
+            >
+                <el-button @click="getData" slot="append" icon="el-icon-search"> </el-button>
+            </el-input>
+        </div>
+        <el-table :data="tableData" row-key="id" ref="table"
+                  header-row-class-name="table-header-row"
+                  header-cell-class-name="table-header-cell"
+                  row-class-name="table-row" cell-class-name="table-cell"
+                  :height="tableHeight" v-loading="fetchingData">
+            <el-table-column v-if="multipleMode" align="center" type="selection"
+                             width="50">
+            </el-table-column>
+            <el-table-column prop="id" label="ID" width="100">
+            </el-table-column>
+                                <el-table-column prop="sessionId" label="会话ID"
+>
+                    </el-table-column>
+                    <el-table-column prop="mail" label="邮箱号"
+>
+                    </el-table-column>
+                    <el-table-column prop="code" label="验证码"
+>
+                    </el-table-column>
+                    <el-table-column prop="expiresAt" label="过期时间"
+>
+                    </el-table-column>
+                    <el-table-column prop="expired" label="是否过期"
+>
+                            <template slot-scope="{row}">
+                                <el-tag :type="row.expired?'':'info'">{{row.expired}}</el-tag>
+                            </template>
+                    </el-table-column>
+                    <el-table-column prop="scope" label="验证码用途"
+>
+                    </el-table-column>
+            <el-table-column
+                    label="操作"
+                    align="center"
+                    fixed="right"
+                    width="150">
+                <template slot-scope="{row}">
+                    <el-button @click="editRow(row)" type="primary" size="mini" plain>编辑</el-button>
+                    <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</el-button>
+                </template>
+            </el-table-column>
+        </el-table>
+        <div class="pagination-wrapper">
+            <!-- <div class="multiple-mode-wrapper">
+                <el-button v-if="!multipleMode" @click="toggleMultipleMode(true)">批量编辑</el-button>
+                <el-button-group v-else>
+                    <el-button @click="operation1">批量操作1</el-button>
+                    <el-button @click="operation2">批量操作2</el-button>
+                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
+                </el-button-group>
+            </div> -->
+            <el-pagination background @size-change="onSizeChange"
+                           @current-change="onCurrentChange" :current-page="page"
+                           :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize"
+                           layout="total, sizes, prev, pager, next, jumper"
+                           :total="totalElements">
+            </el-pagination>
+        </div>
+
+    </div>
+</template>
+<script>
+    import { mapState } from "vuex";
+    import pageableTable from "@/mixins/pageableTable";
+
+    export default {
+        name: 'MailRecordList',
+        mixins: [pageableTable],
+        data() {
+            return {
+                multipleMode: false,
+                search: "",
+                url: "/mailRecord/all",
+                downloading: false,
+            }
+        },
+        computed: {
+            selection() {
+                return this.$refs.table.selection.map(i => i.id);
+            }
+        },
+        methods: {
+            beforeGetData() {
+                return { search: this.search, query: { del: false } };
+            },
+            toggleMultipleMode(multipleMode) {
+                this.multipleMode = multipleMode;
+                if (!multipleMode) {
+                    this.$refs.table.clearSelection();
+                }
+            },
+            addRow() {
+                this.$router.push({
+                    path: "/mailRecordEdit",
+                    query: {
+                        ...this.$route.query
+                    }
+                });
+            },
+            editRow(row) {
+                this.$router.push({
+                    path: "/mailRecordEdit",
+                    query: {
+                    id: row.id
+                    }
+                });
+            },
+            download() {
+                this.downloading = true;
+                this.$axios
+                    .get("/mailRecord/excel", { 
+                        responseType: "blob",
+                        params: { size: 10000 }
+                    })
+                    .then(res => {
+                        console.log(res);
+                        this.downloading = false;
+                        const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
+                        const link = document.createElement("a");
+                        link.href = downloadUrl;
+                        link.setAttribute(
+                            "download",
+                            res.headers["content-disposition"].split("filename=")[1]
+                        );
+                        document.body.appendChild(link);
+                        link.click();
+                        link.remove();
+                    })
+                    .catch(e => {
+                        console.log(e);
+                        this.downloading = false;
+                        this.$message.error(e.error);
+                    });
+            },
+            operation1() {
+                this.$notify({
+                    title: '提示',
+                    message: this.selection
+                });
+            },
+            operation2() {
+                this.$message('操作2');
+            },
+            deleteRow(row) {
+                this.$alert('删除将无法恢复,确认要删除么?', '警告', {type: 'error'}).then(() => {
+                    return this.$http.post(`/mailRecord/del/${row.id}`)
+                }).then(() => {
+                    this.$message.success('删除成功');
+                    this.getData();
+                }).catch(e => {
+                    if (e !== 'cancel') {
+                        this.$message.error(e.error);
+                    }
+                })
+            },
+        }
+    }
+</script>
+<style lang="less" scoped>
+</style>

+ 28 - 0
src/test/java/com/izouma/nineth/mailTest.java

@@ -0,0 +1,28 @@
+package com.izouma.nineth;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.mail.SimpleMailMessage;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class mailTest extends ApplicationTests {
+    @Autowired
+    JavaMailSenderImpl mailSender;
+    private String emailServiceCode;
+
+    @Test
+    public void test() {
+        emailServiceCode = "1234";
+        SimpleMailMessage message = new SimpleMailMessage();
+        message.setSubject("注册验证码");
+        message.setText("注册验证码是:" + emailServiceCode);
+        message.setTo("962140020@qq.com");
+        message.setFrom("modernPoint01@163.com");
+        mailSender.send(message);
+    }
+}