asp.net core 3.1 webapi 接口设计备忘

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace MyWeb.Api.UserService.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly AppDb Db;
        private readonly IConfiguration Configuration;
        private readonly IMemoryCache _memoryCache;

        public UserController(AppDb db, IConfiguration configuration, IMemoryCache memoryCache)
        {
            Db = db;
            Configuration = configuration;
            _memoryCache = memoryCache;
        }

        // POST: api/User/Login
        [AllowAnonymous]
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult<string> Login(LoginModel model)
        {
            if (string.IsNullOrEmpty(model.Account))
            {
                return BadRequest("账号不能为空");
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                return BadRequest("密码不能为空");
            }

            Db.Open();
            AppUserQuery appUserQuery = new AppUserQuery(Db);
            AppUserModel appUserModel = appUserQuery.GetModelByAccount(model.Account);
            if (appUserModel == null || appUserModel.Password != Utils.md5(model.Password))
            {
                return NotFound("账号不存在或密码不正确");
            }

            var claims = new[]
            {
                    new Claim(ClaimTypes.Name, appUserModel.Id.ToString())
                };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Token:Secret"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(Configuration["Token:Issuer"], Configuration["Token:Audience"], claims, expires: DateTime.Now.AddDays(int.Parse(Configuration["Token:AccessExpiration"])), signingCredentials: credentials);
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }

        // POST: api/User/Register
        [AllowAnonymous]
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult Register(RegisterModel model)
        {
            if (string.IsNullOrEmpty(model.Account))
            {
                return BadRequest("账号不能为空");
            }

            if (string.IsNullOrEmpty(model.Password))
            {
                return BadRequest("密码不能为空");
            }

            if (string.IsNullOrEmpty(model.SMSCode))
            {
                return BadRequest("短信验证码不能为空");
            }

            string smsCode;
            if (!_memoryCache.TryGetValue(model.Account, out smsCode))
            {
                return BadRequest("验证码未发送");
            }
            else
            {
                if (smsCode != model.SMSCode)
                {
                    return BadRequest("验证码不正确");
                }
            }

            Db.Open();
            AppUserQuery appUserQuery = new AppUserQuery(Db);
            AppUserModel appUserModel = appUserQuery.GetModelByAccount(model.Account);
            if (appUserModel != null)
            {
                return BadRequest("账号已存在");
            }

            appUserModel = new AppUserModel(Db);
            appUserModel.Account = model.Account;
            appUserModel.Password = Utils.md5(model.Password);
            appUserModel.Createtime = DateTime.Now;
            appUserModel.Insert();
            _memoryCache.Remove(model.Account);
            return Ok();
        }

        // POST: api/User/Password
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult Password(PasswordModel model)
        {
            if (string.IsNullOrEmpty(model.OriginalPassword))
            {
                return BadRequest("原密码不能为空");
            }

            if (string.IsNullOrEmpty(model.NewPassword))
            {
                return BadRequest("新密码不能为空");
            }

            var identity = User.Identity as ClaimsIdentity;
            int uid = int.Parse(identity.Name);

            Db.Open();
            AppUserQuery appUserQuery = new AppUserQuery(Db);
            AppUserModel appUserModel = appUserQuery.GetModelById(uid);
            if (appUserModel == null)
            {
                return BadRequest("账号不存在");
            }

            if (appUserModel.Password != Utils.md5(model.OriginalPassword))
            {
                return NotFound("原密码不正确");
            }
            appUserModel.Password = Utils.md5(model.NewPassword);
            appUserModel.Update();

            return Ok();
        }

        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult<AppUserModel> Info()
        {
            var identity = User.Identity as ClaimsIdentity;
            int uid = int.Parse(identity.Name);

            Db.Open();
            AppUserQuery appUserQuery = new AppUserQuery(Db);
            AppUserModel appUserModel = appUserQuery.GetModelById(uid);
            if (appUserModel == null)
            {
                return BadRequest("账号不存在");
            }

            appUserModel.Password = string.Empty;
            return appUserModel;
        }

        // POST: api/User/Nickname/{nickname}
        [HttpPost("{nickname}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult Nickname(string nickname)
        {
            if (string.IsNullOrEmpty(nickname))
            {
                return BadRequest("昵称不能为空");
            }

            var identity = User.Identity as ClaimsIdentity;
            int uid = int.Parse(identity.Name);

            Db.Open();
            AppUserQuery appUserQuery = new AppUserQuery(Db);
            AppUserModel appUserModel = appUserQuery.GetModelById(uid);
            if (appUserModel == null)
            {
                return BadRequest("账号不存在");
            }

            appUserModel.Nickname = nickname;
            appUserModel.Update();
            return Ok();
        }
    }
}

 

posted @ 2020-01-29 20:39  Old  阅读(672)  评论(0编辑  收藏  举报