Example #1
0
        public async Task <ActionResult <string> > SendMail([FromForm] string email, [FromForm] string title, [FromForm] string type, [FromForm] string username)
        {
            if (string.IsNullOrWhiteSpace(email) && !email.Contains('@'))
            {
                return(BadRequest());
            }

            if (type == "resetpassword")
            {
                var user = await _context.Users.Include(u => u.Claims).SingleOrDefaultAsync(u => u.Username == username);

                if (user == null)
                {
                    return(BadRequest("username doesn't exist"));
                }

                if (user.Claims.SingleOrDefault(c => c.Type == "email" && c.Value == email) == null)
                {
                    return(BadRequest("email don't match to the account"));
                }
            }

            // 移除超过10分钟的验证码
            _codeService.RemoveOverdue();

            // 若当前邮箱十分钟内未申请过验证码
            if (!_codeService.IsExist(email, type))
            {
                // 生成随机验证码
                string verificationCode = new Random().Next(0, 999999).ToString().PadLeft(6, '0');
                // 向目标邮箱发送验证码
                Send(email, verificationCode, title);
                // 更新或添加全局缓存
                _codeService.Add(email, verificationCode, type);
            }
            else
            {
                var createTime = _codeService.GetCreateTime(email, type);
                if (createTime.HasValue)
                {
                    // 一分钟之内申请过验证码
                    if (DateTime.Now - createTime.Value <= TimeSpan.FromMinutes(1))
                    {
                        return(Ok("refused"));
                    }
                    // 大于1分钟小于10分钟
                    else if (DateTime.Now - createTime.Value > TimeSpan.FromMinutes(1) &&
                             DateTime.Now - createTime.Value <= TimeSpan.FromMinutes(10))
                    {
                        //AddOrUpdate(email, _codeService.Update);
                        // 生成随机验证码
                        string verificationCode = new Random().Next(0, 999999).ToString().PadLeft(6, '0');
                        // 向目标邮箱发送验证码
                        Send(email, verificationCode, title);
                        // 更新或添加全局缓存
                        _codeService.Update(email, verificationCode, type);
                    }
                }
            }

            return(Ok("success"));

            //void AddOrUpdate(string email, Func<string,string,bool> action)
            //{
            //    // 生成随机验证码
            //    string verificationCode = new Random().Next(0, 999999).ToString().PadLeft(6, '0');
            //    // 向目标邮箱发送验证码
            //    Send(email, verificationCode, title);
            //    // 更新或添加全局缓存
            //    //_codeService.Update(email, verificationCode);
            //    action(email, verificationCode);
            //}
        }